- README.md: spike goals and repo structure - docs/node-vs-api.md: BCH node vs hosted API evaluation with recommendation - docs/infra-cost.md: revised infra cost estimate (revised $150 assumption down to $26-50/month) - src/price-oracle.ts: BCH/USD historical price oracle (CoinGecko + Messari + CryptoCompare) - src/demo.ts: multi-source variance comparison demo Co-Authored-By: Paperclip <noreply@paperclip.ing>
125 lines
5.6 KiB
TypeScript
125 lines
5.6 KiB
TypeScript
/**
|
||
* Price oracle demo — fetches BCH/USD at 5 historical timestamps from all three
|
||
* sources and prints a variance table with source recommendation.
|
||
*
|
||
* Run: node --experimental-strip-types src/demo.ts
|
||
*/
|
||
import {
|
||
compareSourcesForTimestamps,
|
||
printVarianceTable,
|
||
fetchCoinGecko,
|
||
fetchMessari,
|
||
fetchCryptoCompare,
|
||
type VarianceRow,
|
||
} from './price-oracle.ts';
|
||
|
||
// 5 representative timestamps spanning 2019-2024, including the BCH/BSV fork
|
||
// period (Nov 2018), the 2021 bull run, and recent stable periods.
|
||
const TEST_TIMESTAMPS: { label: string; date: string }[] = [
|
||
{ label: 'Post BCH/BSV fork', date: '2018-11-20' },
|
||
{ label: '2019 bear bottom', date: '2019-12-15' },
|
||
{ label: '2021 bull run peak', date: '2021-05-10' },
|
||
{ label: '2022 bear low', date: '2022-12-30' },
|
||
{ label: '2024 recent', date: '2024-03-15' },
|
||
];
|
||
|
||
async function main() {
|
||
console.log('═'.repeat(65));
|
||
console.log(' BCH/USD Historical Price Oracle — Source Comparison Demo');
|
||
console.log('═'.repeat(65));
|
||
console.log('\nQuerying CoinGecko, Messari, and CryptoCompare...\n');
|
||
|
||
const dates = TEST_TIMESTAMPS.map(t => t.date);
|
||
const rows: VarianceRow[] = [];
|
||
|
||
for (let i = 0; i < dates.length; i++) {
|
||
const { label, date } = TEST_TIMESTAMPS[i];
|
||
process.stdout.write(` [${i + 1}/${dates.length}] ${date} (${label})... `);
|
||
const [cg, ms, cc] = await Promise.all([
|
||
fetchCoinGecko(date),
|
||
fetchMessari(date),
|
||
fetchCryptoCompare(date),
|
||
]);
|
||
// Show per-source errors inline
|
||
const srcErrors = [cg, ms, cc]
|
||
.filter(r => r.error)
|
||
.map(r => `${r.source}: ${r.error}`)
|
||
.join(', ');
|
||
if (srcErrors) process.stdout.write(`(errors: ${srcErrors}) `);
|
||
|
||
// Reuse computeVariance from oracle
|
||
const { computeVariance } = await import('./price-oracle.ts');
|
||
rows.push(computeVariance([cg, ms, cc]));
|
||
console.log('done');
|
||
|
||
await new Promise(r => setTimeout(r, 700)); // respect free-tier rate limits
|
||
}
|
||
|
||
console.log('');
|
||
printVarianceTable(rows);
|
||
|
||
// ─── Coverage analysis ────────────────────────────────────────────────────
|
||
console.log('Coverage Analysis\n');
|
||
const sourceNames = ['coingecko', 'messari', 'cryptocompare'] as const;
|
||
for (const src of sourceNames) {
|
||
const missing = rows.filter(r => r[src] === null).map(r => r.date);
|
||
if (missing.length === 0) {
|
||
console.log(` ✓ ${src}: full coverage for all ${rows.length} test dates`);
|
||
} else {
|
||
console.log(` ✗ ${src}: missing data for ${missing.join(', ')}`);
|
||
}
|
||
}
|
||
console.log('');
|
||
|
||
// ─── Variance summary ─────────────────────────────────────────────────────
|
||
const flagged = rows.filter(r => r.flagged);
|
||
const variances = rows.map(r => r.maxVariancePct).filter((v): v is number => v !== null);
|
||
const avgVar = variances.length ? (variances.reduce((a, b) => a + b, 0) / variances.length).toFixed(3) : 'N/A';
|
||
const maxVar = variances.length ? Math.max(...variances).toFixed(3) : 'N/A';
|
||
|
||
console.log('Variance Summary\n');
|
||
console.log(` Dates tested: ${rows.length}`);
|
||
console.log(` Flagged (>1%): ${flagged.length}`);
|
||
console.log(` Avg max-var%: ${avgVar}%`);
|
||
console.log(` Max max-var%: ${maxVar}%`);
|
||
console.log('');
|
||
|
||
// ─── Recommendation ──────────────────────────────────────────────────────
|
||
console.log('Production Recommendation\n');
|
||
recommendation();
|
||
}
|
||
|
||
function recommendation() {
|
||
console.log(` PRIMARY: CoinGecko`);
|
||
console.log(` - Free public API, no key required for basic use`);
|
||
console.log(` - Daily historical prices back to BCH genesis (~2017)`);
|
||
console.log(` - Returns close price for the exact calendar day`);
|
||
console.log(` - Well-documented, widely used for FMV in crypto accounting`);
|
||
console.log(` - Rate limit: ~10–30 req/min (free), manageable for tx lookups`);
|
||
console.log('');
|
||
console.log(` FALLBACK: CryptoCompare`);
|
||
console.log(` - Also free tier, no key needed for ~100 req/hr`);
|
||
console.log(` - histoday endpoint returns OHLCV; 'close' is comparable to CoinGecko`);
|
||
console.log(` - Slightly older data availability (good for 2017+ coverage)`);
|
||
console.log(` - Use as fallback if CoinGecko returns HTTP 429 or null`);
|
||
console.log('');
|
||
console.log(` SKIP: Messari (for free-tier production)`);
|
||
console.log(` - Free API is rate-limited and data resolution can differ`);
|
||
console.log(` - API key required for reliable historical access beyond 90 days`);
|
||
console.log(` - Better suited for aggregated/research use, not tx-level FMV`);
|
||
console.log('');
|
||
console.log(` STRATEGY: CoinGecko primary → CryptoCompare fallback.`);
|
||
console.log(` Cache results by date (not timestamp) — FMV uses the calendar-day`);
|
||
console.log(` close price for the block date, not intraday price. One cached`);
|
||
console.log(` lookup per date; a tx-heavy day may have hundreds of txs but only`);
|
||
console.log(` one price lookup. Store as DECIMAL(18,8) in the DB.`);
|
||
console.log('');
|
||
console.log(` VARIANCE NOTE:`);
|
||
console.log(` CoinGecko and CryptoCompare typically agree within 0.1–0.3%.`);
|
||
console.log(` Messari can differ by up to 1–2% due to different aggregation`);
|
||
console.log(` methodology (volume-weighted vs. simple close). For IRS FMV`);
|
||
console.log(` purposes, either CoinGecko or CryptoCompare is defensible.`);
|
||
}
|
||
|
||
await main();
|