-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapi_server.py
More file actions
2323 lines (1991 loc) · 103 KB
/
api_server.py
File metadata and controls
2323 lines (1991 loc) · 103 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, BackgroundTasks, Body, Query
from fastapi.middleware.cors import CORSMiddleware
from typing import Optional
from pydantic import BaseModel
from google import genai
from google.genai import types
import os
import pandas as pd
import asyncio
import threading
import time
from dotenv import load_dotenv
from core.weex_api import WeexClient
from core.db_manager import get_db_connection
# NEW: Production-ready components
from core.position_manager import initialize_position_manager, get_position_manager
from core.sentiment_live import get_sentiment_feed, get_real_time_sentiment
from core.safety_layer import ExecutionSafetyLayer
import logging
import sys
import io
from datetime import datetime
# Configure logging with file handler
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')),
logging.FileHandler(f'api_server_{datetime.now().strftime("%Y%m%d")}.log', encoding='utf-8')
]
)
logger = logging.getLogger(__name__)
# 1. Load Environment Variables
load_dotenv()
# 2. Validate Environment Variables
def validate_env():
"""Validates required environment variables on startup."""
required_vars = {
"DATABASE_URL": "PostgreSQL database connection string",
"GEMINI_API_KEY": "Google Gemini API key for AI decisions",
}
optional_vars = {
"WEEX_API_KEY": "WEEX exchange API key (required for live trading)",
"WEEX_SECRET": "WEEX exchange secret key (required for live trading)",
"WEEX_PASSPHRASE": "WEEX exchange passphrase (required for live trading)",
}
missing_required = []
missing_optional = []
for var, description in required_vars.items():
if not os.getenv(var):
missing_required.append(f"{var} - {description}")
for var, description in optional_vars.items():
if not os.getenv(var):
missing_optional.append(f"{var} - {description}")
if missing_required:
print("CRITICAL: Missing required environment variables:")
for var in missing_required:
print(f" - {var}")
print("\nWARNING: Application may not function correctly without these variables.")
print(" Please create a .env file with the required variables.\n")
if missing_optional:
print("WARNING: Missing optional environment variables:")
for var in missing_optional:
print(f" - {var}")
print("\nWARNING: Live trading will not work without WEEX credentials.\n")
if not missing_required and not missing_optional:
print("All environment variables validated successfully.\n")
return len(missing_required) == 0
# Validate on import
env_valid = validate_env()
# 2. Initialize App & Clients
app = FastAPI(title="Chartor Trading Engine API")
client = WeexClient()
# NEW: Initialize production components at module level
try:
position_manager = initialize_position_manager(client, logger)
safety_layer = ExecutionSafetyLayer(client, initial_equity=10000.0, logger=logger)
sentiment_feed = get_sentiment_feed()
logger.info("✅ Production components initialized successfully")
except Exception as init_error:
logger.warning(f"⚠️ Failed to initialize production components at module level: {init_error}")
# Set to None - will be initialized in startup_event
position_manager = None
safety_layer = None
sentiment_feed = None
trading_mode_lock = threading.Lock() # Prevents Sentinel + Institutional conflict
# Background task control
sentinel_running = False
sentinel_thread = None
# Track which mode is active
active_trading_mode = None # "SENTINEL" or "INSTITUTIONAL" or None
def sentinel_loop():
"""Background sentinel service that monitors markets and executes trades when auto-trading is enabled."""
global sentinel_running
from core.weex_api import WeexClient
from core.analysis import analyze_market_structure
from core.llm_brain import get_trading_decision
from core.db_manager import save_ai_analysis, log_market_state, get_db_connection
from core.ml_analyst import MLAnalyst
from core.sentiment import analyze_market_sentiment
client = WeexClient()
ml_analyst = MLAnalyst() # Initialize ML model once
while sentinel_running:
try:
# Get current settings
conn = get_db_connection()
if not conn:
time.sleep(30)
continue
cur = conn.cursor()
cur.execute("SELECT auto_trading, risk_tolerance, current_symbol FROM trade_settings LIMIT 1")
settings = cur.fetchone()
cur.close()
conn.close()
if not settings:
time.sleep(30)
continue
auto_trading = settings.get("auto_trading", False)
risk_tolerance = settings.get("risk_tolerance", 20)
symbol = settings.get("current_symbol", "cmt_btcusdt")
# Only run if auto-trading is enabled
if not auto_trading:
time.sleep(30)
continue
# Check if Gemini is available (don't spam if quota exceeded)
from core.llm_brain import quota_exceeded_until
from datetime import datetime
if quota_exceeded_until and datetime.now() < quota_exceeded_until:
# Quota exceeded, wait longer between checks
logger.warning(f"Sentinel paused: Gemini quota exceeded. Resuming in {int((quota_exceeded_until - datetime.now()).total_seconds()/60)} minutes")
time.sleep(300) # Check every 5 minutes instead of 30 seconds
continue
logger.info(f"\n{'='*60}")
logger.info(f"Sentinel: {symbol} | Auto-Trade: ON | Risk: {risk_tolerance}%")
logger.info(f"{'='*60}")
# Fetch market data (get more for ML training)
candles = client.fetch_candles(symbol=symbol, limit=500)
if candles and len(candles) > 100:
# STEP 1: Train Local ML Model (instant retraining on latest data)
ml_trained = ml_analyst.train_model(candles)
# STEP 2: Technical Analysis
market_state = analyze_market_structure(candles)
if not market_state:
time.sleep(30)
continue
logger.info(f" Technical: Price ${market_state.get('price', 0):.2f} | RSI {market_state.get('rsi', 50):.1f} | Trend {market_state.get('trend', 'Neutral')}")
# STEP 3: Get Local ML Prediction
ml_direction, ml_confidence = ml_analyst.predict_next_move(market_state)
ml_prediction = {"direction": ml_direction, "confidence": ml_confidence} if ml_trained else None
if ml_prediction:
logger.info(f" Local ML: Predicts {ml_direction} ({ml_confidence}% confidence)")
# STEP 4: Get Market Sentiment (REAL-TIME from CryptoPanic or FinBERT)
symbol_clean = symbol.replace("cmt_", "").replace("usdt", "").upper()
# Use real-time sentiment feed
global sentiment_feed
if sentiment_feed:
sentiment_result = sentiment_feed.get_market_sentiment(symbol_clean)
sent_label = sentiment_result["label"]
sent_score = sentiment_result["score"]
sentiment = {
"label": sent_label,
"score": sent_score,
"source": sentiment_result["source"],
"headline": sentiment_result.get("latest_headline", "")
}
logger.info(f" Sentiment ({sentiment_result['source']}): {sent_label} (score: {sent_score:.2f})")
logger.info(f" Headline: {sentiment_result.get('latest_headline', 'N/A')[:60]}...")
else:
# Fallback to legacy sentiment
from core.sentiment import analyze_market_sentiment
sent_label, sent_score = analyze_market_sentiment(symbol_clean)
sentiment = {"label": sent_label, "score": sent_score}
logger.info(f" FinBERT Sentiment: {sent_label} (score: {sent_score})")
# STEP 5: Evaluate Active Strategies
from core.strategy_evaluator import evaluate_strategies
triggered_strategies = evaluate_strategies(market_state)
strategy_decision = None
strategy_name = None
if triggered_strategies:
# Use the first triggered strategy (can be enhanced to handle multiple)
strategy_decision = triggered_strategies[0].get('action')
strategy_name = triggered_strategies[0].get('name')
logger.info(f" Strategy Triggered: {strategy_name} -> {strategy_decision}")
# STEP 6: Hybrid Decision - Send summary to Gemini (if no strategy triggered)
if not strategy_decision or strategy_decision == "WAIT":
logger.info(" Consulting Gemini for final approval...")
ai_result = get_trading_decision(
market_state,
symbol=symbol,
use_cache=False, # Disable cache for sentinel loop to get fresh results
ml_prediction=ml_prediction,
sentiment=sentiment
)
# ============================================================
# CRITICAL: Check Gemini status - abort on persistent errors
# ============================================================
ai_status = ai_result.get("status", "UNKNOWN")
ai_source = ai_result.get("source", "UNKNOWN")
if ai_status == "ERROR":
logger.error(f"Gemini API error - skipping cycle")
logger.error(f" Gemini API error - using fallback decision")
elif ai_status == "FALLBACK":
logger.warning(f"Using fallback decision engine (Gemini unavailable)")
logger.warning(f" Using Fallback Engine (Gemini unavailable)")
decision = ai_result.get("decision", "WAIT")
confidence = ai_result.get("confidence", 0)
reason = ai_result.get("reasoning", "No reason provided")
logger.info(f" {ai_source} Final Decision: {decision} ({confidence}% confidence)")
# Save analysis
save_ai_analysis(symbol, decision, confidence, reason, market_state)
log_market_state(decision, confidence, reason, market_state)
else:
# Use strategy decision
decision = strategy_decision
confidence = 85 # Strategy-based trades get high confidence
reason = f"Strategy '{strategy_name}' triggered: {triggered_strategies[0].get('logic')}"
# Save analysis with strategy info
save_ai_analysis(symbol, decision, confidence, reason, market_state)
log_market_state(decision, confidence, reason, market_state)
# Execute if conditions are met
if decision in ["BUY", "SELL"]:
confidence_threshold = 90 - risk_tolerance
if confidence >= confidence_threshold:
# Risk check
is_safe = True
if decision == "BUY" and market_state.get('rsi', 50) > 70:
logger.warning(" RISK BLOCK: RSI too high for Buy")
is_safe = False
if decision == "SELL" and market_state.get('rsi', 50) < 30:
logger.warning(" RISK BLOCK: RSI too low for Sell")
is_safe = False
if is_safe:
should_execute = True
ml_agrees = False
if strategy_name:
logger.info(f" STRATEGY TRADE: Executing based on user-defined strategy '{strategy_name}'")
else:
if ml_prediction:
ml_dir = ml_prediction.get('direction', 'UNKNOWN')
ml_agrees = (decision == "BUY" and ml_dir == "UP") or (decision == "SELL" and ml_dir == "DOWN")
if ml_prediction and not ml_agrees:
logger.warning(f" CONFLICT: Gemini says {decision}, but ML predicts {ml_prediction.get('direction')}. Being conservative - waiting.")
log_message = f"Confluence check failed: Gemini {decision} vs ML {ml_prediction.get('direction')}. Waiting for alignment."
should_execute = False
try:
conn = get_db_connection()
if conn:
cur = conn.cursor()
cur.execute("""
INSERT INTO market_log (trend, structure, price, rsi, decision, confidence, reason)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", (
str(market_state.get('trend', 'Neutral')),
'Confluence-Check',
float(market_state.get('price', 0)),
float(market_state.get('rsi', 50)),
f"WAIT-CONFLICT",
int(confidence),
log_message
))
conn.commit()
cur.close()
conn.close()
except Exception as log_err:
logger.error(f"Log error: {log_err}")
else:
if ml_agrees:
logger.info(f" CONFLUENCE DETECTED! ML and Gemini agree on {decision}")
if should_execute:
try:
balance_data = client.get_balance()
available_usdt = 0
if balance_data:
if isinstance(balance_data, list):
for asset in balance_data:
if asset.get('coinName') == 'USDT':
available_usdt = float(asset.get('available', 0))
break
elif isinstance(balance_data, dict):
if balance_data.get('coinName') == 'USDT':
available_usdt = float(balance_data.get('available', 0))
position_size_usdt = min(max(available_usdt * 0.03, 5), 30)
current_price = float(market_state.get('price', 0))
if current_price > 0:
contract_size = position_size_usdt / current_price
contract_size = max(round(contract_size, 4), 0.001)
size = str(contract_size)
else:
size = "0.001"
logger.info(f" Balance: {available_usdt:.2f} USDT | Position Size: {size} contracts (~{position_size_usdt:.2f} USDT)")
if available_usdt < 1:
logger.error(f" INSUFFICIENT BALANCE: Only {available_usdt:.2f} USDT available. Skipping trade.")
log_message = f"INSUFFICIENT BALANCE: {available_usdt:.2f} USDT available. Need at least 1 USDT."
try:
conn = get_db_connection()
if conn:
cur = conn.cursor()
cur.execute("""
INSERT INTO market_log (trend, structure, price, rsi, decision, confidence, reason)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", (
str(market_state.get('trend', 'Neutral')),
'Balance-Check',
float(market_state.get('price', 0)),
float(market_state.get('rsi', 50)),
"WAIT-INSUFFICIENT-BALANCE",
0,
log_message
))
conn.commit()
cur.close()
conn.close()
except:
pass
time.sleep(30)
continue
except Exception as balance_err:
logger.error(f"Balance check error: {balance_err}", exc_info=True)
logger.error(f" Balance check error: {balance_err}. Using default size.")
size = "0.01"
# ============================================================
# CRITICAL SAFETY INTEGRATION (Production Upgrade)
# ============================================================
# STEP 1: Calculate ATR-based Stop Loss & Take Profit
atr = market_state.get('volatility') or market_state.get('atr', current_price * 0.015)
if decision == "BUY":
stop_loss = current_price - (atr * 1.5) # 1.5R risk
take_profit = current_price + (atr * 2.0) # 2.0R reward (1.33:1 R:R)
direction = "LONG"
else: # SELL
stop_loss = current_price + (atr * 1.5)
take_profit = current_price - (atr * 2.0)
direction = "SHORT"
logger.info(f" SL/TP calculated: Entry ${current_price:.2f}, SL ${stop_loss:.2f}, TP ${take_profit:.2f}, ATR ${atr:.4f}")
# STEP 2: Check for duplicate positions (prevent stacking)
if position_manager:
existing_pos = position_manager.get_position(symbol)
if existing_pos:
logger.warning(f" ⚠️ Position already open for {symbol} - skipping to prevent duplicate")
logger.warning(f" Position already open for {symbol} - skipping trade")
time.sleep(30)
continue
# STEP 3: Validate trade through Safety Layer
if safety_layer:
try:
# Calculate margin required
leverage = 20 # Default leverage
position_value = float(size) * current_price
margin_required = position_value / leverage
# Get current positions for safety checks
current_positions = []
if position_manager:
current_positions = [
{
"symbol": p.symbol,
"margin_used": p.margin_used,
"direction": p.direction
}
for p in position_manager.get_all_positions()
]
# Run all 10 safety checks
can_execute, safety_results = safety_layer.validate_trade(
symbol=symbol,
direction=direction,
size=float(size),
entry_price=current_price,
stop_loss=stop_loss,
take_profit=take_profit,
leverage=leverage,
margin_required=margin_required,
current_positions=current_positions
)
if not can_execute:
logger.warning(f" 🚫 Trade REJECTED by Safety Layer")
failed_checks = [r.check_name for r in safety_results if not r.passed and r.severity == "CRITICAL"]
logger.error(f" Safety checks failed: {', '.join(failed_checks)}")
time.sleep(30)
continue
else:
logger.info(f" ✅ Trade APPROVED by Safety Layer")
except Exception as safety_err:
logger.error(f"Safety layer validation failed: {safety_err}", exc_info=True)
logger.error(f" Safety validation error - aborting trade for safety")
time.sleep(30)
continue
# STEP 4: Execute order on WEEX
logger.info(f" AUTO-EXECUTING {decision} ORDER...")
side = "buy" if decision == "BUY" else "sell"
order_res = client.place_order(side=side, size=size, symbol=symbol)
if order_res and (order_res.get("code") == "00000" or order_res.get("order_id")):
logger.info(f" Trade Executed Successfully!")
# Extract order_id from response (can be in data.orderId or directly as order_id)
if isinstance(order_res.get("data"), dict) and order_res.get("data", {}).get("orderId"):
order_id = str(order_res.get("data", {}).get("orderId"))
elif order_res.get("order_id"):
order_id = str(order_res.get("order_id"))
else:
order_id = "unknown"
# Upload AI log to WEEX for compliance
try:
# Use 'reason' variable which is defined in the scope
reasoning_text = reason if 'reason' in locals() else f"Strategy '{strategy_name}' triggered" if strategy_name else "Auto-trade decision"
ai_log_input = {
"market_data": {
"symbol": symbol,
"price": float(market_state.get('price', 0)),
"rsi": float(market_state.get('rsi', 50)),
"trend": str(market_state.get('trend', 'Neutral')),
"volume": market_state.get('volume', 0)
},
"ml_prediction": ml_prediction if ml_prediction else {},
"sentiment": sentiment if sentiment else {},
"prompt": f"Analyze {symbol} market data and provide trading decision"
}
ai_log_output = {
"decision": decision,
"confidence": confidence,
"reasoning": reasoning_text[:500] if reasoning_text else "",
"ml_agrees": ml_agrees,
"strategy": strategy_name or "Hybrid Auto-Trade"
}
explanation = f"AI analyzed {symbol} with RSI {market_state.get('rsi', 50):.1f}, trend {market_state.get('trend', 'Neutral')}. Decision: {decision} with {confidence}% confidence. ML model {('agreed' if ml_agrees else 'disagreed')}. Reasoning: {reasoning_text[:400] if reasoning_text else 'N/A'}"
client.upload_ai_log(
order_id=order_id,
stage="Decision Making",
model="Gemini-2.0-Flash-Thinking",
input_data=ai_log_input,
output_data=ai_log_output,
explanation=explanation
)
logger.info(f" AI Log uploaded for order {order_id}")
except Exception as ai_log_err:
logger.error(f" AI Log upload failed: {ai_log_err}")
import traceback
traceback.print_exc()
current_price = float(market_state.get('price', 0))
confluence_note = " [CONFLUENCE]" if ml_agrees else ""
log_message = f"AUTO-EXECUTED {decision} on {symbol}{confluence_note} | Confidence: {confidence}% | ML: {ml_prediction.get('direction') if ml_prediction else 'N/A'} | Sentiment: {sentiment.get('label')} | Order ID: {order_id}"
from core.db_manager import save_trade, update_or_create_position, get_trade_history
notes_parts = []
if strategy_name:
notes_parts.append(f"Strategy: {strategy_name}")
else:
notes_parts.append(f"Hybrid Auto-trade: {decision} at {confidence}%")
notes_parts.append(f"ML: {ml_prediction.get('direction') if ml_prediction else 'N/A'}")
notes_parts.append(f"Sentiment: {sentiment.get('label')}")
# Calculate position value in USDT for tracking
position_value_usdt = float(size) * current_price
save_trade({
"symbol": symbol,
"side": side,
"size": float(size),
"price": current_price,
"order_id": order_id,
"order_type": "market",
"status": "filled",
"notes": " | ".join(notes_parts) + f" | Position Value: ${position_value_usdt:.2f}"
})
# Check profitable trades count
try:
all_trades = get_trade_history(limit=1000)
profitable_trades = [t for t in all_trades if t.get('pnl') and float(t.get('pnl', 0)) > 0]
profitable_count = len(profitable_trades)
logger.info(f" Profitable Trades: {profitable_count}/15 required")
except Exception as profitable_err:
logger.error(f"Failed to count profitable trades: {profitable_err}", exc_info=True)
update_or_create_position({
"symbol": symbol,
"side": side,
"size": float(size),
"entry_price": current_price,
"current_price": current_price,
"unrealized_pnl": 0,
"leverage": leverage,
"order_id": order_id
})
# ============================================================
# CRITICAL: Register position with Position Manager
# ============================================================
if position_manager:
try:
success = position_manager.open_position(
symbol=symbol,
side=side,
direction=direction,
size=float(size),
entry_price=current_price,
stop_loss=stop_loss,
take_profit=take_profit,
leverage=leverage,
margin_used=margin_required,
atr=atr,
order_id=order_id,
source="SENTINEL",
metadata={
"ml_prediction": ml_prediction,
"sentiment": sentiment,
"confidence": confidence,
"strategy": strategy_name
}
)
if success:
logger.info(f" ✅ Position registered with Position Manager - automatic SL/TP monitoring active")
else:
logger.error(f" ❌ Failed to register position with Position Manager")
except Exception as pm_err:
logger.error(f"Position Manager registration failed: {pm_err}", exc_info=True)
else:
logger.warning(f" ⚠️ Position Manager not available - no automatic SL/TP monitoring")
else:
logger.error(f" Trade Failed: {order_res.get('msg', 'Unknown error')}")
log_message = f"AUTO-TRADE FAILED: {decision} on {symbol} | Error: {order_res.get('msg', 'Unknown')}"
# Log the trade attempt
try:
conn = get_db_connection()
if conn:
cur = conn.cursor()
cur.execute("""
INSERT INTO market_log (trend, structure, price, rsi, decision, confidence, reason)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", (
str(market_state.get('trend', 'Neutral')),
'Auto-Trade',
float(market_state.get('price', 0)),
float(market_state.get('rsi', 50)),
f"AUTO-{decision}",
int(confidence),
log_message
))
conn.commit()
cur.close()
conn.close()
except Exception as log_err:
logger.error(f"Log error: {log_err}")
else:
if confidence < confidence_threshold:
logger.info(f" Confidence {confidence}% below threshold {confidence_threshold}%")
else:
logger.info(" Market Indecisive - No Action")
except Exception as e:
logger.error(f"Sentinel Loop Error: {e}", exc_info=True)
time.sleep(30) # Wait 30 seconds before next scan
def start_sentinel():
"""Start the background sentinel service."""
global sentinel_running, sentinel_thread, active_trading_mode, position_manager
with trading_mode_lock:
# Check for conflicts
if active_trading_mode == "INSTITUTIONAL":
logger.error("❌ Cannot start Sentinel: Institutional trading is active")
raise Exception("Trading conflict: Institutional system is already running. Stop it first.")
if not sentinel_running:
sentinel_running = True
active_trading_mode = "SENTINEL"
# ============================================================
# CRITICAL: Start Position Manager monitoring
# ============================================================
if position_manager and not position_manager.monitor_running:
try:
position_manager.start_monitoring()
logger.info("✅ Position Manager monitoring started - automatic SL/TP active")
except Exception as pm_err:
logger.error(f"Failed to start Position Manager monitoring: {pm_err}", exc_info=True)
sentinel_thread = threading.Thread(target=sentinel_loop, daemon=True)
sentinel_thread.start()
logger.info("✅ Sentinel service started")
def stop_sentinel():
"""Stop the background sentinel service."""
global sentinel_running, active_trading_mode
with trading_mode_lock:
sentinel_running = False
if active_trading_mode == "SENTINEL":
active_trading_mode = None
logger.info("🛑 Sentinel service stopped")
# 3. CORS Configuration (CRITICAL for React Connection)
# This allows your frontend (localhost:8080 or 5173) to talk to this backend
app.add_middleware(
CORSMiddleware,
allow_origins=["https://chartor-market.vercel.app"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- Data Models (Pydantic) ---
class ChatRequest(BaseModel):
message: str
class AnalysisRequest(BaseModel):
symbol: str
# --- API ENDPOINTS ---
@app.get("/")
def health_check():
return {"status": "online", "system": "Chartor v2.4.1"}
@app.get("/api/ai-status")
def get_ai_status():
"""
Returns the status of the AI service (Gemini availability, quota status, etc.)
"""
from core.llm_brain import quota_exceeded_until, api_call_count, MAX_DAILY_CALLS
from datetime import datetime
status = {
"available": True,
"using_fallback": False,
"quota_exceeded": False,
"calls_remaining": max(0, MAX_DAILY_CALLS - api_call_count),
"cooldown_until": None
}
if quota_exceeded_until:
if datetime.now() < quota_exceeded_until:
status["available"] = False
status["using_fallback"] = True
status["quota_exceeded"] = True
status["cooldown_until"] = quota_exceeded_until.isoformat()
else:
# Cooldown expired
status["available"] = True
if api_call_count >= MAX_DAILY_CALLS:
status["available"] = False
status["using_fallback"] = True
status["quota_exceeded"] = True
return status
@app.get("/api/watchlist")
def get_watchlist():
"""
Fetches LIVE real-time prices + 24h data for the sidebar assets from WEEX.
"""
import requests
# Official Futures Symbols on Weex
symbols = [
"cmt_btcusdt", "cmt_ethusdt", "cmt_solusdt",
"cmt_dogeusdt", "cmt_xrpusdt", "cmt_bnbusdt",
"cmt_adausdt", "cmt_ltcusdt"
]
watchlist = []
try:
# Fetch from WEEX using candle data (most reliable)
for sym in symbols:
try:
# Get latest 24h candles from WEEX (96 candles for 15m interval = 24 hours)
raw = client.fetch_candles(sym, limit=96, interval="15m")
if raw and len(raw) > 0:
current_price = float(raw[-1][4]) # Latest close price
open_24h = float(raw[0][1]) # Open price 24h ago
change_pct = ((current_price - open_24h) / open_24h) * 100
# Calculate 24h high/low from all candles
high_24h = max(float(candle[2]) for candle in raw)
low_24h = min(float(candle[3]) for candle in raw)
volume_24h = sum(float(candle[5]) for candle in raw)
watchlist.append({
"symbol": sym.upper().replace("CMT_", "").replace("USDT", "/USDT"),
"raw_symbol": sym,
"price": current_price,
"change": round(change_pct, 2),
"volume24h": volume_24h,
"high24h": high_24h,
"low24h": low_24h
})
except Exception as sym_err:
print(f"Error fetching {sym}: {sym_err}")
# Fallback: use single candle
try:
raw = client.fetch_candles(sym, limit=1)
if raw and len(raw) > 0:
current_price = float(raw[-1][4])
open_price = float(raw[-1][1])
change_pct = ((current_price - open_price) / open_price) * 100
watchlist.append({
"symbol": sym.upper().replace("CMT_", "").replace("USDT", "/USDT"),
"raw_symbol": sym,
"price": current_price,
"change": round(change_pct, 2),
"volume24h": 0,
"high24h": 0,
"low24h": 0
})
except:
pass
return watchlist
except Exception as e:
print(f"Watchlist Error: {e}")
return []
@app.get("/api/candles")
def get_candles(symbol: str = "cmt_btcusdt", interval: str = "15m"):
"""
Fetches OHLC data for the TradingView Chart.
"""
try:
# Fetch 500 candles (15m timeframe default)
raw_data = client.fetch_candles(symbol=symbol, limit=500, interval=interval)
formatted_data = []
if raw_data:
# Sort Oldest -> Newest
raw_data.sort(key=lambda x: x[0])
for c in raw_data:
formatted_data.append({
"time": int(c[0] / 1000), # Unix Timestamp
"open": float(c[1]),
"high": float(c[2]),
"low": float(c[3]),
"close": float(c[4])
})
return formatted_data
except Exception as e:
print(f"Candle Error: {e}")
return []
@app.post("/api/chat")
def chat_with_chartor(request: ChatRequest):
"""
Enhanced chat with Chartor AI - includes real-time market data context.
"""
try:
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
return {"response": "Error: GEMINI_API_KEY not found in .env"}
model_name = os.getenv("GEMINI_CHAT_MODEL", "gemini-flash-latest")
client = genai.Client(api_key=api_key)
# Extract symbol from user message if mentioned, otherwise use default
user_message = request.message.lower()
symbol_to_analyze = "cmt_btcusdt" # Default
# Try to detect symbol in message
symbol_map = {
"btc": "cmt_btcusdt", "bitcoin": "cmt_btcusdt",
"eth": "cmt_ethusdt", "ethereum": "cmt_ethusdt",
"sol": "cmt_solusdt", "solana": "cmt_solusdt",
"doge": "cmt_dogeusdt", "dogecoin": "cmt_dogeusdt",
"xrp": "cmt_xrpusdt", "ripple": "cmt_xrpusdt",
"bnb": "cmt_bnbusdt", "binance": "cmt_bnbusdt",
"ada": "cmt_adausdt", "cardano": "cmt_adausdt",
"ltc": "cmt_ltcusdt", "litecoin": "cmt_ltcusdt"
}
for key, val in symbol_map.items():
if key in user_message:
symbol_to_analyze = val
break
# Fetch real-time market data
from core.weex_api import WeexClient
from core.analysis import analyze_market_structure
from core.ml_analyst import MLAnalyst
from core.sentiment import analyze_market_sentiment
market_context = ""
try:
weex_client = WeexClient()
candles = weex_client.fetch_candles(symbol=symbol_to_analyze, limit=500)
if candles and len(candles) >= 100:
# Technical Analysis
market_state = analyze_market_structure(candles)
# ML Prediction
ml_analyst = MLAnalyst()
ml_trained = ml_analyst.train_model(candles)
ml_direction, ml_confidence = ml_analyst.predict_next_move(market_state) if ml_trained else ("UNKNOWN", 0)
# Sentiment
symbol_clean = symbol_to_analyze.replace("cmt_", "").replace("usdt", "").upper()
sent_label, sent_score = analyze_market_sentiment(symbol_clean)
# Build comprehensive market context
price = market_state.get('price', 0)
trend = market_state.get('trend', 'Neutral')
rsi = market_state.get('rsi', 50)
ema_20 = market_state.get('ema_20', price)
volatility = market_state.get('volatility', 0)
volume_spike = market_state.get('volume_spike', False)
market_context = f"""
CURRENT MARKET DATA ({symbol_clean}):
- Current Price: ${price:,.2f}
- Trend: {trend}
- RSI (14): {rsi:.1f}
- EMA 20: ${ema_20:,.2f}
- Volatility (ATR): ${volatility:,.2f}
- Volume Spike: {volume_spike}
- ML Prediction: {ml_direction} ({ml_confidence}% confidence)
- Market Sentiment: {sent_label} (score: {sent_score:.2f})
- Price vs EMA: {"Above" if price > ema_20 else "Below"} EMA (${abs(price - ema_20):,.2f} difference)
"""
except Exception as e:
print(f"Error fetching market data for chat: {e}")
market_context = "\nNote: Real-time market data unavailable. Providing general analysis.\n"
# Enhanced system prompt
system_prompt = """You are Chartor, an elite institutional crypto trading AI with deep expertise in:
- Al Brooks Price Action methodology
- Technical analysis (RSI, EMA, ATR, Volume Profile)
- Machine Learning price predictions
- Market sentiment analysis
- Risk management and position sizing
YOUR COMMUNICATION STYLE:
- Be precise, technical, and data-driven
- Use specific numbers, percentages, and price levels
- Reference actual market conditions when provided
- Explain your reasoning clearly
- Highlight key support/resistance levels
- Mention risk factors and trade setups
- Use professional trading terminology
- Format important data points clearly
When market data is provided, ALWAYS reference the actual numbers (price, RSI, etc.) in your response.
Be specific about entry/exit levels, stop losses, and take profit targets when discussing trades.
If the user asks about a specific asset, use the provided market data to give accurate, real-time analysis.
Keep responses concise but comprehensive - aim for 3-5 sentences for simple questions, up to 2 paragraphs for complex analysis."""
full_prompt = f"""{system_prompt}
{market_context}
USER QUESTION: {request.message}
Provide a detailed, accurate response using the market data above. If specific numbers are provided, use them in your answer."""
response = client.models.generate_content(model=model_name, contents=full_prompt)
return {"response": response.text}
except Exception as e:
import traceback
traceback.print_exc()
return {"response": f"AI Error: {str(e)}"}
@app.post("/api/trigger-analysis")
def trigger_analysis(
request: Optional[AnalysisRequest] = Body(None),
symbol: Optional[str] = Query(None)
):
"""
Triggers on-demand AI analysis for a specific symbol.
Accepts symbol from request body (JSON) or query parameter.
"""
try:
from core.weex_api import WeexClient
from core.analysis import analyze_market_structure
from core.llm_brain import get_trading_decision
from core.db_manager import save_ai_analysis, log_market_state
# Get symbol from request body or query param
if request and hasattr(request, 'symbol') and request.symbol:
symbol = request.symbol
elif not symbol:
# Try to get from current settings
conn = get_db_connection()
if conn:
cur = conn.cursor()
cur.execute("SELECT current_symbol FROM trade_settings LIMIT 1")
settings = cur.fetchone()
cur.close()
conn.close()
symbol = settings["current_symbol"] if settings else "cmt_btcusdt"
else:
symbol = "cmt_btcusdt"
if not symbol:
return {"status": "error", "msg": "Symbol is required"}
print(f"Triggering hybrid ML analysis for {symbol}...")
# Fetch market data (get more for ML training)
client = WeexClient()
candles = client.fetch_candles(symbol=symbol, limit=500)
if not candles or len(candles) < 100:
return {"status": "error", "msg": "Not enough market data for ML analysis"}
# STEP 1: Train Local ML Model
from core.ml_analyst import MLAnalyst
from core.sentiment import analyze_market_sentiment
ml_analyst = MLAnalyst()
ml_trained = ml_analyst.train_model(candles)
# STEP 2: Technical Analysis
market_state = analyze_market_structure(candles)
if not market_state:
return {"status": "error", "msg": "Analysis failed"}
# STEP 3: Get Local ML Prediction
ml_direction, ml_confidence = ml_analyst.predict_next_move(market_state)
ml_prediction = {"direction": ml_direction, "confidence": ml_confidence} if ml_trained else None
# STEP 4: Get Market Sentiment
symbol_clean = symbol.replace("cmt_", "").replace("usdt", "").upper()
sent_label, sent_score = analyze_market_sentiment(symbol_clean)
sentiment = {"label": sent_label, "score": sent_score}
# STEP 5: Hybrid Decision - Get AI decision with all inputs
ai_result = get_trading_decision(
market_state,