PROSTLE commited on
Commit
8d2bab5
·
unverified ·
1 Parent(s): dd941f9

Update trader.py

Browse files
Files changed (1) hide show
  1. trader.py +251 -113
trader.py CHANGED
@@ -5,11 +5,11 @@ from datetime import datetime
5
  from threading import Lock
6
 
7
  INITIAL_BALANCE = 1_000_000.00
8
- STOP_LOSS_PCT = -3.0
9
- TAKE_PROFIT_PCT = 5.0
10
- TRAILING_STOP_PCT = -2.0
11
- MAX_HOLD_DAYS = 5
12
- POSITION_SIZE_PCT = 10.0
13
 
14
  DATA_FILE = "portfolio.json"
15
  _lock = Lock()
@@ -21,7 +21,7 @@ def _default_state():
21
  "initial_balance": INITIAL_BALANCE,
22
  "positions": {},
23
  "trade_history": [],
24
- "bot_active": False,
25
  "created_at": datetime.now().isoformat(),
26
  }
27
 
@@ -59,40 +59,150 @@ def toggle_bot() -> dict:
59
  return {"bot_active": state["bot_active"]}
60
 
61
 
62
- def execute_buy(ticker: str, current_price: float, predicted_prices: list,
63
- confidence: float) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  with _lock:
65
  state = _load_state()
66
 
67
  if ticker in state["positions"]:
68
  return {"status": "skipped", "reason": f"Already holding {ticker}"}
69
 
70
- position_value = state["balance"] * (POSITION_SIZE_PCT / 100)
71
- if position_value < current_price:
72
- return {"status": "skipped", "reason": "Insufficient balance"}
 
 
 
 
 
 
 
 
73
 
