Files
dzentra_bot/docs/roadmap/master-roadmap.md

441 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Master Roadmap — Dzentra Bot
## Цель проекта
Создать Telegram-бота для:
- ручной торговли;
- мониторинга рынка;
- автоторговли;
- аналитики;
- управления стратегиями.
---
# Stage 01 — Bootstrap / Foundation
✔ app bootstrap
✔ config layer
✔ logging
✔ router bootstrap
✔ DB bootstrap
✅ Статус: завершён
---
# Stage 02 — System / Diagnostics
✔ system screen
✔ exchange health
✔ DB health
✔ runtime info
✔ error rendering
✅ Статус: завершён
---
# Stage 03 — Exchange Integration
✔ mock exchange
✔ time handling
✔ exchangeInfo
✔ private auth
✔ account + portfolio
✔ market live polling
⚠ websocket research / fallback polling
✅ Статус: завершён (fallback mode)
---
# Stage 04 — Storage / Journal
✔ storage foundation
✔ event log
✔ repositories
✔ UI integration
✔ journal management
✅ Статус: завершён
---
# Stage 05 — Trading UI / Draft / Validation
✔ order draft flow
✔ interactive builder
✔ validation
✔ runtime mode helpers
✔ UI unification
✔ quantity normalization
✅ Статус: завершён
---
# Stage 06 — Journal / Navigation / Settings
✔ journal UI
✔ navigation improvements
✔ settings screen
✔ system info
✅ Статус: завершён
---
# Stage 07 — Auto Trading
## 07.1 — Skeleton UI
✔ экран автоторговли
✔ state machine
## 07.2 — Real settings
✔ стратегия
✔ риск
✔ символ
✔ leverage (default x2)
## 07.3 — Analysis Cycle
✔ run_cycle()
✔ mock signals
✔ live updates
### 07.3.1 — Background Runner
✔ asyncio loop
### 07.3.2 — Live Screens
✔ market
✔ portfolio
✔ journal
### 07.3.3 — Multi Live
✔ multi-screen
✔ duplicate protection
### 07.3.4 — Monitoring redesign
✔ новый экран мониторинга
### 07.3.5 — WebSocket probe
✔ ws skeleton
⚠ fallback REST polling
## 07.4 — Strategy Plugin Architecture
### 07.4.1
✔ BaseStrategy
✔ SignalResult
### 07.4.2
✔ Strategy Registry
### 07.4.3 — Trend Strategy
✔ signal generation
✔ repeat confirmation logic
✔ confidence scoring
✔ UI integration
#### 07.4.3.1 — UI Optimization ✅
✔ compact auto screen
✔ state-based rendering (OFF / RUNNING / OBSERVING)
✔ minimal trading layout
✔ duplicate info removal
#### 07.4.3.2 — Engine Decoupling (NEXT) ✅
✔ split analysis / UI refresh
✔ fast price polling (1s)
✔ slow UI updates (event-driven / 60s)
✔ anti-flood protection
#### 07.4.3.3 — Paper Position & Execution Engine ✅
- добавлен ExecutionEngine
- реализованы paper-позиции (LONG / SHORT)
- интеграция с AutoTradeService
- синхронизация с UI
- логирование paper execution
- EventBus события (paper_position_opened)
#### Stage 07.4.3.4 — Telegram Strong Signal Alerts ✅
- EventBus-driven уведомления
- Фильтрация READY сигналов
- Поддержка BUY / SELL
- Анти-спам (deduplication)
- Интеграция с Journal
- Runner полностью управляет Telegram-уведомлениями
#### Stage 07.4.3.5 — Debug Commands & Test Mode ✅
- DEBUG_ENABLED env flag
- debug_force_signal API
- instant EventBus processing
- Telegram debug commands
- state inspection (/debug_state)
- journal logging for debug actions
- full pipeline testing without market dependency
#### Stage 07.4.3.6 - Smart Alert Throttling ✅
- cooldown для Telegram сигналов
- suppression повторных BUY/SELL
- journal logging suppressed событий
- не влияет на execution pipeline
#### 07.4.3.7 — Alert priority & UX improvements ✅
- priority levels: HIGH / MEDIUM / LOW
- improved Telegram alert layout
- normalized symbol & leverage formatting
- compatible with cooldown & suppression
- extended debug_signal parameters
#### 07.4.3.8 — Telegram Execution Alerts ✅
- Telegram alerts for paper position opened
- Telegram alerts for paper position closed
- Entry / Exit / Size / PnL rendering
- readable USD formatting
- signal alerts separated from execution alerts
#### 07.4.3.9 — Position flip flow ✅
- instant LONG ↔ SHORT reversal (FLIP)
- new EventBus event: paper_position_flipped
- unified execution alert for flip
- improved execution realism (no idle gap)
#### 07.4.3.10 — Auto UI Refactor & Live Screen ✅
- разделение auto.py → main.py + ui.py
- единый render-пайплайн через AutoTradeRunner
- live-обновление экрана без дублирования сообщений
- компактный UI: Signal / Decision / Position / PnL
- отображение Position Risk и Est. Size
- унификация форматирования (USD / price / leverage)
- защита от лишних edit (message is not modified)
#### 07.4.3.11 — Risk Settings UI & UX ✅
- отдельный экран Risk Settings (SL / TP / Max Loss)
- FSM-ввод значений (проценты и USD)
- inline-редактирование (без новых сообщений)
- временные статусы (auto-clear через ~2.5 сек)
- защита от race condition (убран “скачок” экранов)
- reset risk controls (все параметры → off)
- интеграция в Auto screen (Controls строка)
- интеграция в Settings (Risk Controls summary)
- единая навигация: Auto ↔ Settings ↔ Risk
- UX-подсказки и валидация ввода
#### 07.4.3.12 — Real Risk Engine (execution-level) ✅
- risk checks внутри ExecutionEngine
- SL / TP / ML закрывают позицию
- forced close с risk_reason
- интеграция в основной цикл автоторговли
- Telegram execution alerts с причиной риска
- единая точка принятия решений (execution layer)
#### 07.4.3.13 — Risk-Based Position Sizing & Margin Protection ✅
- risk-based position sizing через SL distance
- размер позиции теперь рассчитывается от Risk %
- execution-level margin validation
- защита от oversized positions
- max reserved balance limit
- execution block reason state
- блокировка ENTRY / FLIP при превышении margin limit
- compact mobile UI redesign
- новый формат SL / TP / ML
- compact position rendering
- estimated margin preview
- max reserved preview
- execution blocked status в UI
- улучшенный mobile formatting
- SL стал обязательным для risk-engine sizing
- 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.3.15 — Isolated Debug Runtime & Debug Auto Screen ✅
- isolated DebugTradeState
- isolated DebugPositionState
- isolated DebugTradeService
- isolated DebugExecutionEngine
- isolated DebugTradeRunner
- separate `/debug_auto_screen`
- separate debug auto UI
- debug commands no longer mutate AutoTradeService
- debug execution no longer mutates ExecutionEngine._position
- debug runner no longer uses AutoTradeRunner
- `/debug_live` disabled as production-runtime injector
- legacy debug commands redirected to isolated debug runtime
- debug LONG / SHORT / FLIP / CLOSE sandbox flow
- debug Start / Stop / Reset controls
- debug PnL live refresh
- debug margin / reserved rendering
- debug bid / ask execution pricing
- fresh REST snapshot support for debug execution
- debug_auto router added
- ordinary 🤖 Автоторговля screen remains unchanged by debug commands
- preparation for production execution pricing layer
#### 07.4.3.16 — Production Execution Pricing Layer
- added isolated runtime market caches
- separated AUTO and DEBUG websocket pricing
- added execution snapshot layer
- added freshness-aware execution pricing
- implemented websocket-first market sourcing
- added REST fallback pricing pipeline
- fixed signal timer reset after START
- removed shared market cache collisions
- stabilized AUTO/DEBUG UI market rendering
#### 07.4.3.17 — Unified Active Screen Lifecycle
- внедрён единый lifecycle основных экранов
- реализовано автоматическое закрытие предыдущего экрана
- устранено накопление Telegram UI-экранов
- унифицировано поведение всех основных экранов
- разделены UI lifecycle и background runtime
- сохранена фоновая работа AutoTradeRunner
- сохранена фоновая работа DebugTradeRunner
- стабилизирована работа live-экранов
- подготовлена архитектура для Telegram push-уведомлений
- подготовлена база для runtime event notifications
#### 07.4.3.18.1 — Runtime Event Skeleton Architecture
- добавлен слой runtime_events
- добавлен слой notifications
- создана модель RuntimeEvent
- создана модель NotificationMessage
- добавлен RuntimeEventPublisher
- добавлен NotificationService skeleton
- добавлен TelegramNotificationChannel
- добавлен NotificationTargetRegistry
- добавлена базовая дедупликация уведомлений
- добавлены шаблоны signal/execution notifications
- зарегистрирован Telegram bot в notification target registry
- зарегистрирован default chat из AUTO/DEBUG runners
- исправлен circular import в package init файлах
- подготовлена архитектура для переноса strong signal alerts
#### 07.4.3.18.2 ✅ Runtime Notification Migration
- strong signal alerts migrated to RuntimeEvent pipeline
- execution alerts migrated to RuntimeEvent pipeline
- detached Telegram delivery
- centralized notification logging
- runtime notification dedupe
- live runtime validation on real paper execution
- auto screen independence from notifications
---
### 07.4.3.19 — Strategy Audit & Signal Quality Layer
- audit SCALP false flip behavior
- add position-aware signal handling
- prevent weak/medium signal flips
- add min hold time before flip
- add flip cooldown
- add spread/slippage buffer
- classify signals as ENTRY / HOLD / EXIT / FLIP
- tune SCALP thresholds
#### 07.4.3.19.1 - Position-aware Flip Protection
- добавлена проверка confidence перед flip
- добавлено подтверждение flip по количеству повторов сигнала
- добавлена минимальная длительность удержания позиции перед flip
- добавлена защита от flip в убыточной позиции без сильного сигнала
- реализована блокировка flip через RuntimeEvent logging
- добавлен dedupe для повторяющихся событий flip-блокировки через _last_flip_block_key
- синхронизировано execution-state после ENTRY / FLIP / CLOSE
- исправлена очистка ghost-позиций после forced exit
- стабилизирован lifecycle paper execution во время ночного runtime-тестирования
#### 07.4.3.19.2 — Journal Noise Reduction & Position-aware Signal Logg
Снижение шума журнала и position-aware signal logging ✅
- отключено журналирование auto_screen_refresh_skipped
- отключено журналирование auto_screen_refreshed
- сохранено журналирование ошибок refresh-цикла
- добавлено подавление сигналов, совпадающих с открытой позицией
- добавлен throttled summary auto_position_aligned_signal_suppressed
- снижено количество повторных strong signal уведомлений
- сохранена обработка противоположных сигналов как reversal / flip candidates
- подготовлена база для Signal Intent Layer в следующем этапе
#### 07.4.3.19.3 ✅ Strategy Noise Filter & Signal Intent Layer
- убрано журналирование одиночных BUY / SELL без серии
- HOLD-серии переведены с repeat-count на duration формат
- добавлен формат 🟡 HOLD 5м 36с завершён сигналом SELL
- добавлен signal_intent в payload сигналов
- добавлены intent-типы ENTRY_CANDIDATE, REVERSAL_CANDIDATE, REINFORCE_POSITION, HOLD_MARKET, NOISE
- добавлена position-aware интерпретация сигналов
- добавлено отдельное событие готового сигнала
- подготовлена база для стандартизации журнала в 07.4.3.19.4
#### 07.4.3.19.4 ✅ Journal Runtime Standardization & Export Layer
- унифицированы execution event_type
- удалены legacy paper_* события
- execution logging переведён в единый human-readable стиль
- унифицированы market runtime events
- стандартизирован export logging
- добавлены account-aware export filename
- добавлены [DEMO]/[LIVE] runtime prefixes
- унифицированы risk-control journal events
- централизован EVENT_TITLES mapping
- журнал подготовлен к filters/search layer
### 07.4.4
⏳ Grid Strategy
### 07.4.5
⏳ Scalping Strategy
### 07.3.6 — Signal Engine
⏳ реальные сигналы
### 07.3.7 — Execution Engine
⏳ исполнение ордеров
### 07.3.8 — Analytics
⏳ статистика торговли
🟡 Статус: в работе
---
# Stage 08 — Analytics / Reports
⏳ отчёты
⏳ pnl
⏳ winrate
⏳ drawdown
⚪ Статус: не начат
---
# Stage 09 — Production Readiness
⏳ deployment
⏳ monitoring
⏳ alerts
⏳ backups
⚪ Статус: не начат
---
## Текущий статус проекта
👉 Завершён: 07.4.3.1
👉 Следующий шаг: 07.4.3.2 — Engine Decoupling + Price Polling