suppa09 commited on
Commit
613cf23
·
verified ·
1 Parent(s): 9f43434

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +478 -956
app.py CHANGED
@@ -1,46 +1,29 @@
1
  """
2
- PolyBloom ML Ensemble Service v16 — OMEGA COUNCIL COMPLETE
3
- All 53 signals consumed. Zero ignored.
4
-
5
- 10 Models × Signal Group Assignment:
6
- ┌─────────────────────┬───────────────┬────────────────────────────────────────────────────────┐
7
- │ Model │ Group │ Primary Signals │
8
- ├─────────────────────┼───────────────┼────────────────────────────────────────────────────────┤
9
- │ Chronos │ PRICE │ closes, highs, lows (wick rejection), htf_trend_* │
10
- │ PatchTST │ PRICE │ closes, highs, lows, volumes (patch body/wick/vol) │
11
- │ DAG │ ORDERFLOW │ funding, cvd, ob_imbal, taker_buy, coinbase_premium, │
12
- │ │ │ korea_premium, exchange_net_inflow, whale_btc, │
13
- │ │ │ bid_vol, ask_vol, bid_ask_spread │
14
- │ River-SNARIMAX │ ORDERFLOW │ recent closes (AR), stoch_rsi_k/d, macd, ema_align │
15
- │ N-BEATS │ TECHNICAL │ closes, highs, lows, volumes (candle bodies), │
16
- │ │ │ atr, bollinger_squeeze, garman_klass_vol │
17
- │ AROpt │ TECHNICAL │ closes, macd, ema_align, vwap_dev, stoch_rsi_k/d │
18
- │ TiDE │ MACRO │ macro layer + all covariate blend: │
19
- │ │ │ fear_greed, dxy, nasdaq, btc_dom, farside, │
20
- │ │ │ stablecoin_supply, cvd, ob_imbal, funding │
21
- │ Informer-Attn │ MACRO │ long-range closes, macro, polymarket_yes, poly_delta, │
22
- │ │ │ chainlink, deribit_pcr, open_interest │
23
- │ MOIRAI │ PROB │ bootstrap on closes + macro adj + ls_ratio, │
24
- │ │ │ open_interest, session, vol_regime │
25
- │ StatsForecast-MSTL │ STRUCTURE │ closes, nearest_support/resistance, market_regime, │
26
- │ │ │ htf_trend_15m/1h, spot, atr, vol_regime, rsi │
27
- └─────────────────────┴───────────────┴────────────────────────────────────────────────────────┘
28
-
29
- Anti-bias system:
30
- - Each model draws from a DIFFERENT primary signal group.
31
- - Group-score normalization prevents one cluster from dominating.
32
- - NEUTRAL dead-band widens in HIGH/EXTREME vol regimes.
33
- - Candle pattern flag (doji/hammer/engulf) dampens any model that disagrees with it.
34
- """
35
 
36
- import os, time, math, hashlib
 
 
 
37
  from typing import List, Optional, Tuple
38
  import numpy as np
39
  from fastapi import FastAPI
40
  from fastapi.middleware.cors import CORSMiddleware
41
  from pydantic import BaseModel, Field
42
 
43
- # ── Optional heavy imports (graceful fallback) ─────────────────────────────────
44
  try:
45
  from chronos import ChronosPipeline
46
  import torch
@@ -58,10 +41,8 @@ except Exception:
58
  CHRONOS_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-small")
59
  MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
60
 
61
- app = FastAPI(title="PolyBloom ML Ensemble v16 Complete", version="16.0.0")
62
- app.add_middleware(
63
- CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
64
- )
65
 
66
  _chronos = None
67
  _moirai = None
@@ -86,87 +67,45 @@ def get_moirai():
86
  return _moirai
87
 
88
 
89
- # ── Request / Response schemas ─────────────────────────────────────────────────
 
90
  class OmegaRequest(BaseModel):
91
- # ── Core price series ──────────────────────────────────────────────────────
92
- closes: List[float] = Field(..., min_length=16)
93
- highs: Optional[List[float]] = None # wick rejection in Chronos/PatchTST/N-BEATS
94
- lows: Optional[List[float]] = None # wick rejection
95
- volumes: Optional[List[float]] = None # volume confirmation
96
-
97
- horizon: int = Field(3, ge=1, le=12)
98
- timeframe: str = Field("5M")
99
-
100
- # ── Orderflow ──────────────────────────────────────────────────────────────
101
- funding: Optional[float] = None
102
- cvd: Optional[float] = None
103
- ob_imbal: Optional[float] = None
104
- taker_buy_ratio: Optional[float] = None
105
- bid_ask_spread_pct: Optional[float] = None # formerly ignored
106
- bid_vol_top20: Optional[float] = None # formerly ignored
107
- ask_vol_top20: Optional[float] = None # formerly ignored
108
-
109
- # ── Technicals ─────────────────────────────────────────────────────────────
110
- rsi: Optional[float] = None
111
- macd: Optional[str] = None # "BULL"/"BEAR"/"FLAT"
112
- ema_align: Optional[str] = None # "BULL"/"BEAR"/"FLAT"
113
- stoch_rsi_k: Optional[float] = None # formerly ignored
114
- stoch_rsi_d: Optional[float] = None # formerly ignored
115
- vwap_dev: Optional[float] = None
116
- atr: Optional[float] = None # absolute ATR
117
- atr_pct_of_spot: Optional[float] = None
118
- bollinger_squeeze: Optional[bool] = None
119
- vol_regime: Optional[str] = None
120
- vol_percentile: Optional[float] = None
121
- garman_klass_vol: Optional[float] = None # formerly ignored
122
-
123
- # ── Structure ──────────────────────────────────────────────────────────────
124
- spot: Optional[float] = None
125
- strike: Optional[float] = None
126
- nearest_support: Optional[float] = None # formerly ignored
127
- nearest_resistance: Optional[float] = None # formerly ignored
128
- market_regime: Optional[str] = None # formerly ignored
129
- htf_trend_15m: Optional[str] = None # formerly ignored
130
- htf_trend_1h: Optional[str] = None # formerly ignored
131
- candle_pattern: Optional[str] = None # formerly ignored
132
-
133
- # ── Derivatives ────────────────────────────────────────────────────────────
134
- open_interest: Optional[float] = None # formerly ignored
135
- ls_ratio: Optional[float] = None # formerly ignored
136
- deribit_pcr: Optional[float] = None # formerly ignored (put/call ratio)
137
-
138
- # ── Macro / Cross-asset ────────────────────────────────────────────────────
139
- fear_greed: Optional[float] = None
140
- dxy_change_pct: Optional[float] = None
141
- nasdaq_fut_change_pct:Optional[float] = None
142
- farside_net_flow_usd: Optional[float] = None # formerly ignored
143
- btc_dom: Optional[float] = None # formerly ignored
144
- stablecoin_supply_change: Optional[float] = None # formerly stablecoin_supply_chg
145
- chainlink_price: Optional[float] = None
146
-
147
- # ── Polymarket ─────────────────────────────────────────────────────────────
148
- polymarket_yes: Optional[float] = None
149
- poly_yes_delta_1m: Optional[float] = None
150
-
151
- # ── Sentiment / On-chain ───────────────────────────────────────────────────
152
- sentiment_polarity: Optional[float] = None
153
- coinbase_premium_pct: Optional[float] = None
154
- exchange_net_inflow_btc_5m: Optional[float]= None # maps to exchange_net_inflow
155
- whale_transfer_btc: Optional[float] = None
156
- whale_transfer_dest: Optional[str] = None # "exchange"/"wallet"/"unknown"
157
- whale_exchange_count_15m: Optional[int] = None
158
- korea_premium_pct: Optional[float] = None
159
-
160
- # ── Session ────────────────────────────────────────────────────────────────
161
- session: Optional[str] = None # "ASIA"/"LONDON"/"NY"/"OVERLAP"
162
-
163
- # ── Adaptive ML weights (frontend-managed) ─────────────────────────────────
164
- adaptive_weights: Optional[dict] = None
165
 
166
  class Config:
167
  extra = "allow"
168
 
169
-
170
  class ModelResult(BaseModel):
171
  name: str
172
  direction: str
@@ -175,8 +114,6 @@ class ModelResult(BaseModel):
175
  available: bool
176
  note: str
177
  reasoning: str
178
- group: str
179
-
180
 
181
  class OmegaResponse(BaseModel):
182
  composite_direction: str
@@ -186,10 +123,30 @@ class OmegaResponse(BaseModel):
186
  elapsed_ms: int
187
  timeframe: str
188
  anti_bias_applied: bool
189
- dominant_group: str
190
 
191
 
192
- # ── Utility ────────────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  def ema(arr: np.ndarray, period: int) -> float:
194
  if len(arr) < period:
195
  return float(np.mean(arr))
@@ -200,936 +157,501 @@ def ema(arr: np.ndarray, period: int) -> float:
200
  return val
201
 
202
 
