File size: 23,854 Bytes
fc115d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# DRL Trading System - Project Architecture

**Last Updated:** March 12, 2026
**System Version:** Ultimate Agent (Whale-Fused PPO-LSTM)

---

## πŸ“‹ Executive Summary

This is an autonomous **Deep Reinforcement Learning (DRL) Trading System** that uses PPO-LSTM agents to trade cryptocurrency on Binance Testnet. The system features real-time whale wallet tracking, multi-timeframe analysis, advanced feature engineering (150+ features), and a Streamlit dashboard for monitoring.

### Key Capabilities
- 🧠 **PPO-LSTM Agent** with 150+ advanced features (Wyckoff, SMC, whale patterns)
- πŸ‹ **Whale Pattern Prediction** using ML models trained on verified whale wallets
- πŸ“Š **Multi-Asset Trading** (BTC, ETH, SOL, XRP)
- πŸ”„ **Self-Improvement Loop** (fine-tunes on successful trades every 24 hours)
- πŸ“ˆ **Real-time Dashboard** with TradingView-style charts
- πŸ›‘οΈ **Advanced Risk Management** (circuit breaker, adaptive SL/TP, regime detection)
- ⚑ **Live Trading** on Binance Testnet with dry-run mode

---

## πŸ—οΈ System Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        USER INTERFACE                            β”‚
β”‚  Streamlit Dashboard (app.py) + API Server (api_server.py)      β”‚
β”‚  - Real-time charts (TradingView-style)                         β”‚
β”‚  - Whale analytics dashboard                                    β”‚
β”‚  - Bot status monitoring                                        β”‚
β”‚  - Market analysis cards (Whale, Funding, Order Flow)           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                         β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   LIVE TRADING ORCHESTRATOR                      β”‚
β”‚         live_trading_multi.py (MultiAssetTradingBot)            β”‚
β”‚  - Multi-threaded bot execution per asset                       β”‚
β”‚  - Global portfolio management                                  β”‚
β”‚  - 30-min cooldown after losses                                 β”‚
β”‚  - 4-hour minimum hold time                                     β”‚
β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
      β”‚                                   β”‚
β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   DRL BRAIN           β”‚       β”‚   MARKET INTELLIGENCE         β”‚
β”‚  (PPO-LSTM Agent)     β”‚       β”‚                               β”‚
β”‚                       β”‚       β”‚  1. Whale Tracker             β”‚
β”‚ β€’ UltimateFeatureEng  β”‚       β”‚     - Pattern Predictor       β”‚
β”‚ β€’ VecNormalize        β”‚       β”‚     - Wallet Collector        β”‚
β”‚ β€’ 150+ features       β”‚       β”‚     - Registry (ETH/SOL/XRP)  β”‚
β”‚ β€’ Model inference     β”‚       β”‚                               β”‚
β”‚                       β”‚       β”‚  2. Order Flow Analyzer       β”‚
β”‚ Models:               β”‚       β”‚     - CVD, OI, funding rates  β”‚
β”‚ β”œβ”€ ultimate_agent.zip β”‚       β”‚                               β”‚
β”‚ └─ vec_normalize.pkl  β”‚       β”‚  3. Multi-Timeframe Analyzer  β”‚
β”‚                       β”‚       β”‚     - 4h, 1d, 1w timeframes   β”‚
β”‚                       β”‚       β”‚                               β”‚
β”‚                       β”‚       β”‚  4. Regime Detector           β”‚
β”‚                       β”‚       β”‚     - Trending/Ranging        β”‚
β”‚                       β”‚       β”‚     - ADX/ATR-based           β”‚
β”‚                       β”‚       β”‚                               β”‚
β”‚                       β”‚       β”‚  5. TFT Price Forecaster      β”‚
β”‚                       β”‚       β”‚     - Neural price prediction β”‚
β”‚                       β”‚       β”‚     - Confidence scoring      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                          β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                      DATA PIPELINE                              β”‚
β”‚                                                                  β”‚
β”‚  1. Historical Data (Multi-Asset Fetcher)                       β”‚
β”‚     └─ CCXT β†’ Binance API β†’ CSV cache                          β”‚
β”‚                                                                  β”‚
β”‚  2. Whale Wallet Data                                           β”‚
β”‚     β”œβ”€ ETH: 8 verified wallets (Binance, Bitfinex, etc.)       β”‚
β”‚     β”œβ”€ SOL: 11 verified wallets                                β”‚
β”‚     └─ XRP: 13 verified wallets                                β”‚
β”‚                                                                  β”‚
β”‚  3. Alternative Data                                            β”‚
β”‚     β”œβ”€ Fear & Greed Index                                      β”‚
β”‚     └─ BTC Dominance                                            β”‚
β”‚                                                                  β”‚
β”‚  4. Storage Layer                                               β”‚
β”‚     β”œβ”€ SQLite (trading.db) - trades, state                     β”‚
β”‚     β”œβ”€ JSON - whale data, backtest reports                     β”‚
β”‚     └─ CSV - historical OHLCV                                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## πŸ“ Directory Structure