74
- shares = int(position_value // current_price)
75
  if shares == 0:
76
- return {"status": "skipped", "reason": "Cannot afford even 1 share"}
77
 
78
  cost = shares * current_price
 
 
 
 
 
79
 
80
- stop_loss = round(current_price * (1 + STOP_LOSS_PCT / 100), 2)
81
- take_profit = round(current_price * (1 + TAKE_PROFIT_PCT / 100), 2)
82
 
83
  position = {
84
  "ticker": ticker,
85
  "shares": shares,
86
  "buy_price": current_price,
87
  "cost": round(cost, 2),
88
- "stop_loss": stop_loss,
89
- "take_profit": take_profit,
90
- "trailing_stop": stop_loss,
 
91
  "peak_price": current_price,
92
  "predicted_prices": predicted_prices,
93
  "confidence": confidence,
 
94
  "buy_time": datetime.now().isoformat(),
95
- "day_count": 0,
96
  }
97
 
98
  state["balance"] -= cost
@@ -106,8 +216,10 @@ def execute_buy(ticker: str, current_price: float, predicted_prices: list,
106
  "shares": shares,
107
  "price": current_price,
108
  "cost": round(cost, 2),
109
- "stop_loss": stop_loss,
110
- "take_profit": take_profit,
 
 
111
  "balance": state["balance"],
112
  }
113
 
@@ -168,34 +280,47 @@ def check_position(ticker: str, current_price: float) -> dict:
168
  buy_price = pos["buy_price"]
169
  change_pct = ((current_price - buy_price) / buy_price) * 100
170
 
171
- if current_price <= pos["stop_loss"]:
172
- return {"action": "sell", "reason": f"Stop-loss triggered ({STOP_LOSS_PCT}%)"}
 
 
 
 
 
173
 
174
- if current_price >= pos["take_profit"]:
175
- return {"action": "sell", "reason": f"Take-profit reached (+{TAKE_PROFIT_PCT}%)"}
 
 
176
 
 
177
  if current_price > pos["peak_price"]:
178
  with _lock:
179
  state = _load_state()
180
- state["positions"][ticker]["peak_price"] = current_price
181
- new_trailing = round(current_price * (1 + TRAILING_STOP_PCT / 100), 2)
182
- if new_trailing > state["positions"][ticker]["trailing_stop"]:
183
- state["positions"][ticker]["trailing_stop"] = new_trailing
184
- _save_state(state)
 
 
 
185
  elif current_price <= pos["trailing_stop"]:
186
- return {"action": "sell", "reason": f"Trailing stop triggered ({TRAILING_STOP_PCT}%)"}
 
187
 
188
- pos["day_count"] += 1
189
- if pos["day_count"] >= MAX_HOLD_DAYS:
190
- return {"action": "sell", "reason": f"Max hold period ({MAX_HOLD_DAYS} days)"}
 
191
 
192
  return {
193
  "action": "hold",
194
  "reason": "Within thresholds",
195
  "current_pnl": round(change_pct, 2),
196
  "current_price": current_price,
197
- "stop_loss": pos["stop_loss"],
198
- "take_profit": pos["take_profit"],
199
  "trailing_stop": pos["trailing_stop"],
200
  }
201
 
@@ -254,6 +379,7 @@ def compute_composite_score(
254
  confidence: float,
255
  indicators: dict | None = None,
256
  sentiment_score: float | None = None,
 
257
  ) -> dict:
258
  pred_day5 = predicted_prices[-1]
259
  pred_change_pct = ((pred_day5 - current_price) / current_price) * 100
@@ -265,10 +391,9 @@ def compute_composite_score(
265
  lstm_score += (confidence - 50) * 0.3
266
  lstm_score = max(0, min(100, lstm_score))
267
 
268
- if indicators:
269
- tech_score = compute_technical_score(indicators)
270
- else:
271
- tech_score = 50.0
272
 
273
  if sentiment_score is not None:
274
  sent_score = 50 + sentiment_score * 50
@@ -276,89 +401,92 @@ def compute_composite_score(
276
  else:
277
  sent_score = 50.0
278
 
279
- LSTM_W, TECH_W, SENT_W = 0.40, 0.35, 0.25
280
- composite = (lstm_score * LSTM_W) + (tech_score * TECH_W) + (sent_score * SENT_W)
 
281
  composite = round(max(0, min(100, composite)), 1)
282
 
283
  return {
284
  "composite_score": composite,
285
  "lstm_score": round(lstm_score, 1),
286
- "tech_score": round(tech_score, 1),
287
  "sent_score": round(sent_score, 1),
288
  "pred_change_pct": round(pred_change_pct, 2),
289
  "days_above": days_above,
290
  }
291
 
292
 
293
- def detect_market_regime(indicators: dict | None) -> dict:
294
- if not indicators:
295
- return {
296
- "regime": "NEUTRAL",
297
- "buy_threshold": 52,
298
- "sell_threshold": 35,
299
- "position_pct": 10,
300
- "min_confidence": 20,
301
- }
302
-
303
- rsi = indicators.get("RSI", 50)
304
- macd = indicators.get("MACD", 0)
305
- macd_signal = indicators.get("MACD_Signal", 0)
306
- sma_20 = indicators.get("SMA_20", 0)
307
- sma_50 = indicators.get("SMA_50", 0)
308
- price = indicators.get("price", 0)
309
-
310
  bull_signals = 0
311
  bear_signals = 0
312
-
313
- if rsi < 40:
314
- bull_signals += 1
315
- elif rsi > 65:
316
- bear_signals += 1
317
-
318
- if macd > macd_signal:
319
- bull_signals += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  else:
321
- bear_signals += 1
322
-
323
- if sma_20 > 0 and price > sma_20:
324
- bull_signals += 1
325
- elif sma_20 > 0:
326
- bear_signals += 1
327
-
328
- if sma_50 > 0 and price > sma_50:
329
- bull_signals += 1
330
- elif sma_50 > 0:
331
- bear_signals += 1
332
 
333
- if sma_20 > sma_50 > 0:
334
- bull_signals += 1
335
- elif sma_50 > sma_20 > 0:
336
- bear_signals += 1
337
-
338
- if bull_signals >= 4:
339
- return {
340
- "regime": "BULL",
341
- "buy_threshold": 45,
342
- "sell_threshold": 30,
343
- "position_pct": 15,
344
- "min_confidence": 15,
345
- }
346
- elif bear_signals >= 4:
347
- return {
348
- "regime": "BEAR",
349
- "buy_threshold": 60,
350
- "sell_threshold": 40,
351
- "position_pct": 5,
352
- "min_confidence": 30,
353
- }
354
- else:
355
- return {
356
- "regime": "NEUTRAL",
357
- "buy_threshold": 52,
358
- "sell_threshold": 35,
359
- "position_pct": 10,
360
- "min_confidence": 20,
361
- }
362
 
363
 
364
  def evaluate_trade_signal(
@@ -369,11 +497,20 @@ def evaluate_trade_signal(
369
  indicators: dict | None = None,
370
  sentiment_score: float | None = None,
371
  ) -> dict:
 
372
  state = _load_state()
373
 
374
- regime = detect_market_regime(indicators)
375
- buy_threshold = regime["buy_threshold"]
376
- sell_threshold = regime["sell_threshold"]
 
 
 
 
 
 
 
 
377
 
378
  scores = compute_composite_score(
379
  predicted_prices, current_price, confidence,
@@ -414,7 +551,7 @@ def evaluate_trade_signal(
414
  signal["action"] = "HOLD"
415
  signal["position"] = check
416
  else:
417
- if composite >= buy_threshold and confidence >= regime["min_confidence"]:
418
  result = execute_buy(ticker, current_price, predicted_prices, confidence)
419
  signal["action"] = "BUY"
420
  signal["trade_result"] = result
@@ -427,7 +564,8 @@ def evaluate_trade_signal(
427
  signal["action"] = "WAIT"
428
  signal["reason"] = (
429
  f"Score {composite}/100 ({regime['regime']} mode, "
430
- f"need ≥{buy_threshold})"
431
  )
432
 
433
  return signal
 
 
5
  from threading import Lock
6
 
7
  INITIAL_BALANCE = 1_000_000.00
8
+ MAX_HOLD_BARS = 60 # ~60 min max hold for intraday
9
+ DEFAULT_POSITION_PCT = 10.0 # fallback if dynamic sizing unavailable
10
+ RISK_PER_TRADE_MIN = 0.008 # 0.8% of capital
11
+ RISK_PER_TRADE_MAX = 0.015 # 1.5% of capital
12
+ RISK_PER_TRADE_DEFAULT = 0.01 # 1.0% default
13
 
14
  DATA_FILE = "portfolio.json"
15
  _lock = Lock()
 
21
  "initial_balance": INITIAL_BALANCE,
22
  "positions": {},
23
  "trade_history": [],
24
+ "bot_active": True, # Bot starts as ACTIVE by default
25
  "created_at": datetime.now().isoformat(),
26
  }
27
 
 
59
  return {"bot_active": state["bot_active"]}
60
 
61
 
62
+ def compute_dynamic_levels(
63
+ current_price: float,
64
+ atr: float,
65
+ regime: str = "SIDEWAYS",
66
+ is_ipo: bool = False,
67
+ ) -> dict:
68
+ """
69
+ Compute ATR-based dynamic SL / TP1 / TP2 levels.
70
+ Regime and IPO flag modulate width.
71
+ """
72
+ if atr <= 0:
73
+ atr = current_price * 0.005 # fallback: 0.5% of price
74
+
75
+ # Base multipliers (in ATR units)
76
+ sl_mult = 1.5
77
+ tp1_mult = 2.5
78
+ tp2_mult = 3.5
79
+
80
+ # Regime modifiers
81
+ regime_mod = {
82
+ "BULL_LOW_VOL": {"sl": 0.9, "tp": 1.2},
83
+ "BULL_HIGH_VOL": {"sl": 1.1, "tp": 1.0},
84
+ "BEAR_HIGH_VOL": {"sl": 1.3, "tp": 0.7},
85
+ "SIDEWAYS": {"sl": 1.0, "tp": 0.8},
86
+ }.get(regime, {"sl": 1.0, "tp": 1.0})
87
+
88
+ sl_mult *= regime_mod["sl"]
89
+ tp1_mult *= regime_mod["tp"]
90
+ tp2_mult *= regime_mod["tp"]
91
+
92
+ # IPO boost: more upside room, tighter stop
93
+ if is_ipo:
94
+ tp1_mult *= 1.5
95
+ tp2_mult *= 1.8
96
+ sl_mult *= 0.8
97
+
98
+ sl_distance = atr * sl_mult
99
+ tp1_distance = atr * tp1_mult
100
+ tp2_distance = atr * tp2_mult
101
+
102
+ sl_price = round(current_price - sl_distance, 2)
103
+ tp1_price = round(current_price + tp1_distance, 2)
104
+ tp2_price = round(current_price + tp2_distance, 2)
105
+
106
+ sl_pct = round(((sl_price - current_price) / current_price) * 100, 2)
107
+ tp1_pct = round(((tp1_price - current_price) / current_price) * 100, 2)
108
+ tp2_pct = round(((tp2_price - current_price) / current_price) * 100, 2)
109
+
110
+ # Clamp target pct to [0.5%, 5.0%]
111
+ tp1_pct = max(0.5, min(5.0, tp1_pct))
112
+ tp2_pct = max(tp1_pct + 0.3, min(5.0, tp2_pct))
113
+ tp1_price = round(current_price * (1 + tp1_pct / 100), 2)
114
+ tp2_price = round(current_price * (1 + tp2_pct / 100), 2)
115
+
116
+ # Include TP2 only in bullish regimes or IPO stocks
117
+ include_tp2 = is_ipo or regime in ("BULL_LOW_VOL", "BULL_HIGH_VOL")
118
+
119
+ return {
120
+ "sl_price": sl_price, "sl_pct": sl_pct,
121
+ "tp1_price": tp1_price, "tp1_pct": tp1_pct,
122
+ "tp2_price": tp2_price, "tp2_pct": tp2_pct,
123
+ "include_tp2": include_tp2,
124
+ "atr_used": round(atr, 4),
125
+ }
126
+
127
+
128
+ def risk_check_position_size(
129
+ balance: float,
130
+ current_price: float,
131
+ sl_price: float,
132
+ risk_pct: float = RISK_PER_TRADE_DEFAULT,
133
+ ) -> int:
134
+ """
135
+ Compute position size so that the max loss (entry→SL) ≤ risk_pct of capital.
136
+ Returns number of shares.
137
+ """
138
+ risk_pct = max(RISK_PER_TRADE_MIN, min(RISK_PER_TRADE_MAX, risk_pct))
139
+ risk_amount = balance * risk_pct
140
+ per_share_risk = abs(current_price - sl_price)
141
+ if per_share_risk <= 0:
142
+ per_share_risk = current_price * 0.01 # fallback 1%
143
+ shares = int(risk_amount // per_share_risk)
144
+ # Also cap at DEFAULT_POSITION_PCT of balance
145
+ max_by_balance = int((balance * DEFAULT_POSITION_PCT / 100) // current_price)
146
+ shares = min(shares, max_by_balance)
147
+ return max(shares, 0)
148
+
149
+
150
+ def execute_buy(
151
+ ticker: str,
152
+ current_price: float,
153
+ predicted_prices: list,
154
+ confidence: float,
155
+ sl_price: float | None = None,
156
+ tp1_price: float | None = None,
157
+ tp2_price: float | None = None,
158
+ regime: str = "SIDEWAYS",
159
+ ) -> dict:
160
  with _lock:
161
  state = _load_state()
162
 
163
  if ticker in state["positions"]:
164
  return {"status": "skipped", "reason": f"Already holding {ticker}"}
165
 
166
+ # Dynamic position sizing based on risk
167
+ if sl_price and sl_price < current_price:
168
+ shares = risk_check_position_size(state["balance"], current_price, sl_price)
169
+ else:
170
+ position_value = state["balance"] * (DEFAULT_POSITION_PCT / 100)
171
+ shares = int(position_value // current_price)
172
+ # Fallback SL/TP if not provided
173
+ if sl_price is None:
174
+ sl_price = round(current_price * 0.985, 2)
175
+ if tp1_price is None:
176
+ tp1_price = round(current_price * 1.02, 2)
177
 
 
178
  if shares == 0:
179
+ return {"status": "skipped", "reason": "Position too small after risk check"}
180
 
181
  cost = shares * current_price
182
+ if cost > state["balance"]:
183
+ shares = int(state["balance"] // current_price)
184
+ if shares == 0:
185
+ return {"status": "skipped", "reason": "Insufficient balance"}
186
+ cost = shares * current_price
187
 
188
+ # Trailing stop starts at the hard SL
189
+ trailing_stop = sl_price
190
 
191
  position = {
192
  "ticker": ticker,
193
  "shares": shares,
194
  "buy_price": current_price,
195
  "cost": round(cost, 2),
196
+ "stop_loss": sl_price,
197
+ "tp1": tp1_price,
198
+ "tp2": tp2_price,
199
+ "trailing_stop": trailing_stop,
200
  "peak_price": current_price,
201
  "predicted_prices": predicted_prices,
202
  "confidence": confidence,
203
+ "regime": regime,
204
  "buy_time": datetime.now().isoformat(),
205
+ "bar_count": 0,
206
  }
207
 
208
  state["balance"] -= cost
 
216
  "shares": shares,
217
  "price": current_price,
218
  "cost": round(cost, 2),
219
+ "stop_loss": sl_price,
220
+ "tp1": tp1_price,
221
+ "tp2": tp2_price,
222
+ "regime": regime,
223
  "balance": state["balance"],
224
  }
225
 
 
280
  buy_price = pos["buy_price"]
281
  change_pct = ((current_price - buy_price) / buy_price) * 100
282
 
283
+ sl = pos["stop_loss"]
284
+ tp1 = pos.get("tp1") or pos.get("take_profit", buy_price * 1.02)
285
+
286
+ # Hard stop-loss
287
+ if current_price <= sl:
288
+ sl_pct = round(((sl - buy_price) / buy_price) * 100, 2)
289
+ return {"action": "sell", "reason": f"Stop-loss triggered ({sl_pct}%)"}
290
 
291
+ # Take-profit 1 hit
292
+ if current_price >= tp1:
293
+ tp_pct = round(((tp1 - buy_price) / buy_price) * 100, 2)
294
+ return {"action": "sell", "reason": f"Target 1 reached (+{tp_pct}%)"}
295
 
296
+ # Trailing stop: move up as price makes new highs
297
  if current_price > pos["peak_price"]:
298
  with _lock:
299
  state = _load_state()
300
+ if ticker in state["positions"]:
301
+ state["positions"][ticker]["peak_price"] = current_price
302
+ # Trailing stop = 50% of the distance from entry to SL
303
+ trail_dist = abs(buy_price - sl) * 0.5
304
+ new_trailing = round(current_price - trail_dist, 2)
305
+ if new_trailing > state["positions"][ticker]["trailing_stop"]:
306
+ state["positions"][ticker]["trailing_stop"] = new_trailing
307
+ _save_state(state)
308
  elif current_price <= pos["trailing_stop"]:
309
+ trail_pct = round(((pos["trailing_stop"] - buy_price) / buy_price) * 100, 2)
310
+ return {"action": "sell", "reason": f"Trailing stop triggered ({trail_pct}%)"}
311
 
312
+ # Max hold bars (intraday)
313
+ pos["bar_count"] = pos.get("bar_count", pos.get("day_count", 0)) + 1
314
+ if pos["bar_count"] >= MAX_HOLD_BARS:
315
+ return {"action": "sell", "reason": f"Max hold period ({MAX_HOLD_BARS} bars)"}
316
 
317
  return {
318
  "action": "hold",
319
  "reason": "Within thresholds",
320
  "current_pnl": round(change_pct, 2),
321
  "current_price": current_price,
322
+ "stop_loss": sl,
323
+ "tp1": tp1,
324
  "trailing_stop": pos["trailing_stop"],
325
  }
326
 
 
379
  confidence: float,
380
  indicators: dict | None = None,
381
  sentiment_score: float | None = None,
382
+ xgb_score: float | None = None,
383
  ) -> dict:
384
  pred_day5 = predicted_prices[-1]
385
  pred_change_pct = ((pred_day5 - current_price) / current_price) * 100
 
391
  lstm_score += (confidence - 50) * 0.3
392
  lstm_score = max(0, min(100, lstm_score))
393
 
394
+ # XGBoost score: if not provided, fallback to 50
395
+ if xgb_score is None:
396
+ xgb_score = 50.0
 
397
 
398
  if sentiment_score is not None:
399
  sent_score = 50 + sentiment_score * 50
 
401
  else:
402
  sent_score = 50.0
403
 
404
+ # Blend: 45% LSTM, 45% XGBoost, 10% news
405
+ LSTM_W, XGB_W, SENT_W = 0.45, 0.45, 0.10
406
+ composite = (lstm_score * LSTM_W) + (xgb_score * XGB_W) + (sent_score * SENT_W)
407
  composite = round(max(0, min(100, composite)), 1)
408
 
409
  return {
410
  "composite_score": composite,
411
  "lstm_score": round(lstm_score, 1),
412
+ "xgb_score": round(xgb_score, 1),
413
  "sent_score": round(sent_score, 1),
414
  "pred_change_pct": round(pred_change_pct, 2),
415
  "days_above": days_above,
416
  }
417
 
418
 
419
+ def detect_market_regime(
420
+ indicators: dict | None = None,
421
+ vix: dict | None = None,
422
+ nifty: dict | None = None,
423
+ ) -> dict:
424
+ """
425
+ 4-state regime detection using VIX, Nifty trend, and stock-level signals.
426
+ States: BULL_LOW_VOL, BULL_HIGH_VOL, BEAR_HIGH_VOL, SIDEWAYS
427
+ """
428
+ vix_level = (vix or {}).get("vix_level", 15.0)
429
+ nifty_trend = (nifty or {}).get("trend", "flat")
430
+ nifty_bullish = nifty_trend == "bullish"
431
+ nifty_bearish = nifty_trend == "bearish"
432
+
433
+ # Stock-level signals
 
 
434
  bull_signals = 0
435
  bear_signals = 0
436
+ if indicators:
437
+ rsi = indicators.get("RSI", 50)
438
+ price = indicators.get("price", 0)
439
+ ema9 = indicators.get("EMA_9", indicators.get("SMA_20", 0))
440
+ ema21 = indicators.get("EMA_21", indicators.get("SMA_50", 0))
441
+ supertrend_dir = indicators.get("Supertrend_Dir", indicators.get("supertrend_dir", 0))
442
+
443
+ if rsi < 40: bull_signals += 1
444
+ elif rsi > 65: bear_signals += 1
445
+
446
+ if ema9 > 0 and price > ema9: bull_signals += 1
447
+ elif ema9 > 0: bear_signals += 1
448
+
449
+ if ema21 > 0 and price > ema21: bull_signals += 1
450
+ elif ema21 > 0: bear_signals += 1
451
+
452
+ if supertrend_dir == 1: bull_signals += 1
453
+ elif supertrend_dir == -1: bear_signals += 1
454
+
455
+ macd = indicators.get("MACD", 0)
456
+ macd_signal = indicators.get("MACD_Signal", 0)
457
+ if macd > macd_signal: bull_signals += 1
458
+ else: bear_signals += 1
459
+
460
+ # Combine VIX + Nifty + stock signals into 4-state regime
461
+ high_vol = vix_level >= 18
462
+ very_high_vol = vix_level >= 22
463
+
464
+ if nifty_bearish and (very_high_vol or bear_signals >= 3):
465
+ regime = "BEAR_HIGH_VOL"
466
+ entry_threshold = 0.1 # DEMO: much easier entry
467
+ min_confidence = 5
468
+ elif nifty_bullish and not high_vol and bull_signals >= 2:
469
+ regime = "BULL_LOW_VOL"
470
+ entry_threshold = 0.05 # DEMO: very easy entry
471
+ min_confidence = 2
472
+ elif nifty_bullish and high_vol:
473
+ regime = "BULL_HIGH_VOL"
474
+ entry_threshold = 0.1
475
+ min_confidence = 5
476
  else:
477
+ regime = "SIDEWAYS"
478
+ entry_threshold = 0.15
479
+ min_confidence = 5
 
 
 
 
 
 
 
 
480
 
481
+ return {
482
+ "regime": regime,
483
+ "entry_threshold": entry_threshold,
484
+ "min_confidence": min_confidence,
485
+ "vix_level": vix_level,
486
+ "nifty_trend": nifty_trend,
487
+ "bull_signals": bull_signals,
488
+ "bear_signals": bear_signals,
489
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
 
491
 
492
  def evaluate_trade_signal(
 
497
  indicators: dict | None = None,
498
  sentiment_score: float | None = None,
499
  ) -> dict:
500
+ """Legacy trade signal evaluation (used by manual /trade/execute endpoint)."""
501
  state = _load_state()
502
 
503
+ regime = detect_market_regime(indicators=indicators)
504
+ # Backwards-compatible thresholds derived from new regime
505
+ regime_thresholds = {
506
+ "BULL_LOW_VOL": {"buy": 5, "sell": 30}, # DEMO: much lower buy threshold
507
+ "BULL_HIGH_VOL": {"buy": 8, "sell": 35},
508
+ "BEAR_HIGH_VOL": {"buy": 10, "sell": 40},
509
+ "SIDEWAYS": {"buy": 7, "sell": 35},
510
+ }
511
+ thresholds = regime_thresholds.get(regime["regime"], {"buy": 7, "sell": 35})
512
+ buy_threshold = thresholds["buy"]
513
+ sell_threshold = thresholds["sell"]
514
 
515
  scores = compute_composite_score(
516
  predicted_prices, current_price, confidence,
 
551
  signal["action"] = "HOLD"
552
  signal["position"] = check
553
  else:
554
+ if composite >= buy_threshold and confidence >= regime.get("min_confidence", 20):
555
  result = execute_buy(ticker, current_price, predicted_prices, confidence)
556
  signal["action"] = "BUY"
557
  signal["trade_result"] = result
 
564
  signal["action"] = "WAIT"
565
  signal["reason"] = (
566
  f"Score {composite}/100 ({regime['regime']} mode, "
567
+ f"need >={buy_threshold})"
568
  )
569
 
570
  return signal
571
+