Naufal Arhab commited on
Commit
0cd5796
·
1 Parent(s): ec3e8eb

feat: implement conviction streak system and fix UI text truncation

Browse files
backend/database/db.py CHANGED
@@ -61,9 +61,20 @@ def _format_row(row: dict | None) -> dict | None:
61
  d["signal_data"] = json.loads(d["signal_data"])
62
  except Exception:
63
  pass
 
 
 
 
 
64
  for bool_col in ("on_binance", "on_bybit", "on_okx", "on_hyperliquid", "is_active"):
65
  if bool_col in d and d[bool_col] is not None:
66
  d[bool_col] = bool(d[bool_col])
 
 
 
 
 
 
67
  return d
68
 
69
 
@@ -77,6 +88,9 @@ def init_db() -> None:
77
  cur.execute("""
78
  ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_okx BOOLEAN DEFAULT FALSE;
79
  ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_hyperliquid BOOLEAN DEFAULT FALSE;
 
 
 
80
  """)
81
  except Exception as e:
82
  logger.warning("Postgres schema add column note: %s", e)
@@ -174,6 +188,25 @@ def db_update_pair_exchanges(
174
  return _format_row(row)
175
 
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  def db_delete_pair(symbol: str) -> bool:
178
  with get_connection() as conn:
179
  with conn.cursor() as cur:
@@ -255,9 +288,14 @@ def db_get_latest_signals() -> list[dict]:
255
  with get_connection() as conn:
256
  with conn.cursor() as cur:
257
  cur.execute(
258
- """SELECT DISTINCT ON (symbol) *
259
- FROM signals
260
- ORDER BY symbol, id DESC"""
 
 
 
 
 
261
  )
262
  rows = cur.fetchall()
263
  return [_format_row(r) for r in rows]
@@ -278,7 +316,10 @@ def db_get_latest_signal(symbol: str) -> dict | None:
278
  with get_connection() as conn:
279
  with conn.cursor() as cur:
280
  cur.execute(
281
- "SELECT * FROM signals WHERE symbol = %s ORDER BY id DESC LIMIT 1",
 
 
 
282
  (symbol,),
283
  )
284
  row = cur.fetchone()
@@ -375,6 +416,16 @@ async def async_update_pair_exchanges(
375
  db_update_pair_exchanges, symbol, on_binance, on_bybit, on_okx, on_hyperliquid
376
  )
377
 
 
 
 
 
 
 
 
 
 
 
378
  async def async_delete_pair(symbol: str) -> bool:
379
  return await asyncio.to_thread(db_delete_pair, symbol)
380
 
 
61
  d["signal_data"] = json.loads(d["signal_data"])
62
  except Exception:
63
  pass
64
+ if isinstance(d.get("signal_data"), dict):
65
+ if "streak" not in d["signal_data"] or d["signal_data"].get("streak") is None:
66
+ d["signal_data"]["streak"] = int(d.get("streak_count") or 0)
67
+ if "streak_direction" not in d["signal_data"] or not d["signal_data"].get("streak_direction"):
68
+ d["signal_data"]["streak_direction"] = str(d.get("streak_direction") or "NEUTRAL")
69
  for bool_col in ("on_binance", "on_bybit", "on_okx", "on_hyperliquid", "is_active"):
70
  if bool_col in d and d[bool_col] is not None:
71
  d[bool_col] = bool(d[bool_col])
72
+ if "streak_count" in d and d["streak_count"] is not None:
73
+ d["streak_count"] = int(d["streak_count"])
74
+ if "last_conviction" in d and d["last_conviction"] is not None:
75
+ d["last_conviction"] = int(d["last_conviction"])
76
+ if "streak_direction" in d and d["streak_direction"] is not None:
77
+ d["streak_direction"] = str(d["streak_direction"])
78
  return d
79
 
80
 
 
88
  cur.execute("""
89
  ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_okx BOOLEAN DEFAULT FALSE;
90
  ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_hyperliquid BOOLEAN DEFAULT FALSE;
91
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_count INTEGER DEFAULT 0;
92
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_direction TEXT DEFAULT 'NEUTRAL';
93
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS last_conviction INTEGER DEFAULT 0;
94
  """)
95
  except Exception as e:
96
  logger.warning("Postgres schema add column note: %s", e)
 
188
  return _format_row(row)
189
 
190
 
191
+ def db_update_pair_streak(
192
+ symbol: str,
193
+ streak_count: int,
194
+ streak_direction: str,
195
+ last_conviction: int,
196
+ ) -> dict | None:
197
+ with get_connection() as conn:
198
+ with conn.cursor() as cur:
199
+ cur.execute(
200
+ """UPDATE pairs
201
+ SET streak_count = %s, streak_direction = %s, last_conviction = %s
202
+ WHERE symbol = %s
203
+ RETURNING *""",
204
+ (int(streak_count), str(streak_direction), int(last_conviction), symbol),
205
+ )
206
+ row = cur.fetchone()
207
+ return _format_row(row)
208
+
209
+
210
  def db_delete_pair(symbol: str) -> bool:
211
  with get_connection() as conn:
212
  with conn.cursor() as cur:
 
288
  with get_connection() as conn:
289
  with conn.cursor() as cur:
290
  cur.execute(
291
+ """SELECT DISTINCT ON (s.symbol)
292
+ s.*,
293
+ p.streak_count,
294
+ p.streak_direction,
295
+ p.last_conviction
296
+ FROM signals s
297
+ LEFT JOIN pairs p ON p.symbol = s.symbol
298
+ ORDER BY s.symbol, s.id DESC"""
299
  )
300
  rows = cur.fetchall()
301
  return [_format_row(r) for r in rows]
 
316
  with get_connection() as conn:
317
  with conn.cursor() as cur:
318
  cur.execute(
319
+ """SELECT s.*, p.streak_count, p.streak_direction, p.last_conviction
320
+ FROM signals s
321
+ LEFT JOIN pairs p ON p.symbol = s.symbol
322
+ WHERE s.symbol = %s ORDER BY s.id DESC LIMIT 1""",
323
  (symbol,),
324
  )
325
  row = cur.fetchone()
 
416
  db_update_pair_exchanges, symbol, on_binance, on_bybit, on_okx, on_hyperliquid
417
  )
