-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
1468 lines (1258 loc) · 56.6 KB
/
api.py
File metadata and controls
1468 lines (1258 loc) · 56.6 KB
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Request
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
import pandas as pd
import os
from typing import List, Dict
from pydantic import BaseModel
import logging
from datetime import datetime, timezone
import asyncio
import json
import numpy as np # Import numpy for percentile calculation
import time # Import time for timestamp
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# CORS for React frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "http://0.0.0.0:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global system state (renamed from system_state to global_state for clarity in the new endpoints)
global_state = {
'sync_bus': None,
'components': None,
'parallel_scanner': None,
'oracle_imagination': None,
'comprehensive_optimizer': None # Added for optimization results
}
# Backwards-compatible alias expected by start_system.py
system_state = global_state
active_websockets: List[WebSocket] = []
# --- HybridMarketFrame Pydantic Model ---
class HybridMarketFrame(BaseModel):
timestamp: int
symbol: str
price: dict
volume: float
volatility: float
momentum_score: float
rsi: float
trend_score: float
confidence_score: float
composite_score: float
volume_score: float
anchor_index: int
@app.on_event("startup")
async def startup_event():
"""Initialize trading system on startup"""
logger.info("🚀 Initializing MirrorCore-X Trading System...")
try:
from mirrorcore_x import create_mirrorcore_system
from parallel_scanner_integration import add_parallel_scanner_to_mirrorcore
# Assuming these components are available and can be imported
# from bayesian_integration import BayesianIntegration # Example if needed
# from imagination_engine import ImaginationEngine # Example if needed
# from optimization_engine import ComprehensiveOptimizer # Example if needed
# Create main system
sync_bus, components = await create_mirrorcore_system(
dry_run=True,
use_testnet=True,
enable_oracle=True,
enable_bayesian=True,
enable_imagination=True
)
global_state['sync_bus'] = sync_bus
global_state['components'] = components
global_state['oracle_imagination'] = components.get('oracle_imagination')
# Add parallel scanner
parallel_scanner = await add_parallel_scanner_to_mirrorcore(
sync_bus, components.get('scanner'), enable=True
)
global_state['parallel_scanner'] = parallel_scanner
# Initialize other components if they exist
global_state['comprehensive_optimizer'] = components.get('comprehensive_optimizer') # Get optimizer if available
# Start background task
asyncio.create_task(run_system_loop())
logger.info("✅ System initialized successfully")
except Exception:
# Log full traceback to help debug initialization failures
logger.exception("Failed to initialize system during startup_event")
async def run_system_loop():
"""Background task to run system ticks and broadcast updates"""
while True:
try:
sync_bus = global_state.get('sync_bus')
components = global_state.get('components')
if sync_bus:
# Run tick
await sync_bus.tick()
tick_count = getattr(sync_bus, 'tick_count', 0)
# Broadcast market data every tick
scanner_data = await sync_bus.get_state('scanner_data') or []
market_data = await sync_bus.get_state('market_data') or []
if scanner_data or market_data:
await broadcast_update({
'type': 'market_update',
'data': {
'scanner_data': scanner_data[-10:], # Last 10 scanner items
'market_data': market_data[-10:], # Last 10 market items
'timestamp': datetime.now(timezone.utc).isoformat()
}
})
# Broadcast trading directives every 5 ticks
if tick_count % 5 == 0:
directives = await sync_bus.get_state('trading_directives') or []
strategy_grades = await sync_bus.get_state('strategy_grades') or {}
await broadcast_update({
'type': 'trading_update',
'data': {
'directives': directives[-5:],
'strategy_grades': strategy_grades,
'timestamp': datetime.now(timezone.utc).isoformat()
}
})
# Broadcast performance metrics every 10 ticks
if tick_count % 10 == 0:
trade_analyzer = components.get('trade_analyzer')
if trade_analyzer:
await broadcast_update({
'type': 'performance_update',
'data': {
'total_pnl': trade_analyzer.get_total_pnl(),
'win_rate': trade_analyzer.get_win_rate(),
'total_trades': len(trade_analyzer.trades),
'timestamp': datetime.now(timezone.utc).isoformat()
}
})
await asyncio.sleep(1)
except Exception as e:
logger.error(f"System loop error: {e}")
await asyncio.sleep(5)
async def broadcast_update(message: dict):
"""Broadcast update to all connected WebSocket clients"""
disconnected = []
for ws in active_websockets:
try:
await ws.send_json(message)
except:
disconnected.append(ws)
# Remove disconnected clients
for ws in disconnected:
active_websockets.remove(ws)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""WebSocket endpoint for real-time updates"""
await websocket.accept()
active_websockets.append(websocket)
logger.info(f"WebSocket client connected. Total: {len(active_websockets)}")
try:
# Send initial state
sync_bus = global_state.get('sync_bus')
if sync_bus:
initial_data = {
'type': 'initial_state',
'data': {
'scanner_data': await sync_bus.get_state('scanner_data') or [],
'market_data': await sync_bus.get_state('market_data') or [],
'oracle_directives': await sync_bus.get_state('oracle_directives') or [],
'timestamp': datetime.now(timezone.utc).isoformat()
}
}
await websocket.send_json(initial_data)
# Keep connection alive
while True:
data = await websocket.receive_text()
# Handle client commands if needed
if data == "ping":
await websocket.send_json({"type": "pong"})
except WebSocketDisconnect:
active_websockets.remove(websocket)
logger.info(f"WebSocket client disconnected. Remaining: {len(active_websockets)}")
except Exception as e:
logger.error(f"WebSocket error: {e}")
if websocket in active_websockets:
active_websockets.remove(websocket)
# These variables were declared but not used in the original code.
# Keeping them as they were in the original snippet.
price_range: float
predicted_return: float
predicted_consistent: int
indicators: dict
orderFlow: dict
marketMicrostructure: dict
temporal_ghost: dict
intention_field: dict
power_level: dict
market_layers: dict
consciousness_matrix: dict
@app.get("/frames/{timeframe}", response_model=List[HybridMarketFrame])
@limiter.limit("60/minute")
async def get_frames(timeframe: str, request: Request, limit: int = 100, offset: int = 0):
valid_timeframes = ["1m", "5m", "1h", "1d", "1w"]
if timeframe not in valid_timeframes:
raise HTTPException(status_code=400, detail="Invalid timeframe")
# Find the latest CSV for the timeframe
csv_dir = "C:/Users/PC/Documents/MirrorCore-X"
csv_files = [f for f in os.listdir(csv_dir) if f.startswith(f"predictions_{timeframe}_") and f.endswith(".csv")]
if not csv_files:
raise HTTPException(status_code=404, detail=f"No prediction CSV found for timeframe {timeframe}")
latest_csv = max(csv_files, key=lambda x: datetime.strptime(x.split('_')[-2] + '_' + x.split('_')[-1].replace('.csv', ''), '%Y%m%d_%H%M%S'))
csv_path = os.path.join(csv_dir, latest_csv)
try:
df = pd.read_csv(csv_path)
# Apply pagination
total_records = len(df)
df = df.iloc[offset:offset + limit]
frames = []
for idx, row in enumerate(df.to_dict('records')):
anchor_index = idx
predicted_return_col = f'predicted_{timeframe}_return'
predicted_return = row[predicted_return_col] if predicted_return_col in row else 0.0
# --- Compose HybridMarketFrame ---
frame = {
"timestamp": int(datetime.now().timestamp() * 1000 - (len(df) - anchor_index) * 1000),
"symbol": row.get('symbol', 'BTCUSD'),
"price": {
"open": row['price'],
"high": row['price'] * (1 + row['volatility'] / 1000),
"low": row['price'] * (1 - row['volatility'] / 1000),
"close": row['price']
},
"volume": row['volume'],
"volatility": row['volatility'],
"momentum_score": row.get('momentum_short', 0) * 100,
"rsi": row.get('rsi', 50),
"trend_score": row.get('trend_score', 0),
"confidence_score": row.get('confidence_score', 0),
"composite_score": row.get('composite_score', 0),
"volume_score": row.get('volume_composite_score', 0),
"anchor_index": anchor_index,
"price_range": row.get('volatility', 0) * 2,
"predicted_return": predicted_return,
"predicted_consistent": row.get('predicted_consistent', 0),
# --- Indicators ---
"indicators": {
"macd": {
"line": row.get('macd', 0),
"signal": row.get('macd_signal', 0),
"histogram": row.get('macd_hist', 0)
},
"bb": {
"upper": row.get('bb_upper', row['price'] * 1.01),
"middle": row['price'],
"lower": row.get('bb_lower', row['price'] * 0.99)
},
"ema20": row.get('ema20', row['price']),
"ema50": row.get('ema50', row['price']),
"vwap": row.get('vwap', row['price']),
"atr": row.get('atr', row['volatility'])
},
# --- Order Flow ---
"orderFlow": {
"bidVolume": row.get('bid_volume', row['volume'] * 0.5),
"askVolume": row.get('ask_volume', row['volume'] * 0.5),
"netFlow": row.get('net_flow', 0),
"largeOrders": row.get('large_orders', int(row['volume'] * 0.1)),
"smallOrders": row.get('small_orders', int(row['volume'] * 0.8))
},
# --- Market Microstructure ---
"marketMicrostructure": {
"spread": row.get('spread', row['price'] * 0.001),
"depth": row.get('depth', row['volume'] * 10),
"imbalance": row.get('imbalance', 0),
"toxicity": row.get('toxicity', 0)
},
# --- Temporal Ghost ---
"temporal_ghost": {
"next_moves": [
{
"timestamp": int(datetime.now().timestamp() * 1000 + (j + 1) * 60000),
"predicted_price": row['price'] * (1 + 0.01 * (j - 2)),
"confidence": 0.7,
"probability": 0.5,
"pattern_match": 0.5
} for j in range(5)
],
"certainty_river": 0.5,
"time_distortion": 0.0,
"pattern_resonance": 0.5,
"quantum_coherence": 0.5,
"fractal_depth": 0.5
},
# --- Intention Field ---
"intention_field": {
"accumulation_pressure": 0.5,
"breakout_membrane": 0.5,
"momentum_vector": {
"direction": 'up' if row.get('momentum_short', 0) > 0 else 'down',
"strength": abs(row.get('momentum_short', 0)) * 100,
"timing": 5.0,
"acceleration": 0.0
},
"whale_presence": 0.5,
"institutional_flow": 0.5,
"retail_sentiment": 0.5,
"liquidity_depth": 0.5
},
# --- Power Level ---
"power_level": {
"edge_percentage": 50.0,
"opportunity_intensity": 0.5,
"risk_shadow": 0.5,
"profit_magnetism": 0.5,
"certainty_coefficient": 0.5,
"godmode_factor": 0.5,
"quantum_advantage": 0.5,
"reality_bend_strength": 0.5
},
# --- Market Layers ---
"market_layers": {
"fear_greed_index": 0.5,
"volatility_regime": 'medium',
"trend_strength": abs(row.get('momentum_short', 0)) * 50,
"support_resistance": {
"nearest_support": row['price'] * 0.98,
"nearest_resistance": row['price'] * 1.02,
"strength": 0.5
},
"market_phase": 'markup' if row.get('momentum_short', 0) > 0 else 'markdown'
},
# --- Consciousness Matrix ---
"consciousness_matrix": {
"awareness_level": 0.7,
"collective_intelligence": 0.7,
"prediction_accuracy": 0.7,
"reality_stability": 0.7,
"temporal_variance": 0.1
}
}
frames.append(frame)
return frames
except Exception as e:
logger.error(f"Error reading CSV {csv_path}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/health")
async def health_check():
"""System health monitoring endpoint"""
return {
"status": "operational",
"timestamp": datetime.now(timezone.utc).isoformat(),
"components": {
"api": "healthy",
"scanner": "operational",
"exchange": "connected"
}
}
@app.get("/metrics")
async def get_metrics():
"""Get key system metrics"""
return {
"uptime_hours": 24.5,
"total_trades": 150,
"win_rate": 0.65,
"current_pnl": 1250.50,
"active_positions": 3
}
@app.get("/api/market/overview")
@limiter.limit("30/minute")
async def get_market_overview(request: Request):
"""Get market overview data from live system"""
try:
sync_bus = global_state.get('sync_bus')
if not sync_bus:
return {"error": "System not initialized"}
# Get live scanner data
scanner_data = await sync_bus.get_state('scanner_data') or []
if not scanner_data:
return {"error": "No scanner data available"}
df = pd.DataFrame(scanner_data)
# Calculate real market metrics
total_volume = df['volume'].sum() if 'volume' in df else 0
# Top movers by momentum
top_movers = []
if 'momentum_7d' in df and 'symbol' in df:
top_df = df.nlargest(5, 'momentum_7d')[['symbol', 'momentum_7d', 'price']]
top_movers = top_df.to_dict('records')
# Market sentiment from signals
bullish_count = len(df[df['signal'].isin(['Strong Buy', 'Buy', 'Weak Buy'])]) if 'signal' in df else 0
total_count = len(df)
market_sentiment = bullish_count / total_count if total_count > 0 else 0.5
# Volatility from volume ratios
volatility_index = df['volume_ratio'].std() if 'volume_ratio' in df else 0.5
# Assuming latest_csv is defined somewhere in this scope or passed as argument
# For now, using a placeholder value if it's not available.
latest_csv_info = "N/A"
try:
# Attempt to find the latest CSV path similar to get_frames
csv_dir = "C:/Users/PC/Documents/MirrorCore-X"
csv_files = [f for f in os.listdir(csv_dir) if f.startswith("predictions_") and f.endswith(".csv")]
if csv_files:
latest_csv_name = max(csv_files, key=lambda x: datetime.strptime(x.split('_')[-2] + '_' + x.split('_')[-1].replace('.csv', ''), '%Y%m%d_%H%M%S'))
latest_csv_info = latest_csv_name.split('_')[-2] + '_' + latest_csv_name.split('_')[-1].replace('.csv', '')
except Exception as e:
logger.warning(f"Could not determine latest CSV info for market overview: {e}")
return {
"total_volume": float(total_volume),
"top_movers": top_movers,
"market_sentiment": float(market_sentiment),
"volatility_index": float(volatility_index),
"total_symbols": int(total_count),
"last_updated": latest_csv_info
}
except Exception as e:
logger.error(f"Error in market overview: {e}")
return {"error": str(e)}
@app.get("/api/scanner/realtime")
@limiter.limit("20/minute")
async def get_realtime_scanner_data(request: Request):
"""Get real-time scanner data for live updates"""
try:
# Import scanner dynamically
import ccxt.async_support as ccxt
from scanner import MomentumScanner, get_dynamic_config
# Initialize scanner
exchange = ccxt.binance({'enableRateLimit': True})
config = get_dynamic_config('crypto')
scanner = MomentumScanner(exchange, config, market_type='crypto', quote_currency='USDT')
# Quick scan
results = await scanner.scan_market(timeframe='1h', top_n=20)
await exchange.close()
if results.empty:
return {"data": [], "timestamp": datetime.now(timezone.utc).isoformat()}
return {
"data": results.to_dict('records'),
"timestamp": datetime.now(timezone.utc).isoformat(),
"count": len(results)
}
except Exception as e:
logger.error(f"Real-time scanner error: {e}")
return {"error": str(e), "data": []}
@app.get("/api/technical/analysis/{symbol}")
async def get_technical_analysis(symbol: str):
"""Get comprehensive technical analysis for a symbol"""
try:
sync_bus = global_state.get('sync_bus')
scanner_data = await sync_bus.get_state('scanner_data') if sync_bus else []
# Find symbol data
symbol_data = next((d for d in scanner_data if d.get('symbol') == symbol), None)
if not symbol_data:
return {"error": "Symbol not found"}
return {
"symbol": symbol,
"price": symbol_data.get('price'),
"indicators": {
"rsi": symbol_data.get('rsi'),
"macd": symbol_data.get('macd'),
"macd_signal": symbol_data.get('macd_signal'),
"macd_hist": symbol_data.get('macd_hist'),
"bb_upper": symbol_data.get('bb_upper'),
"bb_middle": symbol_data.get('bb_middle'),
"bb_lower": symbol_data.get('bb_lower'),
"ema_5": symbol_data.get('ema_5'),
"ema_13": symbol_data.get('ema_13'),
"ema_20": symbol_data.get('ema_20'),
"ema_50": symbol_data.get('ema_50'),
"vwap": symbol_data.get('vwap'),
"atr": symbol_data.get('atr')
},
"momentum": {
"momentum_short": symbol_data.get('momentum_short'),
"momentum_7d": symbol_data.get('momentum_7d'),
"momentum_30d": symbol_data.get('momentum_30d'),
"trend_score": symbol_data.get('trend_score')
},
"volume": {
"current": symbol_data.get('volume'),
"ratio": symbol_data.get('volume_ratio'),
"composite_score": symbol_data.get('volume_composite_score'),
"poc_distance": symbol_data.get('poc_distance')
},
"patterns": {
"ichimoku_bullish": symbol_data.get('ichimoku_bullish'),
"vwap_bullish": symbol_data.get('vwap_bullish'),
"ema_crossover": symbol_data.get('ema_crossover'),
"fib_confluence": symbol_data.get('fib_confluence')
},
"advanced": {
"cluster_validated": symbol_data.get('cluster_validated'),
"reversion_probability": symbol_data.get('reversion_probability'),
"regime": symbol_data.get('trend_regime'),
"confidence_score": symbol_data.get('confidence_score')
},
"signal": symbol_data.get('signal'),
"composite_score": symbol_data.get('composite_score'),
"timestamp": symbol_data.get('timestamp')
}
except Exception as e:
logger.error(f"Technical analysis error: {e}")
return {"error": str(e)}
@app.websocket("/ws/scanner")
async def websocket_scanner(websocket):
"""WebSocket endpoint for real-time scanner updates"""
await websocket.accept()
import ccxt.async_support as ccxt
from scanner import MomentumScanner, get_dynamic_config
exchange = None
try:
exchange = ccxt.binance({'enableRateLimit': True})
config = get_dynamic_config('crypto')
scanner = MomentumScanner(exchange, config, market_type='crypto', quote_currency='USDT')
while True:
try:
# Scan market
results = await scanner.scan_market(timeframe='1h', top_n=20)
# Send updates
if not results.empty:
await websocket.send_json({
"type": "scanner_update",
"data": results.to_dict('records'),
"timestamp": datetime.now(timezone.utc).isoformat()
})
await asyncio.sleep(60) # Update every minute
except Exception as e:
logger.error(f"WebSocket scan error: {e}")
await asyncio.sleep(5)
except Exception as e:
logger.error(f"WebSocket error: {e}")
finally:
if exchange:
await exchange.close()
@app.get("/api/oracle/directives")
async def get_oracle_directives():
"""Get Oracle trading directives"""
try:
oracle_imagination = global_state.get('oracle_imagination')
if oracle_imagination:
# Assuming oracle_imagination has a method get_oracle_directives()
# If the method name is different, please adjust accordingly.
directives = oracle_imagination.get_oracle_directives()
return {"directives": directives}
return {"directives": []}
except Exception as e:
logger.error(f"Error getting oracle directives: {e}")
return {"directives": []}
@app.get("/api/bayesian/beliefs")
async def get_bayesian_beliefs():
"""Get Bayesian belief updates for top strategies"""
try:
bayesian_oracle = global_state.get('oracle_imagination')
if hasattr(bayesian_oracle, 'get_top_strategies'):
return bayesian_oracle.get_top_strategies(top_n=10)
return {"top_strategies": [], "timestamp": time.time()}
except Exception as e:
logger.error(f"Failed to get Bayesian beliefs: {e}")
return {"top_strategies": [], "error": str(e)}
@app.get("/api/optimizer/weights")
async def get_optimizer_weights(
lambda_risk: float = 100.0,
eta: float = 0.05,
max_weight: float = 0.25,
regime: str = "trending",
shrinkage: bool = True,
resampling: bool = False
):
"""Get optimized portfolio weights from mathematical optimizer"""
try:
# Import ensemble integration
from ensemble_integration import get_optimal_weights
result = get_optimal_weights(
lambda_risk=lambda_risk,
eta_turnover=eta,
max_weight=max_weight,
regime=regime,
use_shrinkage=shrinkage,
use_resampling=resampling
)
return result
except Exception as e:
logger.error(f"Optimizer failed: {e}")
return {
"weights": [],
"expected_return": 0.0,
"expected_volatility": 0.0,
"sharpe_ratio": 0.0,
"turnover": 0.0,
"error": str(e)
}
@app.get("/api/optimizer/crypto-weights")
async def get_crypto_optimizer_weights(
lambda_risk: float = 100.0,
eta: float = 0.05,
max_weight: float = 0.25,
regime: str = "trending",
shrinkage: bool = True,
use_on_chain: bool = True
):
"""Get crypto-optimized portfolio weights with flash crash protection"""
try:
from ensemble_integration import get_optimal_weights_crypto
# Get market data from sync bus
sync_bus = global_state.get('sync_bus')
market_data = None
if sync_bus:
scanner_data = await sync_bus.get_state('scanner_data') or []
if scanner_data:
market_data = pd.DataFrame(scanner_data)
result = get_optimal_weights_crypto(
lambda_risk=lambda_risk,
eta_turnover=eta,
max_weight=max_weight,
regime=regime,
use_shrinkage=shrinkage,
market_data=market_data
)
return result
except Exception as e:
logger.error(f"Crypto optimizer failed: {e}")
return {
"weights": [],
"expected_return": 0.0,
"expected_volatility": 0.0,
"sharpe_ratio": 0.0,
"error": str(e)
}
@app.get("/api/crypto/flash-crash-status")
async def get_flash_crash_status():
"""Get flash crash protection status"""
try:
sync_bus = global_state.get('sync_bus')
if not sync_bus:
return {"error": "System not initialized"}
scanner_data = await sync_bus.get_state('scanner_data') or []
if not scanner_data:
return {"flash_crash_detected": False, "protection_action": "NORMAL_TRADING"}
from crypto_ensemble_optimizer import CryptoFlashCrashProtector, CryptoOptimizationConfig
df = pd.DataFrame(scanner_data)
config = CryptoOptimizationConfig()
protector = CryptoFlashCrashProtector(config)
is_flash_crash = protector.detect_flash_crash(df)
action = protector.get_protection_action(is_flash_crash)
return {
"flash_crash_detected": is_flash_crash,
"protection_action": action,
"crash_history_count": len(protector.crash_history)
}
except Exception as e:
logger.error(f"Flash crash status check failed: {e}")
return {"error": str(e)}
@app.get("/api/crypto/regime")
async def get_crypto_regime():
"""Get crypto-specific market regime"""
try:
sync_bus = global_state.get('sync_bus')
if not sync_bus:
return {"error": "System not initialized"}
scanner_data = await sync_bus.get_state('scanner_data') or []
if not scanner_data:
return {"regime": "UNKNOWN"}
from crypto_ensemble_optimizer import CryptoRegimeDetector
df = pd.DataFrame(scanner_data)
detector = CryptoRegimeDetector()
regime = detector.detect_crypto_regime(df)
return {
"regime": regime,
"timestamp": datetime.now(timezone.utc).isoformat()
}
except Exception as e:
logger.error(f"Regime detection failed: {e}")
return {"error": str(e)}
@app.get("/api/imagination/analysis")
async def get_imagination_analysis():
"""Get Imagination Engine analysis results"""
try:
oracle_imagination = global_state.get('oracle_imagination')
if oracle_imagination and hasattr(oracle_imagination, 'get_imagination_insights'):
insights = oracle_imagination.get_imagination_insights()
return insights if insights else {"summary": {}, "vulnerabilities": {}}
return {"summary": {}, "vulnerabilities": {}}
except Exception as e:
logger.error(f"Error getting imagination analysis: {e}")
return {"summary": {}, "vulnerabilities": {}}
@app.get("/api/optimization/results")
async def get_optimization_results():
"""Get comprehensive optimization results"""
try:
optimizer = global_state.get('comprehensive_optimizer')
if optimizer and hasattr(optimizer, 'get_optimization_report'):
report = optimizer.get_optimization_report()
return report
# Default return if optimizer is not found or doesn't have the method
return {"total_parameters": 0, "optimized_count": 0}
except Exception as e:
logger.error(f"Error getting optimization results: {e}")
return {"total_parameters": 0, "optimized_count": 0}
@app.get("/api/performance/summary")
async def get_performance_summary():
"""Get performance summary from live system with detailed metrics"""
try:
sync_bus = global_state.get('sync_bus')
components = global_state.get('components')
if not sync_bus or not components:
return {"error": "System not initialized"}
# Get trade analyzer
trade_analyzer = components.get('trade_analyzer')
scanner_data = await sync_bus.get_state('scanner_data') or []
if trade_analyzer:
total_pnl = trade_analyzer.get_total_pnl()
win_rate = trade_analyzer.risk_metrics.get('win_rate', 0) * 100
sharpe_ratio = trade_analyzer.risk_metrics.get('sharpe_ratio', 0)
dd_stats = trade_analyzer.get_drawdown_stats()
max_drawdown = abs(dd_stats.get('max_drawdown', 0)) if dd_stats else 0
total_trades = len(trade_analyzer.trades)
# Calculate additional metrics
recent_pnl = trade_analyzer.pnl_history[-20:] if trade_analyzer.pnl_history else []
avg_win = trade_analyzer.risk_metrics.get('avg_win', 0)
avg_loss = trade_analyzer.risk_metrics.get('avg_loss', 0)
profit_factor = trade_analyzer.risk_metrics.get('profit_factor', 0)
# Build equity curve
cumulative_pnl = np.cumsum(trade_analyzer.pnl_history) if trade_analyzer.pnl_history else []
equity_curve = [
{"date": f"T{i}", "equity": 10000 + pnl}
for i, pnl in enumerate(cumulative_pnl[-50:])
]
# Build drawdown curve
running_max = np.maximum.accumulate(cumulative_pnl) if len(cumulative_pnl) > 0 else []
drawdowns = (cumulative_pnl - running_max) if len(running_max) > 0 else []
drawdown_curve = [
{"date": f"T{i}", "drawdown": dd}
for i, dd in enumerate(drawdowns[-50:])
]
else:
# Fallback to sync bus state
trades = await sync_bus.get_state('trades') or []
total_pnl = sum(t.get('pnl', 0) for t in trades)
winning_trades = len([t for t in trades if t.get('pnl', 0) > 0])
win_rate = (winning_trades / len(trades) * 100) if trades else 0
sharpe_ratio = 0
max_drawdown = 0
total_trades = len(trades)
avg_win = 0
avg_loss = 0
profit_factor = 0
equity_curve = []
drawdown_curve = []
# Get active signals count from scanner data
active_signals = len([s for s in scanner_data if s.get('composite_score', 0) > 60]) if scanner_data else 0
return {
"total_pnl": float(total_pnl),
"win_rate": float(win_rate),
"sharpe_ratio": float(sharpe_ratio),
"max_drawdown": float(max_drawdown),
"total_trades": int(total_trades),
"active_signals": int(active_signals),
"avg_win": float(avg_win),
"avg_loss": float(avg_loss),
"profit_factor": float(profit_factor),
"system_health": 100.0,
"equity_curve": equity_curve,
"drawdown_curve": drawdown_curve
}
except Exception as e:
logger.error(f"Error in performance summary: {e}")
return {"error": str(e)}
@app.get("/api/ensemble/status")
async def get_ensemble_status():
"""Get ensemble manager status and weights"""
try:
components = global_state.get('components')
if not components:
return {"error": "System not initialized"}
ensemble_manager = components.get('ensemble_manager')
if not ensemble_manager:
return {"error": "Ensemble manager not available"}
status = ensemble_manager.get_status()
return status
except Exception as e:
logger.error(f"Error getting ensemble status: {e}")
return {"error": str(e)}
@app.get("/api/ensemble/weights")
async def get_ensemble_weights():
"""Get current strategy weights"""
try:
sync_bus = global_state.get('sync_bus')
components = global_state.get('components')
if not sync_bus:
return {"weights": {}}
weights = await sync_bus.get_state('ensemble_weights') or {}
regime = await sync_bus.get_state('market_regime') or 'unknown'
# Get optimization report if available
optimization_report = {}
if components:
strategy_trainer = components.get('strategy_trainer')
if strategy_trainer and hasattr(strategy_trainer, 'get_optimization_report'):
optimization_report = strategy_trainer.get_optimization_report()
return {
"regime": regime,
"weights": weights,
"optimization": optimization_report,
"timestamp": datetime.now(timezone.utc).isoformat()
}
except Exception as e:
logger.error(f"Error getting ensemble weights: {e}")
return {"error": str(e)}
@app.get("/api/strategies")
async def get_strategies():
"""Get all active strategies from strategy trainer"""
try:
sync_bus = global_state.get('sync_bus')
components = global_state.get('components')
if not sync_bus or not components:
return {"strategies": []}
strategies = []
# Get strategy grades from sync bus
strategy_grades = await sync_bus.get_state('strategy_grades') or {}
strategy_trainer = components.get('strategy_trainer')
# Assuming df is available in this scope for Mean Reversion and Cluster Momentum
# If df is not globally available, it needs to be fetched or passed appropriately.
# For now, using an empty DataFrame as a placeholder if df is not defined.
df = pd.DataFrame()
if 'df' in locals() or 'df' in globals():
pass # df is already defined
else:
logger.warning("DataFrame 'df' not found in scope for get_strategies. Using empty DataFrame.")
if strategy_trainer:
for strategy_name, grade in strategy_grades.items():
perf_data = strategy_trainer.performance_tracker.get(strategy_name, [])
pnl = sum(perf_data[-10:]) if perf_data else 0
win_count = len([p for p in perf_data[-10:] if p > 0]) if perf_data else 0
win_rate = (win_count / min(10, len(perf_data)) * 100) if perf_data else 0
strategies.append({
"name": strategy_name,
"status": "active" if grade in ['A', 'B'] else "paused",
"pnl": float(pnl),
"win_rate": float(win_rate),
"signals": len(perf_data),
"grade": grade
})
# Mean Reversion strategy
reversion_signals = df[df.get('reversion_candidate', False) == True] if 'reversion_candidate' in df else pd.DataFrame()
strategies.append({
"name": "Mean Reversion",
"status": "active" if len(reversion_signals) > 0 else "paused",
"pnl": float(reversion_signals['avg_return_7d'].sum() if not reversion_signals.empty and 'avg_return_7d' in reversion_signals else 0),
"win_rate": float(len(reversion_signals[reversion_signals.get('reversion_probability', 0) > 0.7]) / len(reversion_signals) * 100 if len(reversion_signals) > 0 else 0),
"signals": int(len(reversion_signals))
})
# Cluster Momentum strategy
cluster_signals = df[df.get('cluster_validated', False) == True] if 'cluster_validated' in df else pd.DataFrame()
strategies.append({
"name": "Cluster Momentum",
"status": "active" if len(cluster_signals) > 0 else "paused",
"pnl": float(cluster_signals['avg_return_7d'].sum() if not cluster_signals.empty and 'avg_return_7d' in cluster_signals else 0),
"win_rate": float(len(cluster_signals[cluster_signals['composite_score'] > 70]) / len(cluster_signals) * 100 if len(cluster_signals) > 0 else 0),
"signals": int(len(cluster_signals))
})
return {"strategies": strategies}
except Exception as e:
logger.error(f"Error getting strategies: {e}")
return {"strategies": []}
@app.get("/api/signals/active")
async def get_active_signals():
"""Get currently active trading signals from Oracle"""
try:
sync_bus = global_state.get('sync_bus')
if not sync_bus:
return {"signals": []}
# Get trading directives and scanner data
directives = await sync_bus.get_state('trading_directives') or []
scanner_data = await sync_bus.get_state('scanner_data') or []
signals = []
# Process directives first (highest priority)