Naufal Arhab commited on
Commit
3fa6950
·
1 Parent(s): f8d50fc

feat(signals): add on-demand stale auto-refresh and batch refresh endpoint for continuous live updates

Browse files
backend/main.py CHANGED
@@ -238,6 +238,30 @@ async def _signal_loop(collector: DataCollector) -> None:
238
  await asyncio.sleep(UPDATE_INTERVAL)
239
 
240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  # ─────────────────────────────────────────────────────────────────────────────
242
  # FastAPI lifespan
243
  # ─────────────────────────────────────────────────────────────────────────────
 
238
  await asyncio.sleep(UPDATE_INTERVAL)
239
 
240
 
241
+ async def process_active_pairs_batch(collector: DataCollector, limit: int = 30) -> int:
242
+ """Process active pairs in parallel (concurrency=6). Returns count of processed pairs."""
243
+ try:
244
+ pairs = await async_get_active_pairs()
245
+ if not pairs:
246
+ return 0
247
+ target_pairs = pairs[:limit] if limit else pairs
248
+ semaphore = asyncio.Semaphore(6)
249
+
250
+ async def _guarded(p: dict) -> None:
251
+ async with semaphore:
252
+ try:
253
+ await _process_pair(p, collector)
254
+ except Exception as e:
255
+ logger.error("[%s] Batch processing error: %s", p.get("symbol"), e)
256
+
257
+ tasks = [_guarded(p) for p in target_pairs]
258
+ await asyncio.gather(*tasks, return_exceptions=True)
259
+ return len(target_pairs)
260
+ except Exception as exc:
261
+ logger.error("process_active_pairs_batch failed: %s", exc)
262
+ return 0
263
+
264
+
265
  # ─────────────────────────────────────────────────────────────────────────────
266
  # FastAPI lifespan
267
  # ─────────────────────────────────────────────────────────────────────────────
backend/routers/signals.py CHANGED
@@ -2,7 +2,9 @@
2
  /api/signals endpoints
3
  """
4
 
5
- from fastapi import APIRouter, HTTPException, Request
 
 
6
 
7
  from database.db import (
8
  async_get_latest_signals,
@@ -20,14 +22,68 @@ from routers.ws import broadcast
20
 
21
  router = APIRouter(prefix="/api/signals", tags=["signals"])
22
  _signal_engine = SignalEngine()
 
23
 
24
 
25
  @router.get("")
26
- async def get_all_signals():
27
- """Get the latest signal for every pair that has been computed."""
 
28
  rows = await async_get_latest_signals()
29
- # Return the clean signal_data dict directly for frontend compatibility
30
- return [r.get("signal_data") or r for r in rows if r]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
 
33
  @router.get("/regime/summary")
 
2
  /api/signals endpoints
3
  """
4
 
5
+ from datetime import datetime, timezone
6
+ import time
7
+ from fastapi import APIRouter, HTTPException, Request, BackgroundTasks
8
 