```
drl-trading-system/
β”œβ”€β”€ .agent/                       # Agent workflow definitions
β”‚   └── workflows/
β”‚       β”œβ”€β”€ feature.md            # Feature development workflow
β”‚       β”œβ”€β”€ fix.md                # Bug fix workflow
β”‚       β”œβ”€β”€ train.md              # Model training workflow
β”‚       └── deploy.md             # Deployment workflow
β”‚
β”œβ”€β”€ config/
β”‚   └── config.yaml               # System configuration (exchange, risk, model params)
β”‚
β”œβ”€β”€ data/                         # All data storage
β”‚   β”œβ”€β”€ historical/               # Cached OHLCV data (CSV)
β”‚   β”œβ”€β”€ models/                   # Trained DRL models
β”‚   β”‚   β”œβ”€β”€ ultimate_agent.zip    # Main PPO model
β”‚   β”‚   β”œβ”€β”€ ultimate_agent_vec_normalize.pkl
β”‚   β”‚   β”œβ”€β”€ tft/                  # TFT price forecaster models
β”‚   β”‚   └── multi_asset/          # Asset-specific fine-tuned models
β”‚   β”œβ”€β”€ whale_wallets/            # Whale wallet transaction data
β”‚   β”‚   β”œβ”€β”€ eth/                  # 8 verified ETH whale wallets
β”‚   β”‚   β”œβ”€β”€ sol/                  # 11 verified SOL whale wallets
β”‚   β”‚   └── xrp/                  # 13 verified XRP whale wallets
β”‚   β”œβ”€β”€ alternative_cache/        # Fear/Greed, BTC dominance
β”‚   β”œβ”€β”€ checkpoints/              # Training checkpoints
β”‚   β”œβ”€β”€ backtest_report.json      # Latest backtest results
β”‚   └── trading.db                # SQLite database (trades, positions, state)
β”‚
β”œβ”€β”€ src/                          # Source code
β”‚   β”œβ”€β”€ env/                      # Gymnasium trading environments
β”‚   β”‚   β”œβ”€β”€ ultimate_env.py       # Main env (150+ features)
β”‚   β”‚   β”œβ”€β”€ advanced_env.py       # Advanced features env
β”‚   β”‚   β”œβ”€β”€ trading_env.py        # Base trading env
β”‚   β”‚   └── rewards.py            # Reward functions (Sharpe/Sortino)
β”‚   β”‚
β”‚   β”œβ”€β”€ brain/                    # DRL agent & training
β”‚   β”‚   β”œβ”€β”€ agent.py              # PPO-LSTM wrapper
β”‚   β”‚   β”œβ”€β”€ trainer.py            # Training loops
β”‚   β”‚   └── replay_buffer.py      # Experience replay
β”‚   β”‚
β”‚   β”œβ”€β”€ features/                 # Feature engineering modules
β”‚   β”‚   β”œβ”€β”€ ultimate_features.py  # 150+ feature engine (Wyckoff, SMC, etc.)
β”‚   β”‚   β”œβ”€β”€ whale_tracker.py      # Real-time whale monitoring (46KB)
β”‚   β”‚   β”œβ”€β”€ whale_pattern_predictor.py  # ML-based whale signal generator
β”‚   β”‚   β”œβ”€β”€ whale_wallet_collector.py   # Scrapes whale wallet data
β”‚   β”‚   β”œβ”€β”€ whale_wallet_registry.py    # Verified wallet addresses
β”‚   β”‚   β”œβ”€β”€ order_flow.py         # CVD, OI, funding rate analysis (25KB)
β”‚   β”‚   β”œβ”€β”€ mtf_analyzer.py       # Multi-timeframe analysis
β”‚   β”‚   β”œβ”€β”€ regime_detector.py    # Market regime classification
β”‚   β”‚   β”œβ”€β”€ risk_manager.py       # Adaptive risk management
β”‚   β”‚   β”œβ”€β”€ correlation_engine.py # Multi-asset correlation
β”‚   β”‚   └── on_chain_whales.py    # On-chain whale watcher
β”‚   β”‚
β”‚   β”œβ”€β”€ models/                   # ML models (non-DRL)
β”‚   β”‚   β”œβ”€β”€ whale_pattern_learner.py  # Random Forest for whale patterns (30KB)
β”‚   β”‚   β”œβ”€β”€ price_forecaster.py   # TFT (Temporal Fusion Transformer)
β”‚   β”‚   β”œβ”€β”€ confidence_engine.py  # Signal confidence scoring
β”‚   β”‚   β”œβ”€β”€ regime_classifier.py  # Regime classification model
β”‚   β”‚   └── ensemble_orchestrator.py  # Model ensemble coordination
β”‚   β”‚
β”‚   β”œβ”€β”€ data/                     # Data fetching & storage
β”‚   β”‚   β”œβ”€β”€ multi_asset_fetcher.py  # CCXT data fetcher
β”‚   β”‚   β”œβ”€β”€ storage.py            # Database abstraction layer
β”‚   β”‚   β”œβ”€β”€ candle_stream.py      # Real-time candle streaming
β”‚   β”‚   └── whale_stream.py       # Real-time whale data streaming
β”‚   β”‚
β”‚   β”œβ”€β”€ api/                      # Exchange integration & execution
β”‚   β”‚   β”œβ”€β”€ binance.py            # Binance API wrapper
β”‚   β”‚   β”œβ”€β”€ executor.py           # Order execution engine
β”‚   β”‚   β”œβ”€β”€ risk_manager.py       # Pre-execution risk checks
β”‚   β”‚   └── portfolio_manager.py  # Global portfolio coordination
β”‚   β”‚
β”‚   β”œβ”€β”€ backtest/                 # Backtesting engine
β”‚   β”‚   β”œβ”€β”€ engine.py             # Main backtest executor
β”‚   β”‚   └── data_loader.py        # Historical data loader
β”‚   β”‚
β”‚   └── ui/                       # User interface
β”‚       β”œβ”€β”€ app.py                # Streamlit dashboard (2470 lines)
β”‚       β”œβ”€β”€ api_server.py         # Flask API server (21KB)
β”‚       β”œβ”€β”€ charts.py             # TradingView chart components
β”‚       └── components.py         # Reusable UI components
β”‚
β”œβ”€β”€ logs/                         # All logs
β”‚   β”œβ”€β”€ trading_log.json          # Trade history
β”‚   β”œβ”€β”€ multi_asset_state.json    # Bot state per asset
β”‚   β”œβ”€β”€ tensorboard/              # TensorBoard training logs
β”‚   └── training/                 # Training session logs
β”‚
β”œβ”€β”€ Main Scripts                  # Top-level executable scripts
β”‚   β”œβ”€β”€ run.py                    # Legacy single-asset runner
β”‚   β”œβ”€β”€ live_trading_multi.py     # Multi-asset live trading (68KB)
β”‚   β”œβ”€β”€ train_ultimate.py         # Ultimate agent training (17KB)
β”‚   β”œβ”€β”€ train_whale_patterns.py   # Train whale ML models
β”‚   β”œβ”€β”€ backtest_strategy.py      # Strategy backtester (28KB)
β”‚   β”œβ”€β”€ launch_dashboard.sh       # Start Streamlit UI
β”‚   └── start.sh                  # Production startup script
β”‚
β”œβ”€β”€ requirements.txt              # Python dependencies
β”œβ”€β”€ Dockerfile                    # Docker deployment config
β”œβ”€β”€ .env                          # Environment variables (API keys)
└── README.md                     # User-facing documentation
```