418
 
419
+ async def async_update_pair_streak(
420
+ symbol: str,
421
+ streak_count: int,
422
+ streak_direction: str,
423
+ last_conviction: int,
424
+ ) -> dict | None:
425
+ return await asyncio.to_thread(
426
+ db_update_pair_streak, symbol, streak_count, streak_direction, last_conviction
427
+ )
428
+
429
  async def async_delete_pair(symbol: str) -> bool:
430
  return await asyncio.to_thread(db_delete_pair, symbol)
431
 
backend/database/models.py CHANGED
@@ -11,6 +11,9 @@ CREATE TABLE IF NOT EXISTS pairs (
11
  on_bybit BOOLEAN DEFAULT FALSE,
12
  on_okx BOOLEAN DEFAULT FALSE,
13
  on_hyperliquid BOOLEAN DEFAULT FALSE,
 
 
 
14
  is_active BOOLEAN DEFAULT TRUE,
15
  created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
16
  );
 
11
  on_bybit BOOLEAN DEFAULT FALSE,
12
  on_okx BOOLEAN DEFAULT FALSE,
13
  on_hyperliquid BOOLEAN DEFAULT FALSE,
14
+ streak_count INTEGER DEFAULT 0,
15
+ streak_direction TEXT DEFAULT 'NEUTRAL',
16
+ last_conviction INTEGER DEFAULT 0,
17
  is_active BOOLEAN DEFAULT TRUE,
18
  created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
19
  );
backend/exchanges/okx.py CHANGED
@@ -110,35 +110,33 @@ class OKXClient(BaseExchange):
110
  logger.warning("[OKX] Symbol discovery failed: %s", exc)
111
 
112
  async def check_symbol_exists(self, symbol: str) -> bool:
113
- # 1. Fast in-memory check
 
 
 
 
114
  if self.resolve_inst_id(symbol):
115
  return True
116
 
