07.4.3.14 — Auto Trading UI. Realistic Pricing & Debug Live Tools

This commit is contained in:
2026-05-09 01:34:46 +03:00
parent ee78f9774a
commit df76490783
15 changed files with 2161 additions and 464 deletions

View File

@@ -242,6 +242,30 @@
- risk_percent теперь реально влияет на размер позиции
- flip теперь проходит через margin protection
#### 07.4.3.14 — Auto UI, Realistic Pricing & Debug Live Tools ✅
- redesigned RUNNING auto-trading UI
- HOLD / BUY / SELL / READY state separation
- compact signal rendering with real duration
- confidence hidden for HOLD state
- direction-aware LONG / SHORT UI blocks
- compact active position rendering
- removed zero-value UI noise without position
- realistic bid / ask pricing in auto UI
- realistic bid / ask execution pricing
- TREND strategy switched to mid-price analysis
- corrected own funds / margin calculations
- safer size rounding for margin protection
- signal_started_at support for real-time duration tracking
- improved auto screen refresh handling
- live UI refresh diagnostics in AutoTradeRunner
- new debug UI-state commands
- new paper execution debug commands
- automatic flip direction detection
- live paper execution monitoring commands
- integration testing flow for SL / TP / ML
- integration testing flow for execution alerts
- preparation for isolated debug runtime architecture
### 07.4.4
⏳ Grid Strategy

View File

@@ -228,6 +228,31 @@
- risk_percent теперь реально влияет на размер позиции
- flip теперь проходит через margin protection
#### 07.4.3.14 — Auto UI, Realistic Pricing & Debug Live Tools ✅
- redesigned RUNNING auto-trading UI
- HOLD / BUY / SELL / READY state separation
- compact signal rendering with real duration
- confidence hidden for HOLD state
- direction-aware LONG / SHORT UI blocks
- compact active position rendering
- removed zero-value UI noise without position
- realistic bid / ask pricing in auto UI
- realistic bid / ask execution pricing
- TREND strategy switched to mid-price analysis
- corrected own funds / margin calculations
- safer size rounding for margin protection
- signal_started_at support for real-time duration tracking
- improved auto screen refresh handling
- live UI refresh diagnostics in AutoTradeRunner
- new debug UI-state commands
- new paper execution debug commands
- automatic flip direction detection
- live paper execution monitoring commands
- integration testing flow for SL / TP / ML
- integration testing flow for execution alerts
- preparation for isolated debug runtime architecture
---
### 07.4.4

View File

