"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getConfig = getConfig; exports.updateConfig = updateConfig; exports.clearIntervalNeutralityEnabledOverrides = clearIntervalNeutralityEnabledOverrides; exports.getRoundByOpenMs = getRoundByOpenMs; exports.createRound = createRound; exports.updateRoundStatus = updateRoundStatus; exports.getPoolTotals = getPoolTotals; exports.getGlobalPoolTotalsForMaturity = getGlobalPoolTotalsForMaturity; exports.listRoundsByCandleOpenMs = listRoundsByCandleOpenMs; exports.listPendingBetsForMaturity = listPendingBetsForMaturity; exports.countPendingBetsForMaturity = countPendingBetsForMaturity; exports.countPendingRealMoneyBetsForMaturity = countPendingRealMoneyBetsForMaturity; exports.settleRound = settleRound; exports.insertGeneratedCandle = insertGeneratedCandle; exports.deleteCandlesOlderThanOpenMs = deleteCandlesOlderThanOpenMs; exports.deleteCandlesBeyondKeepLastPerInterval = deleteCandlesBeyondKeepLastPerInterval; exports.listGeneratedCandles = listGeneratedCandles; exports.listGeneratedCandlesPage = listGeneratedCandlesPage; exports.hasOlderCandles = hasOlderCandles; exports.getLastGeneratedCandle = getLastGeneratedCandle; exports.getLastCandleOpenMs = getLastCandleOpenMs; exports.hasCandle = hasCandle; exports.getPreviousCandleOhlc = getPreviousCandleOhlc; exports.listRecentCandleOutcomes = listRecentCandleOutcomes; exports.incrementRoundBetCount = incrementRoundBetCount; exports.createBet = createBet; exports.getUserBetForRound = getUserBetForRound; exports.getBetById = getBetById; exports.listPendingBetsForRound = listPendingBetsForRound; exports.updateBetOutcome = updateBetOutcome; exports.updateBetSequenceStep = updateBetSequenceStep; exports.listMultiLevels = listMultiLevels; exports.listEnabledMultiLevels = listEnabledMultiLevels; exports.getMultiLevel = getMultiLevel; exports.upsertMultiLevel = upsertMultiLevel; exports.getUserActiveMultiBet = getUserActiveMultiBet; exports.createMultiCandleBet = createMultiCandleBet; exports.listMultiBetsForValidationAtOpenMs = listMultiBetsForValidationAtOpenMs; exports.countMultiBetsForValidationAtOpenMs = countMultiBetsForValidationAtOpenMs; exports.listDueMultiValidationCandleOpenMs = listDueMultiValidationCandleOpenMs; exports.getMultiCandlePoolContributions = getMultiCandlePoolContributions; exports.listRecentBets = listRecentBets; exports.countUserPredictions = countUserPredictions; exports.getAutoSettings = getAutoSettings; exports.upsertAutoSettings = upsertAutoSettings; exports.touchAutoBet = touchAutoBet; exports.listEnabledAutoSettings = listEnabledAutoSettings; exports.listOverdueUnsettledRounds = listOverdueUnsettledRounds; exports.getRoundToSettle = getRoundToSettle; exports.getBettingRound = getBettingRound; exports.listActiveIntervals = listActiveIntervals; exports.listAllIntervals = listAllIntervals; exports.getIntervalByMinutes = getIntervalByMinutes; exports.getDefaultInterval = getDefaultInterval; exports.createInterval = createInterval; exports.updateInterval = updateInterval; exports.clearDefaultIntervalExcept = clearDefaultIntervalExcept; exports.deleteInterval = deleteInterval; exports.countRoundsForInterval = countRoundsForInterval; exports.withDailyRevenueLock = withDailyRevenueLock; exports.getOrCreateDailyRevenueNetRaw = getOrCreateDailyRevenueNetRaw; exports.addDailyRevenuePnl = addDailyRevenuePnl; exports.getDailyRevenueNetRaw = getDailyRevenueNetRaw; const connection_1 = require("../db/connection"); async function getConfig() { const rows = await (0, connection_1.query)('SELECT * FROM candle_predict_config WHERE id = 1'); if (!rows[0]) throw new Error('Candle Predict config not found'); return rows[0]; } async function updateConfig(update) { const current = await getConfig(); const rows = await (0, connection_1.query)(`UPDATE candle_predict_config SET interval_minutes = $1, stake_amounts = $2::jsonb, min_stake_amount = $3, max_stake_amount = $4, pool_winner_rule = $5, allowed_intervals = $6::jsonb, prediction_window_seconds = $7, tie_tolerance_percent = $8, tie_tolerance_max_percent = $9, tie_tolerance_min_enabled = $10, tie_tolerance_max_enabled = $11, base_price = $12, payout_multiplier = $13, pool_multiplier = $14, wallet_type_code = $15, auto_modes = $16::jsonb, is_active = $17, prediction_single_enabled = $18, prediction_auto_enabled = $19, prediction_multi_enabled = $20, daily_revenue_target = $21, daily_revenue_overflow_strategy = $22, instrument_symbol = $23, instrument_display_name = $24, instrument_quote_currency = $25, instrument_price_digits = $26, max_consecutive_same_direction = $27, updated_at = NOW() WHERE id = 1 RETURNING *`, [ update.intervalMinutes ?? current.interval_minutes, JSON.stringify(update.stakeAmounts ?? current.stake_amounts), update.minStakeAmount ?? Number(current.min_stake_amount), update.maxStakeAmount ?? Number(current.max_stake_amount), update.poolWinnerRule ?? current.pool_winner_rule, JSON.stringify(update.allowedIntervals ?? current.allowed_intervals), update.predictionWindowSeconds ?? current.prediction_window_seconds, update.tieTolerancePercent ?? Number(current.tie_tolerance_percent), update.tieToleranceMaxPercent ?? Number(current.tie_tolerance_max_percent), update.tieToleranceMinEnabled ?? current.tie_tolerance_min_enabled, update.tieToleranceMaxEnabled ?? current.tie_tolerance_max_enabled, update.basePrice ?? Number(current.base_price), update.payoutMultiplier ?? Number(current.payout_multiplier), update.poolMultiplier ?? Number(current.pool_multiplier), update.walletTypeCode ?? current.wallet_type_code, JSON.stringify(update.autoModes ?? current.auto_modes), update.isActive ?? current.is_active, update.predictionSingleEnabled ?? current.prediction_single_enabled ?? true, update.predictionAutoEnabled ?? current.prediction_auto_enabled ?? true, update.predictionMultiEnabled ?? current.prediction_multi_enabled ?? true, update.dailyRevenueTarget ?? Number(current.daily_revenue_target ?? 0), update.dailyRevenueOverflowStrategy ?? current.daily_revenue_overflow_strategy ?? 'neutral', update.instrumentSymbol ?? current.instrument_symbol ?? 'FO', update.instrumentDisplayName ?? current.instrument_display_name ?? 'Full Option', update.instrumentQuoteCurrency ?? current.instrument_quote_currency ?? 'USDT', update.instrumentPriceDigits ?? current.instrument_price_digits ?? 2, update.maxConsecutiveSameDirection ?? current.max_consecutive_same_direction ?? 5, ]); return rows[0]; } /** * Clear per-interval enable overrides so global Neutral round toggles take effect. * Interval rows keep optional percent overrides; only the boolean enables are reset to inherit. */ async function clearIntervalNeutralityEnabledOverrides() { await (0, connection_1.query)(`UPDATE candle_predict_intervals SET tie_tolerance_min_enabled = NULL, tie_tolerance_max_enabled = NULL, updated_at = NOW()`); } async function getRoundByOpenMs(openMs, intervalMinutes) { const rows = await (0, connection_1.query)('SELECT * FROM candle_predict_rounds WHERE candle_open_ms = $1 AND interval_minutes = $2', [openMs, intervalMinutes]); return rows[0] ?? null; } async function createRound(input) { const rows = await (0, connection_1.query)(`INSERT INTO candle_predict_rounds (candle_open_ms, interval_minutes, status) VALUES ($1, $2, $3) ON CONFLICT (candle_open_ms, interval_minutes) DO UPDATE SET status = EXCLUDED.status RETURNING *`, [input.candleOpenMs, input.intervalMinutes, input.status]); return rows[0]; } async function updateRoundStatus(id, status) { await (0, connection_1.query)('UPDATE candle_predict_rounds SET status = $2 WHERE id = $1', [id, status]); } /** Only main/bonus stakes affect candle outcome; test wallet bets are settled separately. */ const REAL_MONEY_POOL_SQL = `stake_account_kind IN ('main', 'bonus')`; const REAL_MONEY_POOL_SQL_B = `b.stake_account_kind IN ('main', 'bonus')`; /** Single/auto pool weight = stake × pool_multiplier (interval override, else global config). */ const SINGLE_POOL_WEIGHT_SQL = `b.stake_display * COALESCE(i.pool_multiplier, cfg.pool_multiplier)`; async function getPoolTotals(roundId) { const rows = await (0, connection_1.query)(`SELECT b.direction, COALESCE(SUM(${SINGLE_POOL_WEIGHT_SQL}), 0)::text AS total FROM candle_predict_bets b INNER JOIN candle_predict_rounds r ON r.id = b.round_id LEFT JOIN candle_predict_intervals i ON i.interval_minutes = r.interval_minutes CROSS JOIN candle_predict_config cfg WHERE cfg.id = 1 AND b.round_id = $1 AND ${REAL_MONEY_POOL_SQL_B} GROUP BY b.direction`, [roundId]); let shortPool = 0; let longPool = 0; for (const r of rows) { if (r.direction === 'short') shortPool = Number(r.total); if (r.direction === 'long') longPool = Number(r.total); } return { shortPool, longPool }; } /** Pools for pending single/auto predictions at maturity — real money only (excludes test wallet). * Pool weight = stake × pool_multiplier (aligned with multi-candle pool integration). */ async function getGlobalPoolTotalsForMaturity(candleOpenMs) { const rows = await (0, connection_1.query)(`SELECT b.direction, COALESCE(SUM(${SINGLE_POOL_WEIGHT_SQL}), 0)::text AS total FROM candle_predict_bets b INNER JOIN candle_predict_rounds r ON r.id = b.round_id LEFT JOIN candle_predict_intervals i ON i.interval_minutes = b.interval_minutes CROSS JOIN candle_predict_config cfg WHERE cfg.id = 1 AND r.candle_open_ms = $1 AND b.status = 'pending' AND b.prediction_mode = 'single' AND ${REAL_MONEY_POOL_SQL_B} GROUP BY b.direction`, [candleOpenMs]); let shortPool = 0; let longPool = 0; for (const r of rows) { if (r.direction === 'short') shortPool = Number(r.total); if (r.direction === 'long') longPool = Number(r.total); } return { shortPool, longPool }; } async function listRoundsByCandleOpenMs(candleOpenMs) { return (0, connection_1.query)(`SELECT * FROM candle_predict_rounds WHERE candle_open_ms = $1 ORDER BY interval_minutes ASC`, [candleOpenMs]); } async function listPendingBetsForMaturity(candleOpenMs) { return (0, connection_1.query)(`SELECT b.* FROM candle_predict_bets b INNER JOIN candle_predict_rounds r ON r.id = b.round_id WHERE r.candle_open_ms = $1 AND b.status = 'pending' AND b.prediction_mode = 'single' ORDER BY b.created_at ASC`, [candleOpenMs]); } async function countPendingBetsForMaturity(candleOpenMs) { const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM candle_predict_bets b INNER JOIN candle_predict_rounds r ON r.id = b.round_id WHERE r.candle_open_ms = $1 AND b.status = 'pending' AND b.prediction_mode = 'single'`, [candleOpenMs]); return Number(rows[0]?.count ?? 0); } async function countPendingRealMoneyBetsForMaturity(candleOpenMs) { const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM candle_predict_bets b INNER JOIN candle_predict_rounds r ON r.id = b.round_id WHERE r.candle_open_ms = $1 AND b.status = 'pending' AND b.prediction_mode = 'single' AND ${REAL_MONEY_POOL_SQL_B}`, [candleOpenMs]); return Number(rows[0]?.count ?? 0); } async function settleRound(id, data) { await (0, connection_1.query)(`UPDATE candle_predict_rounds SET status = 'settled', open_price = $2, high_price = $3, low_price = $4, close_price = $5, outcome = $6, neutral_color = $7, short_pool_display = $8, long_pool_display = $9, settled_at = NOW() WHERE id = $1`, [ id, data.open, data.high, data.low, data.close, data.outcome, data.neutralColor, data.shortPool, data.longPool, ]); } async function insertGeneratedCandle(input) { await (0, connection_1.query)(`INSERT INTO candle_predict_candles (candle_open_ms, interval_minutes, open_price, high_price, low_price, close_price, color_hint, outcome) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (candle_open_ms, interval_minutes) DO NOTHING`, [ input.candleOpenMs, input.intervalMinutes, input.open, input.high, input.low, input.close, input.colorHint, input.outcome, ]); } /** Batch-delete candles whose open time is older than `cutoffOpenMs`. */ async function deleteCandlesOlderThanOpenMs(cutoffOpenMs, batchSize = 5000) { const limit = Math.min(Math.max(batchSize, 100), 20000); const result = await (0, connection_1.query)(`WITH deleted AS ( DELETE FROM candle_predict_candles WHERE ctid IN ( SELECT ctid FROM candle_predict_candles WHERE candle_open_ms < $1 LIMIT $2 ) RETURNING 1 ) SELECT COUNT(*)::text AS count FROM deleted`, [cutoffOpenMs, limit]); return parseInt(result[0]?.count ?? '0', 10); } /** * Batch-delete candles beyond the newest `keepLast` rows per interval. * Newer bars (higher `candle_open_ms`) are always kept. */ async function deleteCandlesBeyondKeepLastPerInterval(keepLast, batchSize = 5000) { const keep = Math.max(1, Math.floor(keepLast)); const limit = Math.min(Math.max(batchSize, 100), 20000); const result = await (0, connection_1.query)(`WITH ranked AS ( SELECT ctid, ROW_NUMBER() OVER ( PARTITION BY interval_minutes ORDER BY candle_open_ms DESC ) AS rn FROM candle_predict_candles ), deleted AS ( DELETE FROM candle_predict_candles WHERE ctid IN ( SELECT ctid FROM ranked WHERE rn > $1 LIMIT $2 ) RETURNING 1 ) SELECT COUNT(*)::text AS count FROM deleted`, [keep, limit]); return parseInt(result[0]?.count ?? '0', 10); } async function listGeneratedCandles(limit = 120, intervalMinutes) { if (intervalMinutes != null) { return listGeneratedCandlesPage({ intervalMinutes, limit }); } return (0, connection_1.query)(`SELECT * FROM candle_predict_candles ORDER BY candle_open_ms DESC LIMIT $1`, [limit]); } async function listGeneratedCandlesPage(input) { if (input.beforeOpenMs != null) { return (0, connection_1.query)(`SELECT * FROM candle_predict_candles WHERE interval_minutes = $1 AND candle_open_ms < $2 ORDER BY candle_open_ms DESC LIMIT $3`, [input.intervalMinutes, input.beforeOpenMs, input.limit]); } return (0, connection_1.query)(`SELECT * FROM candle_predict_candles WHERE interval_minutes = $1 ORDER BY candle_open_ms DESC LIMIT $2`, [input.intervalMinutes, input.limit]); } async function hasOlderCandles(intervalMinutes, beforeOpenMs) { const rows = await (0, connection_1.query)(`SELECT 1 AS ok FROM candle_predict_candles WHERE interval_minutes = $1 AND candle_open_ms < $2 LIMIT 1`, [intervalMinutes, beforeOpenMs]); return rows.length > 0; } async function getLastGeneratedCandle(intervalMinutes) { const rows = await (0, connection_1.query)(`SELECT open_price, high_price, low_price, close_price FROM candle_predict_candles WHERE interval_minutes = $1 ORDER BY candle_open_ms DESC LIMIT 1`, [intervalMinutes]); if (!rows[0]) return null; return { open: Number(rows[0].open_price), high: Number(rows[0].high_price), low: Number(rows[0].low_price), close: Number(rows[0].close_price), }; } async function getLastCandleOpenMs(intervalMinutes) { const rows = await (0, connection_1.query)(`SELECT candle_open_ms FROM candle_predict_candles WHERE interval_minutes = $1 ORDER BY candle_open_ms DESC LIMIT 1`, [intervalMinutes]); return rows[0] ? Number(rows[0].candle_open_ms) : null; } async function hasCandle(candleOpenMs, intervalMinutes) { const rows = await (0, connection_1.query)(`SELECT id FROM candle_predict_candles WHERE candle_open_ms = $1 AND interval_minutes = $2 LIMIT 1`, [candleOpenMs, intervalMinutes]); return rows.length > 0; } async function getPreviousCandleOhlc(candleOpenMs, intervalMinutes) { const rows = await (0, connection_1.query)(`SELECT open_price, high_price, low_price, close_price FROM candle_predict_candles WHERE interval_minutes = $2 AND candle_open_ms < $1 ORDER BY candle_open_ms DESC LIMIT 1`, [candleOpenMs, intervalMinutes]); if (!rows[0]) return null; return { open: Number(rows[0].open_price), high: Number(rows[0].high_price), low: Number(rows[0].low_price), close: Number(rows[0].close_price), }; } async function listRecentCandleOutcomes(intervalMinutes, limit = 10) { const rows = await (0, connection_1.query)(`SELECT outcome FROM candle_predict_candles WHERE interval_minutes = $1 ORDER BY candle_open_ms DESC LIMIT $2`, [intervalMinutes, limit]); return rows.map((r) => r.outcome); } async function incrementRoundBetCount(roundId) { await (0, connection_1.query)('UPDATE candle_predict_rounds SET total_bets = total_bets + 1 WHERE id = $1', [roundId]); } async function createBet(input) { const rows = await (0, connection_1.query)(`INSERT INTO candle_predict_bets ( round_id, user_id, direction, stake_raw, stake_display, wallet_type_id, interval_minutes, is_auto, stake_account_kind, prediction_mode ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'single') RETURNING *`, [ input.roundId, input.userId, input.direction, input.stakeRaw.toString(), input.stakeDisplay, input.walletTypeId, input.intervalMinutes, input.isAuto ?? false, input.stakeAccountKind ?? 'main', ]); return rows[0]; } async function getUserBetForRound(roundId, userId) { const rows = await (0, connection_1.query)(`SELECT * FROM candle_predict_bets WHERE round_id = $1 AND user_id = $2 AND prediction_mode = 'single'`, [roundId, userId]); return rows[0] ?? null; } async function getBetById(betId) { const rows = await (0, connection_1.query)(`SELECT b.*, r.settled_at FROM candle_predict_bets b LEFT JOIN candle_predict_rounds r ON r.id = b.round_id WHERE b.id = $1`, [betId]); return rows[0] ?? null; } async function listPendingBetsForRound(roundId) { return (0, connection_1.query)("SELECT * FROM candle_predict_bets WHERE round_id = $1 AND status = 'pending'", [roundId]); } async function updateBetOutcome(betId, status, payoutRaw) { await (0, connection_1.query)('UPDATE candle_predict_bets SET status = $2, payout_raw = $3 WHERE id = $1', [betId, status, payoutRaw.toString()]); } async function updateBetSequenceStep(betId, sequenceStep) { await (0, connection_1.query)('UPDATE candle_predict_bets SET sequence_step = $2 WHERE id = $1', [ betId, sequenceStep, ]); } async function listMultiLevels() { return (0, connection_1.query)('SELECT * FROM candle_predict_multi_levels ORDER BY sort_order ASC, level ASC'); } async function listEnabledMultiLevels() { return (0, connection_1.query)('SELECT * FROM candle_predict_multi_levels WHERE enabled = TRUE ORDER BY sort_order ASC, level ASC'); } async function getMultiLevel(level) { const rows = await (0, connection_1.query)('SELECT * FROM candle_predict_multi_levels WHERE level = $1', [level]); return rows[0] ?? null; } async function upsertMultiLevel(input) { const rows = await (0, connection_1.query)(`INSERT INTO candle_predict_multi_levels (level, enabled, payout_multiplier, pool_multiplier, sort_order) VALUES ( $1::smallint, COALESCE($2::boolean, TRUE), COALESCE($3::numeric, 1::numeric), COALESCE($4::numeric, COALESCE($3::numeric, 1::numeric)), COALESCE($5::integer, $1::integer) ) ON CONFLICT (level) DO UPDATE SET enabled = COALESCE($2::boolean, candle_predict_multi_levels.enabled), payout_multiplier = COALESCE($3::numeric, candle_predict_multi_levels.payout_multiplier), pool_multiplier = COALESCE($4::numeric, candle_predict_multi_levels.pool_multiplier), sort_order = COALESCE($5::integer, candle_predict_multi_levels.sort_order), updated_at = NOW() RETURNING *`, [ input.level, input.enabled ?? null, input.payoutMultiplier ?? null, input.poolMultiplier ?? null, input.sortOrder ?? null, ]); return rows[0]; } async function getUserActiveMultiBet(userId, intervalMinutes) { const rows = await (0, connection_1.query)(`SELECT * FROM candle_predict_bets WHERE user_id = $1 AND interval_minutes = $2 AND prediction_mode = 'multi_candle' AND status = 'in_progress' LIMIT 1`, [userId, intervalMinutes]); return rows[0] ?? null; } async function createMultiCandleBet(input) { const firstDirection = input.sequenceDirections[0]; const rows = await (0, connection_1.query)(`INSERT INTO candle_predict_bets ( round_id, user_id, direction, stake_raw, stake_display, wallet_type_id, interval_minutes, stake_account_kind, prediction_mode, sequence_directions, multi_level, sequence_step, anchor_candle_open_ms, status ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'multi_candle', $9::jsonb, $10, 0, $11, 'in_progress') RETURNING *`, [ input.roundId, input.userId, firstDirection, input.stakeRaw.toString(), input.stakeDisplay, input.walletTypeId, input.intervalMinutes, input.stakeAccountKind, JSON.stringify(input.sequenceDirections), input.level, input.anchorCandleOpenMs, ]); return rows[0]; } /** Multi bets whose current validation candle matches this maturity open time. */ async function listMultiBetsForValidationAtOpenMs(candleOpenMs) { return (0, connection_1.query)(`SELECT * FROM candle_predict_bets WHERE prediction_mode = 'multi_candle' AND status = 'in_progress' AND anchor_candle_open_ms IS NOT NULL AND anchor_candle_open_ms::bigint + sequence_step::bigint * interval_minutes::bigint * 60000 = $1`, [candleOpenMs]); } async function countMultiBetsForValidationAtOpenMs(candleOpenMs) { const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE prediction_mode = 'multi_candle' AND status = 'in_progress' AND anchor_candle_open_ms IS NOT NULL AND anchor_candle_open_ms::bigint + sequence_step::bigint * interval_minutes::bigint * 60000 = $1`, [candleOpenMs]); return Number(rows[0]?.count ?? 0); } /** Distinct candle open times where an in-progress multi bet awaits validation (≤ nowMs). */ async function listDueMultiValidationCandleOpenMs(nowMs) { const rows = await (0, connection_1.query)(`SELECT DISTINCT ( anchor_candle_open_ms::bigint + sequence_step::bigint * interval_minutes::bigint * 60000 ) AS open_ms FROM candle_predict_bets WHERE prediction_mode = 'multi_candle' AND status = 'in_progress' AND anchor_candle_open_ms IS NOT NULL AND anchor_candle_open_ms::bigint + sequence_step::bigint * interval_minutes::bigint * 60000 <= $1 ORDER BY open_ms ASC`, [nowMs]); return rows.map((r) => Number(r.open_ms)); } /** Real-money pool contribution from multi bets at their final candle. * Pool weight = stake × pool_multiplier (admin-configured per level). */ async function getMultiCandlePoolContributions(candleOpenMs) { const rows = await (0, connection_1.query)(`SELECT (b.sequence_directions->>(b.multi_level - 1)) AS direction, COALESCE(SUM(b.stake_display * ml.pool_multiplier), 0)::text AS total FROM candle_predict_bets b INNER JOIN candle_predict_multi_levels ml ON ml.level = b.multi_level WHERE b.prediction_mode = 'multi_candle' AND b.status = 'in_progress' AND ${REAL_MONEY_POOL_SQL_B} AND b.anchor_candle_open_ms::bigint + (b.multi_level - 1)::bigint * b.interval_minutes::bigint * 60000 = $1 AND b.sequence_step = b.multi_level - 1 GROUP BY 1`, [candleOpenMs]); let shortPool = 0; let longPool = 0; for (const r of rows) { if (r.direction === 'short') shortPool = Number(r.total); if (r.direction === 'long') longPool = Number(r.total); } return { shortPool, longPool }; } async function listRecentBets(userId, limit = 20, offset = 0, intervalMinutes, stakeAccountKind, status) { const where = ['b.user_id = $1']; const params = [userId]; if (intervalMinutes != null) { params.push(intervalMinutes); where.push(`b.interval_minutes = $${params.length}`); } if (stakeAccountKind === 'main' || stakeAccountKind === 'bonus' || stakeAccountKind === 'test') { params.push(stakeAccountKind); where.push(`b.stake_account_kind = $${params.length}`); } if (status && ['pending', 'in_progress', 'won', 'lost', 'refunded'].includes(status)) { params.push(status); where.push(`b.status = $${params.length}`); } params.push(limit); const limitIdx = params.length; params.push(offset); const offsetIdx = params.length; return (0, connection_1.query)(`SELECT b.*, r.candle_open_ms FROM candle_predict_bets b INNER JOIN candle_predict_rounds r ON r.id = b.round_id WHERE ${where.join(' AND ')} ORDER BY b.created_at DESC LIMIT $${limitIdx} OFFSET $${offsetIdx}`, params); } async function countUserPredictions(userId, intervalMinutes, stakeAccountKind, status) { const where = ['user_id = $1']; const params = [userId]; if (intervalMinutes != null) { params.push(intervalMinutes); where.push(`interval_minutes = $${params.length}`); } if (stakeAccountKind === 'main' || stakeAccountKind === 'bonus' || stakeAccountKind === 'test') { params.push(stakeAccountKind); where.push(`stake_account_kind = $${params.length}`); } if (status && ['pending', 'in_progress', 'won', 'lost', 'refunded'].includes(status)) { params.push(status); where.push(`status = $${params.length}`); } const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE ${where.join(' AND ')}`, params); return Number(rows[0]?.count ?? 0); } async function getAutoSettings(userId) { const rows = await (0, connection_1.query)('SELECT * FROM candle_predict_auto_settings WHERE user_id = $1', [userId]); return rows[0] ?? null; } async function upsertAutoSettings(userId, input) { const rows = await (0, connection_1.query)(`INSERT INTO candle_predict_auto_settings (user_id, enabled, direction, stake_display, mode, interval_seconds, period_minutes, stake_account_kind, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW()) ON CONFLICT (user_id) DO UPDATE SET enabled = EXCLUDED.enabled, direction = EXCLUDED.direction, stake_display = EXCLUDED.stake_display, mode = EXCLUDED.mode, interval_seconds = EXCLUDED.interval_seconds, period_minutes = EXCLUDED.period_minutes, stake_account_kind = EXCLUDED.stake_account_kind, updated_at = NOW() RETURNING *`, [ userId, input.enabled, input.direction, input.stakeDisplay, input.mode, input.intervalSeconds ?? null, input.periodMinutes ?? 1, input.stakeAccountKind ?? 'main', ]); return rows[0]; } async function touchAutoBet(userId) { await (0, connection_1.query)('UPDATE candle_predict_auto_settings SET last_auto_bet_at = NOW(), updated_at = NOW() WHERE user_id = $1', [userId]); } async function listEnabledAutoSettings() { return (0, connection_1.query)(`SELECT * FROM candle_predict_auto_settings WHERE enabled = TRUE`); } async function listOverdueUnsettledRounds(nowMs) { return (0, connection_1.query)(`SELECT * FROM candle_predict_rounds WHERE settled_at IS NULL AND candle_open_ms <= $1 ORDER BY candle_open_ms ASC`, [nowMs]); } async function getRoundToSettle(intervalMinutes) { const rows = await (0, connection_1.query)(`SELECT * FROM candle_predict_rounds WHERE status = 'locked' AND interval_minutes = $1 AND settled_at IS NULL ORDER BY candle_open_ms ASC LIMIT 1`, [intervalMinutes]); return rows[0] ?? null; } async function getBettingRound(intervalMinutes) { const rows = await (0, connection_1.query)(`SELECT * FROM candle_predict_rounds WHERE status = 'betting' AND interval_minutes = $1 ORDER BY candle_open_ms ASC LIMIT 1`, [intervalMinutes]); return rows[0] ?? null; } async function listActiveIntervals() { return (0, connection_1.query)(`SELECT * FROM candle_predict_intervals WHERE is_active = TRUE ORDER BY sort_order ASC, interval_minutes ASC`); } async function listAllIntervals() { return (0, connection_1.query)(`SELECT * FROM candle_predict_intervals ORDER BY sort_order ASC, interval_minutes ASC`); } async function getIntervalByMinutes(intervalMinutes) { const rows = await (0, connection_1.query)('SELECT * FROM candle_predict_intervals WHERE interval_minutes = $1', [intervalMinutes]); return rows[0] ?? null; } async function getDefaultInterval() { const rows = await (0, connection_1.query)(`SELECT * FROM candle_predict_intervals WHERE is_active = TRUE ORDER BY is_default DESC, sort_order ASC, interval_minutes ASC LIMIT 1`); return rows[0] ?? null; } async function createInterval(input) { const rows = await (0, connection_1.query)(`INSERT INTO candle_predict_intervals ( interval_minutes, label, sort_order, is_active, is_default, prediction_window_seconds, tie_tolerance_percent, tie_tolerance_max_percent, tie_tolerance_min_enabled, tie_tolerance_max_enabled, payout_multiplier, pool_multiplier, base_price, chart_candle_limit ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING *`, [ input.intervalMinutes, input.label, input.sortOrder ?? input.intervalMinutes, input.isActive ?? true, input.isDefault ?? false, input.predictionWindowSeconds ?? null, input.tieTolerancePercent ?? null, input.tieToleranceMaxPercent ?? null, input.tieToleranceMinEnabled ?? null, input.tieToleranceMaxEnabled ?? null, input.payoutMultiplier ?? null, input.poolMultiplier ?? null, input.basePrice ?? null, input.chartCandleLimit ?? 120, ]); return rows[0]; } async function updateInterval(id, input) { const current = await (0, connection_1.query)('SELECT * FROM candle_predict_intervals WHERE id = $1', [id]); if (!current[0]) return null; const c = current[0]; const rows = await (0, connection_1.query)(`UPDATE candle_predict_intervals SET interval_minutes = $2, label = $3, sort_order = $4, is_active = $5, is_default = $6, prediction_window_seconds = $7, tie_tolerance_percent = $8, tie_tolerance_max_percent = $9, tie_tolerance_min_enabled = $10, tie_tolerance_max_enabled = $11, payout_multiplier = $12, pool_multiplier = $13, base_price = $14, chart_candle_limit = $15, updated_at = NOW() WHERE id = $1 RETURNING *`, [ id, input.intervalMinutes ?? c.interval_minutes, input.label ?? c.label, input.sortOrder ?? c.sort_order, input.isActive ?? c.is_active, input.isDefault ?? c.is_default, input.predictionWindowSeconds !== undefined ? input.predictionWindowSeconds : c.prediction_window_seconds, input.tieTolerancePercent !== undefined ? input.tieTolerancePercent : c.tie_tolerance_percent, input.tieToleranceMaxPercent !== undefined ? input.tieToleranceMaxPercent : c.tie_tolerance_max_percent, input.tieToleranceMinEnabled !== undefined ? input.tieToleranceMinEnabled : c.tie_tolerance_min_enabled, input.tieToleranceMaxEnabled !== undefined ? input.tieToleranceMaxEnabled : c.tie_tolerance_max_enabled, input.payoutMultiplier !== undefined ? input.payoutMultiplier : c.payout_multiplier, input.poolMultiplier !== undefined ? input.poolMultiplier : c.pool_multiplier, input.basePrice !== undefined ? input.basePrice : c.base_price, input.chartCandleLimit ?? c.chart_candle_limit, ]); return rows[0] ?? null; } async function clearDefaultIntervalExcept(id) { await (0, connection_1.query)('UPDATE candle_predict_intervals SET is_default = FALSE WHERE id <> $1 AND is_default = TRUE', [id]); } async function deleteInterval(id) { const rows = await (0, connection_1.query)('DELETE FROM candle_predict_intervals WHERE id = $1 RETURNING id', [id]); return rows.length > 0; } async function countRoundsForInterval(intervalMinutes) { const rows = await (0, connection_1.query)('SELECT COUNT(*)::text AS count FROM candle_predict_rounds WHERE interval_minutes = $1', [intervalMinutes]); return Number(rows[0]?.count ?? 0); } /** Advisory lock key for serializing daily-revenue reads/updates across settlements. */ const DAILY_REVENUE_ADVISORY_LOCK = 87231401; /** Max time (ms) to wait for the advisory lock before giving up. */ const DAILY_REVENUE_LOCK_TIMEOUT_MS = 15000; async function withDailyRevenueLock(fn) { const client = await (0, connection_1.getClient)(); try { await client.query('BEGIN'); await client.query(`SET LOCAL lock_timeout = ${DAILY_REVENUE_LOCK_TIMEOUT_MS}`); await client.query(`SET LOCAL statement_timeout = 60000`); await client.query('SELECT pg_advisory_xact_lock($1)', [DAILY_REVENUE_ADVISORY_LOCK]); const result = await fn(); await client.query('COMMIT'); return result; } catch (err) { await client.query('ROLLBACK').catch(() => undefined); throw err; } finally { client.release(); } } /** * Ensure today's UTC row exists and return current net_pnl_raw (locked via advisory lock caller). */ async function getOrCreateDailyRevenueNetRaw(revenueDate) { await (0, connection_1.query)(`INSERT INTO candle_predict_daily_revenue (revenue_date, net_pnl_raw) VALUES ($1::date, 0) ON CONFLICT (revenue_date) DO NOTHING`, [revenueDate]); const rows = await (0, connection_1.query)(`SELECT net_pnl_raw::text AS net_pnl_raw FROM candle_predict_daily_revenue WHERE revenue_date = $1::date`, [revenueDate]); return BigInt(rows[0]?.net_pnl_raw ?? '0'); } async function addDailyRevenuePnl(revenueDate, pnlDeltaRaw) { if (pnlDeltaRaw === 0n) { return getOrCreateDailyRevenueNetRaw(revenueDate); } await (0, connection_1.query)(`INSERT INTO candle_predict_daily_revenue (revenue_date, net_pnl_raw, updated_at) VALUES ($1::date, $2::numeric, NOW()) ON CONFLICT (revenue_date) DO UPDATE SET net_pnl_raw = candle_predict_daily_revenue.net_pnl_raw + EXCLUDED.net_pnl_raw, updated_at = NOW()`, [revenueDate, pnlDeltaRaw.toString()]); return getOrCreateDailyRevenueNetRaw(revenueDate); } async function getDailyRevenueNetRaw(revenueDate) { const rows = await (0, connection_1.query)(`SELECT net_pnl_raw::text AS net_pnl_raw FROM candle_predict_daily_revenue WHERE revenue_date = $1::date`, [revenueDate]); return BigInt(rows[0]?.net_pnl_raw ?? '0'); } //# sourceMappingURL=candlePredictRepository.js.map