Intelligence, Advanced Charting & Trading Platform
feat(risk): pure threshold, long/short trailing ATR, OCO alert state machine without orders
davoodmehraban89 committed
Oct 21, 2026 at 08:49 UTC
d5dd6397d9148124b364668471634e20f2057248
1 file changed
+126
packages/market-domain/src/informational-alert-engine.mjs
new
+126
@@ -0,0 +1,126 @@
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||!Array.isArray(r.legs)||!r.legs.length||r.legs.length>2)
48
+ throw new TypeError('alert id + 1 or 2 legs');
49
+ for(const leg of r.legs)checkLeg(leg);
50
+ if(r.legs.length===2&&r.legs[0].type===r.legs[1].type)
51
+ throw new RangeError('OCO legs must have distinct types');
52
+ if(r.legs.length===2&&r.legs.some(l=>l.type==='TRAILING_STOP'&&l.mode==='PCT'))
53
+ throw new RangeError('percentage trailing OCO needs extra explicit review');
54
+ if(r.legs.some(l=>l.side!==r.legs[0].side))throw new RangeError('OCO same exit side required');
55
+ if(!Number.isInteger(r.confirmSamples??1)||(r.confirmSamples??1)<1||(r.confirmSamples??1)>20)
56
+ throw new RangeError('confirmSamples');
57
+ if(!Number.isFinite(r.confirmMs??0)||(r.confirmMs??0)<0)throw new RangeError('confirmMs');
58
+ if(!Number.isFinite(r.maxGapMs??600000)||(r.maxGapMs??600000)<=0)throw new RangeError('maxGapMs');
59
+ if(!Number.isFinite(r.cooldownMs??0)||(r.cooldownMs??0)<0)throw new RangeError('cooldownMs');
60
+};
61
+export function stepAlert(rule,previous,quote,gate) {
62
+ checkRule(rule);
63
+ const state=previous??initialAlertState(rule.id);
64
+ if(state.id!==rule.id||!PHASE.has(state.phase))throw new RangeError('corrupt state');
65
+ if(state.phase!=='ARMED')return {state,events:[],reason:'ALREADY_TRIGGERED_OR_CLOSED'};
66
+ if(gate?.status!=='GOOD'||gate.alertsSuspended||gate.accepted===null||!quote)
67
+ return {state:{...state,consecutive:0,firstCandidateAt:null},events:[],reason:'QUALITY_HOLD'};
68
+ const t=when(quote.timestamp),last=state.lastTimestamp===null?null:when(state.lastTimestamp);
69
+ if(last!==null&&t<=last)return {state,events:[],reason:t===last?'DUPLICATE':'OUT_OF_ORDER'};
70
+ if(!positive(quote.price)||quote.side!==rule.legs[0].side)
71
+ return {state,events:[],reason:'QUOTE_SIDE_OR_PRICE_INVALID'};
72
+ let high=state.highWater,low=state.lowWater,stop=state.stop;
73
+ // Trailing state must advance on each valid observation before evaluating.
74
+ for(const leg of rule.legs){
75
+ if(leg.type!=='TRAILING_STOP')continue;
76
+ const reference=leg.position==='LONG'?(high=Math.max(high??quote.price,quote.price)):
77
+ (low=Math.min(low??quote.price,quote.price));
78
+ if(leg.mode==='ATR'&&!positive(quote.atr))
79
+ return {state:{...state,lastTimestamp:quote.timestamp,consecutive:0,firstCandidateAt:null},
80
+ events:[],reason:'ATR_DATA_UNAVAILABLE'};
81
+ const distance=leg.mode==='ATR'?leg.distance*quote.atr:reference*leg.distance/100;
82
+ const computed=leg.position==='LONG'?reference-distance:reference+distance;
83
+ stop=leg.position==='LONG'?Math.max(stop??computed,computed):Math.min(stop??computed,computed);
84
+ }
85
+ const matching=rule.legs.map((leg,i)=>({leg,i,match:tickCondition(leg,quote.price,stop)}))
86
+ .filter(v=>v.match);
87
+ // OCO simultaneous trigger resolves deterministically to protective stop.
88
+ matching.sort((a,b)=>{
89
+ const priority=leg=>(leg.type==='STOP_LOSS'||leg.type==='TRAILING_STOP'?0:1);
90
+ return priority(a.leg)-priority(b.leg)||a.i-b.i;
91
+ });
92
+ const matched=matching[0];
93
+ const gap=last===null?0:t-last;
94
+ const carry=gap<=(rule.maxGapMs??600000)&&state.selectedLeg===matched?.i;
95
+ const count=matched?(carry?state.consecutive+1:1):0;
96
+ const first=matched?(carry?state.firstCandidateAt??quote.timestamp:quote.timestamp):null;
97
+ const next={...state,lastTimestamp:quote.timestamp,highWater:high,lowWater:low,stop,
98
+ consecutive:count,firstCandidateAt:first,selectedLeg:matched?.i??null};
99
+ if(!matched)return{state:next,events:[],reason:'NOT_CROSSED'};
100
+ const enoughCount=count>=(rule.confirmSamples??1);
101
+ const enoughTime=t-when(first)>=(rule.confirmMs??0);
102
+ if(!enoughCount||!enoughTime)return{state:next,events:[],reason:'AWAITING_CONFIRMATION'};
103
+ const eventId=rule.id+':'+quote.timestamp+':'+matched.i;
104
+ const triggered={...next,phase:'TRIGGERED',triggeredAt:quote.timestamp,eventId};
105
+ return {state:triggered,events:[{
106
+ kind:'INFORMATIONAL_THRESHOLD',id:eventId,ruleId:rule.id,
107
+ source:quote.provider,symbol:quote.symbol,side:quote.side,price:quote.price,
108
+ at:quote.timestamp,legIndex:matched.i,ruleType:matched.leg.type,
109
+ labels:['اطلاعات آموزشی و غیرتوصیهای'],cancelledOcoLegs:rule.legs
110
+ .map((_,i)=>i).filter(i=>i!==matched.i)
111
+ }],reason:'TRIGGERED'};
112
+}
113
+export function markNotified(rule,state,{eventId,at,deliveryId}) {
114
+ checkRule(rule);
115
+ if(!state||state.id!==rule.id||state.phase!=='TRIGGERED'||state.eventId!==eventId)
116
+ throw new RangeError('Only matching, unnotified triggered event can advance');
117
+ if(typeof deliveryId!=='string'||!deliveryId)throw new TypeError('delivery proof required');
118
+ if(when(at)<when(state.triggeredAt))throw new RangeError('notification before trigger');
119
+ return {...state,phase:'NOTIFIED',notifiedAt:at,deliveryId,
120
+ cooldownUntil:new Date(when(at)+(rule.cooldownMs??0)).toISOString()};
121
+}
122
+export function closeAlert(state,at) {
123
+ if(!state||state.phase!=='NOTIFIED')throw new RangeError('not notified');
124
+ if(when(at)<when(state.notifiedAt))throw new RangeError('close before notify');
125
+ return {...state,phase:'CLOSED',closedAt:at};
126
+}