-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbtcgui.html
More file actions
635 lines (595 loc) · 29.5 KB
/
Copy pathbtcgui.html
File metadata and controls
635 lines (595 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="author" content="Johan & Claude">
<title>Bitcoin Price Tracker</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{background:#0f0f23;color:#e0e0e0;font-family:-apple-system,'Segoe UI',Roboto,'Helvetica Neue',sans-serif}
.container{max-width:1000px;margin:0 auto;padding:28px 20px}
h1{color:#f7931a;margin-bottom:28px;font-size:32px;font-weight:800;letter-spacing:-0.5px}
h2{color:#bbb;margin-bottom:14px;font-size:16px;font-weight:600}
.day-count{color:#666;font-weight:400}
.section{background:#16213e;border-radius:14px;padding:22px;margin-bottom:18px}
.current-price{display:flex;gap:20px;flex-wrap:wrap}
.price-chip{background:#0f3460;border-radius:10px;padding:14px 22px;display:flex;flex-direction:column;gap:2px;min-width:160px}
.chip-label{color:#888;font-size:12px;font-weight:500;text-transform:uppercase;letter-spacing:1px}
.chip-value{font-size:26px;font-weight:800;color:#fff}
.range-bar{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.range-label{color:#888;font-size:13px}
.date-input{background:#0f3460;border:1px solid #333;color:#e0e0e0;padding:8px 12px;border-radius:8px;font-size:16px;font-family:inherit}
.date-input::-webkit-calendar-picker-indicator{filter:invert(0.7)}
.btn{background:#f7931a;color:#fff;border:none;padding:10px 22px;border-radius:8px;cursor:pointer;font-size:14px;font-weight:600;font-family:inherit;transition:background 0.15s}
.btn:hover{background:#e8851a}
.btn:disabled{opacity:0.5;cursor:not-allowed}
.status{color:#f7931a;font-size:13px}
.preset-bar{display:flex;gap:8px;margin-top:12px;flex-wrap:wrap}
.preset{background:#0f3460;color:#ccc;border:1px solid #333;padding:6px 16px;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;font-family:inherit;transition:all 0.15s}
.preset:hover{background:#f7931a;color:#fff;border-color:#f7931a}
.preset.active{background:#f7931a;color:#fff;border-color:#f7931a}
.preset-sep{width:1px;height:20px;background:#333;margin:0 4px}
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px}
.stat-card{background:#0f3460;border-radius:10px;padding:18px;text-align:center}
.stat-label{color:#888;font-size:11px;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px}
.stat-value{font-size:22px;font-weight:800}
.positive{color:#2ecc71}
.negative{color:#e74c3c}
canvas{margin:4px 0}
.table-scroll{max-height:500px;overflow-y:auto;overflow-x:auto;-webkit-overflow-scrolling:touch}
.price-table{width:100%;border-collapse:collapse;font-size:13px}
.price-table thead{position:sticky;top:0;background:#16213e;z-index:1}
.price-table th{text-align:left;padding:10px 14px;border-bottom:2px solid #333;color:#888;font-weight:600}
.sortable{cursor:pointer;user-select:none}.sortable:hover{color:#f7931a}
.price-table td{padding:7px 14px;border-bottom:1px solid #1a1a3e}
.price-table tr:hover{background:#0f3460}
.price-cell{font-variant-numeric:tabular-nums;font-weight:500}
.vol-cell{font-variant-numeric:tabular-nums;color:#4ebaea;font-size:12px}
.vol-chip .chip-value{color:#4ebaea}
::-webkit-scrollbar{width:8px}
::-webkit-scrollbar-track{background:#0f0f23;border-radius:4px}
::-webkit-scrollbar-thumb{background:#333;border-radius:4px}
.loading-pulse{animation:pulse 1.5s ease-in-out infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.4}}
@media(max-width:600px){
h1{font-size:22px;margin-bottom:18px}
.container{padding:16px 12px}
.section{padding:14px;margin-bottom:12px}
.price-chip{flex:1 1 calc(50% - 10px);min-width:0;padding:12px 14px}
.chip-value{font-size:clamp(14px,4.5vw,26px)}
.range-bar{display:grid;grid-template-columns:auto 1fr;gap:8px 10px;align-items:center}
#fetchBtn,#status{grid-column:1/-1}
#fetchBtn{width:100%;padding:12px}
.preset{padding:9px 10px;font-size:12px;min-height:44px}
.preset-sep{display:none}
.stats-grid{grid-template-columns:repeat(2,1fr);gap:10px}
.stat-card{padding:12px 8px}
.stat-value{font-size:17px}
.price-table{min-width:380px;font-size:12px}
.price-table th,.price-table td{padding:9px 8px}
}
</style>
</head>
<body>
<div class="container">
<h1>₿ Bitcoin Price Tracker</h1>
<p style="color:#f7931a;font-size:13px;margin-top:-20px;margin-bottom:20px">by Johan & Claude</p>
<!-- Current price card -->
<div class="section">
<h2>Current Price</h2>
<div class="current-price">
<div class="price-chip">
<span class="chip-label">USD</span>
<span class="chip-value loading-pulse" id="chipUsd">Loading...</span>
</div>
<div class="price-chip">
<span class="chip-label">EUR</span>
<span class="chip-value loading-pulse" id="chipEur">Loading...</span>
</div>
<div class="price-chip">
<span class="chip-label">GBP</span>
<span class="chip-value loading-pulse" id="chipGbp">Loading...</span>
</div>
<div class="price-chip vol-chip">
<span class="chip-label">24h Volume</span>
<span class="chip-value loading-pulse" id="chipVol">Loading...</span>
</div>
</div>
</div>
<!-- Date range controls -->
<div class="section">
<div class="range-bar">
<label class="range-label">From</label>
<input type="date" id="fromDate" class="date-input">
<label class="range-label">To</label>
<input type="date" id="toDate" class="date-input">
<button id="fetchBtn" class="btn" onclick="fetchRange()">Fetch</button>
<span id="status" class="status"></span>
</div>
<div class="preset-bar">
<button class="preset range-btn" onclick="setPreset(1,this)">1D</button>
<button class="preset range-btn" onclick="setPreset(7,this)">1W</button>
<button class="preset range-btn" onclick="setPreset(30,this)">1M</button>
<button class="preset range-btn active" id="btn3m" onclick="setPreset(90,this)">3M</button>
<button class="preset range-btn" onclick="setPreset(365,this)">1Y</button>
<button class="preset range-btn" onclick="setPreset(0,this)">All</button>
<span class="preset-sep"></span>
<button class="preset" id="plBtn" onclick="togglePowerLaw()">Power Law</button>
<button class="preset" id="logBtn" onclick="toggleLog()">Log Scale</button>
<button class="preset" id="llBtn" onclick="toggleLogLog()">Log-Log</button>
</div>
</div>
<!-- Stats cards -->
<div class="section" id="statsSection">
<h2 id="periodHeader">Loading...</h2>
<div class="stats-grid" id="statsGrid"></div>
</div>
<!-- Chart -->
<div class="section">
<canvas id="priceChart"></canvas>
</div>
<!-- Table -->
<div class="section">
<h2 id="tableHeader">Daily Prices</h2>
<div class="table-scroll">
<table class="price-table">
<thead><tr><th class="sortable" onclick="toggleDateSort()">Date <span id="sortArrow" style="font-size:9px;opacity:0.5">▲</span></th><th>Price (USD)</th><th>Volume (USD)</th><th>Change</th></tr></thead>
<tbody id="tableBody"></tbody>
</table>
</div>
</div>
</div>
<script>
var priceChart = null;
var tableSortAsc = true;
var showPL = false;
var showLog = false;
var showLL = false;
var curLabels = [], curData = [], curVols = [];
var curGranularity = 'daily';
var GENESIS = new Date('2009-01-03T00:00:00Z').getTime();
var BINANCE_CUTOFF_MS = new Date('2017-08-17T00:00:00Z').getTime();
function getInterval(f, t) {
var diffDays = (new Date(t + 'T00:00:00Z') - new Date(f + 'T00:00:00Z')) / 86400000;
return diffDays <= 30 ? 'hourly' : 'daily';
}
function dateToDays(ds) {
var t = ds.length > 10 ? new Date(ds.replace(' ', 'T') + ':00Z').getTime() : new Date(ds + 'T00:00:00Z').getTime();
return (t - GENESIS) / 86400000;
}
function calcPowerLaw(labels) {
var support = [], nearSup = [], fair = [], resist = [];
labels.forEach(function(ds) {
var days = dateToDays(ds);
if (days <= 0) { support.push(null); nearSup.push(null); fair.push(null); resist.push(null); return; }
var ld = Math.log10(days);
support.push(Math.pow(10, -17.51 + 5.82 * ld));
nearSup.push(Math.pow(10, -17.35 + 5.82 * ld));
fair.push(Math.pow(10, -17.01 + 5.82 * ld));
resist.push(Math.pow(10, -16.51 + 5.82 * ld));
});
return { support: support, nearSup: nearSup, fair: fair, resist: resist };
}
function calcPowerLawXY(labels) {
var support = [], nearSup = [], fair = [], resist = [];
labels.forEach(function(ds) {
var days = dateToDays(ds);
if (days <= 0) return;
var ld = Math.log10(days);
support.push({ x: days, y: Math.pow(10, -17.51 + 5.82 * ld) });
nearSup.push({ x: days, y: Math.pow(10, -17.35 + 5.82 * ld) });
fair.push({ x: days, y: Math.pow(10, -17.01 + 5.82 * ld) });
resist.push({ x: days, y: Math.pow(10, -16.51 + 5.82 * ld) });
});
return { support: support, nearSup: nearSup, fair: fair, resist: resist };
}
function extendLabels(labels, frac) {
var n = labels.length; if (n < 2) return labels;
var extra = Math.ceil(n * frac);
var isHourly = labels[0].length > 10;
var step = isHourly ? 3600000 : 86400000;
var lastStr = isHourly ? labels[n - 1].replace(' ', 'T') + ':00Z' : labels[n - 1] + 'T00:00:00Z';
var last = new Date(lastStr);
var ext = labels.slice();
for (var i = 1; i <= extra; i++) {
var d = new Date(last.getTime() + i * step);
ext.push(isHourly ? d.toISOString().slice(0, 13).replace('T', ' ') + ':00' : d.toISOString().slice(0, 10));
}
return ext;
}
function getChartOpts() {
if (showLL) return getLogLogOpts();
return {
responsive: true,
interaction: { mode: 'index', intersect: false },
plugins: {
legend: { labels: { color: '#ccc', font: { size: window.innerWidth < 600 ? 11 : 14 }, boxWidth: window.innerWidth < 600 ? 14 : 40 } },
tooltip: {
backgroundColor: '#1e1e3a', titleColor: '#f7931a', bodyColor: '#e0e0e0',
borderColor: '#f7931a', borderWidth: 1, padding: 12,
callbacks: {
label: function(c) {
if (c.dataset.yAxisID === 'y1') return ' Vol: $' + Number(c.raw).toLocaleString(undefined, { maximumFractionDigits: 0 });
if (c.raw === null) return null;
return ' ' + c.dataset.label + ': $' + Number(c.raw).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
},
labelTextColor: function(c) { return c.dataset.borderColor || '#e0e0e0'; }
}
}
},
scales: {
x: { ticks: { color: '#888', maxTicksLimit: 12, font: { size: 11 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
y: {
type: showLog ? 'logarithmic' : 'linear', position: 'left',
ticks: { color: '#888', font: { size: 11 }, callback: function(v) { return '$' + v.toLocaleString(); } },
grid: { color: 'rgba(255,255,255,0.05)' }
},
y1: {
position: 'right',
ticks: {
color: '#555', font: { size: 10 },
callback: function(v) {
if (v >= 1e9) return '$' + Math.round(v / 1e9) + 'B';
if (v >= 1e6) return '$' + Math.round(v / 1e6) + 'M';
return '$' + v.toLocaleString();
}
},
grid: { drawOnChartArea: false }
}
}
};
}
function getLogLogOpts() {
return {
responsive: true,
interaction: { mode: 'x', intersect: false },
plugins: {
legend: { labels: { color: '#ccc', font: { size: window.innerWidth < 600 ? 11 : 14 }, boxWidth: window.innerWidth < 600 ? 14 : 40 } },
tooltip: {
backgroundColor: '#1e1e3a', titleColor: '#f7931a', bodyColor: '#e0e0e0',
borderColor: '#f7931a', borderWidth: 1, padding: 12,
filter: function(item, idx, items) { return items.findIndex(function(i) { return i.datasetIndex === item.datasetIndex; }) === idx; },
callbacks: {
title: function(items) {
if (!items.length) return '';
var days = items[0].raw.x;
var date = new Date(GENESIS + days * 86400000).toISOString().slice(0, 10);
return date + ' (day ' + Math.round(days) + ')';
},
label: function(c) {
if (c.raw === null || c.raw.y === undefined) return null;
return ' ' + c.dataset.label + ': $' + Number(c.raw.y).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
},
labelTextColor: function(c) { return c.dataset.borderColor || '#e0e0e0'; }
}
}
},
scales: {
x: {
type: 'logarithmic', position: 'bottom',
title: { display: true, text: 'Days since genesis (Jan 3, 2009)', color: '#888', font: { size: 12 } },
ticks: { color: '#888', font: { size: 11 }, callback: function(v) { return v.toLocaleString(); } },
grid: { color: 'rgba(255,255,255,0.05)' }
},
y: {
type: 'logarithmic', position: 'left',
title: { display: true, text: 'Price (USD)', color: '#888', font: { size: 12 } },
ticks: {
color: '#888', font: { size: 11 },
callback: function(v) { if (v >= 1000) return '$' + Math.round(v).toLocaleString(); return '$' + v; }
},
grid: { color: 'rgba(255,255,255,0.05)' }
}
}
};
}
function renderChart(labels, data, vols) {
curLabels = labels; curData = data; curVols = vols;
if (priceChart) priceChart.destroy();
var ctx = document.getElementById('priceChart').getContext('2d');
if (showLL) { renderLogLog(ctx, labels, data); return; }
var chartLabels = labels, chartData = data, chartVols = vols;
if (showPL) {
chartLabels = extendLabels(labels, 0.2);
var pad = chartLabels.length - labels.length;
chartData = data.concat(Array(pad).fill(null));
chartVols = vols ? vols.concat(Array(pad).fill(null)) : vols;
}
var datasets = [{
label: 'BTC Price', data: chartData, type: 'line', yAxisID: 'y',
borderColor: '#f7931a', backgroundColor: 'rgba(247,147,26,0.08)',
borderWidth: 2, fill: true, tension: 0.2, pointRadius: 0, pointHitRadius: 10,
pointHoverRadius: 5, pointHoverBackgroundColor: '#f7931a', order: 1
}];
if (chartVols && chartVols.length > 0) {
datasets.push({
label: 'Volume', data: chartVols, type: 'bar', yAxisID: 'y1',
backgroundColor: 'rgba(78,186,234,0.35)', borderColor: 'rgba(78,186,234,0.5)',
borderWidth: 1, order: 0
});
}
if (showPL) {
var pl = calcPowerLaw(chartLabels);
datasets.push({ label: 'PL Support', data: pl.support, type: 'line', yAxisID: 'y', borderColor: '#2ecc71', borderWidth: 1.5, borderDash: [6, 4], pointRadius: 0, fill: false, tension: 0.4, order: 0 });
datasets.push({ label: 'PL Near Support', data: pl.nearSup, type: 'line', yAxisID: 'y', borderColor: '#82e0aa', borderWidth: 1.5, borderDash: [3, 3], pointRadius: 0, fill: false, tension: 0.4, order: 0 });
datasets.push({ label: 'PL Fair Value', data: pl.fair, type: 'line', yAxisID: 'y', borderColor: 'rgba(255,255,255,0.6)', borderWidth: 2, pointRadius: 0, fill: false, tension: 0.4, order: 0 });
datasets.push({ label: 'PL Resistance', data: pl.resist, type: 'line', yAxisID: 'y', borderColor: '#e74c3c', borderWidth: 1.5, borderDash: [6, 4], pointRadius: 0, fill: false, tension: 0.4, order: 0 });
}
priceChart = new Chart(ctx, { type: 'line', data: { labels: chartLabels, datasets: datasets }, options: getChartOpts() });
}
function renderLogLog(ctx, labels, data) {
var priceXY = [];
labels.forEach(function(ds, i) {
var days = dateToDays(ds); if (days > 0) priceXY.push({ x: days, y: data[i] });
});
var datasets = [{
label: 'BTC Price', data: priceXY, type: 'scatter',
showLine: true, tension: 0,
borderColor: '#f7931a', backgroundColor: 'rgba(247,147,26,0.08)',
borderWidth: 2, fill: true,
pointRadius: 0, pointHitRadius: 10, order: 1
}];
if (showPL) {
var extLabels = extendLabels(labels, 0.2);
var pl = calcPowerLawXY(extLabels);
datasets.push({ label: 'PL Support', data: pl.support, type: 'line', borderColor: '#2ecc71', borderWidth: 1.5, borderDash: [6, 4], pointRadius: 0, fill: false, tension: 0, order: 0 });
datasets.push({ label: 'PL Near Support', data: pl.nearSup, type: 'line', borderColor: '#82e0aa', borderWidth: 1.5, borderDash: [3, 3], pointRadius: 0, fill: false, tension: 0, order: 0 });
datasets.push({ label: 'PL Fair Value', data: pl.fair, type: 'line', borderColor: 'rgba(255,255,255,0.6)', borderWidth: 2, pointRadius: 0, fill: false, tension: 0, order: 0 });
datasets.push({ label: 'PL Resistance', data: pl.resist, type: 'line', borderColor: '#e74c3c', borderWidth: 1.5, borderDash: [6, 4], pointRadius: 0, fill: false, tension: 0, order: 0 });
}
priceChart = new Chart(ctx, { type: 'scatter', data: { datasets: datasets }, options: getLogLogOpts() });
}
function togglePowerLaw() { showPL = !showPL; document.getElementById('plBtn').classList.toggle('active'); renderChart(curLabels, curData, curVols); }
function toggleLog() { showLog = !showLog; document.getElementById('logBtn').classList.toggle('active'); renderChart(curLabels, curData, curVols); }
function toggleLogLog() { showLL = !showLL; document.getElementById('llBtn').classList.toggle('active'); renderChart(curLabels, curData, curVols); }
function fmt(n) { return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
function fmtVol(n) { return Math.round(n).toLocaleString(); }
function updateStats(daily) {
var prices = daily.map(function(d) { return d[1]; });
var vols = daily.map(function(d) { return d[2] || 0; });
var hi = Math.max.apply(null, prices), lo = Math.min.apply(null, prices);
var avg = prices.reduce(function(a, b) { return a + b; }, 0) / prices.length;
var totalVol = vols.reduce(function(a, b) { return a + b; }, 0);
var avgVol = totalVol / vols.length;
var chg = (prices[prices.length - 1] - prices[0]) / prices[0] * 100;
var cls = chg >= 0 ? 'positive' : 'negative';
var unit = curGranularity === 'hourly' ? 'hours' : 'days';
var volLabel = curGranularity === 'hourly' ? 'Avg Hourly Vol' : 'Avg Daily Vol';
document.getElementById('periodHeader').innerHTML =
'Period: ' + daily[0][0] + ' → ' + daily[daily.length - 1][0] +
' <span class=\'day-count\'>(' + daily.length + ' ' + unit + ')</span>';
document.getElementById('statsGrid').innerHTML =
sc('High', '$' + fmt(hi), '') + sc('Low', '$' + fmt(lo), '') +
sc('Average', '$' + fmt(avg), '') + sc('Change', (chg >= 0 ? '+' : '') + chg.toFixed(2) + '%', cls) +
sc(volLabel, '$' + fmtVol(avgVol), '') + sc('Total Vol', '$' + fmtVol(totalVol), '');
}
function sc(l, v, c) {
return '<div class=\'stat-card\'><div class=\'stat-label\'>' + l + '</div><div class=\'stat-value ' + c + '\'>' + v + '</div></div>';
}
var curDaily = [];
function updateTable(daily) {
curDaily = daily;
renderTable();
}
function renderTable() {
var rows = curDaily.slice();
if (!tableSortAsc) rows.reverse();
var html = ''; var prev = null;
// Change % is always relative to the chronologically previous day
var chronological = tableSortAsc ? rows : rows.slice().reverse();
var changeMap = {};
var cprev = null;
chronological.forEach(function(d) {
if (cprev !== null) { var pct = (d[1] - cprev) / cprev * 100; changeMap[d[0]] = pct; }
cprev = d[1];
});
rows.forEach(function(d) {
var date = d[0], price = d[1], vol = d[2] || 0, ch = '', cls = '';
if (changeMap[date] !== undefined) { var pct = changeMap[date]; cls = pct >= 0 ? 'positive' : 'negative'; ch = (pct >= 0 ? '+' : '') + pct.toFixed(2) + '%'; }
html += '<tr><td>' + date + '</td><td class=\'price-cell\'>$' + fmt(price) + '</td><td class=\'vol-cell\'>$' + fmtVol(vol) + '</td><td class=\'' + cls + '\'>' + ch + '</td></tr>';
});
document.getElementById('tableBody').innerHTML = html;
document.getElementById('sortArrow').innerHTML = tableSortAsc ? '▲' : '▼';
}
function toggleDateSort() {
tableSortAsc = !tableSortAsc;
renderTable();
}
function downsample(prices, volumes) {
var hourly = curGranularity === 'hourly';
var byKey = {};
prices.forEach(function(p) {
var dt = new Date(p[0]);
var key = hourly ? dt.toISOString().slice(0, 13).replace('T', ' ') + ':00' : dt.toISOString().slice(0, 10);
if (!byKey[key]) byKey[key] = { price: p[1], vol: 0 };
});
if (volumes) volumes.forEach(function(v) {
var dt = new Date(v[0]);
var key = hourly ? dt.toISOString().slice(0, 13).replace('T', ' ') + ':00' : dt.toISOString().slice(0, 10);
if (byKey[key]) byKey[key].vol = v[1];
});
return Object.keys(byKey).sort().map(function(k) { return [k, byKey[k].price, byKey[k].vol]; });
}
function showDaily(daily) {
document.getElementById('tableHeader').textContent = curGranularity === 'hourly' ? 'Hourly Prices' : 'Daily Prices';
renderChart(daily.map(function(d) { return d[0]; }), daily.map(function(d) { return d[1]; }), daily.map(function(d) { return d[2] || 0; }));
updateStats(daily);
updateTable(daily);
}
function fetchBinanceChunks(fromMs, toMs, acc) {
if (fromMs >= toMs) {
if (acc.length === 0) { document.getElementById('status').textContent = 'No data from Binance either'; document.getElementById('fetchBtn').disabled = false; return; }
showDaily(acc); document.getElementById('status').textContent = '(via Binance)'; document.getElementById('fetchBtn').disabled = false; return;
}
var hourly = curGranularity === 'hourly';
var interval = hourly ? '1h' : '1d';
fetch('https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=' + interval + '&startTime=' + fromMs + '&endTime=' + toMs + '&limit=1000')
.then(function(r) { return r.json(); })
.then(function(klines) {
if (!Array.isArray(klines) || klines.length === 0) {
if (acc.length === 0) { document.getElementById('status').textContent = 'No data from Binance either'; document.getElementById('fetchBtn').disabled = false; return; }
showDaily(acc); document.getElementById('status').textContent = '(via Binance)'; document.getElementById('fetchBtn').disabled = false; return;
}
var chunk = klines.map(function(k) {
var dt = new Date(k[0]);
var label = hourly ? dt.toISOString().slice(0, 13).replace('T', ' ') + ':00' : dt.toISOString().slice(0, 10);
return [label, parseFloat(k[4]), parseFloat(k[7])];
});
var all = acc.concat(chunk);
var unit = hourly ? 'hours' : 'days';
var step = hourly ? 3600000 : 86400000;
if (klines.length < 1000) { showDaily(all); document.getElementById('status').textContent = '(via Binance)'; document.getElementById('fetchBtn').disabled = false; }
else { var lastTs = klines[klines.length - 1][0] + step; document.getElementById('status').textContent = 'Fetching from Binance (' + all.length + ' ' + unit + ')...'; fetchBinanceChunks(lastTs, toMs, all); }
})
.catch(function(e) { document.getElementById('status').textContent = 'Both APIs failed: ' + e; document.getElementById('fetchBtn').disabled = false; });
}
function fetchBinance(fromMs, toMs) {
document.getElementById('status').textContent = 'CoinGecko failed, trying Binance...';
fetchBinanceChunks(fromMs, toMs, []);
}
// Bitstamp OHLC: step=86400, limit=1000.
// API returns last `limit` entries ending at `end` (inclusive), ignoring `start`.
// Setting end = fromSec + 999*step makes the batch start exactly at fromSec.
function fetchBitstampChunks(fromSec, toSec, acc, onDone) {
if (fromSec >= toSec) { onDone(acc); return; }
var batchEnd = fromSec + 999 * 86400;
fetch('https://www.bitstamp.net/api/v2/ohlc/btcusd/?step=86400&limit=1000&start=' + fromSec + '&end=' + batchEnd)
.then(function(r) { return r.json(); })
.then(function(j) {
var ohlc = j.data && j.data.ohlc ? j.data.ohlc : [];
if (ohlc.length === 0) { onDone(acc); return; }
var chunk = ohlc
.filter(function(c) { return parseInt(c.timestamp) < toSec; })
.map(function(c) {
var date = new Date(parseInt(c.timestamp) * 1000).toISOString().slice(0, 10);
var price = parseFloat(c.close);
var vol = parseFloat(c.volume) * price; // volume is in BTC → convert to USD
return [date, price, vol];
});
var all = acc.concat(chunk);
document.getElementById('status').textContent = 'Fetching from Bitstamp (' + all.length + ' days)...';
var nextFrom = parseInt(ohlc[ohlc.length - 1].timestamp) + 86400;
if (nextFrom >= toSec) { onDone(all); }
else { fetchBitstampChunks(nextFrom, toSec, all, onDone); }
})
.catch(function() { onDone(acc); });
}
// Smart fallback: Bitstamp for pre-2017-08-17, Binance for the rest.
function fetchWithFallback(fromMs, toMs) {
var fromSec = Math.floor(fromMs / 1000);
var cutoffSec = Math.floor(BINANCE_CUTOFF_MS / 1000);
if (fromSec >= cutoffSec) {
document.getElementById('status').textContent = 'CoinGecko failed, trying Binance...';
fetchBinanceChunks(fromMs, toMs, []);
return;
}
// Need Bitstamp for the pre-cutoff portion
document.getElementById('status').textContent = 'CoinGecko failed, trying Bitstamp...';
var bitstampToSec = Math.min(Math.floor(toMs / 1000), cutoffSec);
fetchBitstampChunks(fromSec, bitstampToSec, [], function(bsData) {
if (toMs <= BINANCE_CUTOFF_MS) {
// Pure Bitstamp range
if (bsData.length === 0) {
document.getElementById('status').textContent = 'No data available';
document.getElementById('fetchBtn').disabled = false;
} else {
showDaily(bsData);
document.getElementById('status').textContent = '(via Bitstamp)';
document.getElementById('fetchBtn').disabled = false;
}
} else {
// Mixed: Bitstamp pre-2017 + Binance post-2017
document.getElementById('status').textContent = 'Fetching from Binance...';
fetchBinanceChunks(BINANCE_CUTOFF_MS, toMs, bsData);
}
});
}
function fetchRange() {
var f = document.getElementById('fromDate').value;
var t = document.getElementById('toDate').value;
if (!f || !t) { document.getElementById('status').textContent = 'Pick both dates'; return; }
var from = Math.floor(new Date(f + 'T00:00:00Z').getTime() / 1000);
var to = Math.floor(new Date(t + 'T00:00:00Z').getTime() / 1000) + 86400;
if (from >= to) { document.getElementById('status').textContent = 'From must be before To'; return; }
curGranularity = getInterval(f, t);
document.getElementById('status').textContent = 'Fetching...';
document.getElementById('fetchBtn').disabled = true;
var fromMs = from * 1000, toMs = to * 1000;
fetch('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&from=' + from + '&to=' + to)
.then(function(r) { if (!r.ok) throw new Error(r.status); return r.json(); })
.then(function(j) {
if (j.error) { fetchWithFallback(fromMs, toMs); return; }
var daily = downsample(j.prices, j.total_volumes);
if (daily.length === 0) { fetchWithFallback(fromMs, toMs); return; }
showDaily(daily); document.getElementById('status').textContent = '';
document.getElementById('fetchBtn').disabled = false;
})
.catch(function(e) { fetchWithFallback(fromMs, toMs); });
}
function clearRangeActive() { document.querySelectorAll('.range-btn').forEach(function(b) { b.classList.remove('active'); }); }
function setPreset(days, btn) {
clearRangeActive(); btn.classList.add('active');
var to = new Date(); var from;
if (days === 0) { from = new Date('2010-07-17'); } else { from = new Date(to); from.setDate(from.getDate() - days); }
document.getElementById('fromDate').value = from.toISOString().slice(0, 10);
document.getElementById('toDate').value = to.toISOString().slice(0, 10);
fetchRange();
}
function fmtChipPrice(n) {
return Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function fmtChipVol(n) {
return Math.round(Number(n)).toLocaleString();
}
function setChip(id, value) {
var el = document.getElementById(id);
el.textContent = value;
el.classList.remove('loading-pulse');
}
function fetchCurrentPrice() {
fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd,eur,gbp&include_24hr_vol=true')
.then(function(r) { if (!r.ok) throw new Error(r.status); return r.json(); })
.then(function(j) {
var b = j.bitcoin;
setChip('chipUsd', '$' + fmtChipPrice(b.usd));
setChip('chipEur', '\u20AC' + fmtChipPrice(b.eur));
setChip('chipGbp', '\u00A3' + fmtChipPrice(b.gbp));
setChip('chipVol', '$' + fmtChipVol(b.usd_24h_vol));
})
.catch(function() {
// Fallback: fetch from Binance
Promise.all([
fetch('https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT').then(function(r) { return r.json(); }),
fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCEUR').then(function(r) { return r.json(); }),
fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCGBP').then(function(r) { return r.json(); })
]).then(function(results) {
setChip('chipUsd', '$' + fmtChipPrice(results[0].lastPrice));
setChip('chipEur', '\u20AC' + fmtChipPrice(results[1].price));
setChip('chipGbp', '\u00A3' + fmtChipPrice(results[2].price));
setChip('chipVol', '$' + fmtChipVol(results[0].quoteVolume));
}).catch(function() {
setChip('chipUsd', '--');
setChip('chipEur', '--');
setChip('chipGbp', '--');
setChip('chipVol', '--');
});
});
}
function init() {
// Set default date range: last 90 days
var to = new Date();
var from = new Date(to);
from.setDate(from.getDate() - 90);
document.getElementById('fromDate').value = from.toISOString().slice(0, 10);
document.getElementById('toDate').value = to.toISOString().slice(0, 10);
// Fetch current price for chips
fetchCurrentPrice();
// Fetch historical data and render chart
fetchRange();
}
init();
</script>
</body>
</html>