---

## 🧩 Core Components Deep Dive

### 1. **DRL Agent (PPO-LSTM)**

**Location:** `src/brain/agent.py`, `src/env/ultimate_env.py`

- **Algorithm:** Proximal Policy Optimization (PPO)
- **Architecture:** LSTM policy network for temporal dependencies
- **Observation Space:** 153 dimensions (150 features + 3 position state variables)
- **Action Space:** Discrete(3) β†’ [0: Hold, 1: Buy/Long, 2: Sell/Short]
- **Reward Function:** Sharpe/Sortino ratio-based (risk-adjusted returns)

**Training Pipeline:**
1. Fetch historical data (1-year, 1h timeframe)
2. Compute 150+ features via UltimateFeatureEngine
3. Create Gymnasium env (UltimateTradingEnv)
4. Wrap with VecNormalize for observation scaling
5. Train PPO agent (500k-2M timesteps)
6. Save model + VecNormalize stats

**Key Training Files:**
- `train_ultimate.py` - Main training script
- `train_multi_asset.py` - Multi-asset transfer learning
- `train_whale_patterns.py` - Whale pattern ML training

### 2. **Feature Engineering (150+ Features)**

**Location:** `src/features/ultimate_features.py`

**Feature Categories:**
1. **Technical Indicators** (40+ features)
   - RSI, MACD, Bollinger Bands, ATR, ADX
   - EMA crossovers (9/21, 50/200)
   - Volume indicators (OBV, MFI)

