Intelligence, Advanced Charting & Trading Platform
feat(risk): guarded offline licensed OHLC ATR vs percentage paper-only simulation
davoodmehraban89 committed
Oct 21, 2026 at 08:54 UTC
8388c4cb41e06d081c486286923e66e66caa94fc
1 file changed
+89
packages/market-domain/src/educational-atr-backtest.mjs
new
+89
@@ -0,0 +1,89 @@
1
+/**
2
+ * Offline educational ATR vs fixed-% trailing-stop comparison on authorized
3
+ * timestamped SOURCE OHLC bars; never consumes 168 unverified price points.
4
+ * No broker, ordering, credentials, future data, network, or execution service.
5
+ */
6
+const pos=x=>Number.isFinite(x)&&x>0;
7
+export function validateBacktestBars(bars,{permission}={}){
8
+ if(!permission||permission.historicalStorage!==true||permission.derivedAnalysis!==true)
9
+ throw new Error('UNLICENSED_HISTORICAL_DATA');
10
+ if(!Array.isArray(bars)||bars.length<4)throw new RangeError('At least 4 OHLC bars required');
11
+ let previous=-Infinity;
12
+ return bars.map((b,i)=>{
13
+ if(!b||typeof b.timestamp!=='string'||!Number.isFinite(Date.parse(b.timestamp))||
14
+ Date.parse(b.timestamp)<=previous)throw new RangeError('OHLC chronology');
15
+ if(!['GOOD'].includes(b.quality)||b.origin!=='PROVIDER_OHLC')throw new RangeError('Unverified OHLC is prohibited');
16
+ for(const k of ['open','high','low','close'])if(!pos(b[k]))throw new RangeError(k);
17
+ if(b.high<Math.max(b.open,b.close)||b.low>Math.min(b.open,b.close)||b.low>b.high)
18
+ throw new RangeError('OHLC inconsistent');
19
+ if(typeof b.unit!=='string'||!b.unit||!['BUY','SELL','REFERENCE'].includes(b.side))
20
+ throw new RangeError('OHLC source side/unit');
21
+ if(i&& (bars[i-1].unit!==b.unit||bars[i-1].side!==b.side))
22
+ throw new RangeError('Changing OHLC units/side');
23
+ previous=Date.parse(b.timestamp);
24
+ return {...b};
25
+ });
26
+}
27
+export function trueRanges(bars) {
28
+ return bars.map((b,i)=>i===0?b.high-b.low:Math.max(
29
+ b.high-b.low,Math.abs(b.high-bars[i-1].close),Math.abs(b.low-bars[i-1].close)
30
+ ));
31
+}
32
+export function atrWilder(bars,period) {
33
+ if(!Number.isInteger(period)||period<2||bars.length<=period)throw new RangeError('ATR period');
34
+ const tr=trueRanges(bars),out=Array(bars.length).fill(null);
35
+ let sum=0;for(let i=0;i<period;i++)sum+=tr[i];
36
+ out[period-1]=sum/period;
37
+ for(let i=period;i<bars.length;i++)out[i]=(out[i-1]*(period-1)+tr[i])/period;
38
+ return out;
39
+}
40
+export function backtestTrailing({
41
+ bars,permission,position='LONG',atrPeriod=3,atrMultiplier=2,fixedPct=3,entryIndex=null
42
+}={}){
43
+ const data=validateBacktestBars(bars,{permission});
44
+ if(!['LONG','SHORT'].includes(position)||!pos(atrMultiplier)||!pos(fixedPct)||fixedPct>=100)
45
+ throw new RangeError('test configuration');
46
+ // Long exit must be priced on sell side; short on buy side.
47
+ if(data[0].side!==(position==='LONG'?'SELL':'BUY'))
48
+ throw new RangeError('EXIT_QUOTE_SIDE_UNVERIFIED');
49
+ const series=atrWilder(data,atrPeriod);
50
+ const entryAt=entryIndex??atrPeriod-1;
51
+ if(!Number.isInteger(entryAt)||entryAt<atrPeriod-1||entryAt>=data.length-1)
52
+ throw new RangeError('entryIndex');
53
+ const entryPrice=data[entryAt].close;
54
+ function sim(mode){
55
+ let peak=entryPrice,low=entryPrice,stop=mode==='ATR'?
56
+ (position==='LONG'?entryPrice-atrMultiplier*series[entryAt]:entryPrice+atrMultiplier*series[entryAt]):
57
+ (position==='LONG'?entryPrice*(1-fixedPct/100):entryPrice*(1+fixedPct/100));
58
+ const initialStop=stop;
59
+ let exit=null;
60
+ // Stop from CLOSED previous candle: check this bar first, update trailing after its close,
61
+ // preventing intrabar lookahead/high-low sequencing inventions.
62
+ for(let i=entryAt+1;i<data.length;i++){
63
+ const b=data[i];
64
+ const hit=position==='LONG'?b.low<=stop:b.high>=stop;
65
+ if(hit){
66
+ const openGap=position==='LONG'?b.open<stop:b.open>stop;
67
+ const level=openGap?b.open:stop;
68
+ exit={index:i,at:b.timestamp,stopLevel:stop,
69
+ referenceExit:level,gapAtOpen:openGap,executionPriceGuaranteed:false};
70
+ break;
71
+ }
72
+ peak=Math.max(peak,b.high);low=Math.min(low,b.low);
73
+ const distance=mode==='ATR'?series[i]*atrMultiplier:null;
74
+ const candidate=position==='LONG'?(mode==='ATR'?peak-distance:peak*(1-fixedPct/100)):
75
+ (mode==='ATR'?low+distance:low*(1+fixedPct/100));
76
+ stop=position==='LONG'?Math.max(stop,candidate):Math.min(stop,candidate);
77
+ }
78
+ return {mode,entryPrice,entryAt:data[entryAt].timestamp,initialStop,
79
+ endStop:stop,exit,
80
+ referenceReturnPct:exit?(position==='LONG'?
81
+ (exit.referenceExit/entryPrice-1)*100:(entryPrice/exit.referenceExit-1)*100):null,
82
+ advisory:false,executionPriceGuaranteed:false};
83
+ }
84
+ return {label:'اطلاعات آموزشی و غیرتوصیهای',paperOnly:true,
85
+ sourceDataKind:'LICENSED_PROVIDER_OHLC',unit:data[0].unit,side:data[0].side,
86
+ position,barCount:data.length,atrPeriod,atrMultiplier,fixedPct,
87
+ fixedPercent:sim('PCT'),atr:sim('ATR'),
88
+ caveat:'Hourly/intrabar ambiguity, commissions, spread, market impact and source outage are not fully simulated. This is not a trading recommendation.'};
89
+}