117
- # 2. Direct lightweight probe fallback
118
- for var in get_symbol_variations(symbol):
119
- for quote in ("USDT", "USDC", "USD"):
120
- inst_cand = f"{var}-{quote}-SWAP" if not var.endswith(quote) else f"{var[:-len(quote)]}-{quote}-SWAP"
121
- try:
122
- resp = await self._client.get(
123
- "/api/v5/market/ticker",
124
- params={"instId": inst_cand},
125
- timeout=4.0,
126
- )
127
- if resp.status_code == 200:
128
- data = resp.json()
129
- if data.get("code") == "0" and len(data.get("data", [])) > 0:
130
- self._known_symbols.add(symbol.upper())
131
- self._inst_map[symbol.upper()] = inst_cand
132
- self._inst_map[var.upper()] = inst_cand
133
- return True
134
- except Exception:
135
- pass
136
-
137
- # 3. If known symbols empty, trigger load
138
- if not self._known_symbols:
139
- await self._load_symbols()
140
- if self.resolve_inst_id(symbol):
141
- return True
142
 
143
  return False
144
 
 
110
  logger.warning("[OKX] Symbol discovery failed: %s", exc)
111
 
112
  async def check_symbol_exists(self, symbol: str) -> bool:
113
+ # 1. Ensure known symbols are loaded first via single bulk call
114
+ if not self._known_symbols:
115
+ await self._load_symbols()
116
+
117
+ # 2. Fast in-memory check
118
  if self.resolve_inst_id(symbol):
119
  return True
120
 
121
+ # 3. Direct lightweight probe fallback (only target most probable instrument IDs)
122
+ clean = symbol.upper().replace("/", "").replace("-", "")
123
+ base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean
124
+ candidates = [f"{base}-USDT-SWAP", f"{clean}-SWAP"]
125
+ for inst_cand in candidates:
126
+ try:
127
+ resp = await self._client.get(
128
+ "/api/v5/market/ticker",
129
+ params={"instId": inst_cand},
130
+ timeout=3.0,
131
+ )
132
+ if resp.status_code == 200:
133
+ data = resp.json()
134
+ if data.get("code") == "0" and len(data.get("data", [])) > 0:
135
+ self._known_symbols.add(symbol.upper())
136
+ self._inst_map[symbol.upper()] = inst_cand
137
+ return True
138
+ except Exception:
139
+ pass
 
 
 
 
 
 
140
 
141
  return False
142
 
backend/main.py CHANGED
@@ -34,6 +34,7 @@ from database.db import (
34
  async_get_pair,
35
  async_insert_pair,
36
  async_update_pair_exchanges,
 
37
  async_prune_old_records,
38
  )
39
  from exchanges.binance import BinanceClient