9
  from database.db import (
10
  async_get_latest_signals,
 
22
 
23
  router = APIRouter(prefix="/api/signals", tags=["signals"])
24
  _signal_engine = SignalEngine()
25
+ _last_batch_trigger_time: float = 0.0
26
 
27
 
28
  @router.get("")
29
+ async def get_all_signals(request: Request, background_tasks: BackgroundTasks):
30
+ """Get the latest signal for every pair that has been computed. Auto-triggers fresh computation if stale."""
31
+ global _last_batch_trigger_time
32
  rows = await async_get_latest_signals()
33
+ signals = [r.get("signal_data") or r for r in rows if r]
34
+
35
+ # Stale-While-Revalidate: If data in DB is older than 60s, schedule fresh batch computation in background
36
+ collector = getattr(request.app.state, "collector", None)
37
+ if collector:
38
+ now = time.time()
39
+ # Avoid spamming background tasks if one was triggered recently (< 45s)
40
+ if now - _last_batch_trigger_time > 45:
41
+ now_dt = datetime.now(timezone.utc)
42
+ newest_dt = None
43
+ for s in signals:
44
+ try:
45
+ u_str = s.get("updated_at")
46
+ if u_str:
47
+ dt = datetime.fromisoformat(u_str)
48
+ if newest_dt is None or dt > newest_dt:
49
+ newest_dt = dt
50
+ except Exception:
51
+ pass
52
+
53
+ is_stale = (newest_dt is None) or ((now_dt - newest_dt).total_seconds() > 60)
54
+ if is_stale:
55
+ _last_batch_trigger_time = now
56
+ from main import process_active_pairs_batch
57
+ background_tasks.add_task(process_active_pairs_batch, collector, 30)
58
+
59
+ return signals
60
+
61
+
62
+ @router.post("/refresh-all")
63
+ async def refresh_all_signals(request: Request):
64
+ """Manually trigger immediate batch recalculation of active pairs."""
65
+ collector = getattr(request.app.state, "collector", None)
66
+ if not collector:
67
+ raise HTTPException(status_code=503, detail="Collector not available")
68
+
69
+ from main import process_active_pairs_batch
70
+ count = await process_active_pairs_batch(collector, limit=None)
71
+ rows = await async_get_latest_signals()
72
+ return {
73
+ "refreshed_count": count,
74
+ "signals": [r.get("signal_data") or r for r in rows if r],
75
+ }
76
+
77
+
78
+ @router.get("/cron")
79
+ async def cron_refresh(request: Request):
80
+ """Cron endpoint for Vercel/external schedulers to keep pairs refreshed."""
81
+ collector = getattr(request.app.state, "collector", None)
82
+ if not collector:
83
+ return {"status": "collector_unavailable"}
84
+ from main import process_active_pairs_batch
85
+ count = await process_active_pairs_batch(collector, limit=25)
86
+ return {"status": "ok", "refreshed_count": count}
87
 
88
 
89
  @router.get("/regime/summary")
frontend/src/api/signals.ts CHANGED
@@ -16,4 +16,9 @@ export const signalsApi = {
16
  const { data } = await apiClient.post<Signal>(`/api/signals/${symbol}/refresh`);
17
  return data;
18
  },
 
 
 
 
 
19
  };
 
16
  const { data } = await apiClient.post<Signal>(`/api/signals/${symbol}/refresh`);
17
  return data;
18
  },
19
+
20
+ refreshAll: async (): Promise<{ refreshed_count: number; signals: Signal[] }> => {
21
+ const { data } = await apiClient.post<{ refreshed_count: number; signals: Signal[] }>('/api/signals/refresh-all');
22
+ return data;
23
+ },
24
  };
frontend/src/hooks/useSignals.ts CHANGED
@@ -39,3 +39,16 @@ export function useRefreshSignal() {
39
  },
40
  });
41
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  },
40
  });
41
  }
42
+
43
+ export function useRefreshAllSignals() {
44
+ const queryClient = useQueryClient();
45
+ return useMutation({
46
+ mutationFn: () => signalsApi.refreshAll(),
47
+ onSuccess: (data) => {
48
+ if (data?.signals) {
49
+ queryClient.setQueryData(SIGNALS_QUERY_KEY, data.signals);
50
+ }
51
+ queryClient.invalidateQueries({ queryKey: SIGNALS_QUERY_KEY });
52
+ },
53
+ });
54
+ }
frontend/src/pages/Dashboard.tsx CHANGED
@@ -7,7 +7,7 @@ import { TopTradeBanner } from '../components/signals/TopTradeBanner';
7
  import { CardSkeleton, Spinner } from '../components/ui/Spinner';
8
  import { Button } from '../components/ui/Button';
9
  import { usePairs } from '../hooks/usePairs';
10
- import { useSignals, useRefreshSignal } from '../hooks/useSignals';
11
 
12
  // Lazy-load modal to keep initial bundle ultra-lightweight
