diff --git a/.vscode/settings.json b/.vscode/settings.json index 0517eb64..af07a91a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,6 +4,6 @@ ".vscode/schemas/pubspec-minimal.json": "**/pubspec.yaml" }, "dart.flutterRunAdditionalArgs": [ - "--dart-define-from-file=dart_defines.dev.json" + "--dart-define-from-file=prediqo_mobile/dart_defines.dev.json" ] } diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 9443ad34..cbffb0a6 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -514,6 +514,8 @@ CREATE TABLE IF NOT EXISTS candle_predict_config ( base_price NUMERIC(18,6) NOT NULL DEFAULT 100.000000, payout_multiplier NUMERIC(6,3) NOT NULL DEFAULT 1.900, pool_multiplier NUMERIC(6,3) NOT NULL DEFAULT 1.900, + daily_revenue_target NUMERIC(18,6) NOT NULL DEFAULT 0, + daily_revenue_overflow_strategy VARCHAR(16) NOT NULL DEFAULT 'neutral', wallet_type_code VARCHAR(32) NOT NULL DEFAULT 'USDT_TRC20', auto_modes JSONB NOT NULL DEFAULT '["each_round","interval"]'::jsonb, is_active BOOLEAN NOT NULL DEFAULT TRUE, @@ -1476,6 +1478,33 @@ BEGIN END IF; END $$; +-- Daily revenue target outcome mode (independent of majority/minority) +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'candle_predict_config' + AND column_name = 'daily_revenue_target' + ) THEN + ALTER TABLE candle_predict_config + ADD COLUMN daily_revenue_target NUMERIC(18,6) NOT NULL DEFAULT 0; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'candle_predict_config' + AND column_name = 'daily_revenue_overflow_strategy' + ) THEN + ALTER TABLE candle_predict_config + ADD COLUMN daily_revenue_overflow_strategy VARCHAR(16) NOT NULL DEFAULT 'neutral'; + END IF; +END $$; + +CREATE TABLE IF NOT EXISTS candle_predict_daily_revenue ( + revenue_date DATE PRIMARY KEY, + net_pnl_raw NUMERIC(28,0) NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + CREATE TABLE IF NOT EXISTS candle_predict_multi_levels ( level SMALLINT PRIMARY KEY CHECK (level >= 2 AND level <= 20), enabled BOOLEAN NOT NULL DEFAULT TRUE, @@ -2269,7 +2298,7 @@ BEGIN 'users', 'roles', 'ledger_accounts', 'ledger_entries', 'transactions', 'hot_wallets', 'cold_wallets', 'ledger_adjustments', 'candle_predict_config', 'candle_predict_intervals', 'candle_predict_multi_levels', - 'candle_predict_bets', 'candle_predict_rounds', + 'candle_predict_bets', 'candle_predict_rounds', 'candle_predict_daily_revenue', 'test_wallet_credits', 'test_wallet_settings', 'referral_program_settings', 'platform_bonus_pools', 'exchange_funding', 'system_settings', 'withdrawal_locks', 'deposit_scanner_state', diff --git a/backend/src/domain/candle-predict/index.ts b/backend/src/domain/candle-predict/index.ts index 12840c6f..fca51211 100644 --- a/backend/src/domain/candle-predict/index.ts +++ b/backend/src/domain/candle-predict/index.ts @@ -24,6 +24,15 @@ import { isMaturityBoundaryForInterval, } from '../../services/gameTimingService'; import * as multiService from '../../services/candlePredictMultiService'; +import { + pickRandomDirectionalOutcome, + projectMajorityWinSettlement, + resolveDailyRevenueOutcome, + usdtDisplayToRaw, + usdtRawToDisplay, + utcRevenueDate, + type DailyRevenueOverflowStrategy, +} from '../../services/dailyRevenueOutcomeService'; import { publishRoundState, publishCandleAppend } from './realtime/publishRoundState'; import { publishRoundEvent } from '../../realtime/redis/pubsub'; import { loadCachedRound } from './read/roundCache'; @@ -143,7 +152,19 @@ function parseStakeDisplay(body: Record, fallback: number): num } function parsePoolWinnerRule(value: string | null | undefined): repo.PoolWinnerRule { - return value === 'majority' ? 'majority' : 'minority'; + if (value === 'majority') return 'majority'; + if (value === 'daily_revenue') return 'daily_revenue'; + return 'minority'; +} + +function parseDailyRevenueOverflowStrategy( + value: string | null | undefined +): DailyRevenueOverflowStrategy { + return value === 'minority' ? 'minority' : 'neutral'; +} + +function isRealMoneyStakeKind(kind: string | null | undefined): boolean { + return kind === 'main' || kind === 'bonus' || kind == null; } function validateNeutralityRules(input: { @@ -203,6 +224,10 @@ function mapConfig(row: repo.CandlePredictConfigRow) { basePrice: Number(row.base_price), payoutMultiplier: Number(row.payout_multiplier), poolMultiplier: Number(row.pool_multiplier), + dailyRevenueTarget: Number(row.daily_revenue_target ?? 0), + dailyRevenueOverflowStrategy: parseDailyRevenueOverflowStrategy( + row.daily_revenue_overflow_strategy + ), walletTypeCode: row.wallet_type_code, autoModes: row.auto_modes, isActive: row.is_active, @@ -223,6 +248,8 @@ type PlayerConfigDto = Omit< | 'tieToleranceMaxPercent' | 'tieToleranceMinEnabled' | 'tieToleranceMaxEnabled' + | 'dailyRevenueTarget' + | 'dailyRevenueOverflowStrategy' >; function mapConfigForPlayer(row: repo.CandlePredictConfigRow): PlayerConfigDto { @@ -233,6 +260,8 @@ function mapConfigForPlayer(row: repo.CandlePredictConfigRow): PlayerConfigDto { tieToleranceMaxPercent: _max, tieToleranceMinEnabled: _minEn, tieToleranceMaxEnabled: _maxEn, + dailyRevenueTarget: _drt, + dailyRevenueOverflowStrategy: _dros, ...player } = mapConfig(row); return player; @@ -497,7 +526,12 @@ function mapBet(row: repo.CandlePredictBetRow & { candle_open_ms?: string }) { export async function getPublicConfig() { const cfg = await repo.getConfig(); - return mapConfig(cfg); + const mapped = mapConfig(cfg); + const netRaw = await repo.getDailyRevenueNetRaw(utcRevenueDate()); + return { + ...mapped, + dailyRevenueNetToday: usdtRawToDisplay(netRaw), + }; } export async function updateAdminConfig(body: Record) { @@ -535,12 +569,35 @@ export async function updateAdminConfig(body: Record) { let poolWinnerRule: repo.PoolWinnerRule | undefined; if (typeof body.poolWinnerRule === 'string') { - if (body.poolWinnerRule !== 'minority' && body.poolWinnerRule !== 'majority') { - throw new Error('poolWinnerRule must be minority or majority'); + if ( + body.poolWinnerRule !== 'minority' && + body.poolWinnerRule !== 'majority' && + body.poolWinnerRule !== 'daily_revenue' + ) { + throw new Error('poolWinnerRule must be minority, majority, or daily_revenue'); } poolWinnerRule = body.poolWinnerRule; } + let dailyRevenueTarget: number | undefined; + if (typeof body.dailyRevenueTarget === 'number') { + if (body.dailyRevenueTarget < 0) { + throw new Error('dailyRevenueTarget must be >= 0'); + } + dailyRevenueTarget = body.dailyRevenueTarget; + } + + let dailyRevenueOverflowStrategy: repo.DailyRevenueOverflowStrategy | undefined; + if (typeof body.dailyRevenueOverflowStrategy === 'string') { + if ( + body.dailyRevenueOverflowStrategy !== 'minority' && + body.dailyRevenueOverflowStrategy !== 'neutral' + ) { + throw new Error('dailyRevenueOverflowStrategy must be minority or neutral'); + } + dailyRevenueOverflowStrategy = body.dailyRevenueOverflowStrategy; + } + const updated = await repo.updateConfig({ stakeAmounts, minStakeAmount, @@ -561,6 +618,8 @@ export async function updateAdminConfig(body: Record) { typeof body.payoutMultiplier === 'number' ? body.payoutMultiplier : undefined, poolMultiplier: typeof body.poolMultiplier === 'number' ? body.poolMultiplier : undefined, + dailyRevenueTarget, + dailyRevenueOverflowStrategy, walletTypeCode: typeof body.walletTypeCode === 'string' ? body.walletTypeCode : undefined, autoModes: Array.isArray(body.autoModes) ? (body.autoModes as string[]) : undefined, isActive: typeof body.isActive === 'boolean' ? body.isActive : undefined, @@ -613,7 +672,12 @@ export async function updateAdminConfig(body: Record) { ); } - return mapConfig(updated); + const mapped = mapConfig(updated); + const netRaw = await repo.getDailyRevenueNetRaw(utcRevenueDate()); + return { + ...mapped, + dailyRevenueNetToday: usdtRawToDisplay(netRaw), + }; } export async function listAdminIntervals() { @@ -902,7 +966,14 @@ export async function getGameState( } return { - config: includeInternal ? mapConfig(cfg) : mapConfigForPlayer(cfg), + config: includeInternal + ? { + ...mapConfig(cfg), + dailyRevenueNetToday: usdtRawToDisplay( + await repo.getDailyRevenueNetRaw(utcRevenueDate()) + ), + } + : mapConfigForPlayer(cfg), intervals: intervals.map(includeInternal ? mapIntervalDto : mapIntervalDtoForPlayer), selectedIntervalMinutes: selected.intervalMinutes, interval: includeInternal ? mapIntervalDto(selected) : mapIntervalDtoForPlayer(selected), @@ -1195,17 +1266,81 @@ async function settleMaturityAtOpenMs( /** Shared pool outcome, or per-interval auto outcomes (5-streak rule per chart). */ const outcomesByIntervalMinutes = new Map(); - if (outcomeMode === 'pool') { - const neutralityRules = buildPoolNeutralityRules(cfg, primary); - const shared = resolvePoolOutcome( - shortPool, - longPool, - neutralityRules, - parsePoolWinnerRule(cfg.pool_winner_rule) - ); + const runPoolSettlement = async () => { + const rule = parsePoolWinnerRule(cfg.pool_winner_rule); + let shared: RoundOutcome; + + if (rule === 'daily_revenue') { + const neutralityRules = buildPoolNeutralityRules(cfg, primary); + shared = await resolveDailyRevenueSharedOutcome( + cfg, + shortPool, + longPool, + candleOpenMs, + neutralityRules + ); + } else { + const neutralityRules = buildPoolNeutralityRules(cfg, primary); + shared = resolvePoolOutcome(shortPool, longPool, neutralityRules, rule); + } + for (const interval of aligning) { outcomesByIntervalMinutes.set(interval.intervalMinutes, shared); } + + const outcomeForInterval = (intervalMinutes: number): RoundOutcome => + outcomesByIntervalMinutes.get(intervalMinutes) ?? + outcomesByIntervalMinutes.get(primary.intervalMinutes)!; + + for (const interval of aligning) { + let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); + if (!round) { + round = await syncRound(interval, candleOpenMs, 'locked'); + } else if (!round.settled_at && round.status !== 'settled') { + await repo.updateRoundStatus(round.id, 'locked'); + } + } + + let housePnlDeltaRaw = 0n; + if (pendingCount > 0) { + housePnlDeltaRaw += await payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg); + } + if (multiValidationCount > 0) { + const levelRows = await repo.listMultiLevels(); + const payoutMultiplierMap = new Map( + levelRows.map((l) => [l.level, Number(l.payout_multiplier)]) + ); + housePnlDeltaRaw += await multiService.processMultiBetsAtMaturity( + candleOpenMs, + outcomeForInterval, + payoutMultiplierMap + ); + } + + if (housePnlDeltaRaw !== 0n) { + await repo.addDailyRevenuePnl(utcRevenueDate(), housePnlDeltaRaw); + } + + for (const interval of aligning) { + let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); + if (!round) { + round = await syncRound(interval, candleOpenMs, 'locked'); + } + if (round.settled_at) continue; + + await finalizeIntervalCandleAtMaturity( + round, + interval, + outcomeForInterval(interval.intervalMinutes), + shortPool, + longPool + ); + } + }; + + if (outcomeMode === 'pool') { + // Serialize daily-revenue reads + settlement PnL updates across concurrent maturities. + await repo.withDailyRevenueLock(runPoolSettlement); } else { // No real-money stake: each interval uses its own history so the // max-5 consecutive same-direction rule applies on every chart. @@ -1216,51 +1351,104 @@ async function settleMaturityAtOpenMs( resolveAutoNoBetOutcome(recentOutcomes) ); } - } - const outcomeForInterval = (intervalMinutes: number): RoundOutcome => - outcomesByIntervalMinutes.get(intervalMinutes) ?? - outcomesByIntervalMinutes.get(primary.intervalMinutes)!; + const outcomeForInterval = (intervalMinutes: number): RoundOutcome => + outcomesByIntervalMinutes.get(intervalMinutes) ?? + outcomesByIntervalMinutes.get(primary.intervalMinutes)!; - for (const interval of aligning) { - let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); - if (!round) { - round = await syncRound(interval, candleOpenMs, 'locked'); - } else if (!round.settled_at && round.status !== 'settled') { - await repo.updateRoundStatus(round.id, 'locked'); + for (const interval of aligning) { + let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); + if (!round) { + round = await syncRound(interval, candleOpenMs, 'locked'); + } else if (!round.settled_at && round.status !== 'settled') { + await repo.updateRoundStatus(round.id, 'locked'); + } + } + + if (pendingCount > 0) { + await payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg); + } + if (multiValidationCount > 0) { + const levelRows = await repo.listMultiLevels(); + const payoutMultiplierMap = new Map( + levelRows.map((l) => [l.level, Number(l.payout_multiplier)]) + ); + await multiService.processMultiBetsAtMaturity( + candleOpenMs, + outcomeForInterval, + payoutMultiplierMap + ); + } + + for (const interval of aligning) { + let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); + if (!round) { + round = await syncRound(interval, candleOpenMs, 'locked'); + } + if (round.settled_at) continue; + + await finalizeIntervalCandleAtMaturity( + round, + interval, + outcomeForInterval(interval.intervalMinutes), + shortPool, + longPool + ); } } +} - if (pendingCount > 0) { - await payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg); - } - if (multiValidationCount > 0) { +async function resolveDailyRevenueSharedOutcome( + cfg: repo.CandlePredictConfigRow, + shortPool: number, + longPool: number, + candleOpenMs: number, + neutralityRules: PoolNeutralityRules +): Promise { + const revenueDate = utcRevenueDate(); + const dailyNetRaw = await repo.getOrCreateDailyRevenueNetRaw(revenueDate); + const random = pickRandomDirectionalOutcome(); + const randomWinner = random.winner ?? 'long'; + + const majority: 'short' | 'long' | null = + shortPool === longPool ? null : shortPool > longPool ? 'short' : 'long'; + + let projectedMajorityRoundPnlRaw = 0n; + if (majority != null) { + const allIntervals = await loadResolvedIntervals(cfg, true); + const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i])); const levelRows = await repo.listMultiLevels(); - const payoutMultiplierMap = new Map( - levelRows.map((l) => [l.level, Number(l.payout_multiplier)]) - ); - await multiService.processMultiBetsAtMaturity( - candleOpenMs, - outcomeForInterval, - payoutMultiplierMap - ); + const multiMult = new Map(levelRows.map((l) => [l.level, Number(l.payout_multiplier)])); + const singles = await repo.listPendingBetsForMaturity(candleOpenMs); + const multis = await repo.listMultiBetsForValidationAtOpenMs(candleOpenMs); + const projected = projectMajorityWinSettlement({ + majority, + singles, + multis: multis.map((b) => ({ + sequence_directions: b.sequence_directions, + multi_level: b.multi_level, + sequence_step: b.sequence_step, + stake_raw: b.stake_raw, + stake_display: b.stake_display, + stake_account_kind: b.stake_account_kind, + })), + singlePayoutMultiplier: (intervalMinutes) => + intervalMap.get(intervalMinutes)?.payoutMultiplier ?? Number(cfg.payout_multiplier), + multiPayoutMultiplier: (level) => multiMult.get(level) ?? 1, + }); + projectedMajorityRoundPnlRaw = projected.roundPnlRaw; } - for (const interval of aligning) { - let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); - if (!round) { - round = await syncRound(interval, candleOpenMs, 'locked'); - } - if (round.settled_at) continue; - - await finalizeIntervalCandleAtMaturity( - round, - interval, - outcomeForInterval(interval.intervalMinutes), - shortPool, - longPool - ); - } + return resolveDailyRevenueOutcome({ + shortPool, + longPool, + randomWinner, + projectedMajorityRoundPnlRaw, + dailyNetRaw, + targetRaw: usdtDisplayToRaw(Number(cfg.daily_revenue_target ?? 0)), + overflowStrategy: parseDailyRevenueOverflowStrategy(cfg.daily_revenue_overflow_strategy), + neutralityRules, + }); } async function finalizeIntervalCandleAtMaturity( @@ -1354,10 +1542,11 @@ async function payOutBetsAtMaturity( candleOpenMs: number, outcomeForInterval: (intervalMinutes: number) => RoundOutcome, cfg: repo.CandlePredictConfigRow -): Promise { +): Promise { const bets = await repo.listPendingBetsForMaturity(candleOpenMs); const allIntervals = await loadResolvedIntervals(cfg, true); const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i])); + let housePnlRaw = 0n; for (const bet of bets) { const outcome = outcomeForInterval(bet.interval_minutes); @@ -1369,10 +1558,12 @@ async function payOutBetsAtMaturity( } as ResolvedInterval); const multiplier = interval.payoutMultiplier; const stakeRaw = BigInt(bet.stake_raw); + const countInDaily = isRealMoneyStakeKind(bet.stake_account_kind); if (outcome.type === 'neutral') { await creditGameOutcome(bet, stakeRaw, 'game_refund'); await repo.updateBetOutcome(bet.id, 'refunded', stakeRaw); + if (countInDaily) housePnlRaw += 0n; void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, @@ -1407,6 +1598,7 @@ async function payOutBetsAtMaturity( const payoutRaw = BigInt(Math.round(Number(stakeRaw) * multiplier)); await creditGameOutcome(bet, payoutRaw, 'game_payout'); await repo.updateBetOutcome(bet.id, 'won', payoutRaw); + if (countInDaily) housePnlRaw += stakeRaw - payoutRaw; void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, @@ -1435,6 +1627,7 @@ async function payOutBetsAtMaturity( }); } else { await repo.updateBetOutcome(bet.id, 'lost', 0n); + if (countInDaily) housePnlRaw += stakeRaw; void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, @@ -1450,6 +1643,8 @@ async function payOutBetsAtMaturity( } queueUserAdminStatsRefresh(bet.user_id); } + + return housePnlRaw; } async function processAutoBets( diff --git a/backend/src/repositories/candlePredictRepository.ts b/backend/src/repositories/candlePredictRepository.ts index 2ca38e2d..b84b15d2 100644 --- a/backend/src/repositories/candlePredictRepository.ts +++ b/backend/src/repositories/candlePredictRepository.ts @@ -1,6 +1,7 @@ -import { query } from '../db/connection'; +import { query, getClient } from '../db/connection'; -export type PoolWinnerRule = 'minority' | 'majority'; +export type PoolWinnerRule = 'minority' | 'majority' | 'daily_revenue'; +export type DailyRevenueOverflowStrategy = 'minority' | 'neutral'; export type CandlePredictConfigRow = { id: number; @@ -18,6 +19,8 @@ export type CandlePredictConfigRow = { base_price: string; payout_multiplier: string; pool_multiplier: string; + daily_revenue_target: string; + daily_revenue_overflow_strategy: DailyRevenueOverflowStrategy; wallet_type_code: string; auto_modes: string[]; is_active: boolean; @@ -147,6 +150,8 @@ export type ConfigUpdate = Partial<{ basePrice: number; payoutMultiplier: number; poolMultiplier: number; + dailyRevenueTarget: number; + dailyRevenueOverflowStrategy: DailyRevenueOverflowStrategy; walletTypeCode: string; autoModes: string[]; isActive: boolean; @@ -179,6 +184,8 @@ export async function updateConfig(update: ConfigUpdate): Promise(fn: () => Promise): Promise { + const client = await getClient(); + try { + await client.query('BEGIN'); + 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). + */ +export async function getOrCreateDailyRevenueNetRaw(revenueDate: string): Promise { + await 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 query<{ net_pnl_raw: string }[]>( + `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'); +} + +export async function addDailyRevenuePnl( + revenueDate: string, + pnlDeltaRaw: bigint +): Promise { + if (pnlDeltaRaw === 0n) { + return getOrCreateDailyRevenueNetRaw(revenueDate); + } + await 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); +} + +export async function getDailyRevenueNetRaw(revenueDate: string): Promise { + const rows = await query<{ net_pnl_raw: string }[]>( + `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'); +} diff --git a/backend/src/services/candleGenerationService.ts b/backend/src/services/candleGenerationService.ts index 503c3fec..898a6b5b 100644 --- a/backend/src/services/candleGenerationService.ts +++ b/backend/src/services/candleGenerationService.ts @@ -105,51 +105,31 @@ export type PoolNeutralityRules = { function neutralOutcome(shortPct: number, longPct: number): RoundOutcome { - let neutralColor: 'red' | 'green' = 'green'; - if (shortPct < longPct) neutralColor = 'red'; - else if (longPct < shortPct) neutralColor = 'green'; - return { type: 'neutral', winner: null, neutralColor }; - } - - -export function resolvePoolOutcome( - +/** + * Shared neutrality checks used by majority/minority and daily-revenue modes. + * Returns a neutral outcome when rules apply; otherwise null. + */ +export function resolvePoolNeutrality( shortPool: number, - longPool: number, - - rules: PoolNeutralityRules, - - poolWinnerRule: PoolWinnerRule = 'minority' - -): RoundOutcome { - + rules: PoolNeutralityRules +): RoundOutcome | null { const total = shortPool + longPool; - if (total <= 0) { - return { type: 'neutral', winner: null, neutralColor: 'green' }; - } - - const shortPct = (shortPool / total) * 100; - const longPct = (longPool / total) * 100; - const gap = Math.abs(shortPct - longPct); - const majorityPct = Math.max(shortPct, longPct); - - if (rules.minToleranceEnabled && gap <= rules.minTolerancePercent) { return neutralOutcome(shortPct, longPct); } @@ -165,6 +145,18 @@ export function resolvePoolOutcome( return neutralOutcome(shortPct, longPct); } + return null; +} + +export function resolvePoolOutcome( + shortPool: number, + longPool: number, + rules: PoolNeutralityRules, + poolWinnerRule: PoolWinnerRule = 'minority' +): RoundOutcome { + const neutral = resolvePoolNeutrality(shortPool, longPool, rules); + if (neutral) return neutral; + const shortWins = poolWinnerRule === 'majority' ? shortPool > longPool : shortPool < longPool; diff --git a/backend/src/services/candlePredictMultiService.ts b/backend/src/services/candlePredictMultiService.ts index e5a0e479..0edb8812 100644 --- a/backend/src/services/candlePredictMultiService.ts +++ b/backend/src/services/candlePredictMultiService.ts @@ -184,15 +184,17 @@ export async function processMultiBetsAtMaturity( candleOpenMs: number, outcomeForInterval: RoundOutcome | ((intervalMinutes: number) => RoundOutcome), payoutMultiplierMap: Map -): Promise { +): Promise { const bets = await repo.listMultiBetsForValidationAtOpenMs(candleOpenMs); - if (!bets.length) return; + if (!bets.length) return 0n; const resolveOutcome = typeof outcomeForInterval === 'function' ? outcomeForInterval : (_intervalMinutes: number) => outcomeForInterval; + let housePnlRaw = 0n; + for (const bet of bets) { const outcome = resolveOutcome(bet.interval_minutes); const sequence = parseSequenceDirections(bet.sequence_directions); @@ -200,6 +202,10 @@ export async function processMultiBetsAtMaturity( const step = bet.sequence_step ?? 0; const expected = sequence[step]; const stakeRaw = BigInt(bet.stake_raw); + const countInDaily = + bet.stake_account_kind === 'main' || + bet.stake_account_kind === 'bonus' || + bet.stake_account_kind == null; if (outcome.type === 'neutral') { await creditGameOutcome(bet, stakeRaw, 'game_refund'); @@ -239,6 +245,7 @@ export async function processMultiBetsAtMaturity( const actual = outcome.winner; if (!expected || actual !== expected) { await repo.updateBetOutcome(bet.id, 'lost', 0n); + if (countInDaily) housePnlRaw += stakeRaw; void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, @@ -271,6 +278,7 @@ export async function processMultiBetsAtMaturity( const payoutRaw = stakeToRaw(computeMultiCandleWinPayout(Number(bet.stake_display), payoutMultiplier)); await creditGameOutcome(bet, payoutRaw, 'game_payout'); await repo.updateBetOutcome(bet.id, 'won', payoutRaw); + if (countInDaily) housePnlRaw += stakeRaw - payoutRaw; void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, @@ -303,4 +311,6 @@ export async function processMultiBetsAtMaturity( queueUserAdminStatsRefresh(bet.user_id); await notifyMultiBetUpdate(bet.user_id, bet.interval_minutes, null); } + + return housePnlRaw; } diff --git a/backend/src/services/dailyRevenueOutcomeService.ts b/backend/src/services/dailyRevenueOutcomeService.ts new file mode 100644 index 00000000..ec9832d1 --- /dev/null +++ b/backend/src/services/dailyRevenueOutcomeService.ts @@ -0,0 +1,209 @@ +/** + * Daily-revenue outcome strategy for candle-predict. + * + * Pipeline: + * 1. Optional shared pool neutrality (min/max tolerance, equal pools) — same as other modes. + * 2. Random directional candle. + * 3. Financial gate if the random pick is the majority side. + * 4. Overflow strategy when the daily revenue floor would be breached. + */ + +import type { PoolNeutralityRules, RoundOutcome } from './candleGenerationService'; +import { resolvePoolNeutrality } from './candleGenerationService'; + +export type DailyRevenueOverflowStrategy = 'minority' | 'neutral'; + +export type DailyRevenueOutcomeInput = { + shortPool: number; + longPool: number; + /** Random directional pick before the financial gate. */ + randomWinner: 'short' | 'long'; + /** Projected house PnL (stakes − payouts) if the majority side wins. */ + projectedMajorityRoundPnlRaw: bigint; + dailyNetRaw: bigint; + targetRaw: bigint; + overflowStrategy: DailyRevenueOverflowStrategy; + /** When set, existing neutral-round rules run first (shared with majority/minority). */ + neutralityRules?: PoolNeutralityRules; +}; + +function directional(winner: 'short' | 'long'): RoundOutcome { + return winner === 'short' + ? { type: 'short_win', winner: 'short', neutralColor: null } + : { type: 'long_win', winner: 'long', neutralColor: null }; +} + +function neutralFromPools(shortPool: number, longPool: number): RoundOutcome { + let neutralColor: 'red' | 'green' = 'green'; + if (shortPool < longPool) neutralColor = 'red'; + else if (longPool < shortPool) neutralColor = 'green'; + return { type: 'neutral', winner: null, neutralColor }; +} + +function majoritySide(shortPool: number, longPool: number): 'short' | 'long' | null { + if (shortPool === longPool) return null; + return shortPool > longPool ? 'short' : 'long'; +} + +function minoritySide(shortPool: number, longPool: number): 'short' | 'long' | null { + if (shortPool === longPool) return null; + return shortPool < longPool ? 'short' : 'long'; +} + +/** 50/50 random directional candle outcome. */ +export function pickRandomDirectionalOutcome( + random: () => number = Math.random +): RoundOutcome { + return random() < 0.5 ? directional('short') : directional('long'); +} + +/** + * Resolve round outcome for daily-revenue mode. + * + * 1. Optional neutrality pre-filter (same rules as majority/minority). + * 2. Start from `randomWinner`. + * 3. If that side is not the majority pool, keep it. + * 4. If it is the majority, keep only when + * `dailyNetRaw + projectedMajorityRoundPnlRaw >= targetRaw`. + * 5. Otherwise apply overflow: force minority win or neutral. + */ +export function resolveDailyRevenueOutcome(input: DailyRevenueOutcomeInput): RoundOutcome { + const { + shortPool, + longPool, + randomWinner, + projectedMajorityRoundPnlRaw, + dailyNetRaw, + targetRaw, + overflowStrategy, + neutralityRules, + } = input; + + if (neutralityRules) { + const neutral = resolvePoolNeutrality(shortPool, longPool, neutralityRules); + if (neutral) return neutral; + } + + if (shortPool + longPool <= 0) { + return { type: 'neutral', winner: null, neutralColor: 'green' }; + } + + const majority = majoritySide(shortPool, longPool); + if (majority == null || randomWinner !== majority) { + return directional(randomWinner); + } + + const netAfter = dailyNetRaw + projectedMajorityRoundPnlRaw; + if (netAfter >= targetRaw) { + return directional(randomWinner); + } + + if (overflowStrategy === 'neutral') { + return neutralFromPools(shortPool, longPool); + } + + const minority = minoritySide(shortPool, longPool); + // Solo pool (empty minority): forcing minority still yields that empty side as winner. + return directional(minority ?? (majority === 'short' ? 'long' : 'short')); +} + +/** House PnL if majority wins: totalSettlingStakeRaw − majorityPayoutRaw. */ +export function projectedMajorityRoundPnl( + totalSettlingStakeRaw: bigint, + majorityPayoutRaw: bigint +): bigint { + return totalSettlingStakeRaw - majorityPayoutRaw; +} + +const STAKE_DECIMALS = 6; + +function isRealMoney(kind: string | null | undefined): boolean { + return kind === 'main' || kind === 'bonus' || kind == null; +} + +export type ProjectableSingleBet = { + direction: 'short' | 'long'; + stake_raw: string; + stake_account_kind?: string | null; + interval_minutes: number; +}; + +export type ProjectableMultiBet = { + sequence_directions: ('short' | 'long')[] | null; + multi_level: number | null; + sequence_step: number; + stake_raw: string; + stake_display: string; + stake_account_kind?: string | null; +}; + +/** + * Project house PnL if `majority` wins this maturity. + * Counts only real-money bets that would reach a terminal status (won/lost/refunded). + */ +export function projectMajorityWinSettlement(input: { + majority: 'short' | 'long'; + singles: ProjectableSingleBet[]; + multis: ProjectableMultiBet[]; + singlePayoutMultiplier: (intervalMinutes: number) => number; + multiPayoutMultiplier: (level: number) => number; +}): { totalStakeRaw: bigint; majorityPayoutRaw: bigint; roundPnlRaw: bigint } { + let totalStakeRaw = 0n; + let majorityPayoutRaw = 0n; + const { majority } = input; + + for (const bet of input.singles) { + if (!isRealMoney(bet.stake_account_kind)) continue; + const stake = BigInt(bet.stake_raw); + totalStakeRaw += stake; + if (bet.direction === majority) { + const mult = input.singlePayoutMultiplier(bet.interval_minutes); + majorityPayoutRaw += BigInt(Math.round(Number(stake) * mult)); + } + } + + for (const bet of input.multis) { + if (!isRealMoney(bet.stake_account_kind)) continue; + const sequence = bet.sequence_directions ?? []; + const level = bet.multi_level ?? sequence.length; + const step = bet.sequence_step ?? 0; + const expected = sequence[step]; + const stake = BigInt(bet.stake_raw); + const isFinal = step >= level - 1; + + if (expected === majority) { + if (isFinal) { + totalStakeRaw += stake; + const mult = input.multiPayoutMultiplier(level); + const displayPayout = + Number(bet.stake_display) * mult; + majorityPayoutRaw += BigInt(Math.round(displayPayout * 10 ** STAKE_DECIMALS)); + } + // Intermediate correct step: bet continues — no terminal PnL yet. + continue; + } + + // Wrong direction (or missing expected): bet is lost at this candle. + totalStakeRaw += stake; + } + + return { + totalStakeRaw, + majorityPayoutRaw, + roundPnlRaw: projectedMajorityRoundPnl(totalStakeRaw, majorityPayoutRaw), + }; +} + +/** Convert USDT display amount to ledger raw (6 decimals). */ +export function usdtDisplayToRaw(display: number): bigint { + return BigInt(Math.round(display * 10 ** STAKE_DECIMALS)); +} + +export function usdtRawToDisplay(raw: bigint | string | number): number { + return Number(raw) / 10 ** STAKE_DECIMALS; +} + +/** UTC calendar date `YYYY-MM-DD` for daily revenue bucketing. */ +export function utcRevenueDate(now: Date = new Date()): string { + return now.toISOString().slice(0, 10); +} diff --git a/backend/src/tests/dailyRevenueOutcomeService.test.ts b/backend/src/tests/dailyRevenueOutcomeService.test.ts new file mode 100644 index 00000000..45e3c354 --- /dev/null +++ b/backend/src/tests/dailyRevenueOutcomeService.test.ts @@ -0,0 +1,216 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + pickRandomDirectionalOutcome, + projectMajorityWinSettlement, + projectedMajorityRoundPnl, + resolveDailyRevenueOutcome, +} from '../services/dailyRevenueOutcomeService'; + +describe('dailyRevenueOutcomeService', () => { + test('pickRandomDirectionalOutcome respects RNG', () => { + assert.equal(pickRandomDirectionalOutcome(() => 0.1).winner, 'short'); + assert.equal(pickRandomDirectionalOutcome(() => 0.9).winner, 'long'); + }); + + test('keeps random when it is the minority side', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 30, + longPool: 70, + randomWinner: 'short', + projectedMajorityRoundPnlRaw: -1000n, + dailyNetRaw: 0n, + targetRaw: 5_000_000n, + overflowStrategy: 'neutral', + }); + assert.equal(outcome.type, 'short_win'); + assert.equal(outcome.winner, 'short'); + }); + + test('keeps majority random when floor is respected', () => { + // daily 10 + round pnl +2 >= target 5 + const outcome = resolveDailyRevenueOutcome({ + shortPool: 30, + longPool: 70, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: 2_000_000n, + dailyNetRaw: 10_000_000n, + targetRaw: 5_000_000n, + overflowStrategy: 'neutral', + }); + assert.equal(outcome.type, 'long_win'); + assert.equal(outcome.winner, 'long'); + }); + + test('overflow to neutral when majority would breach floor', () => { + // daily 10 + round pnl -8 = 2 < target 5 + const outcome = resolveDailyRevenueOutcome({ + shortPool: 30, + longPool: 70, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -8_000_000n, + dailyNetRaw: 10_000_000n, + targetRaw: 5_000_000n, + overflowStrategy: 'neutral', + }); + assert.equal(outcome.type, 'neutral'); + assert.equal(outcome.winner, null); + }); + + test('overflow to minority when configured', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 30, + longPool: 70, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -8_000_000n, + dailyNetRaw: 10_000_000n, + targetRaw: 5_000_000n, + overflowStrategy: 'minority', + }); + assert.equal(outcome.type, 'short_win'); + assert.equal(outcome.winner, 'short'); + }); + + test('equal pools keep random (no majority) when neutrality is not passed', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 50, + longPool: 50, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -1n, + dailyNetRaw: 0n, + targetRaw: 5_000_000n, + overflowStrategy: 'neutral', + }); + assert.equal(outcome.type, 'long_win'); + }); + + test('neutrality pre-filter: equal pools → neutral before random/financial gate', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 50, + longPool: 50, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -1n, + dailyNetRaw: 0n, + targetRaw: 5_000_000n, + overflowStrategy: 'minority', + neutralityRules: { + minTolerancePercent: 2, + maxTolerancePercent: 95, + minToleranceEnabled: false, + maxToleranceEnabled: false, + }, + }); + assert.equal(outcome.type, 'neutral'); + }); + + test('neutrality pre-filter: max imbalance → neutral (solo 100/0)', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 0, + longPool: 10, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -9_000_000n, + dailyNetRaw: 0n, + targetRaw: 5_000_000n, + overflowStrategy: 'minority', + neutralityRules: { + minTolerancePercent: 2, + maxTolerancePercent: 95, + minToleranceEnabled: true, + maxToleranceEnabled: true, + }, + }); + assert.equal(outcome.type, 'neutral'); + }); + + test('with neutrality disabled for max, solo majority still hits financial overflow', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 0, + longPool: 10, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -9_000_000n, + dailyNetRaw: 0n, + targetRaw: 5_000_000n, + overflowStrategy: 'neutral', + neutralityRules: { + minTolerancePercent: 2, + maxTolerancePercent: 95, + minToleranceEnabled: false, + maxToleranceEnabled: false, + }, + }); + assert.equal(outcome.type, 'neutral'); + }); + + test('solo majority that breaches floor → minority overflow (empty side wins)', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 0, + longPool: 10, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -9_000_000n, + dailyNetRaw: 0n, + targetRaw: 5_000_000n, + overflowStrategy: 'minority', + }); + assert.equal(outcome.type, 'short_win'); + assert.equal(outcome.winner, 'short'); + }); + + test('solo majority that breaches floor → neutral overflow', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 0, + longPool: 10, + randomWinner: 'long', + projectedMajorityRoundPnlRaw: -9_000_000n, + dailyNetRaw: 0n, + targetRaw: 5_000_000n, + overflowStrategy: 'neutral', + }); + assert.equal(outcome.type, 'neutral'); + }); + + test('projectedMajorityRoundPnl = stakes − payouts', () => { + assert.equal(projectedMajorityRoundPnl(20_000_000n, 19_000_000n), 1_000_000n); + assert.equal(projectedMajorityRoundPnl(10_000_000n, 19_000_000n), -9_000_000n); + }); + + test('empty pools → neutral', () => { + const outcome = resolveDailyRevenueOutcome({ + shortPool: 0, + longPool: 0, + randomWinner: 'short', + projectedMajorityRoundPnlRaw: 0n, + dailyNetRaw: 0n, + targetRaw: 0n, + overflowStrategy: 'neutral', + }); + assert.equal(outcome.type, 'neutral'); + }); + + test('projectMajorityWinSettlement sums singles and final multi wins', () => { + const projected = projectMajorityWinSettlement({ + majority: 'long', + singles: [ + { direction: 'long', stake_raw: '1000000', stake_account_kind: 'main', interval_minutes: 1 }, + { direction: 'short', stake_raw: '500000', stake_account_kind: 'main', interval_minutes: 1 }, + { direction: 'long', stake_raw: '1000000', stake_account_kind: 'test', interval_minutes: 1 }, + ], + multis: [ + { + sequence_directions: ['long', 'long'], + multi_level: 2, + sequence_step: 1, + stake_raw: '2000000', + stake_display: '2', + stake_account_kind: 'bonus', + }, + ], + singlePayoutMultiplier: () => 1.9, + multiPayoutMultiplier: () => 2, + }); + // singles real: 1.0 + 0.5 = 1.5 USDT raw units 1e6; multi final 2.0 + assert.equal(projected.totalStakeRaw, 3_500_000n); + // long single payout 1.9 + multi 2*2=4 → 1.9e6 + 4e6 + assert.equal(projected.majorityPayoutRaw, 5_900_000n); + assert.equal(projected.roundPnlRaw, 3_500_000n - 5_900_000n); + }); +}); diff --git a/backend/src/validation/adminResourceSchemas.ts b/backend/src/validation/adminResourceSchemas.ts index b07e4fa1..a6ceb825 100644 --- a/backend/src/validation/adminResourceSchemas.ts +++ b/backend/src/validation/adminResourceSchemas.ts @@ -24,7 +24,7 @@ export const candlePredictAdminConfigBodySchema = atLeastOneField( stakeAmounts: z.array(z.number().positive()).max(50).optional(), minStakeAmount: z.number().positive().optional(), maxStakeAmount: z.number().positive().optional(), - poolWinnerRule: z.enum(['minority', 'majority']).optional(), + poolWinnerRule: z.enum(['minority', 'majority', 'daily_revenue']).optional(), predictionWindowSeconds: z.number().int().min(0).max(3600).optional(), tieTolerancePercent: z.number().min(0).max(100).optional(), tieToleranceMaxPercent: z.number().min(0).max(100).optional(), @@ -33,6 +33,8 @@ export const candlePredictAdminConfigBodySchema = atLeastOneField( basePrice: z.number().positive().optional(), payoutMultiplier: z.number().positive().optional(), poolMultiplier: z.number().positive().optional(), + dailyRevenueTarget: z.number().min(0).optional(), + dailyRevenueOverflowStrategy: z.enum(['minority', 'neutral']).optional(), walletTypeCode: z.string().trim().max(32).optional(), autoModes: z.array(z.string().trim().max(32)).max(10).optional(), isActive: z.boolean().optional(), diff --git a/prediqo_mobile/README.md b/prediqo_mobile/README.md index dd1d249c..1087cefc 100644 --- a/prediqo_mobile/README.md +++ b/prediqo_mobile/README.md @@ -1,16 +1,25 @@ -# crypto_wallet_app +# Prediqo Mobile -A new Flutter project. +## API URL (compile-time) -## Getting Started +`API_BASE_URL` is set via `--dart-define` / `--dart-define-from-file`. +Without it, the app defaults to `http://10.0.2.2:9080` (Android emulator only). -This project is a starting point for a Flutter application. +1. Copy `dart_defines.dev.example.json` → `dart_defines.dev.json` +2. Set your API base, e.g. `http://prediqo.redirectme.net:9080` -A few resources to get you started if this is your first Flutter project: +### Run -- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) +```bash +flutter run --dart-define-from-file=dart_defines.dev.json +``` -For help getting started with Flutter development, view the -[online documentation](https://docs.flutter.dev/), which offers tutorials, -samples, guidance on mobile development, and a full API reference. +### Release APK + +```bash +flutter build apk --release --dart-define-from-file=dart_defines.dev.json +``` + +Output: `build/app/outputs/flutter-apk/app-release.apk` + +A plain `flutter build apk --release` **will not** include your VPS URL. diff --git a/prediqo_mobile/TESTING.md b/prediqo_mobile/TESTING.md index 2d0cd9e0..b245292f 100644 --- a/prediqo_mobile/TESTING.md +++ b/prediqo_mobile/TESTING.md @@ -94,6 +94,16 @@ Après chaque changement d’`API_BASE_URL` : **Stop** puis **Run** (ou `flutter Par défaut (sans dart-define) : `http://10.0.2.2:9080`. +### APK release + +`flutter build apk --release` **sans** `--dart-define-from-file` compile avec `http://10.0.2.2:9080` → connexion impossible sur un vrai téléphone. + +```bash +cd prediqo_mobile +flutter build apk --release --dart-define-from-file=dart_defines.dev.json +# APK : build/app/outputs/flutter-apk/app-release.apk +``` + L’écran login affiche une bannière d’erreur en cas d’échec (sans URL API ni détails d’infra). ## E2E contre un backend live (manuel) diff --git a/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx b/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx index 6d347d69..6e27e69b 100644 --- a/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx +++ b/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx @@ -15,6 +15,7 @@ export function AdminPoolInsights({ config, interval, round }: Props) { if (!config.poolWinnerRule) return null; + const isDailyRevenue = config.poolWinnerRule === 'daily_revenue'; const parts: string[] = []; const tieTolerancePercent = interval.tieTolerancePercent ?? config.tieTolerancePercent ?? 0; const tieToleranceMaxPercent = interval.tieToleranceMaxPercent ?? config.tieToleranceMaxPercent ?? 100; @@ -32,15 +33,26 @@ export function AdminPoolInsights({ config, interval, round }: Props) { parts.push(t('candlePredict.adminInsights.neutralMax', { percent: tieToleranceMaxPercent })); } - const neutralityRulesSummary = - parts.length > 0 - ? `${parts.join(' · ')}. ${t('candlePredict.adminInsights.neutralBehavior')}` - : t('candlePredict.adminInsights.neutralNone'); + const neutralityPart = + parts.length > 0 ? parts.join(' · ') : t('candlePredict.adminInsights.neutralNone'); + + const rulesSummary = isDailyRevenue + ? [ + t('candlePredict.adminInsights.dailyRevenueSummary', { + target: config.dailyRevenueTarget ?? 0, + net: config.dailyRevenueNetToday ?? 0, + }), + t('candlePredict.adminInsights.dailyRevenueNeutralityPrefix'), + neutralityPart, + ].join(' ') + : neutralityPart; const poolWinnerLabel = config.poolWinnerRule === 'majority' ? t('candlePredict.adminInsights.poolWinnerMajority') - : t('candlePredict.adminInsights.poolWinnerMinority'); + : config.poolWinnerRule === 'daily_revenue' + ? t('candlePredict.adminInsights.poolWinnerDailyRevenue') + : t('candlePredict.adminInsights.poolWinnerMinority'); return ( @@ -52,7 +64,7 @@ export function AdminPoolInsights({ config, interval, round }: Props) { - {neutralityRulesSummary} + {rulesSummary} {t('candlePredict.adminInsights.footer')} diff --git a/prediqo_web/src/features/candle-predict/components/PoolBar.tsx b/prediqo_web/src/features/candle-predict/components/PoolBar.tsx index 72d0d1a0..91339a83 100644 --- a/prediqo_web/src/features/candle-predict/components/PoolBar.tsx +++ b/prediqo_web/src/features/candle-predict/components/PoolBar.tsx @@ -21,7 +21,9 @@ export function PoolBar({ round, poolWinnerRule }: Props) { const winner = poolWinnerRule === 'majority' ? t('candlePredict.poolBar.winnerMajority') - : t('candlePredict.poolBar.winnerMinority'); + : poolWinnerRule === 'daily_revenue' + ? t('candlePredict.poolBar.winnerDailyRevenue') + : t('candlePredict.poolBar.winnerMinority'); return ( {t('admin.catalog.candlePredict.config.loading')}; @@ -258,11 +271,58 @@ export function CandlePredictConfigPanel() { {t('admin.catalog.candlePredict.config.poolWinnerMajority')} + + {t('admin.catalog.candlePredict.config.poolWinnerDailyRevenue')} + {poolWinnerDesc} {t('admin.catalog.candlePredict.config.poolWinnerApplied')} + {form.poolWinnerRule === 'daily_revenue' && ( + <> + setForm({ ...form, dailyRevenueTarget: Number(e.target.value) })} + fullWidth + helperText={t('admin.catalog.candlePredict.config.dailyRevenueTargetHint')} + /> + + + {t('admin.catalog.candlePredict.config.dailyRevenueOverflow')} + + + + {t('admin.catalog.candlePredict.config.dailyRevenueOverflowHint')} + + + + {t('admin.catalog.candlePredict.config.dailyRevenueNetToday', { + amount: form.dailyRevenueNetToday.toFixed(2), + })} + + + )}