@@ -134,6 +135,35 @@ async def _process_pair(
134
  logger.error("[%s] Signal computation error: %s", symbol, exc)
135
  return
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  # Persist signal
138
  await async_save_signal(
139
  symbol=symbol,
 
34
  async_get_pair,
35
  async_insert_pair,
36
  async_update_pair_exchanges,
37
+ async_update_pair_streak,
38
  async_prune_old_records,
39
  )
40
  from exchanges.binance import BinanceClient
 
135
  logger.error("[%s] Signal computation error: %s", symbol, exc)
136
  return
137
 
138
+ # Calculate signal streak
139
+ curr_dir = signal.get("direction", "NEUTRAL")
140
+ curr_conv = signal.get("conviction", 0)
141
+ prev_streak = int(pair.get("streak_count", 0)) if pair.get("streak_count") is not None else 0
142
+ prev_dir = str(pair.get("streak_direction", "NEUTRAL")) if pair.get("streak_direction") is not None else "NEUTRAL"
143
+ prev_conv = int(pair.get("last_conviction", 0)) if pair.get("last_conviction") is not None else 0
144
+
145
+ if curr_dir in ("LONG", "SHORT") and curr_conv >= 3:
146
+ if curr_dir == prev_dir and curr_conv >= max(3, prev_conv - 1):
147
+ new_streak = prev_streak + 1
148
+ else:
149
+ new_streak = 1
150
+ else:
151
+ new_streak = 0
152
+
153
+ signal["streak"] = new_streak
154
+ signal["streak_direction"] = curr_dir
155
+
156
+ if new_streak != prev_streak or curr_dir != prev_dir or curr_conv != prev_conv:
157
+ pair["streak_count"] = new_streak
158
+ pair["streak_direction"] = curr_dir
159
+ pair["last_conviction"] = curr_conv
160
+ try:
161
+ updated_p = await async_update_pair_streak(symbol, new_streak, curr_dir, curr_conv)
162
+ if updated_p:
163
+ await broadcast({"type": "pair_updated", "data": updated_p})
164
+ except Exception as exc:
165
+ logger.debug("[%s] Failed to persist streak: %s", symbol, exc)
166
+
167
  # Persist signal
168
  await async_save_signal(
169
  symbol=symbol,
backend/routers/signals.py CHANGED
@@ -13,6 +13,7 @@ from database.db import (
13
  async_save_snapshot,
14
  async_save_snapshots_batch,
15
  async_update_pair_exchanges,
 
16
  )
17
  from engine.signal_engine import SignalEngine
18
  from routers.ws import broadcast
@@ -108,6 +109,32 @@ async def refresh_signal(symbol: str, request: Request):
108
  )
109
  signal = _signal_engine.compute(raw)
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  await async_save_signal(
112
  symbol=sym,
113
  timeframe=signal.get("active_timeframe", "adaptive"),
 
13
  async_save_snapshot,
14
  async_save_snapshots_batch,
15
  async_update_pair_exchanges,
16
+ async_update_pair_streak,
17
  )
18
  from engine.signal_engine import SignalEngine
19
  from routers.ws import broadcast
 
109
  )
110
  signal = _signal_engine.compute(raw)
111
 