@@ -0,0 +1,343 @@
# 07.4.3.14 — Auto Trading UI, Realistic Pricing & Debug Live Tools
## Цель
Привести экран автоторговли к более понятному trading-terminal формату и сделать расчёты paper execution ближе к реальности:
- обновить UI блока автоторговли
- разделить состояния HOLD / BUY / SELL / READY
- использовать bid / ask цены для входа и выхода
- улучшить отображение позиции
- добавить live debug-команды для проверки paper execution
- подготовить основу для последующей изоляции debug-режима
---
## Что было раньше
Ранее экран `Автоторговля — Работает` показывал технические данные:
- `HOLD ×N`
- `Зарезервировано · $ 0`
- `P&L · $ 0`
- confidence даже для HOLD
- расчёты от одной цены `lastPrice`
Это создавало лишний шум и не отражало реальную механику исполнения.
Также debug-команды смешивали UI-проверку и execution-проверку.
---
## Что реализовано
## 1. Новый формат экрана RUNNING
Для состояния без позиции экран стал компактнее.
Было:
```text
📡 Ожидание сигнала
🟡 HOLD ×18
Уверенность · 0.00
```
Стало:
```text
Сигнал 🟡 HOLD · 5м 35с
```
Для HOLD больше не отображается confidence, так как он не несёт торгового смысла.
---
## 2. BUY / SELL signal UI
Для BUY:
```text
Сигнал 🟢 BUY · 12с
Уверенность · 0.74
```
После подтверждения:
```text
Сигнал 🟢 BUY · READY
Уверенность · 0.88
```
Для SELL:
```text
Сигнал 🔴 SELL · 9с
Уверенность · 0.71
```
После подтверждения:
```text
Сигнал 🔴 SELL · READY
Уверенность · 0.91
```
---
## 3. Direction-aware order block
Для HOLD:
```text
BTC · Trend · x2
Цена · $ ...
```
Для BUY:
```text
🟢 BTC · Trend · LONG x2
Цена входа · $ ...
```
Для SELL:
```text
🔴 BTC · Trend · SHORT x2
Цена входа · $ ...
```
---
## 4. Убран UI-шум без открытой позиции
Если позиция не открыта, экран больше не показывает:
```text
Зарезервировано · $ 0
P&L · $ 0
```
Эти строки остаются только для активной позиции.
---
## 5. Realistic bid / ask pricing в UI
UI теперь использует market snapshot:
```python
ExchangeService().get_market_snapshot(symbol)
```
Правила:
```text
HOLD → last_price
BUY / LONG → ask_price
SELL / SHORT → bid_price
```
Если bid / ask недоступны, используется fallback на `last_price`.
---
## 6. TREND strategy переведена на mid price
Стратегия TREND теперь анализирует рынок по:
```text
mid_price = (bid_price + ask_price) / 2
```
Fallback:
```text
last_price
```
Это делает сигнал более стабильным и не искажает анализ spread-ом.
---
## 7. Realistic paper execution pricing
ExecutionEngine теперь использует более реалистичные цены:
```text
LONG entry → ask_price
SHORT entry → bid_price
LONG exit → bid_price
SHORT exit → ask_price
```
Flip теперь состоит из:
```text
exit текущей позиции по стороне
+
entry новой позиции по стороне
```
---
## 8. Own funds / margin calculation fix
Исправлен расчёт собственных средств:
```text
own_funds = position_notional / leverage
```
А не через статичный процент от allocated balance.
Также size округляется вниз, чтобы reserved margin не превышал лимит.
---
## 9. Signal duration
Добавлена поддержка реального времени удержания сигнала через:
```python
signal_started_at
```
Если timestamp недоступен, используется fallback:
```text
last_signal_repeat_count × 5 sec
```
---
## 10. Debug UI states
Добавлены команды для проверки UI-состояний:
```text
/debug_auto hold 335
/debug_auto buy 12 0.74
/debug_auto buy_ready 0.88
/debug_auto sell 9 0.71
/debug_auto sell_ready 0.91
/debug_auto long
/debug_auto short
/debug_auto reset
/debug_auto state
```
---
## 11. Debug paper execution
Добавлены команды разового paper execution:
```text
/debug_exec buy
/debug_exec sell
/debug_exec flip
/debug_exec flip_buy
/debug_exec flip_sell
/debug_exec close
/debug_exec state
```
`/debug_exec flip` автоматически определяет текущую позицию:
```text
LONG → SELL / SHORT
SHORT → BUY / LONG
```
---
## 12. Debug live paper test
Добавлен live debug режим:
```text
/debug_live buy
/debug_live sell
/debug_live flip
/debug_live close
/debug_live stop
/debug_live state
```
Этот режим открывает paper-позицию и запускает обычный AutoTradeRunner, чтобы проверить:
- мониторинг рынка
- обновление UI
- P&L
- SL / TP / ML
- flip по стратегии
- execution alerts
---
## 13. Auto screen runner diagnostics
В debug state добавлена диагностика AutoTradeRunner:
```text
Screen
Chat ID
Message ID
Has bot
Has render_text
Task running
```
Это помогает быстро понять, зарегистрирован ли экран автоторговли для live refresh.
---
## Архитектурный результат
Теперь:
- экран RUNNING стал компактнее и понятнее
- HOLD не перегружает UI
- BUY / SELL отображают направление LONG / SHORT
- расчёты preview используют bid / ask
- strategy анализирует mid price
- paper execution использует bid / ask для входа и выхода
- active position screen обновляется live
- debug-команды позволяют тестировать UI и execution быстрее
---
## Ограничения текущей реализации
Текущий debug live режим пока не изолирован.
Он вмешивается в реальные runtime-компоненты:
```text
AutoTradeState
ExecutionEngine._position
AutoTradeRunner
EventBus
Auto screen
```
Это удобно для integration testing, но не является полноценным sandbox.
---
## Следующий этап
07.4.3.15 — Isolated Debug Runtime
Планируется:
- отделить debug runtime от обычной автоторговли
- создать отдельный DebugAutoState
- создать отдельный DebugRunner
- создать отдельный DebugExecutionEngine
- создать отдельный debug screen
- исключить влияние debug-команд на AutoTradeService
- маркировать debug-логи и уведомления как `[DEBUG]`
- оставить `/debug_live` только как временный legacy integration test