Intelligence, Advanced Charting & Trading Platform
feature/paper-trading-risk-controls-2026-10-14
diagnostics/chartnova-blank-screen-2026-10-15
diagnostics/chartnova-stage2-v27-preview-2026-10-15
docs/chartnova-stage1-reconcile-manifest-2026-10-15
feature/chartnova-ios-widget
feature/chartnova-light-catalog-lazy-series-2026-10-15
feature/chartnova-market-terminal
feature/chartnova-multimarket-chart-ws-foundation
feature/chartnova-neon-direct-history
feature/chartnova-neon-history
feature/paper-trading-risk-controls-2026-10-14
fix/alpha-vantage-live-payload
fix/chartnova-progressive-loading-2026-10-15
fix/live-proof-runner-cwd-2026-10-14
foundation/phase-0
foundation/postgres-core
main
ops/chartnova-emergency-rollback-2026-10-15
phase-1/candle-builder
phase-1/data-proof-artifact
phase-1/data-proof-metrics
phase-1/data-proof-report
phase-1/external-gates-state
phase-1/gold-api-fallback
phase-1/ingestion-pipeline
phase-1/live-proof-runner
phase-1/market-calendar
phase-1/market-domain
phase-1/neon-live-proof
phase-1/persistence-contract
phase-1/postgres-ci
phase-1/provider-adapters
phase-1/provider-recovery
phase-1/quality-propagation
phase-1/spike-detection
phase-1/xau-provider-adapter
risk/chartnova-alert-runtime-atomic-2026-10-22
risk/chartnova-atomic-outbox-2026-10-22
risk/chartnova-seven-track-safety-2026-10-21
safety/p0-triage-2026-10-13
| 1 | /** |
| 2 | * VELYQOR paper-only position risk simulation. |
| 3 | * NO BROKER, WALLET, EXCHANGE, NETWORK, DATABASE or LIVE ORDER calls. |
| 4 | * Price inputs are caller-supplied scenarios, NEVER claimed as executable market quotes. |
| 5 | */ |
| 6 | const MAX_BPS = 500; |
| 7 | const asPositive = (value, name) => { |
| 8 | const x = Number(value); |
| 9 | if (!Number.isFinite(x) || x <= 0) throw new RangeError(name + ' must be positive and finite'); |
| 10 | return x; |
| 11 | }; |
| 12 | const asPercent = (value, name) => { |
| 13 | const x = asPositive(value, name); |
| 14 | if (x >= 100) throw new RangeError(name + ' must be below 100%'); |
| 15 | return x; |
| 16 | }; |
| 17 | const asBps = (value, name) => { |
| 18 | const x = Number(value); |
| 19 | if (!Number.isFinite(x) || x < 0 || x > MAX_BPS) { |
| 20 | throw new RangeError(name + ' must be in [0, 500] basis points'); |
| 21 | } |
| 22 | return x; |
| 23 | }; |
| 24 | const asTimestamp = (timestamp, name) => { |
| 25 | if (typeof timestamp !== 'string' || |
| 26 | !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(timestamp) || |
| 27 | !Number.isFinite(Date.parse(timestamp))) { |
| 28 | throw new TypeError(name + ' must be a valid ISO timestamp with timezone'); |
| 29 | } |
| 30 | return new Date(timestamp).toISOString(); |
| 31 | }; |
| 32 | const decimal = (x) => { |
| 33 | const rounded = Math.round(x * 1e10) / 1e10; |
| 34 | return Object.is(rounded, -0) ? 0 : rounded; |
| 35 | }; |
| 36 | const sideSign = (side) => side === 'LONG' ? 1 : -1; |
| 37 | |
| 38 | export function openPaperPosition({ |
| 39 | symbol, side = 'LONG', entryPrice, capital, stopLossPercent, |
| 40 | takeProfitPercent, trailingStopPercent = null, commissionBps = 0, |
| 41 | slippageBps = 0, at |
| 42 | }) { |
| 43 | if (typeof symbol !== 'string' || !/^[A-Z0-9_]{3,48}$/.test(symbol)) { |
| 44 | throw new TypeError('invalid canonical symbol'); |
| 45 | } |
| 46 | if (!['LONG', 'SHORT'].includes(side)) throw new TypeError('side must be LONG or SHORT'); |
| 47 | const entry = asPositive(entryPrice, 'entryPrice'); |
| 48 | const budget = asPositive(capital, 'capital'); |
| 49 | const loss = asPercent(stopLossPercent, 'stopLossPercent'); |
| 50 | const profit = asPercent(takeProfitPercent, 'takeProfitPercent'); |
| 51 | const trailing = trailingStopPercent === null || trailingStopPercent === '' ? |
| 52 | null : asPercent(trailingStopPercent, 'trailingStopPercent'); |
| 53 | const fee = asBps(commissionBps, 'commissionBps'); |
| 54 | const slip = asBps(slippageBps, 'slippageBps'); |
| 55 | const enteredAt = asTimestamp(at, 'at'); |
| 56 | const direction = sideSign(side); |
| 57 | const initialStop = decimal(entry * (1 - direction * loss / 100)); |
| 58 | const takeProfit = decimal(entry * (1 + direction * profit / 100)); |
| 59 | const trailStop = trailing === null ? null : decimal(entry * (1 - direction * trailing / 100)); |
| 60 | const stopPrice = trailing === null ? initialStop : |
| 61 | side === 'LONG' ? Math.max(initialStop, trailStop) : Math.min(initialStop, trailStop); |
| 62 | const quantity = budget / entry; |
| 63 | return { |
| 64 | kind: 'PAPER_POSITION', version: 1, symbol, side, status: 'OPEN', |
| 65 | currency: 'QUOTE_UNIT', capital: budget, entryPrice: entry, quantity, |
| 66 | entryAt: enteredAt, lastAt: enteredAt, markPrice: entry, |
| 67 | highestPrice: entry, lowestPrice: entry, |
| 68 | rules: { stopLossPercent: loss, takeProfitPercent: profit, |
| 69 | trailingStopPercent: trailing, commissionBps: fee, slippageBps: slip }, |
| 70 | initialStop, stopPrice, takeProfitPrice: takeProfit, |
| 71 | estimatedPnL: decimal(-budget * fee / 10000 * 2), |
| 72 | realizedPnL: null, exit: null, |
| 73 | events: [{ type: 'OPEN', at: enteredAt, price: entry, source: 'MANUAL_SCENARIO' }] |
| 74 | }; |
| 75 | } |
| 76 | function checkOpen(position) { |
| 77 | if (!position || position.kind !== 'PAPER_POSITION' || position.status !== 'OPEN') |
| 78 | throw new TypeError('an OPEN paper position is required'); |
| 79 | } |
| 80 | function outcome(position, price) { |
| 81 | const sign = sideSign(position.side); |
| 82 | const { commissionBps, slippageBps } = position.rules; |
| 83 | const executed = price * (1 - sign * slippageBps / 10000); |
| 84 | const entryFee = position.entryPrice * position.quantity * commissionBps / 10000; |
| 85 | const exitFee = executed * position.quantity * commissionBps / 10000; |
| 86 | return { |
| 87 | fillPrice: decimal(executed), |
| 88 | netPnL: decimal(sign * (executed - position.entryPrice) * position.quantity - entryFee - exitFee), |
| 89 | fees: decimal(entryFee + exitFee) |
| 90 | }; |
| 91 | } |
| 92 | export function markPaperPosition(position, { price, at }) { |
| 93 | checkOpen(position); |
| 94 | const quote = asPositive(price, 'scenario price'); |
| 95 | const timestamp = asTimestamp(at, 'at'); |
| 96 | if (Date.parse(timestamp) <= Date.parse(position.lastAt)) |
| 97 | throw new RangeError('scenario timestamps must strictly increase'); |
| 98 | const high = Math.max(position.highestPrice, quote); |
| 99 | const low = Math.min(position.lowestPrice, quote); |
| 100 | const { trailingStopPercent } = position.rules; |
| 101 | let stop = position.initialStop; |
| 102 | if (trailingStopPercent !== null) { |
| 103 | const trailingStop = position.side === 'LONG' ? |
| 104 | high * (1 - trailingStopPercent / 100) : |
| 105 | low * (1 + trailingStopPercent / 100); |
| 106 | stop = position.side === 'LONG' ? Math.max(stop, trailingStop) : Math.min(stop, trailingStop); |
| 107 | } |
| 108 | stop = decimal(stop); |
| 109 | const stopHit = position.side === 'LONG' ? quote <= stop : quote >= stop; |
| 110 | const profitHit = position.side === 'LONG' ? quote >= position.takeProfitPrice : quote <= position.takeProfitPrice; |
| 111 | const event = { type: 'MARK', at: timestamp, price: quote, source: 'MANUAL_SCENARIO' }; |
| 112 | const changed = { |
| 113 | ...position, lastAt: timestamp, markPrice: quote, |
| 114 | highestPrice: high, lowestPrice: low, stopPrice: stop, |
| 115 | events: [...position.events, event] |
| 116 | }; |
| 117 | if (stopHit || profitHit) return exitPaperPosition(changed, { |
| 118 | price: quote, at: timestamp, reason: stopHit ? 'STOP' : 'TAKE_PROFIT', alreadyMarked: true |
| 119 | }); |
| 120 | return { ...changed, estimatedPnL: outcome(changed, quote).netPnL }; |
| 121 | } |
| 122 | function exitPaperPosition(position, { price, at, reason, alreadyMarked = false }) { |
| 123 | const fill = outcome(position, price); |
| 124 | return { |
| 125 | ...position, status: 'CLOSED', markPrice: price, |
| 126 | lastAt: at, estimatedPnL: fill.netPnL, realizedPnL: fill.netPnL, |
| 127 | exit: { reason, at, observedPrice: price, fillPrice: fill.fillPrice, fees: fill.fees, |
| 128 | caution: 'scenario observed price and conservative model slippage; not a guaranteed executable fill' }, |
| 129 | events: [...position.events, { type: 'CLOSE', reason, at, observedPrice: price, |
| 130 | fillPrice: fill.fillPrice, source: 'MANUAL_SCENARIO' }] |
| 131 | }; |
| 132 | } |
| 133 | export function closePaperPosition(position, { price, at }) { |
| 134 | checkOpen(position); |
| 135 | const quote = asPositive(price, 'price'); |
| 136 | const timestamp = asTimestamp(at, 'at'); |
| 137 | if (Date.parse(timestamp) <= Date.parse(position.lastAt)) throw new RangeError('timestamp must increase'); |
| 138 | return exitPaperPosition(position, { price: quote, at: timestamp, reason: 'MANUAL' }); |
| 139 | } |
| 140 | export function paperRiskSummary(position) { |
| 141 | if (!position || position.kind !== 'PAPER_POSITION') throw new TypeError('invalid paper position'); |
| 142 | return { |
| 143 | symbol: position.symbol, side: position.side, status: position.status, |
| 144 | entryPrice: position.entryPrice, markPrice: position.markPrice, |
| 145 | stopPrice: position.stopPrice, takeProfitPrice: position.takeProfitPrice, |
| 146 | capital: position.capital, quantity: position.quantity, |
| 147 | netPnL: position.status === 'CLOSED' ? position.realizedPnL : position.estimatedPnL, |
| 148 | netPnLPct: decimal(100 * (position.status === 'CLOSED' ? |
| 149 | position.realizedPnL : position.estimatedPnL) / position.capital), |
| 150 | exitReason: position.exit?.reason ?? null, |
| 151 | eventCount: position.events.length, |
| 152 | }; |
| 153 | } |