Intelligence, Advanced Charting & Trading Platform
Phase 1: integrate fresh Gold API XAU source
Phase 1: integrate fresh Gold API XAU source
Davood Mehraban committed
Oct 10, 2026 at 16:00 UTC
1730b3fb549015baea61f077d7a3770eb7d036d5
3 files changed
+21
-2
packages/market-domain/src/adapters/gold-api.mjs
new
+14
@@ -0,0 +1,14 @@
1
+import { canonicalObservation } from '../provider-contract.mjs';
2
+export const GOLD_API_XAU_URL='https://api.gold-api.com/price/XAU';
3
+export function parseGoldApiXau({payload,receivedAt}){
4
+ if(!(receivedAt instanceof Date)||Number.isNaN(receivedAt.valueOf()))throw new TypeError('receivedAt must be a valid Date');
5
+ if(!payload||typeof payload!=='object'||Array.isArray(payload))throw new TypeError('payload must be an object');
6
+ if(payload.symbol!=='XAU'||payload.currency!=='USD')throw new RangeError('expected XAU in USD');
7
+ const price=typeof payload.price==='string'&&payload.price.trim()?Number(payload.price):payload.price;
8
+ if(!Number.isFinite(price)||price<=0)throw new RangeError('price must be positive');
9
+ if(typeof payload.updatedAt!=='string'||!payload.updatedAt.trim())throw new TypeError('updatedAt is required');
10
+ const timestamp=new Date(payload.updatedAt);
11
+ if(Number.isNaN(timestamp.valueOf()))throw new TypeError('invalid updatedAt');
12
+ const observation=canonicalObservation({providerCode:'gold_api',canonicalSymbol:'XAU_USD',providerTimestamp:timestamp,receivedAt,price,rawUnit:'USD_PER_TROY_OUNCE'});
13
+ return {...observation,raw:{symbol:payload.symbol,currency:payload.currency,price:payload.price,updatedAt:payload.updatedAt}};
14
+}
packages/market-domain/test/gold-api-adapter.test.mjs
new
+4
@@ -0,0 +1,4 @@
1
+import test from 'node:test';import assert from 'node:assert/strict';
2
+import {parseGoldApiXau,GOLD_API_XAU_URL} from '../src/adapters/gold-api.mjs';
3
+test('Gold API endpoint and observed response normalize to XAU_USD',()=>{assert.equal(GOLD_API_XAU_URL,'https://api.gold-api.com/price/XAU');const r=parseGoldApiXau({payload:{symbol:'XAU',currency:'USD',price:4195.6,updatedAt:'2026-10-10T12:28:32Z'},receivedAt:new Date('2026-10-10T12:28:35Z')});assert.equal(r.price,4195.6);assert.equal(r.canonicalSymbol,'XAU_USD');assert.equal(r.providerCode,'gold_api')});
4
+test('rejects mismatched currency and future provider timestamps',()=>{assert.throws(()=>parseGoldApiXau({payload:{symbol:'XAU',currency:'EUR',price:1,updatedAt:'2026-10-10T12:28:32Z'},receivedAt:new Date('2026-10-10T12:28:35Z')}));assert.throws(()=>parseGoldApiXau({payload:{symbol:'XAU',currency:'USD',price:1,updatedAt:'2026-10-10T12:28:40Z'},receivedAt:new Date('2026-10-10T12:28:35Z')}))});
scripts/phase1-live-data-proof.mjs
+3
-2
@@ -1,6 +1,7 @@
1
import fs from 'node:fs/promises';
2
import path from 'node:path';
3
import { buildAlphaVantageGoldSpotUrl, parseAlphaVantageGoldSpot } from '../packages/market-domain/src/adapters/alpha-vantage.mjs';
4
+import { GOLD_API_XAU_URL, parseGoldApiXau } from '../packages/market-domain/src/adapters/gold-api.mjs';
5
import { parseNavasanLatest } from '../packages/market-domain/src/adapters/navasan.mjs';
6
import { buildDataProofReport } from '../packages/market-domain/src/data-proof-report.mjs';
7
import { buildDataProofArtifact } from '../packages/market-domain/src/data-proof-artifact.mjs';
@@ -10,8 +11,8 @@ const required=n=>{const v=process.env[n]?.trim();if(!v)throw new Error(n+' is r
11
const safeJson=async r=>{const t=await r.text();let p;try{p=JSON.parse(t)}catch{throw new Error('provider returned non-JSON HTTP '+r.status)}if(!r.ok)throw new Error('provider HTTP '+r.status);return p};
12
const navasanUrl=k=>{const u=new URL('https://api.navasan.tech/latest/');u.searchParams.set('api_key',k);return u};
13
const observations=new Map([['USD_IRT_FREE',[]],['GOLD18_IRT',[]],['XAU_USD',[]]]),providerErrors=[];
13
-const sample=async()=>{const nk=required('NAVASAN_API_KEY'),ak=required('ALPHAVANTAGE_API_KEY');try{const receivedAt=new Date(),p=await safeJson(await fetch(navasanUrl(nk),{signal:AbortSignal.timeout(15000)}));for(const x of parseNavasanLatest({payload:p,receivedAt}))observations.get(x.canonicalSymbol)?.push({timestamp:x.providerTimestamp,price:x.price})}catch(e){providerErrors.push({provider:'navasan',at:new Date().toISOString(),message:e.message})}try{const receivedAt=new Date(),p=await safeJson(await fetch(buildAlphaVantageGoldSpotUrl(ak),{signal:AbortSignal.timeout(15000)}));if(p.Note||p.Information||p['Error Message'])throw new Error(p.Note||p.Information||p['Error Message']);const x=parseAlphaVantageGoldSpot({payload:p,receivedAt});observations.get('XAU_USD').push({timestamp:x.providerTimestamp,price:x.price})}catch(e){providerErrors.push({provider:'alpha_vantage',at:new Date().toISOString(),message:e.message})}};
14
+const sample=async()=>{const nk=required('NAVASAN_API_KEY'),goldProvider=process.env.XAU_PROVIDER||'gold_api';if(!['gold_api','alpha_vantage'].includes(goldProvider))throw new Error('unsupported XAU_PROVIDER');const ak=goldProvider==='alpha_vantage'?required('ALPHAVANTAGE_API_KEY'):null;try{const receivedAt=new Date(),p=await safeJson(await fetch(navasanUrl(nk),{signal:AbortSignal.timeout(15000)}));for(const x of parseNavasanLatest({payload:p,receivedAt}))observations.get(x.canonicalSymbol)?.push({timestamp:x.providerTimestamp,price:x.price})}catch(e){providerErrors.push({provider:'navasan',at:new Date().toISOString(),message:e.message})}try{const receivedAt=new Date(),p=await safeJson(await fetch(goldProvider==='gold_api'?GOLD_API_XAU_URL:buildAlphaVantageGoldSpotUrl(ak),{signal:AbortSignal.timeout(15000)}));if(p.Note||p.Information||p['Error Message'])throw new Error(p.Note||p.Information||p['Error Message']);const x=goldProvider==='gold_api'?parseGoldApiXau({payload:p,receivedAt}):parseAlphaVantageGoldSpot({payload:p,receivedAt});observations.get('XAU_USD').push({timestamp:x.providerTimestamp,price:x.price})}catch(e){providerErrors.push({provider:goldProvider,at:new Date().toISOString(),message:e.message})}};
15
const samples=Math.max(1,int('DATA_PROOF_SAMPLES',3)),intervalMs=int('DATA_PROOF_INTERVAL_MS',60000);for(let i=0;i<samples;i++){await sample();if(i+1<samples)await sleep(intervalMs)}
15
-const generatedAt=new Date(),configs={USD_IRT_FREE:{providerCode:'navasan',thresholds:{maxGapMs:14400000,maxFreshnessMs:14400000,maxDuplicateCount:Math.max(0,samples-1),maxOutOfOrderCount:0}},GOLD18_IRT:{providerCode:'navasan',thresholds:{maxGapMs:14400000,maxFreshnessMs:14400000,maxDuplicateCount:Math.max(0,samples-1),maxOutOfOrderCount:0}},XAU_USD:{providerCode:'alpha_vantage',thresholds:{maxGapMs:3600000,maxFreshnessMs:3600000,maxDuplicateCount:Math.max(0,samples-1),maxOutOfOrderCount:0}}},reports=[];
16
+const generatedAt=new Date(),configs={USD_IRT_FREE:{providerCode:'navasan',thresholds:{maxGapMs:14400000,maxFreshnessMs:14400000,maxDuplicateCount:Math.max(0,samples-1),maxOutOfOrderCount:0}},GOLD18_IRT:{providerCode:'navasan',thresholds:{maxGapMs:14400000,maxFreshnessMs:14400000,maxDuplicateCount:Math.max(0,samples-1),maxOutOfOrderCount:0}},XAU_USD:{providerCode:process.env.XAU_PROVIDER||'gold_api',thresholds:{maxGapMs:3600000,maxFreshnessMs:3600000,maxDuplicateCount:Math.max(0,samples-1),maxOutOfOrderCount:0}}},reports=[];
17
for(const [symbol,c] of Object.entries(configs)){const items=observations.get(symbol);if(!items.length){reports.push({providerCode:c.providerCode,canonicalSymbol:symbol,checkedAt:generatedAt.toISOString(),status:'FAIL',failures:['NO_LIVE_OBSERVATIONS'],thresholds:c.thresholds,metrics:{count:0}});continue}reports.push(buildDataProofReport({providerCode:c.providerCode,canonicalSymbol:symbol,observations:items,checkedAt:generatedAt,thresholds:c.thresholds}))}
18
const artifact=buildDataProofArtifact({generatedAt,reports}),output={...artifact,samplePlan:{samples,intervalMs},providerErrors},outPath=process.env.DATA_PROOF_OUTPUT||path.join('artifacts','phase1-live-data-proof.json');await fs.mkdir(path.dirname(outPath),{recursive:true});await fs.writeFile(outPath,JSON.stringify(output,null,2)+'\n','utf8');console.log('DATA_PROOF_STATUS='+artifact.status);for(const r of reports)console.log(r.canonicalSymbol+'='+r.status+';count='+(r.metrics.count??0)+';failures='+(r.failures.join(',')||'none'));console.log('PROVIDER_ERRORS='+providerErrors.length);console.log('ARTIFACT='+outPath);process.exitCode=artifact.status==='PASS'?0:2;