203
- def slope_to_direction(slope_pct: float, threshold: float = 0.012) -> Tuple[str, float]:
204
- if abs(slope_pct) < threshold:
205
- return "NEUTRAL", 50.0
206
- conf = min(95.0, 50.0 + abs(slope_pct) / threshold * 7.0)
207
- return ("UP" if slope_pct > 0 else "DOWN"), conf
208
-
209
-
210
- def _hash_seed(closes: np.ndarray) -> int:
211
- h = hashlib.md5(closes[-8:].tobytes()).hexdigest()
212
- return int(h[:8], 16) % (2**31)
213
-
214
-
215
- def _str_sign(s: Optional[str], bull_val: str = "BULL", bear_val: str = "BEAR") -> float:
216
- """Convert a string enum like 'BULL'/'BEAR'/'FLAT' to -1/0/+1."""
217
- if s is None: return 0.0
218
- u = s.upper()
219
- if u in (bull_val.upper(), "UP", "BULLISH", "RISING", "LONG"): return 1.0
220
- if u in (bear_val.upper(), "DOWN", "BEARISH", "FALLING", "SHORT"): return -1.0
221
- return 0.0
222
-
223
-
224
- def _session_mult(session: Optional[str]) -> float:
225
- """NY/OVERLAP sessions = higher confidence multiplier (more liquid)."""
226
- if session is None: return 1.0
227
- s = session.upper()
228
- if "OVERLAP" in s or "NY" in s: return 1.08
229
- if "LONDON" in s: return 1.03
230
- return 0.94 # Asia = wider spreads, less directional
231
-
232
-
233
- def _vol_dampen(slope: float, vol_regime: Optional[str], vol_pct: Optional[float]) -> float:
234
- """Dampen slope in extreme vol so models don't over-fire on noise."""
235
- if vol_regime in ("EXTREME",):
236
- slope *= 0.45
237
- elif vol_regime in ("HIGH",):
238
- slope *= 0.70
239
- if vol_pct is not None and vol_pct > 90:
240
- slope *= 0.80
241
- return slope
242
-
243
-
244
- def get_threshold(timeframe: str, vol_regime: Optional[str], vol_pct: Optional[float]) -> float:
245
- base = {"5M": 0.04, "15M": 0.035, "1D": 0.025}.get(timeframe, 0.04)
246
- if vol_regime in ("HIGH", "EXTREME"):
247
- base *= 1.5
248
- if vol_pct is not None and vol_pct > 90:
249
- base *= 1.3
250
- return base
251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
- def _wick_signal(
254
- closes: np.ndarray,
255
- highs: Optional[List[float]],
256
- lows: Optional[List[float]],
257
- n: int = 5,
258
- ) -> float:
259
- """
260
- Wick rejection signal: a long lower wick on recent candles is bullish,
261
- long upper wick is bearish. Returns [-1, +1].
262
- Uses last `n` candles. Requires highs/lows arrays.
263
- """
264
- if highs is None or lows is None or len(highs) < n or len(lows) < n:
265
- return 0.0
266
- h = np.array(highs[-n:], dtype=float)
267
- l = np.array(lows[-n:], dtype=float)
268
- c = closes[-n:]
269
- ranges = h - l
270
- ranges = np.where(ranges == 0, 1e-9, ranges)
271
- lower_wick = (np.minimum(c, np.roll(c, 1)[1:] if n > 1 else c) - l[-len(c):])
272
- upper_wick = (h[-len(c):] - np.maximum(c, np.roll(c, 1)[1:] if n > 1 else c))
273
- # Simplified: use open=prev_close approximation
274
- lower_wick = c - l[-len(c):] # close - low (lower shadow)
275
- upper_wick = h[-len(c):] - c # high - close (upper shadow)
276
- lw_ratio = float(np.mean(lower_wick / ranges[-len(c):]))
277
- uw_ratio = float(np.mean(upper_wick / ranges[-len(c):]))
278
- return math.tanh((lw_ratio - uw_ratio) * 4)
279
-
280
-
281
- def _volume_confirmation(
282
- closes: np.ndarray,
283
- volumes: Optional[List[float]],
284
- n: int = 5,
285
- ) -> float:
286
- """
287
- Volume confirms direction: rising price + high volume = strong UP.
288
- Returns multiplier adjustment in [-0.3, +0.3].
289
- """
290
- if volumes is None or len(volumes) < n + 1:
291
- return 0.0
292
- vol = np.array(volumes[-(n + 1):], dtype=float)
293
- avg_vol = float(np.mean(vol[:-1]))
294
- last_vol = float(vol[-1])
295
- vol_ratio = (last_vol / avg_vol - 1.0) if avg_vol > 0 else 0.0
296
- price_dir = 1.0 if closes[-1] > closes[-2] else (-1.0 if closes[-1] < closes[-2] else 0.0)
297
- return math.tanh(vol_ratio * price_dir * 2) * 0.3
298
 
 
299
 
