/** * Round timing helpers for Candle Predict (synthetic candles, no market data). */ export function currentCandleOpenMs(nowMs: number, intervalMinutes: number): number { const intervalMs = intervalMinutes * 60 * 1000; return Math.floor(nowMs / intervalMs) * intervalMs; } /** True when this timestamp is a candle close for the given interval grid. */ export function isMaturityBoundaryForInterval( candleOpenMs: number, intervalMinutes: number ): boolean { const intervalMs = intervalMinutes * 60 * 1000; return candleOpenMs % intervalMs === 0; } export type RoundPhase = 'waiting' | 'betting' | 'locked'; /** Max configurable prediction window (leaves at least 5s of live candle per period). */ export function maxPredictionWindowSeconds(intervalMinutes: number): number { const intervalSec = intervalMinutes * 60; return Math.max(5, intervalSec - 5); } /** Cap window so at least 5s of "live candle" remains before the next betting phase. */ export function effectivePredictionWindowSeconds( intervalMinutes: number, predictionWindowSeconds: number ): number { return Math.min(predictionWindowSeconds, maxPredictionWindowSeconds(intervalMinutes)); } export function getActiveRoundTiming( nowMs: number, intervalMinutes: number, predictionWindowSeconds: number ): { openMs: number; phase: RoundPhase; nextOpenMs: number; nextBettingStartMs: number } { const windowSec = effectivePredictionWindowSeconds(intervalMinutes, predictionWindowSeconds); const intervalMs = intervalMinutes * 60 * 1000; const currentOpen = currentCandleOpenMs(nowMs, intervalMinutes); const nextOpen = currentOpen + intervalMs; const bettingStart = nextOpen - windowSec * 1000; if (nowMs >= bettingStart && nowMs < nextOpen) { return { openMs: nextOpen, phase: 'betting', nextOpenMs: nextOpen, nextBettingStartMs: bettingStart }; } if (nowMs >= currentOpen && nowMs < nextOpen) { return { openMs: currentOpen, phase: 'locked', nextOpenMs: nextOpen, nextBettingStartMs: bettingStart, }; } return { openMs: nextOpen, phase: 'waiting', nextOpenMs: nextOpen, nextBettingStartMs: bettingStart }; } /** Client-facing status: settled rounds stay "locked" until the candle interval ends. */ export function resolveDisplayStatus( dbStatus: 'waiting' | 'betting' | 'locked' | 'settled', timingPhase: RoundPhase, candleOpenMs: number, intervalMinutes: number, nowMs: number ): 'waiting' | 'betting' | 'locked' | 'settled' { const closeMs = candleOpenMs + intervalMinutes * 60 * 1000; if (dbStatus === 'settled' && nowMs < closeMs) { return 'locked'; } if (timingPhase === 'betting' && dbStatus !== 'settled') { return 'betting'; } if (timingPhase === 'locked') { return 'locked'; } if (timingPhase === 'waiting') { return 'waiting'; } return dbStatus; }