112
+ # Calculate signal streak
113
+ curr_dir = signal.get("direction", "NEUTRAL")
114
+ curr_conv = signal.get("conviction", 0)
115
+ prev_streak = int(pair.get("streak_count", 0)) if pair and pair.get("streak_count") is not None else 0
116
+ prev_dir = str(pair.get("streak_direction", "NEUTRAL")) if pair and pair.get("streak_direction") is not None else "NEUTRAL"
117
+ prev_conv = int(pair.get("last_conviction", 0)) if pair and pair.get("last_conviction") is not None else 0
118
+
119
+ if curr_dir in ("LONG", "SHORT") and curr_conv >= 3:
120
+ if curr_dir == prev_dir and curr_conv >= max(3, prev_conv - 1):
121
+ new_streak = prev_streak + 1
122
+ else:
123
+ new_streak = 1
124
+ else:
125
+ new_streak = 0
126
+
127
+ signal["streak"] = new_streak
128
+ signal["streak_direction"] = curr_dir
129
+
130
+ if new_streak != prev_streak or curr_dir != prev_dir or curr_conv != prev_conv:
131
+ try:
132
+ updated_p = await async_update_pair_streak(sym, new_streak, curr_dir, curr_conv)
133
+ if updated_p:
134
+ await broadcast({"type": "pair_updated", "data": updated_p})
135
+ except Exception:
136
+ pass
137
+
138
  await async_save_signal(
139
  symbol=sym,
140
  timeframe=signal.get("active_timeframe", "adaptive"),
frontend/src/components/layout/Sidebar.tsx CHANGED
@@ -23,7 +23,7 @@ export function Sidebar({ pairs, signals, isLoading, selectedSymbol, onSelect }:
23
 
24
  return (
25
  <>
26
- <aside className="w-56 lg:w-64 shrink-0 flex flex-col border-r border-border bg-bg-card overflow-hidden">
27
  {/* Sidebar header */}
28
  <div className="px-4 py-3 border-b border-border">
29
  <div className="flex items-center justify-between mb-3">
 
23
 
24
  return (
25
  <>
26
+ <aside className="w-64 lg:w-72 xl:w-80 shrink-0 flex flex-col border-r border-border bg-bg-card overflow-hidden">
27
  {/* Sidebar header */}
28
  <div className="px-4 py-3 border-b border-border">
29
  <div className="flex items-center justify-between mb-3">
frontend/src/components/pairs/PairItem.tsx CHANGED
@@ -23,6 +23,10 @@ export function PairItem({ pair, signal, isSelected, onSelect }: PairItemProps)
23
  });
24
  };
25
 
 
 
 
 
26
  return (
27
  <div
28
  className={`group relative flex flex-col gap-1.5 px-3 py-2.5 rounded-lg cursor-pointer transition-colors
@@ -35,19 +39,33 @@ export function PairItem({ pair, signal, isSelected, onSelect }: PairItemProps)
35
  `}
36
  onClick={() => onSelect(pair.symbol)}
37
  >
38
- {/* Top row: status dot + symbol + signal badge + remove button */}
39
  <div className="flex items-center gap-2">
40
  <span
41
  className={`w-2 h-2 rounded-full shrink-0 ${
42
  pair.is_active ? 'bg-signal-long' : 'bg-text-muted'
43
  }`}
44
  />
45
- <span className="font-mono text-sm font-semibold text-text-primary flex-1 min-w-0 truncate">
46
- {pair.symbol}
47
- </span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  {signal && (
50
- <div className="flex items-center gap-1.5 shrink-0">
51
  <SignalBadge direction={signal.direction} size="sm" />
52
  <span
53
  className={`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${
 
23
  });
24
  };
25
 
26
+ const streak = signal?.streak ?? pair.streak_count ?? 0;
27
+ const baseCoin = pair.symbol.replace(/(USDT|USDC|PERP)$/, '');
28
+ const quote = pair.symbol.slice(baseCoin.length) || 'USDT';
29
+
30
  return (
31
  <div
32
  className={`group relative flex flex-col gap-1.5 px-3 py-2.5 rounded-lg cursor-pointer transition-colors
 
39
  `}
40
  onClick={() => onSelect(pair.symbol)}
41
  >
42
+ {/* Top row: status dot + symbol + streak + signal badge + remove button */}
43
  <div className="flex items-center gap-2">
44
  <span
45
  className={`w-2 h-2 rounded-full shrink-0 ${
46
  pair.is_active ? 'bg-signal-long' : 'bg-text-muted'
47
  }`}
48
  />
49
+ <div className="flex items-baseline gap-0.5 flex-1 min-w-0">
50
+ <span className="font-mono text-sm font-bold text-text-primary whitespace-nowrap">
51
+ {baseCoin}
52
+ </span>
53
+ <span className="font-mono text-[10px] text-text-muted/70">
54
+ /{quote}
55
+ </span>
56
+ </div>
57
+
58
+ {streak >= 2 && (
59
+ <span
60
+ className="text-[10px] font-mono font-bold px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30 shrink-0 flex items-center gap-0.5 animate-pulse"
61
+ title={`Consistent Streak: ${streak}x cycles`}
62
+ >
63
+ 🔥 {streak}x
64
+ </span>
65
+ )}
66
 
67
  {signal && (
68
+ <div className="flex items-center gap-1 shrink-0">
69
  <SignalBadge direction={signal.direction} size="sm" />
70
  <span
71
  className={`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${
frontend/src/components/signals/SignalBreakdown.tsx CHANGED
@@ -152,7 +152,7 @@ export function SignalBreakdown({ signals, predictive }: SignalBreakdownProps) {
152
  <span className="text-[11px] sm:text-xs text-text-secondary w-24 sm:w-32 shrink-0 font-medium">
153
  {row.label}
154
  </span>
155
- <span className="font-mono text-xs text-text-primary flex-1 min-w-0 truncate">
156
  {value}
157
  </span>
158
  <ScoreContrib score={score} />
 
152
  <span className="text-[11px] sm:text-xs text-text-secondary w-24 sm:w-32 shrink-0 font-medium">
153
  {row.label}
154
  </span>
155
+ <span className="font-mono text-xs text-text-primary flex-1 min-w-0 break-words leading-tight">
156
  {value}
157
  </span>
158
  <ScoreContrib score={score} />
frontend/src/components/signals/SignalCard.tsx CHANGED
@@ -120,6 +120,14 @@ Forward Anticipation: ${signal.anticipation || levels?.anticipation || ''}`;
120
  </div>
121
 
122
  <div className="flex items-center gap-1.5 shrink-0">
 
 
 
 
 
 
 
 
123
  <SignalBadge direction={signal.direction} size="sm" />
124
  <span
125
  className={`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${
@@ -224,48 +232,58 @@ Forward Anticipation: ${signal.anticipation || levels?.anticipation || ''}`;
224
  {/* Pre-Calculated Trade Levels Box */}
225
  {levels && (
226
  <div
227
- className={`mt-3 p-2 sm:p-2.5 rounded-lg border flex items-center justify-between gap-2 ${
228
  signal.has_spot === false
229
  ? 'bg-amber-950/15 border-amber-500/25'
230
  : 'bg-bg-primary/80 border-border/70'
231
  }`}
232
  >
233
- <div className="grid grid-cols-3 sm:grid-cols-4 gap-2 flex-1 min-w-0 font-mono text-[10px] sm:text-[11px]">
234
- <div className="min-w-0">
235
- <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-text-muted block">Entry</span>
236
- <span className="font-bold text-text-primary truncate block">{levels.entry_zone}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  </div>
238
- <div className="min-w-0">
239
- <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-short block">SL</span>
240
- <span className="font-bold text-signal-short truncate block">{levels.stop_loss_str}</span>
241
  </div>
242
- <div className="min-w-0">
243
- <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-long block">TP1</span>
244
- <span className="font-bold text-signal-long truncate block">{levels.take_profit_1_str}</span>
245
  </div>
246
  {levels.predicted_target ? (
247
- <div className="hidden sm:block min-w-0">
248
- <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-amber-400 flex items-center gap-0.5 truncate">
249
  <Target size={9} /> Magnet
250
  </span>
251
- <span className="font-bold text-amber-300 truncate block">{levels.predicted_target}</span>
252
  </div>
253
  ) : (
254
- <div className="hidden sm:block min-w-0">
255
- <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-text-muted block">R:R</span>
256
- <span className="font-bold text-text-secondary truncate block">{levels.risk_reward}</span>
257
  </div>
258
  )}
259
  </div>
260
-
261
- <button
262
- onClick={handleCopyPlan}
263
- title="Copy Trade Plan"
264
- className="p-1.5 sm:px-2 sm:py-1 rounded-md hover:bg-bg-elevated border border-border/60 hover:border-border text-text-muted hover:text-text-primary transition-all shrink-0 flex items-center gap-1 text-[10px] font-mono active:scale-95"
265
- >
266
- {copied ? <Check size={12} className="text-signal-long" /> : <Copy size={12} />}
267
- <span className="hidden xs:inline">{copied ? 'Copied' : 'Plan'}</span>
268
- </button>
269
  </div>
270
  )}
271
  </div>
 
120
  </div>
121
 
122
  <div className="flex items-center gap-1.5 shrink-0">
123
+ {signal.streak && signal.streak >= 2 && (
124
+ <span
125
+ className="text-[10px] font-mono font-bold px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30 flex items-center gap-0.5 shrink-0 animate-pulse"
126
+ title={`Consistent Conviction Streak: ${signal.streak} cycles`}
127
+ >
128
+ 🔥 {signal.streak}x
129
+ </span>
130
+ )}
131
  <SignalBadge direction={signal.direction} size="sm" />
132
  <span
133
  className={`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${
 
232
  {/* Pre-Calculated Trade Levels Box */}
233
  {levels && (
234
  <div
235
+ className={`mt-3 p-2.5 rounded-lg border flex flex-col gap-2 ${
236
  signal.has_spot === false
237
  ? 'bg-amber-950/15 border-amber-500/25'
238
  : 'bg-bg-primary/80 border-border/70'
239
  }`}
240
  >
241
+ {/* Row 1: Entry Zone & Copy Plan Button */}
242
+ <div className="flex items-center justify-between text-[11px] font-mono border-b border-border/40 pb-1.5 gap-2">
243
+ <div className="flex items-center gap-1.5 flex-1 min-w-0">
244
+ <span className="text-[9px] uppercase font-bold tracking-wider text-text-muted shrink-0">ENTRY:</span>
245
+ <span className="font-bold text-text-primary text-[11px] whitespace-normal">
246
+ {levels.entry_zone}
247
+ </span>
248
+ </div>
249
+ <button
250
+ onClick={handleCopyPlan}
251
+ title="Copy Trade Plan"
252
+ className="px-2 py-0.5 rounded-md hover:bg-bg-elevated border border-border/60 hover:border-border text-text-muted hover:text-text-primary transition-all shrink-0 flex items-center gap-1 text-[10px] font-mono active:scale-95"
253
+ >
254
+ {copied ? <Check size={11} className="text-signal-long" /> : <Copy size={11} />}
255
+ <span>{copied ? 'Copied' : 'Plan'}</span>
256
+ </button>
257
+ </div>
258
+
259
+ {/* Row 2: SL, TP1, TP2, Magnet / RR */}
260
+ <div className="grid grid-cols-3 sm:grid-cols-4 gap-2 font-mono text-[10px] sm:text-[11px]">
261
+ <div>
262
+ <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-short block font-semibold">SL</span>
263
+ <span className="font-bold text-signal-short block whitespace-nowrap">{levels.stop_loss_str}</span>
264
  </div>
265
+ <div>
266
+ <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-long block font-semibold">TP1</span>
267
+ <span className="font-bold text-signal-long block whitespace-nowrap">{levels.take_profit_1_str}</span>
268
  </div>
269
+ <div>
270
+ <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-long/80 block font-semibold">TP2</span>
271
+ <span className="font-bold text-signal-long/90 block whitespace-nowrap">{levels.take_profit_2_str || '—'}</span>
272
  </div>
273
  {levels.predicted_target ? (
274
+ <div>
275
+ <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-amber-400 flex items-center gap-0.5 font-semibold">
276
  <Target size={9} /> Magnet
277
  </span>
278
+ <span className="font-bold text-amber-300 block whitespace-nowrap">{levels.predicted_target}</span>
279
  </div>
280
  ) : (
281
+ <div>
282
+ <span className="text-[8px] sm:text-[9px] uppercase tracking-wider text-text-muted block font-semibold">R:R</span>
283
+ <span className="font-bold text-text-secondary block whitespace-nowrap">{levels.risk_reward}</span>
284
  </div>
285
  )}
286
  </div>
 
 
 
 
 
 
 
 
 
287
  </div>
288
  )}
289
  </div>
frontend/src/components/signals/TopTradeBanner.tsx CHANGED
@@ -94,6 +94,15 @@ Forward Anticipation: ${topSignal.anticipation || levels?.anticipation || ''}`;
94
  {topSignal.conviction}/10
95
  </span>
96
 
 
 
 
 
 
 
 
 
 
97
  <span className="text-[11px] font-mono text-text-secondary uppercase px-1.5 py-0.5 rounded bg-bg-elevated border border-border">
98
  {topSignal.active_timeframe}
99
  </span>
 
94
  {topSignal.conviction}/10
95
  </span>
96
 
97
+ {topSignal.streak && topSignal.streak >= 2 && (
98
+ <span
99
+ className="font-mono text-xs font-bold px-2 py-0.5 rounded-md bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1 animate-pulse"
100
+ title={`Consistent Conviction Streak: ${topSignal.streak} cycles`}
101
+ >
102
+ 🔥 {topSignal.streak}x Streak
103
+ </span>
104
+ )}
105
+
106
  <span className="text-[11px] font-mono text-text-secondary uppercase px-1.5 py-0.5 rounded bg-bg-elevated border border-border">
107
  {topSignal.active_timeframe}
108
  </span>
frontend/src/types/index.ts CHANGED
@@ -7,6 +7,9 @@ export interface Pair {
7
  on_bybit: boolean;
8
  on_okx?: boolean;
9
  on_hyperliquid?: boolean;
 
 
 
10
  is_active: boolean;
11
  created_at: string;
12
  }
@@ -129,6 +132,8 @@ export interface Signal {
129
  direction: Direction;
130
  conviction: number;
131
  score: number;
 
 
132
  has_spot?: boolean;
133
  spot_status?: 'SPOT_BACKED' | 'PERP_ONLY';
134
  safety_status?: 'SAFE' | 'UNSAFE';
 
7
  on_bybit: boolean;
8
  on_okx?: boolean;
9
  on_hyperliquid?: boolean;
10
+ streak_count?: number;
11
+ streak_direction?: string;
12
+ last_conviction?: number;
13
  is_active: boolean;
14
  created_at: string;
15
  }
 
132
  direction: Direction;
133
  conviction: number;
134
  score: number;
135
+ streak?: number;
136
+ streak_direction?: string;
137
  has_spot?: boolean;
138
  spot_status?: 'SPOT_BACKED' | 'PERP_ONLY';
139
  safety_status?: 'SAFE' | 'UNSAFE';
tests/test_streak.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit tests for Signal Streak Logic
3
+ ==================================
4
+ Tests that:
5
+ 1. When direction and conviction stay consistent (e.g. LONG with conviction >= 3), streak increments by 1.
6
+ 2. Slight conviction fluctuations within -1 don't break streak if conviction >= 3.
7
+ 3. When conviction drops below 3 or direction turns NEUTRAL, streak resets to 0.
8
+ 4. When direction flips from LONG to SHORT or vice versa, streak resets to 1 (if conviction >= 3).
9
+ """
10
+
11
+ import pytest
12
+
13
+ def calculate_new_streak(curr_dir: str, curr_conv: int, prev_streak: int, prev_dir: str, prev_conv: int) -> int:
14
+ if curr_dir in ("LONG", "SHORT") and curr_conv >= 3:
15
+ if curr_dir == prev_dir and curr_conv >= max(3, prev_conv - 1):
16
+ return prev_streak + 1
17
+ else:
18
+ return 1
19
+ else:
20
+ return 0
21
+
22
+
23
+ def test_initial_streak_starts_at_1_for_strong_signal():
24
+ # Initial state: Neutral with streak 0
25
+ new_streak = calculate_new_streak(
26
+ curr_dir="LONG", curr_conv=4,
27
+ prev_streak=0, prev_dir="NEUTRAL", prev_conv=0
28
+ )
29
+ assert new_streak == 1
30
+
31
+
32
+ def test_streak_increments_when_direction_and_conviction_persist():
33
+ # Previous state: LONG, conv 4, streak 2
34
+ new_streak = calculate_new_streak(
35
+ curr_dir="LONG", curr_conv=4,
36
+ prev_streak=2, prev_dir="LONG", prev_conv=4
37
+ )
38
+ assert new_streak == 3
39
+
40
+
41
+ def test_streak_persists_through_minor_conviction_jitter():
42
+ # Conviction drops slightly from 5 to 4, still strong
43
+ new_streak = calculate_new_streak(
44
+ curr_dir="LONG", curr_conv=4,
45
+ prev_streak=3, prev_dir="LONG", prev_conv=5
46
+ )
47
+ assert new_streak == 4
48
+
49
+
50
+ def test_streak_resets_when_conviction_drops_below_threshold():
51
+ # Conviction collapses to 2
52
+ new_streak = calculate_new_streak(
53
+ curr_dir="LONG", curr_conv=2,
54
+ prev_streak=5, prev_dir="LONG", prev_conv=4
55
+ )
56
+ assert new_streak == 0
57
+
58
+
59
+ def test_streak_resets_when_direction_becomes_neutral():
60
+ new_streak = calculate_new_streak(
61
+ curr_dir="NEUTRAL", curr_conv=1,
62
+ prev_streak=6, prev_dir="LONG", prev_conv=4
63
+ )
64
+ assert new_streak == 0
65
+
66
+
67
+ def test_streak_resets_to_1_on_direction_flip():
68
+ # Direction flips from LONG to SHORT with strong conviction
69
+ new_streak = calculate_new_streak(
70
+ curr_dir="SHORT", curr_conv=4,
71
+ prev_streak=7, prev_dir="LONG", prev_conv=4
72
+ )
73
+ assert new_streak == 1