Intelligence, Advanced Charting & Trading Platform
feature/chartnova-neon-history
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 | import fs from 'node:fs/promises'; |
| 2 | import path from 'node:path'; |
| 3 | |
| 4 | // Official ECB daily REFERENCE rates, NOT OHLC candles. |
| 5 | // Free commercial reuse with source attribution: https://www.ecb.europa.eu/stats/ecb_statistics/governance_and_quality_framework/html/usage_policy.en.html |
| 6 | const ROOT = path.resolve(import.meta.dirname,'..'); |
| 7 | const FROM = '2025-10-11', TO = '2026-10-11'; |
| 8 | const ECB_URL = 'https://data-api.ecb.europa.eu/service/data/EXR/D.USD+GBP+CHF.EUR.SP00.A?startPeriod='+FROM+'&endPeriod='+TO+'&format=csvdata'; |
| 9 | const MAP = { USD:'EUR_USD_ECB', GBP:'EUR_GBP_ECB', CHF:'EUR_CHF_ECB' }; |
| 10 | const dryRun = !process.argv.includes('--commit'); |
| 11 | |
| 12 | function csvRows(text){ |
| 13 | let rows=[],row=[],item='',quoted=false; |
| 14 | for(let i=0;i<text.length;i++){ |
| 15 | const ch=text[i]; |
| 16 | if(ch==='"'){ |
| 17 | if(quoted && text[i+1]==='"'){item+='"';i++;} |
| 18 | else quoted=!quoted; |
| 19 | }else if(ch===','&&!quoted){row.push(item);item='';} |
| 20 | else if((ch==='\n'||ch==='\r')&&!quoted){ |
| 21 | if(ch==='\r'&&text[i+1]==='\n')i++; |
| 22 | row.push(item);item=''; |
| 23 | if(row.some(x=>x.trim()))rows.push(row); |
| 24 | row=[]; |
| 25 | }else item+=ch; |
| 26 | } |
| 27 | if(quoted)throw Error('Unclosed CSV quote'); |
| 28 | if(item||row.length){row.push(item);rows.push(row);} |
| 29 | const header=rows.shift(); |
| 30 | if(!header||!header.includes('TIME_PERIOD')||!header.includes('OBS_VALUE'))throw Error('ECB schema mismatch'); |
| 31 | return rows.map(row=>Object.fromEntries(header.map((k,i)=>[k,row[i]??'']))); |
| 32 | } |
| 33 | function normalize(csv){ |
| 34 | const parsed=csvRows(csv); |
| 35 | const bySymbol=new Map(),report={total:parsed.length,accepted:0,duplicates:0}; |
| 36 | for(const record of parsed){ |
| 37 | if(record.FREQ!=='D'||record.CURRENCY_DENOM!=='EUR'||!Object.hasOwn(MAP,record.CURRENCY)||record.EXR_TYPE!=='SP00'||record.EXR_SUFFIX!=='A') |
| 38 | throw Error('Unexpected ECB series'); |
| 39 | if(record.OBS_STATUS!=='A')throw Error('Unconfirmed ECB observation '+record.TIME_PERIOD); |
| 40 | const day=record.TIME_PERIOD; |
| 41 | if(!/^\d{4}-\d\d-\d\d$/.test(day)||day<FROM||day>TO||!Number.isFinite(Date.parse(day+'T00:00:00.000Z')))throw Error('Invalid trade date '+day); |
| 42 | const price=Number(record.OBS_VALUE); |
| 43 | if(!Number.isFinite(price)||price<=0||price>100)throw Error('Invalid ECB rate '+day); |
| 44 | const symbol=MAP[record.CURRENCY],key=symbol+'|'+day; |
| 45 | const original=bySymbol.get(key); |
| 46 | if(original){if(original.price!==String(price))throw Error('Conflicting duplicate '+key);report.duplicates++;continue;} |
| 47 | bySymbol.set(key,{ |
| 48 | symbol, |
| 49 | // Point timestamp is end-of-day UTC, avoiding intraday look-ahead from publication-time ambiguity. |
| 50 | ts:day+'T23:59:59.000Z', |
| 51 | price:String(price), |
| 52 | flags:{ |
| 53 | data_kind:'daily_reference_point_not_ohlc', |
| 54 | source:'ECB EXR', |
| 55 | source_series:record.KEY, |
| 56 | observation_date:day, |
| 57 | release_time:'unknown', |
| 58 | publish_time_policy:'end_of_day_utc_conservative', |
| 59 | unit:record.UNIT, |
| 60 | license:'ECB/ESCB open statistics; attribution required' |
| 61 | } |
| 62 | }); |
| 63 | report.accepted++; |
| 64 | } |
| 65 | const list=[...bySymbol.values()].sort((a,b)=>a.ts.localeCompare(b.ts)||a.symbol.localeCompare(b.symbol)); |
| 66 | for(const key of Object.values(MAP)){ |
| 67 | const sub=list.filter(x=>x.symbol===key); |
| 68 | if(sub.length<200||sub.length>270)throw Error('Unexpected yearly coverage for '+key+': '+sub.length); |
| 69 | report[key]={count:sub.length,first:sub[0].ts.slice(0,10),last:sub.at(-1).ts.slice(0,10)}; |
| 70 | } |
| 71 | return {list,report}; |
| 72 | } |
| 73 | async function databaseURL(){ |
| 74 | const text=await fs.readFile(path.join(ROOT,'.env.local'),'utf8'); |
| 75 | const line=text.split(/\r?\n/).find(x=>x.startsWith('DATABASE_URL=')); |
| 76 | if(!line)throw Error('Missing DATABASE_URL'); |
| 77 | return line.slice('DATABASE_URL='.length).trim().replace(/^["']|["']$/g,''); |
| 78 | } |
| 79 | async function execute(dbURL,query,params){ |
| 80 | const u=new URL(dbURL); |
| 81 | const r=await fetch('https://'+u.hostname+'/sql',{ |
| 82 | method:'POST',headers:{'content-type':'application/json','Neon-Connection-String':dbURL,'Neon-Raw-Text-Output':'true','Neon-Array-Mode':'false'}, |
| 83 | body:JSON.stringify({query,params}),signal:AbortSignal.timeout(20000) |
| 84 | }); |
| 85 | const t=await r.text(); |
| 86 | if(!r.ok)throw Error('Neon HTTP '+r.status+': '+t.slice(0,450)); |
| 87 | return JSON.parse(t); |
| 88 | } |
| 89 | const INSERT = ` |
| 90 | INSERT INTO market_ticks(instrument_id,provider_id,ts,price,quality,quality_score,flags) |
| 91 | SELECT i.id,p.id,x.ts,x.price,'GOOD'::quality_state,95::numeric,x.flags |
| 92 | FROM jsonb_to_recordset($1::jsonb) AS x(symbol text,ts timestamptz,price numeric,flags jsonb) |
| 93 | JOIN instruments i ON i.symbol=x.symbol |
| 94 | JOIN providers p ON p.code='ecb_exr' |
| 95 | ON CONFLICT (instrument_id,provider_id,ts) DO NOTHING |
| 96 | `; |
| 97 | async function main(){ |
| 98 | let r, lastError; |
| 99 | for(let attempt=1;attempt<=4;attempt++){ |
| 100 | try{r=await fetch(ECB_URL,{headers:{Accept:'text/csv','User-Agent':'ChartNova/1.0 (+https://chartnova.ir)'},signal:AbortSignal.timeout(22000)});if(r.ok)break;lastError=new Error('ECB HTTP '+r.status)} |
| 101 | catch(e){lastError=e} |
| 102 | if(attempt<4)await new Promise(resolve=>setTimeout(resolve,attempt*900)); |
| 103 | } |
| 104 | if(!r||!r.ok)throw lastError || Error('ECB not reachable'); |
| 105 | if(!r.ok)throw Error('ECB HTTP '+r.status); |
| 106 | const data=normalize(await r.text()); |
| 107 | const report={provider:'ECB',source:ECB_URL,window:[FROM,TO],dryRun,...data.report}; |
| 108 | const reportFile=path.join(ROOT,'artifacts','ecb-history-import-report.json'); |
| 109 | await fs.mkdir(path.dirname(reportFile),{recursive:true}); |
| 110 | if(!dryRun){ |
| 111 | const db=await databaseURL(); |
| 112 | let inserted=0; |
| 113 | for(let i=0;i<data.list.length;i+=100){ |
| 114 | const batch=data.list.slice(i,i+100); |
| 115 | const result=await execute(db,INSERT,[JSON.stringify(batch)]); |
| 116 | inserted+=Number(result.rowCount||0); |
| 117 | } |
| 118 | report.insertedThisRun=inserted; |
| 119 | const verify=await execute(db,`SELECT i.symbol,COUNT(*)::int AS count, MIN(t.ts)::text AS first_date, MAX(t.ts)::text AS last_date FROM market_ticks t JOIN instruments i ON i.id=t.instrument_id JOIN providers p ON p.id=t.provider_id WHERE p.code='ecb_exr' GROUP BY i.symbol ORDER BY i.symbol`,[]); |
| 120 | report.database=verify.rows; |
| 121 | for(const [symbol,expected] of Object.entries(data.report).filter(([name])=>name.startsWith('EUR_'))){ |
| 122 | const got=verify.rows.find(x=>x.symbol===symbol); |
| 123 | if(!got||Number(got.count)!==expected.count)throw Error('Neon verification mismatch '+symbol); |
| 124 | } |
| 125 | } |
| 126 | await fs.writeFile(reportFile,JSON.stringify(report,null,2)+'\n'); |
| 127 | console.log(JSON.stringify(report,null,2)); |
| 128 | } |
| 129 | main().catch(e=>{console.error('FAILED',e.message);process.exitCode=1}); |