Intelligence, Advanced Charting & Trading Platform
risk/chartnova-seven-track-safety-2026-10-21
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 | * Deterministic, paper-only alert state machine. No broker/network dependencies. |
| 3 | * Every accepted data sample is uniquely identified by source timestamp. |
| 4 | * Delivery is a SEPARATE concern; state changes never send notifications. |
| 5 | */ |
| 6 | const POS=new Set(['LONG','SHORT']), PHASE=new Set(['ARMED','TRIGGERED','NOTIFIED','CLOSED']); |
| 7 | const TYPES=new Set(['ABOVE','BELOW','ENTRY_PCT','STOP_LOSS','TAKE_PROFIT','TRAILING_STOP']); |
| 8 | const positive=n=>Number.isFinite(n)&&n>0; |
| 9 | const when=v=>{const t=Date.parse(v);if(typeof v!=='string'||!Number.isFinite(t))throw new TypeError('timestamp');return t}; |
| 10 | function checkLeg(rule){ |
| 11 | if(!rule||typeof rule!=='object'||!TYPES.has(rule.type))throw new RangeError('type'); |
| 12 | if(!['BUY','SELL'].includes(rule.side))throw new RangeError('side'); |
| 13 | if(rule.type==='TRAILING_STOP'){ |
| 14 | if(!POS.has(rule.position))throw new RangeError('position'); |
| 15 | if(!['ATR','PCT'].includes(rule.mode))throw new RangeError('mode'); |
| 16 | if(!positive(rule.distance))throw new RangeError('distance'); |
| 17 | if(rule.mode==='PCT'&&rule.distance>=100)throw new RangeError('percent range'); |
| 18 | }else if(!positive(rule.threshold)&&!(['STOP_LOSS','TAKE_PROFIT','ENTRY_PCT'].includes(rule.type)&&positive(rule.entry))) { |
| 19 | throw new RangeError('threshold'); |
| 20 | } |
| 21 | if(['STOP_LOSS','TAKE_PROFIT','ENTRY_PCT'].includes(rule.type)){ |
| 22 | if(!POS.has(rule.position)||!positive(rule.entry))throw new RangeError('entry and position'); |
| 23 | if(!positive(rule.threshold))throw new RangeError('threshold'); |
| 24 | } |
| 25 | if(['STOP_LOSS','TAKE_PROFIT','TRAILING_STOP'].includes(rule.type)&& |
| 26 | rule.side!==(rule.position==='LONG'?'SELL':'BUY'))throw new RangeError('exit side wrong'); |
| 27 | } |
| 28 | function tickCondition(rule,price,trailStop){ |
| 29 | switch(rule.type){ |
| 30 | case 'ABOVE':return price>=rule.threshold; |
| 31 | case 'BELOW':return price<=rule.threshold; |
| 32 | case 'ENTRY_PCT':return rule.position==='LONG'? |
| 33 | (price/rule.entry-1)*100>=rule.threshold: |
| 34 | (rule.entry/price-1)*100>=rule.threshold; |
| 35 | case 'STOP_LOSS':return rule.position==='LONG'?price<=rule.threshold:price>=rule.threshold; |
| 36 | case 'TAKE_PROFIT':return rule.position==='LONG'?price>=rule.threshold:price<=rule.threshold; |
| 37 | case 'TRAILING_STOP':return rule.position==='LONG'?price<=trailStop:price>=trailStop; |
| 38 | } |
| 39 | } |
| 40 | export function initialAlertState(id) { |
| 41 | if(typeof id!=='string'||!id.trim())throw new TypeError('alert id required'); |
| 42 | return {id,phase:'ARMED',lastTimestamp:null,consecutive:0,firstCandidateAt:null, |
| 43 | highWater:null,lowWater:null,stop:null,triggeredAt:null,eventId:null,notifiedAt:null,closedAt:null, |
| 44 | selectedLeg:null,cooldownUntil:null}; |
| 45 | } |
| 46 | const checkRule=r=>{ |
| 47 | if(!r||typeof r.id!=='string'||!r.id|| |
| 48 | typeof r.symbol!=='string'||!r.symbol|| |
| 49 | typeof r.unit!=='string'||!r.unit|| |
| 50 | typeof r.provider!=='string'||!r.provider|| |
| 51 | !Array.isArray(r.legs)||!r.legs.length||r.legs.length>2) |
| 52 | throw new TypeError('alert id + 1 or 2 legs'); |
| 53 | for(const leg of r.legs)checkLeg(leg); |
| 54 | if(r.legs.length===2&&r.legs[0].type===r.legs[1].type) |
| 55 | throw new RangeError('OCO legs must have distinct types'); |
| 56 | if(r.legs.length===2&&r.legs.some(l=>l.type==='TRAILING_STOP'&&l.mode==='PCT')) |
| 57 | throw new RangeError('percentage trailing OCO needs extra explicit review'); |
| 58 | if(r.legs.some(l=>l.side!==r.legs[0].side))throw new RangeError('OCO same exit side required'); |
| 59 | if(!Number.isInteger(r.confirmSamples??1)||(r.confirmSamples??1)<1||(r.confirmSamples??1)>20) |
| 60 | throw new RangeError('confirmSamples'); |
| 61 | if(!Number.isFinite(r.confirmMs??0)||(r.confirmMs??0)<0)throw new RangeError('confirmMs'); |
| 62 | if(!Number.isFinite(r.maxGapMs??600000)||(r.maxGapMs??600000)<=0)throw new RangeError('maxGapMs'); |
| 63 | if(!Number.isFinite(r.cooldownMs??0)||(r.cooldownMs??0)<0)throw new RangeError('cooldownMs'); |
| 64 | }; |
| 65 | export function stepAlert(rule,previous,quote,gate) { |
| 66 | checkRule(rule); |
| 67 | const state=previous??initialAlertState(rule.id); |
| 68 | if(state.id!==rule.id||!PHASE.has(state.phase))throw new RangeError('corrupt state'); |
| 69 | if(state.phase!=='ARMED')return {state,events:[],reason:'ALREADY_TRIGGERED_OR_CLOSED'}; |
| 70 | if(gate?.status!=='GOOD'||gate.alertsSuspended||!gate.accepted||!quote|| |
| 71 | gate.accepted.symbol!==quote.symbol||gate.accepted.provider!==quote.provider|| |
| 72 | gate.accepted.side!==quote.side||gate.accepted.unit!==quote.unit|| |
| 73 | gate.accepted.price!==quote.price||gate.accepted.timestamp!==quote.timestamp) |
| 74 | return {state:{...state,consecutive:0,firstCandidateAt:null},events:[],reason:'QUALITY_HOLD'}; |
| 75 | const t=when(quote.timestamp),last=state.lastTimestamp===null?null:when(state.lastTimestamp); |
| 76 | if(last!==null&&t<=last)return {state,events:[],reason:t===last?'DUPLICATE':'OUT_OF_ORDER'}; |
| 77 | if(!positive(quote.price)||quote.side!==rule.legs[0].side|| |
| 78 | quote.symbol!==rule.symbol||quote.unit!==rule.unit||quote.provider!==rule.provider) |
| 79 | return {state,events:[],reason:'QUOTE_SIDE_OR_PRICE_INVALID'}; |
| 80 | let high=state.highWater,low=state.lowWater,stop=state.stop; |
| 81 | // Trailing state must advance on each valid observation before evaluating. |
| 82 | for(const leg of rule.legs){ |
| 83 | if(leg.type!=='TRAILING_STOP')continue; |
| 84 | const reference=leg.position==='LONG'?(high=Math.max(high??quote.price,quote.price)): |
| 85 | (low=Math.min(low??quote.price,quote.price)); |
| 86 | if(leg.mode==='ATR'&&!positive(quote.atr)) |
| 87 | return {state:{...state,lastTimestamp:quote.timestamp,consecutive:0,firstCandidateAt:null}, |
| 88 | events:[],reason:'ATR_DATA_UNAVAILABLE'}; |
| 89 | const distance=leg.mode==='ATR'?leg.distance*quote.atr:reference*leg.distance/100; |
| 90 | const computed=leg.position==='LONG'?reference-distance:reference+distance; |
| 91 | stop=leg.position==='LONG'?Math.max(stop??computed,computed):Math.min(stop??computed,computed); |
| 92 | } |
| 93 | const matching=rule.legs.map((leg,i)=>({leg,i,match:tickCondition(leg,quote.price,stop)})) |
| 94 | .filter(v=>v.match); |
| 95 | // OCO simultaneous trigger resolves deterministically to protective stop. |
| 96 | matching.sort((a,b)=>{ |
| 97 | const priority=leg=>(leg.type==='STOP_LOSS'||leg.type==='TRAILING_STOP'?0:1); |
| 98 | return priority(a.leg)-priority(b.leg)||a.i-b.i; |
| 99 | }); |
| 100 | const matched=matching[0]; |
| 101 | const gap=last===null?0:t-last; |
| 102 | const carry=gap<=(rule.maxGapMs??600000)&&state.selectedLeg===matched?.i; |
| 103 | const count=matched?(carry?state.consecutive+1:1):0; |
| 104 | const first=matched?(carry?state.firstCandidateAt??quote.timestamp:quote.timestamp):null; |
| 105 | const next={...state,lastTimestamp:quote.timestamp,highWater:high,lowWater:low,stop, |
| 106 | consecutive:count,firstCandidateAt:first,selectedLeg:matched?.i??null}; |
| 107 | if(!matched)return{state:next,events:[],reason:'NOT_CROSSED'}; |
| 108 | const enoughCount=count>=(rule.confirmSamples??1); |
| 109 | const enoughTime=t-when(first)>=(rule.confirmMs??0); |
| 110 | if(!enoughCount||!enoughTime)return{state:next,events:[],reason:'AWAITING_CONFIRMATION'}; |
| 111 | const eventId=rule.id+':'+quote.timestamp+':'+matched.i; |
| 112 | const triggered={...next,phase:'TRIGGERED',triggeredAt:quote.timestamp,eventId}; |
| 113 | return {state:triggered,events:[{ |
| 114 | kind:'INFORMATIONAL_THRESHOLD',id:eventId,ruleId:rule.id, |
| 115 | source:quote.provider,symbol:quote.symbol,side:quote.side,price:quote.price, |
| 116 | at:quote.timestamp,legIndex:matched.i,ruleType:matched.leg.type, |
| 117 | labels:['اطلاعات آموزشی و غیرتوصیهای'],cancelledOcoLegs:rule.legs |
| 118 | .map((_,i)=>i).filter(i=>i!==matched.i) |
| 119 | }],reason:'TRIGGERED'}; |
| 120 | } |
| 121 | export function markNotified(rule,state,{eventId,at,deliveryId}) { |
| 122 | checkRule(rule); |
| 123 | if(!state||state.id!==rule.id||state.phase!=='TRIGGERED'||state.eventId!==eventId) |
| 124 | throw new RangeError('Only matching, unnotified triggered event can advance'); |
| 125 | if(typeof deliveryId!=='string'||!deliveryId)throw new TypeError('delivery proof required'); |
| 126 | if(when(at)<when(state.triggeredAt))throw new RangeError('notification before trigger'); |
| 127 | return {...state,phase:'NOTIFIED',notifiedAt:at,deliveryId, |
| 128 | cooldownUntil:new Date(when(at)+(rule.cooldownMs??0)).toISOString()}; |
| 129 | } |
| 130 | export function closeAlert(state,at) { |
| 131 | if(!state||state.phase!=='NOTIFIED')throw new RangeError('not notified'); |
| 132 | if(when(at)<when(state.notifiedAt))throw new RangeError('close before notify'); |
| 133 | return {...state,phase:'CLOSED',closedAt:at}; |
| 134 | } |