2. **Wyckoff Analysis** (20+ features)
   - Accumulation/Distribution phases
   - Spring/Upthrust detection
   - Volume spread analysis

3. **Smart Money Concepts (SMC)** (15+ features)
   - Order blocks
   - Fair value gaps
   - Liquidity zones

4. **Multi-Timeframe** (30+ features)
   - 4h, 1d, 1w trend alignment
   - Higher timeframe support/resistance

5. **Whale Patterns** (20+ features)
   - Exchange dump ratio
   - Accumulator hoard ratio
   - Flow velocity, momentum
   - Wallet-specific hit rates

6. **Market Regime** (10+ features)
   - Trending/Ranging classification
   - Volatility regime

7. **Correlation Features** (15+ features)
   - BTC dominance
   - Multi-asset correlation matrix
   - Fear & Greed Index

### 3. **Whale Tracking System**

**Location:** `src/features/whale_tracker.py`, `src/models/whale_pattern_learner.py`

**Verified Whale Wallets:**
- **ETH (8 wallets):** Binance, Bitfinex, Kraken hot/cold wallets
- **SOL (11 wallets):** Major exchange wallets + accumulators
- **XRP (13 wallets):** Ripple, exchanges, known whales

**Data Collection:**
1. `whale_wallet_collector.py` scrapes blockchain APIs (Etherscan, Solscan, XRPScan)
2. Stores transaction history in JSON files (`data/whale_wallets/`)
3. Updates every 1 hour (configurable)

**Pattern Learning:**
1. `whale_pattern_learner.py` trains Random Forest models per chain
2. Features: flow velocity, exchange dump ratio, accumulator hoard ratio, wallet-specific patterns
3. Predicts price impact (momentum signal: -1 to +1)
4. Wallets weighted by historical hit rate (>55% = 2x weight)

**Real-time Prediction:**
1. `whale_pattern_predictor.py` loads trained models
2. Fetches recent wallet data from cache
3. Computes flow features
4. Returns aggregated signal with confidence score

### 4. **Live Trading Pipeline**

**Location:** `live_trading_multi.py`

**Flow:**
```
1. Initialize MultiAssetTradingBot for each asset (BTC, ETH, SOL, XRP)
2. Load ultimate_agent.zip + vec_normalize.pkl
3. Initialize feature engines (UltimateFeatureEngine, WhaleTracker, etc.)
4. Loop every 5 minutes:
   a. Fetch latest OHLCV data
   b. Compute 150+ features
   c. Normalize observation with VecNormalize
   d. Get PPO model prediction (action 0/1/2)
   e. Compute confidence score (TFT forecast + whale signals + regime)
   f. Execute trade if confidence > 0.6
   g. Manage position (trailing SL, TP, min hold time)
   h. Update state to database
5. Self-improvement: Every 24h, fine-tune on high-reward trades
```

**Risk Management:**
- **Circuit Breaker:** Stops trading at 5% daily loss
- **Position Sizing:** 25% of balance per trade (was 50%)
- **Stop Loss:** 2.5% (adaptive based on regime)
- **Take Profit:** 5% (2:1 R:R ratio)
- **Trailing Stop:** 60% of max profit
- **Min Hold Time:** 4 hours
- **Cooldown:** 30 minutes after stop loss hit