300
- def _candle_pattern_adj(candle_pattern: Optional[str]) -> Tuple[float, str]:
301
- """
302
- Maps candle pattern string to a directional adjustment and description.
303
- Returns (signal [-1..+1], label).
304
- """
305
- if candle_pattern is None:
306
- return 0.0, "no pattern"
307
- p = candle_pattern.upper()
308
- if any(x in p for x in ("HAMMER", "MORNING_STAR", "BULLISH_ENGULF", "DRAGONFLY")):
309
- return 0.4, candle_pattern
310
- if any(x in p for x in ("SHOOTING_STAR", "EVENING_STAR", "BEARISH_ENGULF", "GRAVESTONE")):
311
- return -0.4, candle_pattern
312
- if "DOJI" in p:
313
- return 0.0, "doji (neutral)"
314
- return 0.0, candle_pattern
315
-
316
-
317
- # ── GROUP 1: PRICE — Chronos (wick-aware Holt fallback) ───────────────────────
318
- def run_chronos(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
319
  pipe = get_chronos()
320
  if pipe is None:
321
- raise RuntimeError("Chronos not loaded")
322
- ctx = torch.tensor(closes[-64:]).unsqueeze(0)
323
- fc = pipe.predict(ctx, prediction_length=horizon)
324
- arr = fc[0].numpy()
325
- med = float(np.quantile(arr, 0.5, axis=0)[-1])
326
- p10 = float(np.quantile(arr, 0.1, axis=0)[-1])
327
- p90 = float(np.quantile(arr, 0.9, axis=0)[-1])
328
- sp = (med - float(closes[-1])) / float(closes[-1]) * 100
329
- unc = (p90 - p10) / float(closes[-1]) * 100
330
- return sp, "chronos-t5-small", f"Chronos: med={med:.2f}, unc={unc:.4f}%"
331
-
332
-
333
- def run_chronos_with_structure(
334
- closes: np.ndarray,
335
- horizon: int,
336
- req: "OmegaRequest",
337
- ) -> Tuple[float, str, str]:
338
- """
339
- Chronos + wick rejection + HTF trend bias.
340
- HTF trend is the most important structural overlay for Chronos — it
341
- prevents Chronos from calling UP during a confirmed downtrend.
342
  """
343
- # Base Chronos or fallback
344
- try:
345
- sp, note, rsn = run_chronos(closes, horizon)
346
- except Exception:
347
- sp, note, rsn = _chronos_holt_fallback(closes, horizon)
348
-
349
- # Wick rejection overlay
350
- wick = _wick_signal(closes, req.highs, req.lows, n=5)
351
- sp += wick * 0.03 * 100 # ±3% adjustment from wick
352
-
353
- # HTF trend bias — strongest overlay: if both HTFs disagree with Chronos, dampen hard
354
- htf15 = _str_sign(req.htf_trend_15m)
355
- htf1h = _str_sign(req.htf_trend_1h)
356
- htf_combined = (htf15 * 0.4 + htf1h * 0.6) # 1h has more weight
357
- if htf_combined != 0:
358
- price_sign = 1 if sp > 0 else -1 if sp < 0 else 0
359
- if price_sign != 0 and math.copysign(1, htf_combined) != price_sign:
360
- # HTF disagrees → dampen by 35%
361
- sp *= 0.65
362
- else:
363
- # HTF agrees → boost by 12%
364
- sp *= 1.12
365
- sp = float(np.clip(sp, -1.5, 1.5))
366
- return sp, note, rsn + f" | wick={wick:.3f}, htf={htf_combined:.2f}"
367
 
 
 
 
 
 
 
 
368
 
369
- def _chronos_holt_fallback(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
370
  alpha, beta = 0.3, 0.2
371
- level = float(closes[0]); trend = float(closes[1] - closes[0]) if len(closes) > 1 else 0
372
- for p in closes[1:]:
373
- pl = level
374
- level = alpha * float(p) + (1 - alpha) * (level + trend)
375
- trend = beta * (level - pl) + (1 - beta) * trend
376
- fval = level + trend * horizon
377
- sp = (fval - float(closes[-1])) / float(closes[-1]) * 100
378
- return sp, "holt-fallback", f"Holt: level={level:.2f}, trend={trend:.4f}/candle"
379
-
380
-
381
- # ── GROUP 1: PRICE — PatchTST (patch body + wick + volume) ────────────────────
382
- def run_patchtst(
383
- closes: np.ndarray,
384
- horizon: int,
385
- req: "OmegaRequest",
386
- ) -> Tuple[float, str, str]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  """
388
- PatchTST with full OHLCV awareness:
389
- - Patch weighted return (price structure, as before)
390
- - Wick rejection per patch (NEW)
391
- - Volume confirmation on last patch (NEW)
392
- """
393
- n = len(closes); patch_size = 8; n_patches = n // patch_size
394
- if n_patches < 2:
395
- return 0.0, "patchtst", "Insufficient patches"
396
-
397
- patches = []
398
- for i in range(n_patches):
399
- seg_c = closes[i * patch_size:(i + 1) * patch_size]
400
- pr = (seg_c[-1] - seg_c[0]) / seg_c[0] if seg_c[0] != 0 else 0
401
- pv = float(np.std(seg_c)) / float(np.mean(seg_c)) if np.mean(seg_c) != 0 else 0
402
- patches.append((pr, pv))
403
-
404
- # Exponential attention weights
405
- raw_w = np.array([math.exp(0.4 * i) for i in range(len(patches))])
406
- att = raw_w / raw_w.sum()
407
- w_ret = sum(p[0] * w for p, w in zip(patches, att))
408
-
409
- # Volatility penalty from intra-patch std
410
- mean_vol = np.mean([p[1] for p in patches[-3:]])
411
- vol_pen = min(0.5, mean_vol * 10)
412
- sp = w_ret * horizon * 100 * (1 - vol_pen)
413
-
414
- # Wick rejection (uses last 2 patches worth of candles)
415
- wick = _wick_signal(closes, req.highs, req.lows, n=min(16, n))
416
- sp += wick * 0.025 * 100
417
 
418
- # Volume confirmation on last 5 candles
419
- vol_conf = _volume_confirmation(closes, req.volumes, n=5)
420
- sp += vol_conf * 100
421
-
422
- # Garman-Klass vol — if high, widen neutral zone (reduce absolute slope)
423
- if req.garman_klass_vol is not None and req.garman_klass_vol > 0.003:
424
- sp *= (1 - min(0.4, (req.garman_klass_vol - 0.003) / 0.002 * 0.4))
425
-
426
- sp = float(np.clip(sp, -1.5, 1.5))
427
- return sp, "patchtst-ohlcv", (
428
- f"PatchTST: {n_patches}p w_ret={w_ret*100:.4f}% vpen={vol_pen:.3f} "
429
- f"wick={wick:.3f} vol_conf={vol_conf:.3f}"
430
- )
431
-
432
-
433
- # ── GROUP 2: ORDERFLOW — DAG (all 11 flow signals) ────────────────────────────
434
- def run_dag(closes: np.ndarray, req: "OmegaRequest") -> Tuple[float, str, str]:
435
- """
436
- DAG causal orderflow.
437
- Now consumes: funding, cvd, ob_imbal, taker_buy, coinbase_premium,
438
- korea_premium, exchange_net_inflow, whale_transfer_btc,
439
- bid_vol_top20, ask_vol_top20, bid_ask_spread_pct.
440
  """
441
  n = len(closes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  if n < 8:
443
  return 0.0, "dag", "Insufficient"
444
 
445
- price_sig = sum(
446
- (closes[-1] - closes[-(lag + 1)]) / closes[-(lag + 1)] * (0.5 ** lag)
447
- for lag in [1, 2, 3] if n > lag
448
- )
449
-
450
- exog = 0.0; exog_n = 0
451
 
 
 
452
  if req.funding is not None:
453
- exog += -math.tanh(req.funding * 10000) * 0.35; exog_n += 1
 
454
  if req.cvd is not None:
455
- exog += math.tanh(req.cvd / 30_000_000) * 0.45; exog_n += 1
 
456
  if req.ob_imbal is not None:
457
- exog += math.tanh(req.ob_imbal * 2) * 0.35; exog_n += 1
 
458
  if req.taker_buy_ratio is not None:
459
- exog += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.25; exog_n += 1
460
- if req.coinbase_premium_pct is not None:
461
- exog += math.tanh(req.coinbase_premium_pct / 0.3) * 0.20; exog_n += 1
462
- if req.korea_premium_pct is not None:
463
- exog += math.tanh(req.korea_premium_pct / 0.5) * 0.15; exog_n += 1
464
- if req.exchange_net_inflow_btc_5m is not None:
465
- # Net inflow to exchanges = selling pressure = bearish
466
- exog += -math.tanh(req.exchange_net_inflow_btc_5m / 500) * 0.20; exog_n += 1
467
- if req.whale_transfer_btc is not None:
468
- wdest_sign = -1.0 if req.whale_transfer_dest == "exchange" else 0.5
469
- exog += -math.tanh(req.whale_transfer_btc / 200) * 0.10 * abs(wdest_sign)
470
- exog *= math.copysign(1, wdest_sign) if wdest_sign != 0 else 1
471
  exog_n += 1
 
 
 
 
 
472
 
473
- # Bid/ask volume imbalance (order book depth signal)
474
- if req.bid_vol_top20 is not None and req.ask_vol_top20 is not None:
475
- total = req.bid_vol_top20 + req.ask_vol_top20
476
- if total > 0:
477
- depth_imbal = (req.bid_vol_top20 - req.ask_vol_top20) / total
478
- exog += math.tanh(depth_imbal * 4) * 0.25; exog_n += 1
479
-
480
- # Wide spread = uncertainty → dampen conviction
481
- spread_dampen = 1.0
482
- if req.bid_ask_spread_pct is not None:
483
- spread_dampen = max(0.5, 1.0 - min(0.5, req.bid_ask_spread_pct / 0.1))
484
-
485
- if exog_n > 0: exog /= exog_n
486
- combined = (price_sig * 0.50 + exog * 0.50) * spread_dampen
487
- sp = math.tanh(combined) * 0.15 * 100
488
-
489
- return sp, "dag-causal-full", (
490
- f"DAG: psig={price_sig*100:.4f}% exog({exog_n})={exog:.4f} "
491
- f"spread_d={spread_dampen:.3f} sp={sp:.4f}%"
492
- )
493
-
494
-
495
- # ── GROUP 2: ORDERFLOW — River-SNARIMAX (recency + technicals) ─────────────────
496
- def run_river_snarimax(closes: np.ndarray, req: "OmegaRequest") -> Tuple[float, str, str]:
497
- """
498
- River SNARIMAX: online AR(3) on most recent 40 candles.
499
- Now adds stoch_rsi_k/d and macd/ema_align as exogenous correction
500
- applied to the AR forecast — giving it a technical colour so it's
501
- not purely autoregressive.
502
- """
503
- horizon = 2 # fixed short horizon for recency model
504
- n = len(closes); window = min(40, n)
505
- recent = closes[-window:]
506
- if len(recent) < 8:
507
- return 0.0, "river-snarimax", "Insufficient"
508
-
509
- diff1 = np.diff(recent.astype(float))
510
- if len(diff1) < 4:
511
- return 0.0, "river-snarimax", "Insufficient diff"
512
-
513
- order = min(3, len(diff1) - 1)
514
- y = diff1[order:]
515
- X = np.column_stack([diff1[i:len(diff1) - order + i] for i in range(order)])
516
- if len(y) < 2 or X.shape[0] != len(y):
517
- return 0.0, "river-snarimax", "Matrix mismatch"
518
-
519
- try:
520
- coeffs, *_ = np.linalg.lstsq(X, y, rcond=None)
521
- except np.linalg.LinAlgError:
522
- return 0.0, "river-snarimax", "lstsq failed"
523
-
524
- buf = list(diff1[-order:])
525
- fc_diff = []
526
- for _ in range(horizon):
527
- nv = float(np.dot(coeffs, buf[-order:]))
528
- fc_diff.append(nv); buf.append(nv)
529
-
530
- last_price = float(recent[-1])
531
- for d in fc_diff:
532
- last_price += d
533
- sp = (last_price - float(closes[-1])) / float(closes[-1]) * 100
534
-
535
- # Stoch RSI correction: overbought/oversold counter-signal
536
- stoch_adj = 0.0
537
- if req.stoch_rsi_k is not None:
538
- stoch_adj += -math.tanh((req.stoch_rsi_k - 50) / 25) * 0.015 * 100
539
- if req.stoch_rsi_d is not None:
540
- stoch_adj += -math.tanh((req.stoch_rsi_d - 50) / 25) * 0.008 * 100
541
- sp += stoch_adj
542
-
543
- # MACD / EMA alignment confirmation
544
- macd_sign = _str_sign(req.macd, "BULL", "BEAR")
545
- ema_sign = _str_sign(req.ema_align, "BULL", "BEAR")
546
- technical_confirm = (macd_sign + ema_sign) / 2.0
547
- # If AR says UP but MACD+EMA say DOWN → reduce by 25%
548
- if technical_confirm != 0 and sp != 0:
549
- if math.copysign(1, technical_confirm) != math.copysign(1, sp):
550
- sp *= 0.75
551
-
552
- return sp, "river-snarimax-ar3+tech", (
553
- f"River: coeffs[:3]={[round(float(c),4) for c in coeffs[:3]]} "
554
- f"stoch_adj={stoch_adj:.4f}% tc={technical_confirm:.2f}"
555
- )
556
-
557
-
558
- # ── GROUP 3: TECHNICAL — N-BEATS (candle body + ATR + Bollinger) ──────────────
559
- def run_nbeats(closes: np.ndarray, horizon: int, req: "OmegaRequest") -> Tuple[float, str, str]:
560
- """
561
- N-BEATS polynomial + FFT seasonality.
562
- Now also uses:
563
- - highs/lows/volumes for candle body analysis (body strength)
564
- - ATR for absolute volatility context
565
- - Bollinger squeeze flag (coiled spring = bigger move imminent)
566
- - Garman-Klass vol for regime-aware scaling
567
- """
568
- n = len(closes)
569
- if n < 16:
570
- return 0.0, "nbeats", "Insufficient"
571
 
572
- # Polynomial trend
573
- x = np.arange(min(32, n)); y = closes[-len(x):]
574
- try:
575
- poly2 = np.polyfit(x, y, 2)
576
- x_next = np.arange(len(x), len(x) + horizon)
577
- trend_fc = np.polyval(poly2, x_next)
578
- trend_sl = (trend_fc[-1] - float(closes[-1])) / float(closes[-1]) * 100
579
- except Exception:
580
- trend_sl = 0.0
581
 
582
- # FFT seasonality
583
- seasonal_sig = 0.0; period = 32.0
584
- if n >= 32:
585
- fft = np.fft.rfft(closes[-32:] - np.mean(closes[-32:]))
586
- dom = np.argmax(np.abs(fft[1:])) + 1
587
- period = 32 / dom if dom > 0 else 32
588
- phase = (n % period) / period * 2 * math.pi
589
- seasonal_sig = math.sin(phase + math.pi / 2)
590
-
591
- residual = (closes[-1] - closes[-5]) / closes[-5] if n >= 5 else 0
592
-
593
- # Candle body strength (if OHLCV available)
594
- body_signal = 0.0
595
- if req.highs is not None and req.lows is not None and len(req.highs) >= 3:
596
- h = np.array(req.highs[-5:], dtype=float)
597
- l = np.array(req.lows[-5:], dtype=float)
598
- c = closes[-5:]
599
- ranges = h - l
600
- bodies = np.abs(c - np.array([closes[-6:-1][i] if n > 5 else c[i] for i in range(len(c))]))
601
- body_ratio = float(np.mean(bodies / np.where(ranges == 0, 1e-9, ranges)))
602
- price_dir = 1.0 if closes[-1] > closes[-2] else -1.0
603
- body_signal = math.tanh(body_ratio * 3) * price_dir * 0.03 * 100
604
-
605
- # Volume confirmation
606
- vol_conf = _volume_confirmation(closes, req.volumes, n=5)
607
-
608
- # ATR context: small ATR relative to price = trending / high conviction
609
- atr_signal = 0.0
610
- if req.atr_pct_of_spot is not None:
611
- # Very small ATR (< 0.1%) in direction of trend → amplify; large ATR → dampen
612
- if req.atr_pct_of_spot < 0.001:
613
- atr_signal = math.copysign(0.005 * 100, trend_sl)
614
- elif req.atr_pct_of_spot > 0.005:
615
- trend_sl *= 0.75 # wide ATR = chop → reduce trend confidence
616
-
617
- # Bollinger squeeze = energy building → amplify the directional signal
618
- squeeze_boost = 1.0
619
- if req.bollinger_squeeze:
620
- squeeze_boost = 1.25 # coiled spring
621
-
622
- # Garman-Klass dampener (high intrabar vol = noisy bars)
623
- gk_dampen = 1.0
624
- if req.garman_klass_vol is not None and req.garman_klass_vol > 0.004:
625
- gk_dampen = max(0.5, 1.0 - (req.garman_klass_vol - 0.004) / 0.002 * 0.25)
626
-
627
- sp = (trend_sl * 0.60 + seasonal_sig * 0.03 * 100 + float(residual) * 25
628
- + body_signal + vol_conf * 100 + atr_signal) * squeeze_boost * gk_dampen
629
- sp = float(np.clip(sp, -1.5, 1.5))
630
-
631
- return sp, "nbeats-ohlcv-atr", (
632
- f"N-BEATS: trend={trend_sl:.4f}% seasonal(p≈{period:.1f})={seasonal_sig:.3f} "
633
- f"body={body_signal:.4f} atr_d={atr_signal:.4f} sq={squeeze_boost}"
634
- )
635
-
636
-
637
- # ── GROUP 3: TECHNICAL — AROpt (AR + MACD + EMA + VWAP + StochRSI) ───────────
638
- def run_aropt(closes: np.ndarray, horizon: int, req: "OmegaRequest") -> Tuple[float, str, str]:
639
- """
640
- AROpt least-squares AR(p) with technical overlay.
641
- Now adds: macd, ema_align, vwap_dev, stoch_rsi_k/d.
642
- These are treated as exogenous momentum confirmations that
643
- AROpt uses to weight its forecast.
644
- """
645
- n = len(closes); order = min(6, n - 1)
646
  if order < 2:
647
  return 0.0, "aropt", "Insufficient"
648
-
649
- y = closes[order:]; X = np.column_stack([closes[i:n - order + i] for i in range(order)])
650
  if len(y) < 2:
651
  return 0.0, "aropt", "Insufficient pairs"
652
  try:
653
  coeffs, *_ = np.linalg.lstsq(X, y, rcond=None)
654
  except np.linalg.LinAlgError:
655
  return 0.0, "aropt", "lstsq failed"
656
-
657
- window = list(closes[-order:])
658
  forecast = []
659
  for _ in range(horizon):
660
  nv = float(np.dot(coeffs, window[-order:]))
661
- forecast.append(nv); window.append(nv)
662
-
663
- sp = (forecast[-1] - float(closes[-1])) / float(closes[-1]) * 100
664
-
665
- # MACD + EMA align: treat as a multiplier on AR forecast
666
- tech_score = 0.0; tech_n = 0
667
- if req.macd is not None:
668
- tech_score += _str_sign(req.macd) * 0.4; tech_n += 1
669
- if req.ema_align is not None:
670
- tech_score += _str_sign(req.ema_align) * 0.35; tech_n += 1
671
-
672
- # VWAP deviation: price above VWAP = bullish bias
673
- if req.vwap_dev is not None:
674
- tech_score += math.tanh(req.vwap_dev / 0.002) * 0.25; tech_n += 1
675
-
676
- # StochRSI: overbought/oversold counter-signal (mean-reversion layer for AROpt)
677
- if req.stoch_rsi_k is not None:
678
- tech_score += -math.tanh((req.stoch_rsi_k - 50) / 30) * 0.15; tech_n += 1
679
- if req.stoch_rsi_d is not None:
680
- tech_score += -math.tanh((req.stoch_rsi_d - 50) / 30) * 0.10; tech_n += 1
681
-
682
- if tech_n > 0:
683
- ts = tech_score / tech_n
684
- # Blend: AR(p) at 65%, technical at 35%
685
- sp = sp * 0.65 + ts * 0.15 * 100 * 0.35
686
-
687
- return sp, "aropt-full-tech", (
688
- f"AR({order}): coeffs[:3]={[round(float(c),4) for c in coeffs[:3]]} "
689
- f"tech({tech_n})={tech_score/max(1,tech_n):.4f} sp={sp:.4f}%"
690
- )
691
-
692
-
693
- # ── GROUP 4: MACRO — build_macro_score (shared by TiDE + Informer) ────────────
694
- def build_macro_score(req: "OmegaRequest") -> float:
695
- score = 0.0; count = 0
696
-
697
- if req.fear_greed is not None:
698
- score += -math.tanh((req.fear_greed - 50) / 25) * 0.12; count += 1
699
- if req.dxy_change_pct is not None:
700
- score += math.tanh(-req.dxy_change_pct / 0.5) * 0.18; count += 1
701
- if req.nasdaq_fut_change_pct is not None:
702
- score += math.tanh(req.nasdaq_fut_change_pct / 0.5) * 0.15; count += 1
703
- if req.sentiment_polarity is not None:
704
- score += math.tanh(req.sentiment_polarity * 2) * 0.12; count += 1
705
- if req.chainlink_price is not None and req.strike is not None and req.strike > 0:
706
- drift = (req.chainlink_price - req.strike) / req.strike
707
- score += math.tanh(drift / 0.001) * 0.50; count += 1
708
- if req.deribit_pcr is not None:
709
- score += math.tanh((1 - req.deribit_pcr) * 2) * 0.10; count += 1
710
- if req.stablecoin_supply_change is not None:
711
- score += math.tanh(req.stablecoin_supply_change / 0.02) * 0.10; count += 1
712
 
713
- # NEW: BTC dominance — high BTC dom = rotation from alts → BTC bullish
714
- if req.btc_dom is not None:
715
- score += math.tanh((req.btc_dom - 50) / 10) * 0.08; count += 1
716
 
717
- # NEW: Farside ETF flows — large inflow = institutional buying = bullish
718
- if req.farside_net_flow_usd is not None:
719
- score += math.tanh(req.farside_net_flow_usd / 100_000_000) * 0.12; count += 1
720
 
721
- return score / max(1, count)
 
 
 
 
 
 
 
722
 
 
 
 
 
 
 
723
 
724
- # ── GROUP 4: MACRO — TiDE (full covariate dense encoder) ──────────────────────
725
- def run_tide(closes: np.ndarray, req: "OmegaRequest", horizon: int) -> Tuple[float, str, str]:
726
- """
727
- TiDE dense encoder: price trend + macro + orderflow blend.
728
- Now includes btc_dom, farside, stablecoin_supply_change in the macro layer.
729
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730
  n = len(closes)
731
  if n < 16:
732
  return 0.0, "tide", "Insufficient"
733
-
734
- sl5 = (closes[-1] - closes[-6]) / closes[-6] if n >= 6 else 0
735
- sl20 = (closes[-1] - closes[-21]) / closes[-21] if n >= 21 else 0
736
- e8 = ema(closes[-20:], 8); e20 = ema(closes[-40:], 20)
737
- ts_signal = sl5 * 0.6 + sl20 * 0.4 + ((e8 - e20) / e20 * 0.3 if e20 != 0 else 0)
738
-
739
- macro = build_macro_score(req) # includes btc_dom, farside, dxy, nasdaq, etc.
740
-
741
- # Orderflow layer
742
- flow = 0.0; flow_n = 0
743
- if req.cvd is not None: flow += math.tanh(req.cvd / 50_000_000) * 0.4; flow_n += 1
744
- if req.ob_imbal is not None: flow += math.tanh(req.ob_imbal * 2) * 0.3; flow_n += 1
745
- if req.funding is not None: flow += -math.tanh(req.funding * 10000) * 0.3; flow_n += 1
746
- if flow_n > 0: flow /= flow_n
747
-
748
- # HTF trend multiplier — TiDE also respects the trend context
749
- htf15 = _str_sign(req.htf_trend_15m)
750
- htf1h = _str_sign(req.htf_trend_1h)
751
- htf = (htf15 * 0.3 + htf1h * 0.7)
752
-
753
- combined = ts_signal * 0.40 + macro * 0.35 + flow * 0.25
754
- # HTF multiplier
755
- if htf != 0:
756
- if math.copysign(1, htf) == math.copysign(1, combined):
757
- combined *= 1.10
758
- else:
759
- combined *= 0.80
760
-
761
- sp = math.tanh(combined * 3) * 0.14 * 100
762
- return sp, "tide-dense-full", (
763
- f"TiDE: ts={ts_signal*100:.4f}% macro={macro:.4f} flow={flow:.4f} htf={htf:.2f}"
764
- )
765
-
766
-
767
- # ── GROUP 4: MACRO — Informer (long-range + polymarket + derivatives) ──────────
768
- def run_informer(closes: np.ndarray, req: "OmegaRequest", horizon: int) -> Tuple[float, str, str]:
769
- """
770
- Informer ProbSparse multi-scale attention.
771
- Now includes: deribit_pcr, open_interest, polymarket signals.
772
- OI-weighted direction (rising OI in direction of price = conviction).
773
- """
774
- n = len(closes)
775
- if n < 24:
776
- return 0.0, "informer", "Insufficient (need 24+)"
777
-
778
- window = min(128, n)
779
- ctx = closes[-window:].astype(float)
780
- lags = [1, 2, 3, 5, 8, 13, 21]
781
- attn_signals = []
782
- for lag in lags:
783
- if window > lag:
784
- ret = (ctx[-1] - ctx[-(lag + 1)]) / ctx[-(lag + 1)]
785
- weight = math.exp(-lag * 0.05)
786
- attn_signals.append(ret * weight)
787
- ts_attn = sum(attn_signals) / max(1, len(attn_signals))
788
-
789
- x = np.arange(len(ctx)); slope_coef = np.polyfit(x, ctx, 1)[0]
790
- long_sl = slope_coef / ctx[-1] if ctx[-1] != 0 else 0
791
-
792
- macro = build_macro_score(req)
793
-
794
- # Polymarket probability
795
- polymarket = 0.0
796
- if req.polymarket_yes is not None:
797
- polymarket = math.tanh((req.polymarket_yes - 0.5) * 6) * 0.30
798
- if req.poly_yes_delta_1m is not None:
799
- polymarket += math.tanh(req.poly_yes_delta_1m * 20) * 0.20
800
-
801
- # NEW: Deribit put/call ratio (bearish when > 1.2, bullish when < 0.8)
802
- pcr_signal = 0.0
803
- if req.deribit_pcr is not None:
804
- pcr_signal = math.tanh((1.0 - req.deribit_pcr) * 3) * 0.12
805
-
806
- # NEW: Open Interest direction
807
- # Rising OI with rising price = more longs building = bullish
808
- # Rising OI with falling price = shorts building = bearish
809
- oi_signal = 0.0
810
- if req.open_interest is not None:
811
- price_dir = 1.0 if ts_attn > 0 else -1.0 if ts_attn < 0 else 0.0
812
- # Normalize OI: we can only infer direction if we had OI history
813
- # Use sign of price direction weighted by OI magnitude proxy
814
- oi_signal = price_dir * math.tanh(req.open_interest / 5_000_000_000) * 0.08
815
-
816
- combined = (ts_attn * 100 * 0.35 + long_sl * 100 * 0.20
817
- + macro * 0.18 + polymarket * 0.15
818
- + pcr_signal * 0.07 + oi_signal * 0.05)
819
- sp = float(np.clip(combined, -1.5, 1.5))
820
-
821
- return sp, "informer-probsparse-full", (
822
- f"Informer: attn={ts_attn*100:.4f}% lsl={long_sl*100:.4f}% "
823
- f"macro={macro:.4f} pcr={pcr_signal:.4f} oi={oi_signal:.4f}"
824
- )
825
-
826
-
827
- # ── GROUP 5: PROBABILISTIC — MOIRAI (bootstrap + ls_ratio + session) ──────────
828
- def run_moirai(closes: np.ndarray, horizon: int, req: "OmegaRequest") -> Tuple[float, str, str]:
829
- """
830
- MOIRAI bootstrap probabilistic model.
831
- Now adds: ls_ratio (long/short ratio), open_interest, session weighting.
832
- """
833
  model = get_moirai()
834
  if model is not None:
835
  try:
836
- ctx = th.tensor(closes[-64:], dtype=th.float32).unsqueeze(0).unsqueeze(-1)
837
  samples = model.predict(ctx)
838
- arr = samples.squeeze().numpy()
839
- if arr.ndim == 1: arr = arr.reshape(1, -1)
840
- med = float(np.median(arr[:, -1]))
841
- p10 = float(np.percentile(arr[:, -1], 10))
842
- p90 = float(np.percentile(arr[:, -1], 90))
843
- sp = (med - float(closes[-1])) / float(closes[-1]) * 100
844
- unc = (p90 - p10) / float(closes[-1]) * 100
845
- macro = build_macro_score(req)
846
- sp += macro * 0.08 * 100
 
847
  except Exception:
848
- model = None # fall through
849
-
850
- if model is None:
851
- seed = _hash_seed(closes)
852
- rng = np.random.default_rng(seed=seed)
853
- returns = np.diff(closes) / closes[:-1]
854
- if len(returns) < 5:
855
- return 0.0, "moirai-bootstrap", "Insufficient returns"
856
- samples_list = []
857
- for _ in range(200):
858
- path = float(closes[-1])
859
- for _ in range(horizon):
860
- path *= (1 + rng.choice(returns[-50:]))
861
- samples_list.append(path)
862
- med = float(np.median(samples_list))
863
- p10 = float(np.percentile(samples_list, 10))
864
- p90 = float(np.percentile(samples_list, 90))
865
- sp = (med - float(closes[-1])) / float(closes[-1]) * 100
866
- unc = (p90 - p10) / float(closes[-1]) * 100
867
- macro = build_macro_score(req)
868
- sp += macro * 0.06 * 100
869
-
870
- # NEW: L/S ratio — more shorts outstanding → contrarian bullish potential
871
- if req.ls_ratio is not None:
872
- # ls_ratio < 1 means more shorts, counter-trend signal
873
- ls_adj = math.tanh((1.0 - req.ls_ratio) * 2) * 0.04 * 100
874
- sp += ls_adj
875
-
876
- # NEW: Open interest — large OI in low-vol = coiled spring, amplify
877
- if req.open_interest is not None and req.vol_regime in ("LOW", "NORMAL", None):
878
- oi_coil = math.tanh(req.open_interest / 10_000_000_000) * 0.02 * 100
879
- if sp > 0: sp += oi_coil
880
- else: sp -= oi_coil
881
-
882
- # NEW: Session multiplier (MOIRAI is probability-based, so session liquidity matters)
883
- session_m = _session_mult(req.session)
884
- sp *= session_m
885
-
886
- return sp, "moirai-prob-full", (
887
- f"MOIRAI: med_sp={sp:.4f}% unc={unc:.4f}% macro={macro:.4f} "
888
- f"session_m={session_m:.2f}"
889
- )
890
-
891
-
892
- # ── GROUP 6: STRUCTURE — StatsForecast-MSTL (support/resistance + HTF) ────────
893
- def run_statsforecast_mstl(
894
- closes: np.ndarray,
895
- horizon: int,
896
- req: "OmegaRequest",
897
- ) -> Tuple[float, str, str]:
898
- """
899
- MSTL multi-seasonality decomposition.
900
- Now the dedicated STRUCTURE model: consumes nearest_support/resistance,
901
- market_regime, htf_trend_15m/1h, spot vs strike distance.
902
- These were previously unused anywhere.
903
- """
904
  n = len(closes)
905
  if n < 16:
906
- return 0.0, "statsforecast-mstl", "Insufficient"
907
-
908
- # Trend component
909
- win = min(32, n)
910
- x = np.arange(win); y = closes[-win:]
911
- trend_coef = np.polyfit(x, y, 1)[0]
912
- trend_sl = trend_coef / closes[-1] if closes[-1] != 0 else 0
913
-
914
- # Seasonal: 5-bar and 12-bar cycles
915
- seasonal = 0.0
916
- for period in [5, 12]:
917
- if n >= period * 2:
918
- cycle = closes[-period * 2:]
919
- s1 = float(np.mean(cycle[:period])); s2 = float(np.mean(cycle[period:]))
920
- if s1 != 0: seasonal += (s2 - s1) / s1 * 0.5
921
-
922
- # Mean-reversion residual
923
- ma10 = float(np.mean(closes[-10:])) if n >= 10 else closes[-1]
924
- dev = (closes[-1] - ma10) / ma10 if ma10 != 0 else 0
925
- mean_rev = -math.tanh(dev * 30) * 0.04
926
-
927
- # Vol regime dampener
928
- if req.vol_regime == "EXTREME":
929
- trend_sl *= 0.5; seasonal *= 0.5
930
- elif req.vol_regime == "HIGH":
931
- trend_sl *= 0.75
932
-
933
- combined = trend_sl * 100 * 0.45 + seasonal * 100 * 0.15 + mean_rev * 100 * 0.15
934
-
935
- # RSI overlay
936
- rsi_adj = 0.0
937
- if req.rsi is not None:
938
- rsi_adj = -math.tanh((req.rsi - 50) / 25) * 0.05 * 100
939
- combined += rsi_adj
940
-
941
- # NEW: Support/resistance proximity
942
- # If price is near support, bias UP; near resistance, bias DOWN
943
- sr_signal = 0.0
944
- price = req.spot or float(closes[-1])
945
- if req.nearest_support is not None and req.nearest_support > 0:
946
- dist_pct = (price - req.nearest_support) / price
947
- sr_signal += math.tanh(-dist_pct * 50) * 0.03 * 100 # close to support = UP
948
- if req.nearest_resistance is not None and req.nearest_resistance > 0:
949
- dist_pct = (req.nearest_resistance - price) / price
950
- sr_signal += math.tanh(-dist_pct * 50) * -0.03 * 100 # close to resistance = DOWN
951
- combined += sr_signal
952
-
953
- # NEW: Market regime
954
- regime_signal = 0.0
955
- if req.market_regime is not None:
956
- mr = req.market_regime.upper()
957
- if "TREND" in mr or "BULL" in mr: regime_signal = 0.025 * 100
958
- if "BEAR" in mr: regime_signal = -0.025 * 100
959
- if "CHOP" in mr or "RANGE" in mr: trend_sl *= 0.5 # chop = don't trust trend
960
- combined += regime_signal
961
-
962
- # NEW: HTF trend from both 15m and 1h
963
- # MSTL as a structure model gives significant weight to HTF
964
- htf15 = _str_sign(req.htf_trend_15m)
965
- htf1h = _str_sign(req.htf_trend_1h)
966
- htf = htf15 * 0.35 + htf1h * 0.65
967
- if htf != 0:
968
- combined += htf * 0.035 * 100 # direct add of HTF bias
969
-
970
- # NEW: Spot vs strike distance (for polymarket binary)
971
- spot_signal = 0.0
972
- if req.spot is not None and req.strike is not None and req.strike > 0:
973
- dist = (req.spot - req.strike) / req.strike
974
- spot_signal = math.tanh(dist / 0.005) * 0.04 * 100
975
- combined += spot_signal
976
-
977
- sp = float(np.clip(combined, -1.8, 1.8))
978
-
979
- return sp, "statsforecast-mstl-structure", (
980
- f"MSTL: trend={trend_sl*100:.4f}% seasonal={seasonal*100:.4f}% "
981
- f"sr={sr_signal:.4f} regime={regime_signal:.4f} htf={htf:.3f} spot={spot_signal:.4f}"
982
- )
983
-
984
-
985
- # ── Model weights ──────────────────────────────────────────────────────────────
986
  STATIC_WEIGHTS = {
987
- "Chronos": 0.13,
988
- "PatchTST": 0.11,
989
- "DAG": 0.13,
990
- "River": 0.09,
991
- "N-BEATS": 0.10,
992
- "AROpt": 0.10,
993
- "TiDE": 0.12,
994
- "Informer": 0.10,
995
- "MOIRAI": 0.08,
996
- "StatsForecast":0.04,
997
  }
998
 
999
 
1000
- # ── FastAPI endpoints ──────────────────────────────────────────────────────────
 
1001
  @app.get("/")
1002
  def health():
1003
  return {
1004
- "ok": True, "chronos": CHRONOS_AVAILABLE, "moirai": MOIRAI_AVAILABLE,
1005
- "version": "16.0.0",
1006
- "signals_consumed": 53,
1007
- "models": list(STATIC_WEIGHTS.keys()),
 
1008
  }
1009
 
1010
 
1011
  @app.post("/omega", response_model=OmegaResponse)
1012
  def omega_forecast(req: OmegaRequest):
1013
- t0 = time.time()
1014
  closes = np.array(req.closes, dtype=np.float64)
1015
  horizon = req.horizon
1016
  results: List[ModelResult] = []
1017
- threshold = get_threshold(req.timeframe, req.vol_regime, req.vol_percentile)
1018
-
1019
- def add(name: str, group: str, slope_pct: float, note: str, reasoning: str,
1020
- is_avail: bool, conf_mult: float = 1.0):
1021
- slope_pct = _vol_dampen(slope_pct, req.vol_regime, req.vol_percentile)
1022
- # Session multiplier on confidence (not direction)
1023
- sess_m = _session_mult(req.session)
1024
- # Candle pattern adjustment
1025
- cp_signal, cp_label = _candle_pattern_adj(req.candle_pattern)
1026
- if cp_signal != 0:
1027
- cp_sign = math.copysign(1, cp_signal)
1028
- our_sign = math.copysign(1, slope_pct) if slope_pct != 0 else 0
1029
- if our_sign != 0 and cp_sign != our_sign:
1030
- slope_pct *= 0.80 # candle pattern disagrees → reduce 20%
1031
- direction, conf = slope_to_direction(slope_pct, threshold)
1032
- conf = min(95.0, conf * conf_mult * sess_m)
1033
  results.append(ModelResult(
1034
  name=name, direction=direction, confidence=conf,
1035
  slope_pct=round(slope_pct, 6), available=is_avail,
1036
- note=note, reasoning=reasoning + (f" | candle={cp_label}" if cp_signal != 0 else ""),
1037
- group=group,
1038
  ))
1039
 
1040
- # ── Run all 10 models ────────────────────────────────────────────────────
 
1041
  runners = [
1042
- ("Chronos", "PRICE", lambda: run_chronos_with_structure(closes, horizon, req)),
1043
- ("PatchTST", "PRICE", lambda: run_patchtst(closes, horizon, req)),
1044
- ("DAG", "ORDERFLOW", lambda: run_dag(closes, req)),
1045
- ("River", "ORDERFLOW", lambda: run_river_snarimax(closes, req)),
1046
- ("N-BEATS", "TECHNICAL", lambda: run_nbeats(closes, horizon, req)),
1047
- ("AROpt", "TECHNICAL", lambda: run_aropt(closes, horizon, req)),
1048
- ("TiDE", "MACRO", lambda: run_tide(closes, req, horizon)),
1049
- ("Informer", "MACRO", lambda: run_informer(closes, req, horizon)),
1050
- ("MOIRAI", "PROB", lambda: run_moirai(closes, horizon, req)),
1051
- ("StatsForecast", "STRUCTURE", lambda: run_statsforecast_mstl(closes, horizon, req)),
1052
  ]
1053
 
1054
- for name, group, fn in runners:
1055
  try:
1056
  sp, note, rsn = fn()
1057
- add(name, group, sp, note, rsn, True)
1058
  except Exception as e:
1059
- # Fallback for Chronos only (heavy model)
1060
- if name == "Chronos":
1061
  try:
1062
- sp, note, rsn = _chronos_holt_fallback(closes, horizon)
1063
- add(name, group, sp, note, rsn + f" | htf applied", False, conf_mult=0.75)
1064
  continue
1065
  except Exception:
1066
  pass
1067
- add(name, group, 0.0, str(e)[:60], f"Error in {name}: {e}", False)
1068
 
1069
- # ── Adaptive weight blending ─────────────────────────────────────────────
1070
- adaptive = req.adaptive_weights or {}
1071
- eff_weights: dict = {}
1072
  for m, sw in STATIC_WEIGHTS.items():
1073
  aw = adaptive.get(m)
1074
  if isinstance(aw, (int, float)) and 0.01 <= aw <= 0.95:
1075
- blend = min(1.0, (adaptive.get("_n_settled", 0) or 0) / 30)
 
1076
  eff_weights[m] = aw * blend + sw * (1 - blend)
1077
  else:
1078
  eff_weights[m] = sw
1079
- tw = sum(eff_weights.values())
1080
- eff_weights = {k: v / tw for k, v in eff_weights.items()}
1081
 
1082
- # ── Anti-bias: group-score normalization ─────────────────────────────────
1083
- group_scores: dict = {}
1084
- group_weights: dict = {}
1085
  for r in results:
1086
  w = eff_weights.get(r.name, 0.0)
1087
  sign = 1.0 if r.direction == "UP" else (-1.0 if r.direction == "DOWN" else 0.0)
1088
- vs = sign * (r.confidence / 100.0) * w
1089
- group_scores[r.group] = group_scores.get(r.group, 0.0) + vs
1090
- group_weights[r.group] = group_weights.get(r.group, 0.0) + w
1091
-
1092
- norm_group: dict = {}
1093
- for g, gs in group_scores.items():
1094
- gw = group_weights.get(g, 1.0)
1095
- norm_group[g] = gs / gw if gw > 0 else 0.0
1096
-
1097
- # Dominant group check
1098
- dominant_group = max(norm_group, key=lambda g: abs(norm_group[g])) if norm_group else "NONE"
1099
- anti_bias_applied = False
1100
- dom_score = norm_group.get(dominant_group, 0.0)
1101
- others = [v for g, v in norm_group.items() if g != dominant_group]
1102
- if abs(dom_score) > 0.60 and others and all(
1103
- math.copysign(1, dom_score) != math.copysign(1, v) for v in others if abs(v) > 0.1
1104
- ):
1105
- # One group is strongly dominant but others disagree → dampen dominant group models
1106
- anti_bias_applied = True
1107
- for r in results:
1108
- if r.group == dominant_group:
1109
- r.confidence = round(r.confidence * 0.65, 2)
1110
-
1111
- # ── Final composite ───────────────────────────────────────────────────────
1112
- composite_score = 0.0
1113
- for r in results:
1114
- w = eff_weights.get(r.name, 0.0)
1115
- sign = 1.0 if r.direction == "UP" else (-1.0 if r.direction == "DOWN" else 0.0)
1116
- composite_score += sign * (r.confidence / 100.0) * w
1117
-
1118
- comp_dir, comp_conf = slope_to_direction(composite_score * 0.15 * 100, threshold * 0.5)
1119
- if comp_dir == "NEUTRAL":
1120
- # Check if one side has clear majority even if small
1121
- up_w = sum(eff_weights.get(r.name, 0) for r in results if r.direction == "UP")
1122
- down_w = sum(eff_weights.get(r.name, 0) for r in results if r.direction == "DOWN")
1123
- if up_w > 0.60: comp_dir = "UP"; comp_conf = 52.0
1124
- elif down_w > 0.60: comp_dir = "DOWN"; comp_conf = 52.0
1125
 
1126
  return OmegaResponse(
1127
- composite_direction = comp_dir,
1128
- composite_confidence = round(comp_conf, 2),
1129
- composite_score = round(composite_score, 6),
1130
- models = results,
1131
- elapsed_ms = int((time.time() - t0) * 1000),
1132
- timeframe = req.timeframe,
1133
- anti_bias_applied = anti_bias_applied,
1134
- dominant_group = dominant_group,
1135
  )
 
1
  """
2
+ PolyBloom ML Ensemble Service v14.1 — OMEGA COUNCIL (8 Models)
3
+
4
+ FIXES in v14.1:
5
+ 1. slope_to_direction: per-timeframe thresholds (was hardcoded 0.008% for all TFs)
6
+ 5M=0.003%, 15M=0.005%, 1D=0.018% — calibrated to actual BTC intraday move size
7
+ This was the root cause of Chronos/PatchTST always showing NEUTRAL
8
+
9
+ 2. add() closure: uses tf_threshold from SLOPE_THRESHOLDS instead of hardcoded 0.008
10
+
11
+ 3. run_chronos_fallback: blends in RSI mean-reversion + funding fade to prevent
12
+ pure-trend UP bias when Chronos model is unavailable
13
+
14
+ 4. run_tabpfn / run_patchtst: added bearish context signals (RSI, funding, CVD)
15
+ so these models can output DOWN even when price trend is flat-to-up
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ 5. Composite NEUTRAL threshold tightened: NEUTRAL only fires when truly mixed,
18
+ not whenever the score is merely small
19
+ """
20
+ import os, time, math
21
  from typing import List, Optional, Tuple
22
  import numpy as np
23
  from fastapi import FastAPI
24
  from fastapi.middleware.cors import CORSMiddleware
25
  from pydantic import BaseModel, Field
26
 
 
27
  try:
28
  from chronos import ChronosPipeline
29
  import torch
 
41
  CHRONOS_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-small")
42
  MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
43
 
44
+ app = FastAPI(title="PolyBloom ML Ensemble v14.1", version="14.1.0")
45
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
 
 
46
 
47
  _chronos = None
48
  _moirai = None
 
67
  return _moirai
68
 
69
 
70
+ # ── Request / Response models ─────────────────────────────────────────────────
71
+
72
  class OmegaRequest(BaseModel):
73
+ closes: List[float] = Field(..., min_length=16)
74
+ highs: Optional[List[float]] = None
75
+ lows: Optional[List[float]] = None
76
+ volumes: Optional[List[float]] = None
77
+ horizon: int = Field(3, ge=1, le=12)
78
+ timeframe: str = Field("5M")
79
+ funding: Optional[float] = None
80
+ ob_imbal: Optional[float] = None
81
+ cvd: Optional[float] = None
82
+ taker_buy_ratio: Optional[float] = None
83
+ rsi: Optional[float] = None
84
+ macd: Optional[str] = None
85
+ ema_align: Optional[str] = None
86
+ vwap_dev: Optional[float] = None
87
+ vol_regime: Optional[str] = None
88
+ spot: Optional[float] = None
89
+ strike: Optional[float] = None
90
+ nearest_support: Optional[float] = None
91
+ nearest_resistance:Optional[float] = None
92
+ market_regime: Optional[str] = None
93
+ htf_trend_15m: Optional[str] = None
94
+ htf_trend_1h: Optional[str] = None
95
+ open_interest: Optional[float] = None
96
+ ls_ratio: Optional[float] = None
97
+ fear_greed: Optional[float] = None
98
+ dxy_change_pct: Optional[float] = None
99
+ nasdaq_fut_change_pct: Optional[float] = None
100
+ polymarket_yes: Optional[float] = None
101
+ chainlink_price: Optional[float] = None
102
+ sentiment_polarity:Optional[float] = None
103
+ session: Optional[str] = None
104
+ adaptive_weights: Optional[dict] = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  class Config:
107
  extra = "allow"
108
 
 
109
  class ModelResult(BaseModel):
110
  name: str
111
  direction: str
 
114
  available: bool
115
  note: str
116
  reasoning: str
 
 
117
 
118
  class OmegaResponse(BaseModel):
119
  composite_direction: str
 
123
  elapsed_ms: int
124
  timeframe: str
125
  anti_bias_applied: bool
 
126
 
127
 
128
+ # ── FIX 1: Per-timeframe slope thresholds ────────────────────────────────────
129
+ # Old: hardcoded 0.008% for every timeframe.
130
+ # At $100k BTC, Chronos T5 median forecast moves ~$3–8 over 2 candles = 0.003–0.008%.
131
+ # Hardcoded 0.008 meant the majority of 5M Chronos outputs triggered NEUTRAL.
132
+ # New: calibrated to actual BTC intraday volatility per timeframe.
133
+ SLOPE_THRESHOLDS = {
134
+ "5M": 0.003, # $3 move at $100k — realistic 2-candle forecast range
135
+ "15M": 0.005, # $5 move — slightly larger 15-min window
136
+ "1D": 0.018, # $18 move — daily forecast has wider range
137
+ }
138
+
139
+ def slope_to_direction(slope_pct: float, threshold: float = 0.003) -> Tuple[str, float]:
140
+ """Convert a forecast slope percentage to a direction + confidence."""
141
+ if abs(slope_pct) < threshold:
142
+ return "NEUTRAL", 50.0
143
+ # Confidence scales more steeply: 2× the threshold = meaningful boost
144
+ conf = min(95.0, 50.0 + (abs(slope_pct) / threshold - 1.0) * 12.0)
145
+ return ("UP" if slope_pct > 0 else "DOWN"), conf
146
+
147
+
148
+ # ── Helper: EMA ───────────────────────────────────────────────────────────────
149
+
150
  def ema(arr: np.ndarray, period: int) -> float:
151
  if len(arr) < period:
152
  return float(np.mean(arr))
 
157
  return val
158
 
159
 
160
+ # ── Helper: Context score from exogenous signals ──────────────────────────────
161
+ # Used by TiDE, MOIRAI, and fallbacks to incorporate market context beyond price.
162
+ # Returns a score in roughly -1..+1 where positive = bullish context.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ def build_context_score(req: OmegaRequest) -> float:
165
+ score = 0.0
166
+ count = 0
167
+ if req.funding is not None:
168
+ # High positive funding = longs crowded = bearish fade
169
+ score += -math.tanh(req.funding * 10000) * 0.3
170
+ count += 1
171
+ if req.cvd is not None:
172
+ score += math.tanh(req.cvd / 50_000_000) * 0.4
173
+ count += 1
174
+ if req.ob_imbal is not None:
175
+ score += math.tanh(req.ob_imbal * 2) * 0.3
176
+ count += 1
177
+ if req.taker_buy_ratio is not None:
178
+ score += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.25
179
+ count += 1
180
+ if req.rsi is not None:
181
+ # RSI mean-reversion: overbought = bearish, oversold = bullish
182
+ score += -math.tanh((req.rsi - 50) / 20) * 0.2
183
+ count += 1
184
+ if req.sentiment_polarity is not None:
185
+ score += math.tanh(req.sentiment_polarity * 2) * 0.15
186
+ count += 1
187
+ if req.fear_greed is not None:
188
+ score += -math.tanh((req.fear_greed - 50) / 25) * 0.1
189
+ count += 1
190
+ if req.dxy_change_pct is not None:
191
+ score += math.tanh(-req.dxy_change_pct / 0.5) * 0.15
192
+ count += 1
193
+ if req.nasdaq_fut_change_pct is not None:
194
+ score += math.tanh(req.nasdaq_fut_change_pct / 0.5) * 0.1
195
+ count += 1
196
+ if req.chainlink_price is not None and req.strike is not None and req.strike > 0:
197
+ drift = (req.chainlink_price - req.strike) / req.strike
198
+ score += math.tanh(drift / 0.001) * 0.5
199
+ count += 1
200
+ return score / max(1, count)
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
+ # ── Model runners ─────────────────────────────────────────────────────────────
204
 
205
+ def run_chronos(closes, horizon):
206
+ """Real Chronos T5 inference via HuggingFace."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  pipe = get_chronos()
208
  if pipe is None:
209
+ raise RuntimeError("not loaded")
210
+ context = torch.tensor(closes[-64:]).unsqueeze(0)
211
+ forecast = pipe.predict(context, prediction_length=horizon)
212
+ median = np.quantile(forecast[0].numpy(), 0.5, axis=0)
213
+ p10 = np.quantile(forecast[0].numpy(), 0.1, axis=0)
214
+ p90 = np.quantile(forecast[0].numpy(), 0.9, axis=0)
215
+ slope_pct = (float(median[-1]) - float(closes[-1])) / float(closes[-1]) * 100
216
+ uncertainty = float(p90[-1] - p10[-1]) / float(closes[-1]) * 100
217
+ return slope_pct, "amazon/chronos-t5-small", \
218
+ f"Chronos T5: median={float(median[-1]):.2f}, uncertainty={uncertainty:.4f}%."
219
+
220
+
221
+ def run_chronos_fallback(closes, horizon, req=None):
 
 
 
 
 
 
 
 
222
  """
223
+ Holt-Winters fallback when Chronos model is unavailable.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
+ FIX v14.1: Blends in RSI mean-reversion + funding fade to prevent
226
+ pure price-trend UP bias. Without this, the fallback always trended
227
+ UP whenever BTC had a positive recent slope (which is ~60% of sessions).
228
+ """
229
+ n = len(closes)
230
+ if n < 4:
231
+ return 0.0, "holt-winters-fallback", "Insufficient data"
232
 
233
+ # Holt-Winters double exponential smoothing
234
  alpha, beta = 0.3, 0.2
235
+ level = float(closes[0])
236
+ trend = float(closes[1] - closes[0]) if n > 1 else 0.0
237
+ for price in closes[1:]:
238
+ prev_level = level
239
+ level = alpha * float(price) + (1 - alpha) * (level + trend)
240
+ trend = beta * (level - prev_level) + (1 - beta) * trend
241
+ fval = level + trend * horizon
242
+ slope_pct = (fval - float(closes[-1])) / float(closes[-1]) * 100
243
+
244
+ # FIX: Blend in context signals so fallback can output DOWN
245
+ if req is not None:
246
+ funding = req.funding if req.funding is not None else 0.0
247
+ rsi = req.rsi if req.rsi is not None else 50.0
248
+
249
+ # Funding fade: high positive funding = longs crowded = bearish adj
250
+ if funding > 0.04: funding_adj = -0.020
251
+ elif funding > 0.02: funding_adj = -0.010
252
+ elif funding < -0.025: funding_adj = 0.015
253
+ elif funding < -0.01: funding_adj = 0.007
254
+ else: funding_adj = 0.0
255
+
256
+ # RSI mean-reversion: overbought = bearish adj
257
+ if rsi > 72: rsi_adj = -0.012
258
+ elif rsi > 65: rsi_adj = -0.006
259
+ elif rsi < 28: rsi_adj = 0.012
260
+ elif rsi < 35: rsi_adj = 0.006
261
+ else: rsi_adj = 0.0
262
+
263
+ # Blend: 75% Holt-Winters price trend, 25% context adjustment
264
+ ctx_adj = (funding_adj + rsi_adj) * 100
265
+ slope_pct = slope_pct * 0.75 + ctx_adj * 0.25
266
+
267
+ return slope_pct, "holt-winters-fallback", \
268
+ f"Holt-Winters: level={level:.2f}, trend={trend:.2f}/candle, slope={slope_pct:.4f}%."
269
+
270
+
271
+ def run_tabpfn(closes, horizon, req=None):
272
  """
273
+ TabPFN numeric approximation.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
 
275
+ FIX v14.1: Added RSI, funding, and CVD context so TabPFN can output
276
+ DOWN when price is flat but orderflow is bearish. Previously only used
277
+ price returns which biased toward UP in trending markets.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  """
279
  n = len(closes)
280
+ if n < 8:
281
+ return 0.0, "tabpfn", "Insufficient data"
282
+ last = float(closes[-1])
283
+
284
+ # Price returns
285
+ ret1 = (closes[-1] - closes[-2]) / closes[-2] if n >= 2 else 0.0
286
+ ret3 = (closes[-1] - closes[-4]) / closes[-4] if n >= 4 else 0.0
287
+ ret8 = (closes[-1] - closes[-9]) / closes[-9] if n >= 9 else 0.0
288
+
289
+ # EMA signal
290
+ ema8 = float(np.mean(closes[-8:]))
291
+ ema16 = float(np.mean(closes[-16:])) if n >= 16 else ema8
292
+ ema_sig = (ema8 - ema16) / ema16 if ema16 != 0 else 0.0
293
+
294
+ vol = float(np.std(closes[-8:])) / last if last != 0 else 0.0
295
+
296
+ # Base price score
297
+ price_score = ret1 * 0.40 + ret3 * 0.30 + ret8 * 0.20 + ema_sig * 0.10 - vol * 0.05
298
+
299
+ # FIX: Context adjustment from exogenous signals
300
+ ctx_adj = 0.0
301
+ ctx_n = 0
302
+ if req is not None:
303
+ if req.funding is not None:
304
+ # High funding = crowded longs = fade UP
305
+ ctx_adj += -math.tanh(req.funding * 8000) * 0.3
306
+ ctx_n += 1
307
+ if req.rsi is not None:
308
+ # RSI overbought = mean-reversion bias
309
+ ctx_adj += -math.tanh((req.rsi - 50) / 22) * 0.25
310
+ ctx_n += 1
311
+ if req.cvd is not None:
312
+ ctx_adj += math.tanh(req.cvd / 40_000_000) * 0.2
313
+ ctx_n += 1
314
+ if ctx_n > 0:
315
+ ctx_adj /= ctx_n
316
+
317
+ # Blend: 70% price, 30% context
318
+ combined = price_score * 0.70 + ctx_adj * 0.30
319
+ slope_pct = combined * horizon * 100
320
+
321
+ ctx_note = f", ctx_adj={ctx_adj:.4f}" if ctx_n > 0 else ""
322
+ return slope_pct, "tabpfn-numeric", \
323
+ f"TabPFN: ret1={ret1*100:.4f}%, ret3={ret3*100:.4f}%, ema_sig={ema_sig*100:.4f}%, vol={vol*100:.3f}%{ctx_note}."
324
+
325
+
326
+ def run_dag(closes, req):
327
+ """DAG Granger-causality approximation — uses exogenous signals heavily."""
328
+ n = len(closes)
329
  if n < 8:
330
  return 0.0, "dag", "Insufficient"
331
 
332
+ price_signal = 0.0
333
+ for lag in [1, 2, 3]:
334
+ if n > lag:
335
+ price_signal += (closes[-1] - closes[-(lag+1)]) / closes[-(lag+1)] * (0.5 ** lag)
 
 
336
 
337
+ exog = 0.0
338
+ exog_n = 0
339
  if req.funding is not None:
340
+ exog += -math.tanh(req.funding * 10000) * 0.3
341
+ exog_n += 1
342
  if req.cvd is not None:
343
+ exog += math.tanh(req.cvd / 30_000_000) * 0.4
344
+ exog_n += 1
345
  if req.ob_imbal is not None:
346
+ exog += math.tanh(req.ob_imbal * 2) * 0.3
347
+ exog_n += 1
348
  if req.taker_buy_ratio is not None:
349
+ exog += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.2
 
 
 
 
 
 
 
 
 
 
 
350
  exog_n += 1
351
+ if req.rsi is not None:
352
+ exog += -math.tanh((req.rsi - 50) / 20) * 0.15
353
+ exog_n += 1
354
+ if exog_n > 0:
355
+ exog /= exog_n
356
 
357
+ combined = price_signal * 0.6 + exog * 0.4
358
+ slope_pct = math.tanh(combined) * 0.15 * 100
359
+ return slope_pct, "dag-granger", \
360
+ f"DAG: price_signal={price_signal*100:.4f}%, exog({exog_n})={exog:.4f}, combined={combined:.4f}."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
 
 
 
 
 
 
 
 
 
362
 
363
+ def run_aropt(closes, horizon):
364
+ """Autoregressive model via least-squares fitting."""
365
+ n = len(closes)
366
+ order = min(6, n - 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  if order < 2:
368
  return 0.0, "aropt", "Insufficient"
369
+ y = closes[order:]
370
+ X = np.column_stack([closes[i:n - order + i] for i in range(order)])
371
  if len(y) < 2:
372
  return 0.0, "aropt", "Insufficient pairs"
373
  try:
374
  coeffs, *_ = np.linalg.lstsq(X, y, rcond=None)
375
  except np.linalg.LinAlgError:
376
  return 0.0, "aropt", "lstsq failed"
377
+ window = list(closes[-order:])
 
378
  forecast = []
379
  for _ in range(horizon):
380
  nv = float(np.dot(coeffs, window[-order:]))
381
+ forecast.append(nv)
382
+ window.append(nv)
383
+ slope_pct = (forecast[-1] - float(closes[-1])) / float(closes[-1]) * 100
384
+ return slope_pct, "aropt-ls", \
385
+ f"AR({order}) lstsq: coeffs[:3]={[round(float(c),4) for c in coeffs[:3]]}, slope={slope_pct:.4f}%."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
 
 
 
 
387
 
388
+ def run_patchtst(closes, horizon, req=None):
389
+ """
390
+ PatchTST numeric approximation.
391
 
392
+ FIX v14.1: Added funding fade + RSI context so PatchTST can output DOWN.
393
+ Previously relied only on patch-weighted returns which bias UP in uptrends.
394
+ """
395
+ n = len(closes)
396
+ patch_size = 8
397
+ n_patches = n // patch_size
398
+ if n_patches < 2:
399
+ return 0.0, "patchtst", "Insufficient"
400
 
401
+ patches = []
402
+ for i in range(n_patches):
403
+ seg = closes[i * patch_size:(i + 1) * patch_size]
404
+ pr = (seg[-1] - seg[0]) / seg[0] if seg[0] != 0 else 0.0
405
+ pv = float(np.std(seg)) / float(np.mean(seg)) if np.mean(seg) != 0 else 0.0
406
+ patches.append((pr, pv))
407
 
408
+ raw_weights = np.array([math.exp(0.4 * i) for i in range(len(patches))])
409
+ att = raw_weights / raw_weights.sum()
410
+ weighted_return = sum(p[0] * w for p, w in zip(patches, att))
411
+ mean_vol = np.mean([p[1] for p in patches[-3:]])
412
+ vol_penalty = min(0.5, mean_vol * 10)
413
+ price_slope = weighted_return * horizon * 100 * (1 - vol_penalty)
414
+
415
+ # FIX: Context adjustment — funding fade + RSI overbought
416
+ ctx_adj = 0.0
417
+ ctx_n = 0
418
+ if req is not None:
419
+ if req.funding is not None:
420
+ ctx_adj += -math.tanh(req.funding * 9000) * 0.35
421
+ ctx_n += 1
422
+ if req.rsi is not None:
423
+ ctx_adj += -math.tanh((req.rsi - 50) / 20) * 0.30
424
+ ctx_n += 1
425
+ if req.cvd is not None:
426
+ ctx_adj += math.tanh(req.cvd / 35_000_000) * 0.20
427
+ ctx_n += 1
428
+ if ctx_n > 0:
429
+ ctx_adj /= ctx_n
430
+
431
+ # Blend: 72% price patches, 28% context
432
+ slope_pct = price_slope * 0.72 + (ctx_adj * 100) * 0.28
433
+
434
+ ctx_note = f", ctx_adj={ctx_adj:.4f}" if ctx_n > 0 else ""
435
+ return slope_pct, "patchtst-numeric", \
436
+ f"PatchTST: {n_patches} patches, weighted_ret={weighted_return*100:.4f}%, vol_penalty={vol_penalty:.3f}{ctx_note}."
437
+
438
+
439
+ def run_tide(closes, req, horizon):
440
+ """TiDE — time-series dense encoder, blends price trend + context signals."""
441
  n = len(closes)
442
  if n < 16:
443
  return 0.0, "tide", "Insufficient"
444
+ sl5 = (closes[-1] - closes[-6]) / closes[-6] if n >= 6 else 0.0
445
+ sl20 = (closes[-1] - closes[-21]) / closes[-21] if n >= 21 else 0.0
446
+ e8 = ema(closes[-20:], 8)
447
+ e20 = ema(closes[-40:], 20)
448
+ ts_signal = sl5 * 0.6 + sl20 * 0.4 + ((e8 - e20) / e20 * 0.3 if e20 != 0 else 0)
449
+ cov_signal = build_context_score(req)
450
+ combined = ts_signal * 0.55 + cov_signal * 0.45
451
+ slope_pct = math.tanh(combined * 3) * 0.12 * 100
452
+ return slope_pct, "tide-numeric", \
453
+ f"TiDE: ts={ts_signal*100:.4f}%, cov={cov_signal:.4f}, combined={combined:.4f}, slope={slope_pct:.4f}%."
454
+
455
+
456
+ def run_moirai(closes, horizon, req):
457
+ """MOIRAI — Salesforce probabilistic forecaster with bootstrap fallback."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  model = get_moirai()
459
  if model is not None:
460
  try:
461
+ ctx = th.tensor(closes[-64:], dtype=th.float32).unsqueeze(0).unsqueeze(-1)
462
  samples = model.predict(ctx)
463
+ arr = samples.squeeze().numpy()
464
+ if arr.ndim == 1:
465
+ arr = arr.reshape(1, -1)
466
+ median = float(np.median(arr[:, -1]))
467
+ p10 = float(np.percentile(arr[:, -1], 10))
468
+ p90 = float(np.percentile(arr[:, -1], 90))
469
+ slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
470
+ uncertainty = (p90 - p10) / float(closes[-1]) * 100
471
+ return slope_pct, "moirai-salesforce", \
472
+ f"MOIRAI: median={median:.2f}, uncertainty={uncertainty:.4f}%."
473
  except Exception:
474
+ pass
475
+
476
+ # Bootstrap fallback
477
+ n = len(closes)
478
+ returns = np.diff(closes) / closes[:-1]
479
+ if len(returns) < 5:
480
+ return 0.0, "moirai", "Insufficient"
481
+ rng = np.random.default_rng(seed=42)
482
+ samples = []
483
+ for _ in range(200):
484
+ path = float(closes[-1])
485
+ for _ in range(horizon):
486
+ path *= (1 + rng.choice(returns[-50:]))
487
+ samples.append(path)
488
+ median = float(np.median(samples))
489
+ p10 = float(np.percentile(samples, 10))
490
+ p90 = float(np.percentile(samples, 90))
491
+ slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
492
+ uncertainty = (p90 - p10) / float(closes[-1]) * 100
493
+ ctx_score = build_context_score(req)
494
+ slope_pct += ctx_score * 0.05 * 100
495
+ return slope_pct, "moirai-bootstrap", \
496
+ f"MOIRAI bootstrap: median={median:.2f}, uncertainty={uncertainty:.4f}%, ctx={ctx_score:.4f}."
497
+
498
+
499
+ def run_nbeats(closes, horizon):
500
+ """N-BEATS: polynomial trend + FFT seasonal + residual momentum."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
  n = len(closes)
502
  if n < 16:
503
+ return 0.0, "nbeats", "Insufficient"
504
+ x = np.arange(min(32, n))
505
+ y = closes[-len(x):]
506
+ try:
507
+ poly2 = np.polyfit(x, y, 2)
508
+ x_next = np.arange(len(x), len(x) + horizon)
509
+ trend_forecast = np.polyval(poly2, x_next)
510
+ trend_slope = (trend_forecast[-1] - float(closes[-1])) / float(closes[-1]) * 100
511
+ except Exception:
512
+ trend_slope = 0.0
513
+ trend_forecast = np.full(horizon, closes[-1])
514
+
515
+ if n >= 32:
516
+ fft = np.fft.rfft(closes[-32:] - np.mean(closes[-32:]))
517
+ dominant_freq = np.argmax(np.abs(fft[1:])) + 1
518
+ period = 32 / dominant_freq if dominant_freq > 0 else 32
519
+ phase = (n % period) / period * 2 * math.pi
520
+ seasonal_signal = math.sin(phase + math.pi / 2)
521
+ else:
522
+ seasonal_signal = 0.0
523
+ period = 32.0
524
+
525
+ residual = (closes[-1] - closes[-5]) / closes[-5] if n >= 5 else 0.0
526
+ slope_pct = trend_slope * 0.7 + seasonal_signal * 0.03 * 100 + float(residual) * 30
527
+ slope_pct = float(np.clip(slope_pct, -1.0, 1.0))
528
+ return slope_pct, "nbeats-numeric", \
529
+ f"N-BEATS: trend={trend_slope:.4f}%, seasonal(period≈{period:.1f})={seasonal_signal:.3f}, residual={float(residual)*100:.4f}%."
530
+
531
+
532
+ # ── Static model weights ──────────────────────────────────────────────────────
533
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  STATIC_WEIGHTS = {
535
+ "Chronos": 0.18,
536
+ "TabPFN-TS": 0.14,
537
+ "DAG": 0.16,
538
+ "AROpt": 0.12,
539
+ "PatchTST": 0.15,
540
+ "TiDE": 0.13,
541
+ "MOIRAI": 0.07,
542
+ "N-BEATS": 0.05,
 
 
543
  }
544
 
545
 
546
+ # ── Endpoints ─────────────────────────────────────────────────────────────────
547
+
548
  @app.get("/")
549
  def health():
550
  return {
551
+ "ok": True,
552
+ "chronos": CHRONOS_AVAILABLE,
553
+ "moirai": MOIRAI_AVAILABLE,
554
+ "version": "14.1.0",
555
+ "models": list(STATIC_WEIGHTS.keys()),
556
  }
557
 
558
 
559
  @app.post("/omega", response_model=OmegaResponse)
560
  def omega_forecast(req: OmegaRequest):
561
+ t0 = time.time()
562
  closes = np.array(req.closes, dtype=np.float64)
563
  horizon = req.horizon
564
  results: List[ModelResult] = []
565
+
566
+ # FIX 2: Use per-timeframe threshold instead of hardcoded 0.008
567
+ tf_threshold = SLOPE_THRESHOLDS.get(req.timeframe, 0.003)
568
+
569
+ def add(name, slope_pct, note, reasoning, is_avail, threshold=None, conf_mult=1.0):
570
+ # FIX: threshold defaults to tf_threshold (was hardcoded 0.008)
571
+ t = threshold if threshold is not None else tf_threshold
572
+ direction, conf = slope_to_direction(slope_pct, t)
573
+ conf = min(95.0, conf * conf_mult)
 
 
 
 
 
 
 
574
  results.append(ModelResult(
575
  name=name, direction=direction, confidence=conf,
576
  slope_pct=round(slope_pct, 6), available=is_avail,
577
+ note=note, reasoning=reasoning,
 
578
  ))
579
 
580
+ # FIX 3: Pass req into tabpfn, patchtst, and chronos fallback so they
581
+ # can use RSI/funding/CVD context to output DOWN when appropriate
582
  runners = [
583
+ ("Chronos", lambda: run_chronos(closes, horizon),
584
+ lambda: run_chronos_fallback(closes, horizon, req)),
585
+ ("TabPFN-TS", lambda: run_tabpfn(closes, horizon, req), None),
586
+ ("DAG", lambda: run_dag(closes, req), None),
587
+ ("AROpt", lambda: run_aropt(closes, horizon), None),
588
+ ("PatchTST", lambda: run_patchtst(closes, horizon, req), None),
589
+ ("TiDE", lambda: run_tide(closes, req, horizon), None),
590
+ ("MOIRAI", lambda: run_moirai(closes, horizon, req), None),
591
+ ("N-BEATS", lambda: run_nbeats(closes, horizon), None),
 
592
  ]
593
 
594
+ for name, fn, fb in runners:
595
  try:
596
  sp, note, rsn = fn()
597
+ add(name, sp, note, rsn, True)
598
  except Exception as e:
599
+ if fb is not None:
 
600
  try:
601
+ sp, note, rsn = fb()
602
+ add(name, sp, note, rsn, False, conf_mult=0.75)
603
  continue
604
  except Exception:
605
  pass
606
+ add(name, 0.0, str(e)[:60], f"Error in {name}", False)
607
 
608
+ # ── Adaptive weight blending ──────────────────────────────────────────────
609
+ adaptive = req.adaptive_weights or {}
610
+ eff_weights = {}
611
  for m, sw in STATIC_WEIGHTS.items():
612
  aw = adaptive.get(m)
613
  if isinstance(aw, (int, float)) and 0.01 <= aw <= 0.95:
614
+ n_settled = adaptive.get("_n_settled", 0) or 0
615
+ blend = min(1.0, n_settled / 30)
616
  eff_weights[m] = aw * blend + sw * (1 - blend)
617
  else:
618
  eff_weights[m] = sw
619
+ total_w = sum(eff_weights.values())
620
+ eff_weights = {k: v / total_w for k, v in eff_weights.items()}
621
 
622
+ # ── Composite scoring ─────────────────────────────────────────────────────
623
+ composite = 0.0
624
+ total_weight = 0.0
625
  for r in results:
626
  w = eff_weights.get(r.name, 0.0)
627
  sign = 1.0 if r.direction == "UP" else (-1.0 if r.direction == "DOWN" else 0.0)
628
+ composite += sign * (r.confidence / 100.0) * w
629
+ total_weight += w
630
+ comp_score = composite / total_weight if total_weight > 0 else 0.0
631
+
632
+ # ── Composite direction + confidence ──────────────────────────────────────
633
+ # FIX: NEUTRAL threshold tightened to match the new per-TF model thresholds.
634
+ # Old: fixed 0.03 regardless of timeframe.
635
+ # New: consistent with how individual models are thresholded.
636
+ COMPOSITE_THRESHOLD = {
637
+ "5M": 0.018, # tighter — 5M signals are higher frequency
638
+ "15M": 0.015,
639
+ "1D": 0.012,
640
+ }.get(req.timeframe, 0.018)
641
+
642
+ if abs(comp_score) < COMPOSITE_THRESHOLD:
643
+ comp_dir = "NEUTRAL"
644
+ comp_conf = 50.0 + abs(comp_score) / COMPOSITE_THRESHOLD * 10.0
645
+ else:
646
+ comp_dir = "UP" if comp_score > 0 else "DOWN"
647
+ comp_conf = min(95.0, 50.0 + abs(comp_score) / 0.3 * 45.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
648
 
649
  return OmegaResponse(
650
+ composite_direction=comp_dir,
651
+ composite_confidence=round(comp_conf, 1),
652
+ composite_score=round(comp_score, 4),
653
+ models=results,
654
+ elapsed_ms=int((time.time() - t0) * 1000),
655
+ timeframe=req.timeframe,
656
+ anti_bias_applied=abs(comp_score) > 0.001,
 
657
  )