Intelligence, Advanced Charting & Trading Platform

1 // License-gated historical OHLC preflight. No network calls, no fabricated bars.
2 // Prices remain exact base-10 strings; PostgreSQL NUMERIC should receive these strings.
3 const DAY=86_400_000;
4 const UNIT_FACTORS=Object.freeze({
5 "IRR_PER_USD->IRT_PER_USD":10,
6 "IRR_PER_GRAM->IRT_PER_GRAM":10,
7 "IRT_PER_USD->IRT_PER_USD":1,
8 "IRT_PER_GRAM->IRT_PER_GRAM":1,
9 "USD_PER_TROY_OUNCE->USD_PER_TROY_OUNCE":1,
10 "USD_PER_BTC->USD_PER_BTC":1,
11 "USD_PER_ETH->USD_PER_ETH":1,
12 });
13 const dateValid=(s)=>typeof s==="string"&&/^\d{4}-\d{2}-\d{2}$/.test(s)&&!Number.isNaN(Date.parse(s+"T00:00:00Z"))&&new Date(s+"T00:00:00Z").toISOString().slice(0,10)===s;
14 const ms=(s,name)=>{
15 if(typeof s!=="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(s))throw Error(name+" must specify a timezone offset");
16 const n=Date.parse(s);if(!Number.isFinite(n))throw Error(name+" is invalid");return n;
17 };
18 function decimal(value,name,factor=1){
19 const str=typeof value==="number"?String(value):value;
20 if(typeof str!=="string"||!/^\d{1,20}(?:\.\d{1,10})?$/.test(str))throw Error(name+" must be a positive finite decimal without exponent");
21 const [a,f=""]=str.split(".");
22 const scale=f.length+(factor===10?1:0);
23 if(scale>10)throw Error(name+" has excessive precision after unit conversion");
24 let digits=(a+f).replace(/^0+(?=\d)/,""), padded=digits.padStart(scale+1,"0");
25 const text=scale?padded.slice(0,-scale)+"."+padded.slice(-scale):padded;
26 const clean=text.includes(".")?text.replace(/0+$/,"").replace(/\.$/,""):text;
27 const canonical=clean.replace(/^0+(?=\d)/,"");
28 const n=BigInt(digits)*10n**BigInt(10-scale);
29 if(n<=0n)throw Error(name+" must be positive");
30 return {canonical,value:n};
31 }
32 function dateInZone(timestamp,timeZone){
33 const bits=new Intl.DateTimeFormat("en-CA",{timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(timestamp));
34 const part=(kind)=>bits.find(x=>x.type===kind)?.value;
35 return [part("year"),part("month"),part("day")].join("-");
36 }
37 function licenseGate(license,intendedUse,providerCode,receivedAt){
38 if(!license||license.providerCode!==providerCode||license.status!=="approved"||
39 typeof license.evidenceRef!=="string"||license.evidenceRef.length<8||
40 !license.reviewedBy||!license.reviewedAt||
41 license.rights?.commercialStorage!==true)throw Error("Licensed commercial storage not verified");
42 if(intendedUse==="public_api"&&license.rights?.publicRedistribution!==true)throw Error("Public redistribution not authorized");
43 const approvedAt=ms(license.reviewedAt,"license.reviewedAt");
44 if(approvedAt>receivedAt)throw Error("Future license review");
45 if(license.expiresAt&&ms(license.expiresAt,"license.expiresAt")<receivedAt)throw Error("Expired source license");
46 // This checks supplied assertions, not the authenticity of a legal agreement.
47 }
48 export function preflightOhlcHistory({
49 rows,providerCode,symbol,timeframe="1d",rawUnit,canonicalUnit,timeZone,
50 license,intendedUse="public_api",receivedAt,from,to,isSessionDay=null
51 }){
52 if(!["public_api","internal_storage"].includes(intendedUse))throw Error("Unsupported intendedUse");
53 if(!/^[a-z][a-z0-9_]{1,39}$/.test(providerCode||""))throw Error("Invalid providerCode");
54 if(!/^[A-Z0-9_]{3,48}$/.test(symbol||""))throw Error("Invalid canonical symbol");
55 if(timeframe!=="1d")throw Error("Only source-provided daily OHLC accepted");
56 if(!dateValid(from)||!dateValid(to)||from>to||Date.parse(to+"T00:00:00Z")-Date.parse(from+"T00:00:00Z")>800*DAY)throw Error("Invalid date window");
57 if(typeof timeZone!=="string")throw Error("Missing IANA timezone");
58 try{new Intl.DateTimeFormat("en-US",{timeZone})}catch{throw Error("Invalid IANA timezone")}
59 const factor=UNIT_FACTORS[rawUnit+"->"+canonicalUnit];
60 if(!factor)throw Error("Undocumented currency/commodity unit conversion");
61 if(!Array.isArray(rows)||rows.length>3000)throw Error("Invalid batch size");
62 if(isSessionDay!==null&&typeof isSessionDay!=="function")throw Error("Invalid calendar");
63 const ingestedAt=ms(receivedAt,"receivedAt");
64 licenseGate(license,intendedUse,providerCode,ingestedAt);
65 let outOfOrder=0,duplicates=0;
66 const unique=new Map();
67 for(const [index,row] of rows.entries()){
68 if(!row||typeof row!=="object"||Array.isArray(row))throw Error("Invalid row "+index);
69 if(row.dataKind!=="source_ohlc"||row.symbol!==symbol||row.providerCode!==providerCode)throw Error("Reject reference point, derived or mismatched OHLC "+index);
70 if(!dateValid(row.sessionDate)||row.sessionDate<from||row.sessionDate>to)throw Error("Invalid session date "+index);
71 const openMs=ms(row.openTime,"openTime"), closeMs=ms(row.closeTime,"closeTime");
72 if(openMs>=closeMs||closeMs-openMs>2*DAY||openMs>ingestedAt||closeMs>ingestedAt)throw Error("Invalid or future bar interval "+index);
73 if(dateInZone(openMs,timeZone)!==row.sessionDate)throw Error("Timezone/session mismatch "+index);
74 const open=decimal(row.open,"open",factor),high=decimal(row.high,"high",factor),
75 low=decimal(row.low,"low",factor),close=decimal(row.close,"close",factor);
76 if(low.value>open.value||low.value>close.value||high.value<open.value||high.value<close.value)throw Error("Invalid OHLC ordering "+index);
77 const volume=row.volume===undefined||row.volume===null?null:/^0+(?:\.0+)?$/.test(String(row.volume))?"0":decimal(row.volume,"volume",1).canonical;
78 const key=symbol+"|"+timeframe+"|"+row.sessionDate;
79 const entry={symbol,providerCode,timeframe:"1d",sessionDate:row.sessionDate,
80 openTime:new Date(openMs).toISOString(),closeTime:new Date(closeMs).toISOString(),
81 open:open.canonical,high:high.canonical,low:low.canonical,close:close.canonical,
82 volume,unit:canonicalUnit,sourceUnit:rawUnit,quality:"DEGRADED",qualityReason:"source_ohlc_not_cross_verified",
83 provenance:{providerCode,licenseEvidenceRef:license.evidenceRef,sourceRecordId:row.sourceRecordId??null,ingestedAt:new Date(ingestedAt).toISOString(),timeZone}};
84 if(index>0&&row.sessionDate<rows[index-1].sessionDate)outOfOrder++;
85 if(unique.has(key)){
86 const prior=unique.get(key);
87 if(["open","high","low","close","volume","openTime","closeTime"].some(k=>prior[k]!==entry[k]))throw Error("Conflicting duplicate OHLC "+key);
88 duplicates++;
89 continue;
90 }
91 unique.set(key,entry);
92 }
93 const candles=[...unique.values()].sort((a,b)=>a.sessionDate.localeCompare(b.sessionDate));
94 let maxCalendarGapDays=0,missingExpectedSessions=0;
95 for(let i=1;i<candles.length;i++){
96 const a=Date.parse(candles[i-1].sessionDate+"T00:00:00Z"),b=Date.parse(candles[i].sessionDate+"T00:00:00Z");
97 const delta=(b-a)/DAY;
98 maxCalendarGapDays=Math.max(maxCalendarGapDays,delta);
99 if(isSessionDay){
100 for(let t=a+DAY;t<b;t+=DAY){if(isSessionDay(new Date(t).toISOString().slice(0,10)))missingExpectedSessions++}
101 }
102 }
103 const coverageDays=candles.length?1+(Date.parse(candles.at(-1).sessionDate+"T00:00:00Z")-Date.parse(candles[0].sessionDate+"T00:00:00Z"))/DAY:0;
104 const annualCoverageMet=coverageDays>=365;
105 // Compare requested window against an independently configured exchange calendar.
106 // Never assume every calendar day (or every weekday) is an open market session.
107 let expectedWindowSessions=null,missingWindowSessions=null,unexpectedClosedSessions=null;
108 if(isSessionDay){
109 expectedWindowSessions=0;missingWindowSessions=0;unexpectedClosedSessions=0;
110 const known=new Set(candles.map(x=>x.sessionDate));
111 for(let at=Date.parse(from+"T00:00:00Z");at<=Date.parse(to+"T00:00:00Z");at+=DAY){
112 const day=new Date(at).toISOString().slice(0,10);
113 const expected=isSessionDay(day);
114 if(typeof expected!=="boolean")throw Error("Session calendar returned non-boolean");
115 if(expected){expectedWindowSessions++;if(!known.has(day))missingWindowSessions++}
116 else if(known.has(day))unexpectedClosedSessions++;
117 }
118 }
119 return {
120 symbol,providerCode,timeframe,unit:canonicalUnit,dataKind:"source_ohlc",
121 licenseEvidenceRef:license.evidenceRef,intendedUse,candles,
122 audit:{receivedCount:rows.length,uniqueCount:candles.length,duplicates,outOfOrder,
123 firstSession:candles[0]?.sessionDate??null,lastSession:candles.at(-1)?.sessionDate??null,
124 coverageDays,annualCoverageMet,maxCalendarGapDays,missingExpectedSessions,expectedWindowSessions,missingWindowSessions,unexpectedClosedSessions,
125 calendarVerified:Boolean(isSessionDay),gapsFilled:0,
126 // Authorization metadata alone is not legal proof: human licensing approval is required.
127 readyForAnnualPublication:intendedUse==="public_api"&&annualCoverageMet&&Boolean(isSessionDay)&&
128 expectedWindowSessions>0&&missingWindowSessions===0&&unexpectedClosedSessions===0&&
129 missingExpectedSessions===0&&duplicates===0&&outOfOrder===0}
130 };
131 }