### 5. **Backtesting System**

**Location:** `backtest_strategy.py`, `src/backtest/engine.py`

**Process:**
1. Load historical data (default: 1 year)
2. Replay EXACT live trading pipeline:
   - Same feature computation
   - Same VecNormalize scaling
   - Same PPO model
   - Same risk management rules
3. Track all trades, equity curve, Sharpe ratio
4. Save report to `data/backtest_report.json`

**Metrics:**
- Total Return (%)
- Sharpe Ratio
- Sortino Ratio
- Max Drawdown (%)
- Win Rate (%)
- Average Trade Duration
- Total Trades

### 6. **Streamlit Dashboard**

**Location:** `src/ui/app.py` (2470 lines)

**Pages:**
1. **Bot Status**
   - Current position, PnL, equity
   - Model info (last trained, confidence)
   - Start/Stop bot controls

2. **Charts**
   - TradingView-style candlestick charts
   - Buy/Sell signal markers
   - Support/Resistance levels
   - Volume bars

3. **Whale Analytics**
   - Real-time whale flow signals
   - Top wallets by accuracy
   - Exchange dump ratio trends

4. **Market Analysis**
   - Funding rates
   - Order flow (CVD, OI)
   - Multi-timeframe alignment
   - Regime detection

5. **Trade History**
   - All executed trades
   - PnL breakdown
   - Performance metrics

**API Server:** `src/ui/api_server.py`
- Flask REST API for real-time data
- 60-second caching for external APIs
- Endpoints: `/whale`, `/funding`, `/order_flow`, `/trades`

---

## πŸ”„ Data Flow

### Training Flow
```
Historical Data (CSV)
  β†’ DataLoader
  β†’ UltimateTradingEnv
  β†’ VecNormalize
  β†’ PPO.learn()
  β†’ Save model + VecNormalize stats
```

### Live Trading Flow
```
Binance API (real-time)
  β†’ MultiAssetDataFetcher
  β†’ Feature Engines (Whale, MTF, OrderFlow, etc.)
  β†’ UltimateFeatureEngine (150+ features)
  β†’ VecNormalize
  β†’ PPO.predict()
  β†’ Risk Manager
  β†’ Order Executor
  β†’ Database (trading.db)
```

### Whale Tracking Flow
```
Blockchain APIs (Etherscan, Solscan, XRPScan)
  β†’ WhaleWalletCollector
  β†’ JSON cache (data/whale_wallets/)
  β†’ WhalePatternLearner (Random Forest)
  β†’ WhalePatternPredictor
  β†’ Signal aggregation
  β†’ Live Trading Bot
```

---

## πŸ› οΈ Technology Stack

### Core Frameworks
- **DRL:** `stable-baselines3` (PPO), `gymnasium` (env)
- **ML:** `scikit-learn` (Random Forest), `hmmlearn` (regime detection)
- **Neural Networks:** `torch` (TFT forecaster)
- **UI:** `streamlit`, `streamlit-lightweight-charts`, `plotly`
- **API:** `flask`, `flask-cors`

### Data & Exchange
- **Exchange:** `ccxt` (Binance API)
- **Data Processing:** `pandas`, `numpy`
- **Database:** SQLite (`sqlite3`), JSON, CSV

### Utilities
- **Config:** `pyyaml`, `python-dotenv`
- **Testing:** `pytest`, `pytest-asyncio`
- **Deployment:** Docker, Hugging Face Spaces

---

## πŸ” Security & Configuration

### Environment Variables (`.env`)
```bash
BINANCE_TESTNET_API_KEY=<key>
BINANCE_TESTNET_API_SECRET=<secret>
BINANCE_PROXY=<optional_proxy>
HF_TOKEN=<huggingface_token>
ETHERSCAN_API_KEY=<etherscan_key>
SOLSCAN_API_KEY=<solscan_key>
```

### Risk Parameters (`config/config.yaml`)
- Max Daily Loss: 5%
- Max Drawdown: 20%
- Stop Loss: 2.5%
- Take Profit: 5%
- Position Size: 25%

---

## πŸ“Š Model Performance