13
  const AddPairModal = lazy(() =>
@@ -36,6 +36,7 @@ export function Dashboard({
36
  const { data: pairs = [], isLoading: pairsLoading } = usePairs();
37
  const { data: signals = [], isLoading: signalsLoading } = useSignals();
38
  const { mutate: refreshSignal, isPending: isRefreshing } = useRefreshSignal();
 
39
 
40
  // All active signals sorted by conviction desc (Used by TopTradeBanner for best setup)
41
  const allSortedSignals = useMemo(() => {
@@ -74,6 +75,19 @@ export function Dashboard({
74
  }
75
  }, [selectedSymbol, signals, refreshSignal]);
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  const activePairs = pairs.filter((p) => p.is_active);
78
  // Only show skeletons on the very first load when zero data exists in memory
79
  const isInitialLoading = (pairsLoading || signalsLoading) && pairs.length === 0 && signals.length === 0;
@@ -173,18 +187,32 @@ export function Dashboard({
173
  </p>
174
  </div>
175
 
176
- {/* Stable Layout Toggle (Zero-Jumping Mode) */}
177
- <button
178
- type="button"
179
- onClick={() => setSortMode((prev) => (prev === 'STABLE' ? 'CONVICTION' : 'STABLE'))}
180
- className="px-2.5 py-1.5 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary flex items-center gap-1.5 transition-all shadow-sm shrink-0"
181
- title={sortMode === 'STABLE' ? 'Posisi kartu stabil (A-Z, kartu tidak loncat-loncat)' : 'Diurutkan berdasarkan skor keyakinan tertinggi'}
182
- >
183
- <span className="text-[10px] text-text-muted hidden xs:inline">Tata Letak:</span>
184
- <span className="font-semibold text-text-primary">
185
- {sortMode === 'STABLE' ? '📌 A-Z' : '🔥 Skor'}
186
- </span>
187
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  </div>
189
 
190
  {/* Bottom row: Filter Pills with smooth horizontal scrolling */}
 
7
  import { CardSkeleton, Spinner } from '../components/ui/Spinner';
8
  import { Button } from '../components/ui/Button';
9
  import { usePairs } from '../hooks/usePairs';
10
+ import { useSignals, useRefreshSignal, useRefreshAllSignals } from '../hooks/useSignals';
11
 
12
  // Lazy-load modal to keep initial bundle ultra-lightweight
13
  const AddPairModal = lazy(() =>
 
36
  const { data: pairs = [], isLoading: pairsLoading } = usePairs();
37
  const { data: signals = [], isLoading: signalsLoading } = useSignals();
38
  const { mutate: refreshSignal, isPending: isRefreshing } = useRefreshSignal();
39
+ const { mutate: refreshAll, isPending: isRefreshingAll } = useRefreshAllSignals();
40
 
41
  // All active signals sorted by conviction desc (Used by TopTradeBanner for best setup)
42
  const allSortedSignals = useMemo(() => {
 
75
  }
76
  }, [selectedSymbol, signals, refreshSignal]);
77
 
78
+ // Auto-refresh stale signals on mount if database data is older than 2 minutes
79
+ useEffect(() => {
80
+ if (signals.length > 0 && !isRefreshingAll) {
81
+ const now = Date.now();
82
+ const newestTime = Math.max(
83
+ ...signals.map((s) => (s.updated_at ? new Date(s.updated_at).getTime() : 0))
84
+ );
85
+ if (newestTime > 0 && now - newestTime > 120_000) {
86
+ refreshAll();
87
+ }
88
+ }
89
+ }, [signals.length, isRefreshingAll, refreshAll]);
90
+
91
  const activePairs = pairs.filter((p) => p.is_active);
92
  // Only show skeletons on the very first load when zero data exists in memory
93
  const isInitialLoading = (pairsLoading || signalsLoading) && pairs.length === 0 && signals.length === 0;
 
187
  </p>
188
  </div>
189
 
190
+ <div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
191
+ {/* Global Market Batch Refresh Button */}
192
+ <button
193
+ type="button"
194
+ onClick={() => refreshAll()}
195
+ disabled={isRefreshingAll}
196
+ className="px-2.5 py-1.5 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary flex items-center gap-1.5 transition-all shadow-sm shrink-0 active:scale-95 disabled:opacity-60"
197
+ title="Perbarui seluruh data sinyal pasar sekarang"
198
+ >
199
+ <RefreshCw size={12} className={isRefreshingAll ? 'animate-spin text-accent-blue' : ''} />
200
+ <span className="hidden xs:inline">{isRefreshingAll ? 'Memperbarui...' : 'Refresh Pasar'}</span>
201
+ </button>
202
+
203
+ {/* Stable Layout Toggle (Zero-Jumping Mode) */}
204
+ <button
205
+ type="button"
206
+ onClick={() => setSortMode((prev) => (prev === 'STABLE' ? 'CONVICTION' : 'STABLE'))}
207
+ className="px-2.5 py-1.5 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary flex items-center gap-1.5 transition-all shadow-sm shrink-0"
208
+ title={sortMode === 'STABLE' ? 'Posisi kartu stabil (A-Z, kartu tidak loncat-loncat)' : 'Diurutkan berdasarkan skor keyakinan tertinggi'}
209
+ >
210
+ <span className="text-[10px] text-text-muted hidden xs:inline">Tata Letak:</span>
211
+ <span className="font-semibold text-text-primary">
212
+ {sortMode === 'STABLE' ? '📌 A-Z' : '🔥 Skor'}
213
+ </span>
214
+ </button>
215
+ </div>
216
  </div>
217
 
218
  {/* Bottom row: Filter Pills with smooth horizontal scrolling */}