Intelligence, Advanced Charting & Trading Platform

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.provider!=='string'||!b.provider.trim()||
20 typeof b.symbol!=='string'||!b.symbol.trim()||
21 typeof b.unit!=='string'||!b.unit||!['BUY','SELL','REFERENCE'].includes(b.side))
22 throw new RangeError('OHLC source identity, side or unit');
23 if(i&& (bars[i-1].unit!==b.unit||bars[i-1].side!==b.side||
24 bars[i-1].provider!==b.provider||bars[i-1].symbol!==b.symbol))
25 throw new RangeError('Changing OHLC provider/symbol/units/side');
26 previous=Date.parse(b.timestamp);
27 return {...b};
28 });
29 }
30 export function trueRanges(bars) {
31 return bars.map((b,i)=>i===0?b.high-b.low:Math.max(
32 b.high-b.low,Math.abs(b.high-bars[i-1].close),Math.abs(b.low-bars[i-1].close)
33 ));
34 }
35 export function atrWilder(bars,period) {
36 if(!Number.isInteger(period)||period<2||bars.length<=period)throw new RangeError('ATR period');
37 const tr=trueRanges(bars),out=Array(bars.length).fill(null);
38 let sum=0;for(let i=0;i<period;i++)sum+=tr[i];
39 out[period-1]=sum/period;
40 for(let i=period;i<bars.length;i++)out[i]=(out[i-1]*(period-1)+tr[i])/period;
41 return out;
42 }
43 export function backtestTrailing({
44 bars,permission,position='LONG',atrPeriod=3,atrMultiplier=2,fixedPct=3,entryIndex=null
45 }={}){
46 const data=validateBacktestBars(bars,{permission});
47 if(!['LONG','SHORT'].includes(position)||!pos(atrMultiplier)||!pos(fixedPct)||fixedPct>=100)
48 throw new RangeError('test configuration');
49 // Long exit must be priced on sell side; short on buy side.
50 if(data[0].side!==(position==='LONG'?'SELL':'BUY'))
51 throw new RangeError('EXIT_QUOTE_SIDE_UNVERIFIED');
52 const series=atrWilder(data,atrPeriod);
53 const entryAt=entryIndex??atrPeriod-1;
54 if(!Number.isInteger(entryAt)||entryAt<atrPeriod-1||entryAt>=data.length-1)
55 throw new RangeError('entryIndex');
56 const entryPrice=data[entryAt].close;
57 function sim(mode){
58 let peak=entryPrice,low=entryPrice,stop=mode==='ATR'?
59 (position==='LONG'?entryPrice-atrMultiplier*series[entryAt]:entryPrice+atrMultiplier*series[entryAt]):
60 (position==='LONG'?entryPrice*(1-fixedPct/100):entryPrice*(1+fixedPct/100));
61 const initialStop=stop;
62 let exit=null;
63 // Stop from CLOSED previous candle: check this bar first, update trailing after its close,
64 // preventing intrabar lookahead/high-low sequencing inventions.
65 for(let i=entryAt+1;i<data.length;i++){
66 const b=data[i];
67 const hit=position==='LONG'?b.low<=stop:b.high>=stop;
68 if(hit){
69 const openGap=position==='LONG'?b.open<stop:b.open>stop;
70 const level=openGap?b.open:stop;
71 exit={index:i,at:b.timestamp,stopLevel:stop,
72 referenceExit:level,gapAtOpen:openGap,executionPriceGuaranteed:false};
73 break;
74 }
75 peak=Math.max(peak,b.high);low=Math.min(low,b.low);
76 const distance=mode==='ATR'?series[i]*atrMultiplier:null;
77 const candidate=position==='LONG'?(mode==='ATR'?peak-distance:peak*(1-fixedPct/100)):
78 (mode==='ATR'?low+distance:low*(1+fixedPct/100));
79 stop=position==='LONG'?Math.max(stop,candidate):Math.min(stop,candidate);
80 }
81 return {mode,entryPrice,entryAt:data[entryAt].timestamp,initialStop,
82 endStop:stop,exit,
83 referenceReturnPct:exit?(position==='LONG'?
84 (exit.referenceExit/entryPrice-1)*100:(entryPrice/exit.referenceExit-1)*100):null,
85 advisory:false,executionPriceGuaranteed:false};
86 }
87 return {label:'اطلاعات آموزشی و غیرتوصیه‌ای',paperOnly:true,
88 sourceDataKind:'LICENSED_PROVIDER_OHLC',provider:data[0].provider,symbol:data[0].symbol,unit:data[0].unit,side:data[0].side,
89 position,barCount:data.length,atrPeriod,atrMultiplier,fixedPct,
90 fixedPercent:sim('PCT'),atr:sim('ATR'),
91 caveat:'Hourly/intrabar ambiguity, commissions, spread, market impact and source outage are not fully simulated. This is not a trading recommendation.'};
92 }