### Ultimate Agent (Latest Training)
- **Training Data:** 1 year (2024-2025), 1h timeframe
- **Assets:** BTC, ETH, SOL, XRP
- **Timesteps:** 2M+ per asset
- **Validation Sharpe:** ~1.2-1.8 (asset-dependent)
- **Backtest Win Rate:** 55-65%

### Whale Pattern Models
- **ETH Whale Model:** 62% hit rate (top wallets)
- **SOL Whale Model:** 58% hit rate
- **XRP Whale Model:** 60% hit rate

---

## πŸš€ Deployment

### Hugging Face Spaces
- **Space:** `chen470/drl-trading-bot`
- **Runtime:** Docker container
- **Auto-deploy:** Triggered by `git push origin main`
- **Build Time:** ~90 seconds
- **Logs:** Via HF API + `api_server.log`

### Local Development
```bash
# Install dependencies
pip install -r requirements.txt

# Run backtest
python backtest_strategy.py

# Start dashboard
streamlit run src/ui/app.py

# Run live trading (dry-run)
python live_trading_multi.py --assets BTCUSDT ETHUSDT --dry-run
```

---

## πŸ“ Key Files Reference

### Configuration
- `config/config.yaml` - All system parameters
- `.env` - API keys & secrets
- `requirements.txt` - Python dependencies

### Training
- `train_ultimate.py` - Main DRL training
- `train_whale_patterns.py` - Whale ML training
- `train_multi_asset.py` - Multi-asset transfer learning

### Live Trading
- `live_trading_multi.py` - Multi-asset trading bot (68KB)
- `src/api/executor.py` - Order execution
- `src/api/portfolio_manager.py` - Portfolio coordination

### Backtesting
- `backtest_strategy.py` - Strategy backtester (28KB)
- `src/backtest/engine.py` - Backtest engine

### UI
- `src/ui/app.py` - Streamlit dashboard (2470 lines)
- `src/ui/api_server.py` - Flask API server (21KB)

### Feature Engineering
- `src/features/ultimate_features.py` - Main feature engine
- `src/features/whale_tracker.py` - Whale tracking (46KB)
- `src/features/whale_pattern_predictor.py` - Whale ML predictor

---

## πŸ› Known Issues & Limitations

1. **scikit-learn 1.7.2 pinned** - Prevents pickle OOM crash on Hugging Face
2. **Proxy required for some APIs** - Binance Futures API, Etherscan (rate limits)
3. **TFT forecaster optional** - Falls back gracefully if model not trained
4. **Whale data collection blocking** - Should be async/background cron
5. **VecNormalize dependency** - Model predictions fail without proper normalization stats

---

## 🎯 Future Roadmap

1. **Async whale data collection** - Background scraper instead of blocking API calls
2. **Advanced ensemble methods** - Combine DRL + TFT + whale patterns more intelligently
3. **Real money trading** - Migrate from Testnet to production (with proper safeguards)
4. **More chains** - Add BTC-native whale tracking (currently uses ETH proxy)
5. **Improved UI** - Add more charts, alerts, mobile responsiveness
6. **Paper trading mode** - Simulate trades without Binance API

---

## πŸ“š Learning Resources

### Understanding the System
1. Start with `README.md` for high-level overview
2. Read `.agent/workflows/*.md` for development workflows
3. Study `config/config.yaml` for all parameters
4. Explore `src/env/ultimate_env.py` to understand the environment
5. Dive into `live_trading_multi.py` to see how it all connects

### Key Concepts
- **PPO (Proximal Policy Optimization):** DRL algorithm that balances exploration/exploitation
- **VecNormalize:** Critical for normalizing observations to prevent gradient explosion
- **Sharpe Ratio:** Risk-adjusted return metric (reward function)
- **Whale Tracking:** Monitor large holders to predict price movements
- **Wyckoff Analysis:** Market phase detection (accumulation, distribution)
- **Smart Money Concepts:** Institutional order flow analysis

---

## 🀝 Contributing

See `.agent/workflows/` for development workflows:
- `feature.md` - Adding new features
- `fix.md` - Bug fixes
- `train.md` - Model training
- `deploy.md` - Deployment process

---

## πŸ“„ License

MIT License - See LICENSE file

---

**Document Version:** 1.0
**Last Reviewed:** March 12, 2026
**Maintainer:** DRL Trading System Team