-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
890 lines (821 loc) · 35.8 KB
/
index.html
File metadata and controls
890 lines (821 loc) · 35.8 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Brownian Motion OHLCV Chart</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet"
/>
<script src="./lightweight-charts.standalone.production.js"></script>
<style>
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', Arial, sans-serif;
margin: 0;
padding: 15px;
background-color: #222;
color: white;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 100%;
max-width: 1200px;
display: flex;
flex-direction: column;
gap: 20px;
justify-content: center;
align-items: center;
}
#controls {
background-color: #333;
padding: 20px;
border-radius: 8px;
width: 100%;
max-width: 800px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 15px;
align-items: start;
}
.control-item {
display: flex;
flex-direction: column;
gap: 8px;
}
.control-item.full-width {
grid-column: 1 / -1;
}
.control-item.auto-generate {
flex-direction: row;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
label {
font-size: 14px;
color: #ddd;
}
input, select {
padding: 8px;
border-radius: 4px;
border: none;
background-color: #444;
color: white;
width: 100%;
}
.auto-generate-group {
display: flex;
align-items: center;
gap: 10px;
}
.auto-generate-group input[type="checkbox"] {
max-width: 20px;
width: 20px;
margin: 0;
}
.auto-generate-group input[type="number"] {
max-width: 80px;
width: 100%;
}
.preloaded-data-group {
display: flex;
align-items: center;
gap: 10px;
}
.preloaded-data-group input[type="checkbox"] {
max-width: 20px;
width: 20px;
margin: 0;
}
.preloaded-data-group textarea {
width: 100%;
background-color: #444;
color: white;
}
.preloaded-data-group textarea::placeholder {
color: #d1d1d1;
}
.button-group {
display: flex;
gap: 15px;
justify-content: center;
flex-wrap: wrap;
}
button {
padding: 10px 25px;
border-radius: 4px;
border: none;
cursor: pointer;
transition: background-color 0.2s;
background-color: #4CAF50;
color: white;
}
#regenerateBtn {
background-color: #4CAF50;
}
#regenerateBtn:hover {
background-color: #45a049;
}
#oneStepBtn {
background-color: #504CAF;
}
#oneStepBtn:hover {
background-color: #4945a0;
}
#chart-container {
width: 100%;
max-width: 1000px;
max-height: 600px;
overflow: hidden;
}
#chart {
width: 100%;
border: 1px solid #444;
border-radius: 4px;
}
#error {
color: #ff4444;
text-align: center;
font-size: 14px;
padding: 5px;
}
input[type=checkbox]
{
-ms-transform: scale(1.3); /* IE */
-moz-transform: scale(1.3); /* FF */
-webkit-transform: scale(1.3); /* Safari and Chrome */
-o-transform: scale(1.3); /* Opera */
transform: scale(1.3);
}
@media (max-width: 600px) {
#controls {
grid-template-columns: 1fr;
padding: 15px;
}
.button-group {
flex-direction: column;
align-items: center;
}
button {
width: 100%;
max-width: 250px;
}
.control-item.auto-generate {
flex-direction: column;
align-items: flex-start;
}
}
@media (max-width: 400px) {
body {
padding: 10px;
}
.control-item {
gap: 5px;
}
button {
padding: 8px 20px;
}
.preloaded-data-group {
display: block;
text-align: center;
border: 3px solid #444;
border-radius: 5px;
padding: 3px;
}
.preloaded-data-group * {
margin: 3px;
}
}
</style>
</head>
<body>
<div class="container">
<div id="controls">
<div class="control-item">
<label for="startDate">Start Date:</label>
<input type="date" id="startDate" value="2021-05-25">
</div>
<div class="control-item">
<label for="timeframe">Timeframe:</label>
<select id="timeframe">
<option value="1m" selected>1 Minute</option>
<option value="3m">3 Minutes</option>
<option value="5m">5 Minutes</option>
<option value="15m">15 Minutes</option>
<option value="30m">30 Minutes</option>
<option value="1h">1 Hour</option>
<option value="2h">2 Hours</option>
<option value="4h">4 Hours</option>
<option value="6h">6 Hours</option>
<option value="8h">8 Hours</option>
<option value="12h">12 Hours</option>
<option value="1d">1 Day</option>
</select>
</div>
<div class="control-item">
<label for="ohlcShift">Initial Price (ohlcShift):</label>
<input type="number" id="ohlcShift" value="10000" min="1" step="1">
</div>
<div class="control-item">
<label for="numCandles">Number of Candles:</label>
<input type="number" id="numCandles" value="200" min="1" max="1000" step="1">
</div>
<div class="control-item">
<label for="price-percentage">Price % Change:</label>
<input type="number" id="price-percentage" value="0.5" min="0" step="0.1">
</div>
<div class="control-item">
<label for="volume-percentage">Volume % Change:</label>
<input type="number" id="volume-percentage" value="10" min="0" step="0.1">
</div>
<div class="control-item auto-generate">
<label for="autoGenerate">Auto-generate every N seconds:</label>
<div class="auto-generate-group">
<input type="checkbox" id="autoGenerate">
<input type="number" id="intervalSeconds" value="0.1" step="0.1">
</div>
</div>
<div class="control-item full-width">
<label for="preloadedDataToggle">Preloaded data:</label>
<div class="preloaded-data-group">
<input type="checkbox" id="preloadedDataToggle" checked>
<textarea id="preloadedDataText" rows="5" placeholder="timestamp;open;high;low;close;volume"></textarea>
<button id="fileBtn">File...</button>
<button id="binanceBtn">Binance...</button>
<!-- <button id="clearBtn">Clear</button> -->
</div>
</div>
<div class="control-item full-width">
<div class="button-group">
<button id="regenerateBtn">Regenerate Chart</button>
<button id="oneStepBtn">One Step</button>
</div>
</div>
</div>
<div id="error"></div>
<div id="chart-container">
<div id="chart"></div>
</div>
</div>
<script>
// Function to generate a standard normal random variable using Box-Muller transform
function normalRandom() {
let u1 = Math.random();
let u2 = Math.random();
let z0 = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
return z0;
}
// Function to convert timeframe string (e.g., '1m', '5h') to seconds
function convertTimeframeToSeconds(timeframe) {
let match = timeframe.match(/^(\d+)([mhd])$/);
if (!match) throw new Error('Invalid timeframe format');
let value = parseInt(match[1]);
let unit = match[2];
switch (unit) {
case 'm': return value * 60;
case 'h': return value * 3600;
case 'd': return value * 86400;
default: throw new Error('Unsupported timeframe unit');
}
}
// Function to shuffle array
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Class to generate OHLCV data points based on Brownian motion
class OHLCVGenerator {
constructor(dateFromTimestamp, timeframe, ohlcShift, oneCandlePricePercentageApprox, oneCandleVolumePercentageApprox, initOhlcv) {
this.timestamp = dateFromTimestamp;
this.timeframeSeconds = convertTimeframeToSeconds(timeframe);
this.ohlcShift = ohlcShift;
this.volumeShift = 0;
this.oneCandlePricePercentageApprox = oneCandlePricePercentageApprox;
this.oneCandleVolumePercentageApprox = oneCandleVolumePercentageApprox;
this.eventsPerCandle = 100;
this.oneEventPricePercentage = (oneCandlePricePercentageApprox / 100) / this.eventsPerCandle;
this.oneEventVolumePercentage = (oneCandleVolumePercentageApprox / 100) / this.eventsPerCandle;
this.ohlcValues = [];
this.volumeValues = [];
this.initOhlcv = [];
if (initOhlcv.length > 1) {
initOhlcv = initOhlcv.slice().sort((a, b) => a[0] - b[0]); // Sort by timestamp
const timeframeMilliseconds = this.timeframeSeconds * 1000;
let tmpOhlcv = [];
for (const ohlcv of initOhlcv) {
const ts = ohlcv[0], open = ohlcv[1], high = ohlcv[2], low = ohlcv[3], close = ohlcv[4], volume = ohlcv[5];
if (tmpOhlcv.length > 0 && tmpOhlcv[tmpOhlcv.length - 1].timestamp >= ts) {
continue; // Remove duplicates
}
tmpOhlcv.push({
timestamp: ts,
open: open,
high: high,
low: low,
close: close,
volume: volume
});
}
initOhlcv = tmpOhlcv;
tmpOhlcv = [];
for (let i = 0; i < initOhlcv.length;) {
let currentOhlcv = initOhlcv[i];
let currentOhlcvTimestamp = Math.floor(currentOhlcv.timestamp / timeframeMilliseconds) * timeframeMilliseconds;
let ohlcv = {
timestamp: currentOhlcvTimestamp,
open: currentOhlcv.open,
high: currentOhlcv.high,
low: currentOhlcv.low,
close: currentOhlcv.close,
volume: currentOhlcv.volume
};
let k = 1;
for (let j = i + 1; j < initOhlcv.length; ++j) {
let nextOhlcv = initOhlcv[j];
let nextOhlcvTimestamp = Math.floor(nextOhlcv.timestamp / timeframeMilliseconds) * timeframeMilliseconds;
if (nextOhlcvTimestamp - currentOhlcvTimestamp >= timeframeMilliseconds) {
break;
}
ohlcv.close = nextOhlcv.close;
ohlcv.high = Math.max(ohlcv.high, nextOhlcv.high);
ohlcv.low = Math.min(ohlcv.low, nextOhlcv.low);
ohlcv.volume += nextOhlcv.volume;
k += 1;
}
tmpOhlcv.push(ohlcv);
i += k;
}
for (let x of tmpOhlcv) {
x.volume *= (x.high + x.low) / 2;
}
initOhlcv = tmpOhlcv;
let newOhlcv = [], ohlcValues = [], volumeValues = [], ohlcShift = 0, volumeShift = 0;
for (let i = 0; i < initOhlcv.length; ++i) {
let currentOhlcv = initOhlcv[i];
let nextOhlcv = i + 1 < initOhlcv.length ? initOhlcv[i + 1] : currentOhlcv;
if (nextOhlcv == currentOhlcv && initOhlcv.length > 1) {
const tfMs = (initOhlcv[i].timestamp - initOhlcv[i - 1].timestamp);
nextOhlcv = {
timestamp: (Math.floor(currentOhlcv.timestamp / tfMs) + 1) * tfMs,
open: currentOhlcv.open,
high: currentOhlcv.high,
low: currentOhlcv.low,
close: currentOhlcv.close,
volume: currentOhlcv.volume
};
}
let k = 0;
for (let ts = currentOhlcv.timestamp; ts < nextOhlcv.timestamp; ts += timeframeMilliseconds) {
k += 1;
}
if (k === 0) {
k = 1;
}
if (k === 1) {
newOhlcv.push(currentOhlcv);
continue;
}
const [_, __, ohlcValuesList, volumeValuesList] = this.generateValuesForOHLCV(currentOhlcv, this.eventsPerCandle * k);
for (let ts = currentOhlcv.timestamp, i = 0; i < ohlcValuesList.length; ts += timeframeMilliseconds, i += this.eventsPerCandle) {
ohlcValues = ohlcValuesList.slice(i, i + this.eventsPerCandle);
volumeValues = volumeValuesList.slice(i, i + this.eventsPerCandle);
let open = ohlcValues[0];
let high = Math.max(...ohlcValues);
let low = Math.min(...ohlcValues);
let close = ohlcValues[ohlcValues.length - 1];
let volume = volumeValues.reduce((a, b) => a + b, 0);
let ohlcv = {
timestamp: ts,
open: open,
high: high,
low: low,
close: close,
volume: volume
};
ohlcShift = ohlcValues[ohlcValues.length - 1];
volumeShift = volumeValues[volumeValues.length - 1];
newOhlcv.push(ohlcv);
}
}
const lastOhlcv = newOhlcv[newOhlcv.length - 1];
const lastTimestamp = lastOhlcv.timestamp;
if (ohlcValues.length === 0 || volumeValues.length === 0) {
[ohlcShift, volumeShift, ohlcValues, volumeValues] = this.generateValuesForOHLCV(lastOhlcv, this.eventsPerCandle);
}
this.ohlcShift = ohlcShift;
this.volumeShift = volumeShift;
this.ohlcValues = ohlcValues.slice(-this.eventsPerCandle);
this.volumeValues = volumeValues.slice(-this.eventsPerCandle);
this.initOhlcv = newOhlcv;
this.timestamp = (Math.floor(lastTimestamp / timeframeMilliseconds) + 1) * timeframeMilliseconds;
}
}
generateValuesForOHLCV(lastOhlcv, eventsPerCandle) {
let volumeShift = lastOhlcv.volume / eventsPerCandle, volumeShiftMax = volumeShift, volumeValues = [];
let ohlcShift = lastOhlcv.open, ohlcValues = [];
for (let i = 0; i < eventsPerCandle; ++i) {
if (i === 0) {
ohlcValues.push(ohlcShift);
volumeValues.push(volumeShift);
continue;
}
volumeShift = volumeValues[volumeValues.length - 1];
let value = volumeShift * this.oneEventVolumePercentage * normalRandom();
volumeValues.push(volumeShift + value);
if (i === eventsPerCandle - 1) {
ohlcValues.push(lastOhlcv.close);
continue;
}
ohlcShift = ohlcValues[ohlcValues.length - 1];
value = ohlcShift * this.oneEventPricePercentage * normalRandom();
ohlcValues.push(ohlcShift + value);
}
let ohlcHigh = Math.max(...ohlcValues.slice(1, -1)), ohlcLow = Math.min(...ohlcValues.slice(1, -1));
let volumeSum = volumeValues.reduce((a, b) => a + b, 0);
for (let i = 0; i < ohlcValues.length; ++i) {
volumeValues[i] = volumeValues[i] / volumeSum * lastOhlcv.volume;
if (i === 0 || i === ohlcValues.length - 1) {
continue;
}
ohlcValues[i] = (ohlcValues[i] - ohlcLow) / (ohlcHigh - ohlcLow) * (lastOhlcv.high - lastOhlcv.low) + lastOhlcv.low;
}
let highIndex = 0, highDx = null;
let lowIndex = 0, lowDx = null;
for (let i = 1; i < ohlcValues.length - 1; ++i) {
if (highDx == null || Math.abs(ohlcValues[i] - lastOhlcv.high) < highDx) {
highIndex = i;
highDx = Math.abs(ohlcValues[i] - lastOhlcv.high);
}
if (lowDx == null || Math.abs(ohlcValues[i] - lastOhlcv.low) < lowDx) {
lowIndex = i;
lowDx = Math.abs(ohlcValues[i] - lastOhlcv.low);
}
}
if (highDx !== null) {
ohlcValues[highIndex] = lastOhlcv.high;
}
if (lowDx !== null) {
ohlcValues[lowIndex] = lastOhlcv.low;
}
volumeShift = volumeValues[volumeValues.length - 1];
ohlcShift = ohlcValues[ohlcValues.length - 1];
return [ohlcShift, volumeShift, ohlcValues, volumeValues];
}
first() {
return this.initOhlcv.slice();
}
next() {
for (let i = 0; i < this.eventsPerCandle; i++) {
if (this.ohlcValues.length > 0) {
this.ohlcShift = this.ohlcValues[this.ohlcValues.length - 1];
}
if (this.volumeValues.length > 0) {
this.volumeShift = this.volumeValues[this.volumeValues.length - 1];
}
else if (!this.volumeShift) {
this.volumeShift = this.ohlcShift;
}
let value = 0;
if (i !== 0) {
value = this.volumeShift * this.oneEventVolumePercentage * normalRandom();
}
this.volumeValues.push(Math.max(0, this.volumeShift + value));
value = 0;
if (i !== 0) {
value = this.ohlcShift * this.oneEventPricePercentage * normalRandom();
}
this.ohlcValues.push(this.ohlcShift + value);
}
this.ohlcValues = this.ohlcValues.slice(-this.eventsPerCandle);
this.volumeValues = this.volumeValues.slice(-this.eventsPerCandle);
let open = this.ohlcValues[0];
let high = Math.max(...this.ohlcValues);
let low = Math.min(...this.ohlcValues);
let close = this.ohlcValues[this.ohlcValues.length - 1];
let volume = this.volumeValues.reduce((a, b) => a + b, 0);
let ohlcv = {
timestamp: this.timestamp,
open: open,
high: high,
low: low,
close: close,
volume: volume
};
this.timestamp += this.timeframeSeconds * 1000;
return ohlcv;
}
}
// Chart initialization
let ohlcvGenerator = null, candleData = null, volumeData = null;
const chartContainer = document.getElementById('chart-container');
const chartElement = document.getElementById('chart');
let preloadedDataChanged = true;
const chart = LightweightCharts.createChart(chartElement, {
width: chartContainer.clientWidth,
height: Math.max(400, window.innerHeight * 0.6),
timeScale: { timeVisible: true, secondsVisible: true },
layout: {
background: { color: '#222' },
textColor: '#DDD',
},
grid: {
vertLines: { color: '#444' },
horzLines: { color: '#444' },
}
});
const candleSeries = chart.addSeries(LightweightCharts.CandlestickSeries);
const volumeSeries = chart.addSeries(LightweightCharts.HistogramSeries, {
priceFormat: {
type: 'volume',
},
priceScaleId: '',
});
candleSeries.priceScale().applyOptions({
scaleMargins: {
top: 0.05, // highest point of the series will be 5% away from the top
bottom: 0.15, // lowest point will be 15% away from the bottom
},
});
volumeSeries.priceScale().applyOptions({
// set the positioning of the volume series
scaleMargins: {
top: 0.9, // highest point of the series will be 90% away from the top
bottom: 0,
},
});
chart.applyOptions({
crosshair: {
mode: LightweightCharts.CrosshairMode.Normal,
},
color: '#2962FF',
rightPriceScale: { visible: true }
});
chart.priceScale().applyOptions({
borderColor: '#71649C',
});
chart.timeScale().applyOptions({
borderColor: '#71649C',
});
// Get the current users primary locale
const currentLocale = window.navigator.languages[0];
// Create a number format using Intl.NumberFormat
const myPriceFormatter = Intl.NumberFormat(currentLocale, {
style: 'currency',
currency: 'USD', // Currency for data points
}).format;
chart.applyOptions({
localization: {
priceFormatter: myPriceFormatter,
},
});
chart.applyOptions({
layout: {
fontFamily: "'Roboto', Arial, sans-serif",
},
});
// Function to generate and update chart data
function updateChart() {
const errorDiv = document.getElementById('error');
errorDiv.innerText = '';
try {
let initOhlcv = [];
const preloadedDataToggle = document.getElementById('preloadedDataToggle');
if (preloadedDataToggle.checked) {
const preloadedDataText = document.getElementById('preloadedDataText');
for (const line of preloadedDataText.value.split('\n')) {
const values = line.split(/[,;\t ]+/);
if (values.length < 2) {
continue;
}
let tsIndex = null;
for (let i = 0; i < values.length; ++i) {
const floatValue = parseFloat(values[i]);
if (floatValue === floatValue && floatValue >= 1000000000) {
tsIndex = i;
break;
}
}
if (tsIndex == null || tsIndex + 1 >= values.length) {
continue;
}
let timeValue = parseFloat(values[tsIndex]);
if (timeValue >= 1000000000000) {
timeValue /= 1000;
}
if (timeValue >= 1000000000000) {
timeValue /= 1000;
}
timeValue = Math.floor(timeValue * 1000); // milliseconds
const openPrice = parseFloat(values[tsIndex + 1]);
const highPrice = parseFloat(values[tsIndex + 2] || values[tsIndex + 1]);
const lowPrice = parseFloat(values[tsIndex + 3] || values[tsIndex + 1]);
const closePrice = parseFloat(values[tsIndex + 4] || values[tsIndex + 1]);
const volume = parseFloat(values[tsIndex + 5] || '0');
initOhlcv.push([timeValue, openPrice, highPrice, lowPrice, closePrice, volume]);
}
}
// Get input values
const startDate = new Date(document.getElementById('startDate').value).getTime();
if (isNaN(startDate)) throw new Error('Invalid start date');
const timeframe = document.getElementById('timeframe').value;
const ohlcShift = parseFloat(document.getElementById('ohlcShift').value);
if (isNaN(ohlcShift) || ohlcShift <= 0) throw new Error('ohlcShift must be a positive number');
const pricePercentage = parseFloat(document.getElementById('price-percentage').value);
const volumePercentage = parseFloat(document.getElementById('volume-percentage').value);
if (isNaN(pricePercentage) || pricePercentage < 0) throw new Error('Price percentage must be non-negative');
if (isNaN(volumePercentage) || volumePercentage < 0) throw new Error('Volume percentage must be non-negative');
const numCandles = parseInt(document.getElementById('numCandles').value);
if (isNaN(numCandles) || numCandles < 0 || numCandles > 5000) throw new Error('Number of candles must be between 0 and 5000');
// Generate new data
ohlcvGenerator = new OHLCVGenerator(startDate, timeframe, ohlcShift, pricePercentage, volumePercentage, initOhlcv);
let data = [...ohlcvGenerator.first()];
for (let i = 0; i < numCandles; i++) {
data.push(ohlcvGenerator.next());
}
// Prepare chart data
candleData = data.map(d => ({
time: Math.floor(d.timestamp / 1000),
open: d.open,
high: d.high,
low: d.low,
close: d.close
}));
volumeData = data.map(d => ({
time: Math.floor(d.timestamp / 1000),
value: d.volume,
color: d.close > d.open ? 'rgba(0, 150, 136, 0.8)' : 'rgba(255, 82, 82, 0.8)'
}));
// Update chart
candleSeries.setData(candleData);
volumeSeries.setData(volumeData);
if (preloadedDataChanged || !preloadedDataToggle.checked) {
chart.timeScale().fitContent();
}
preloadedDataChanged = false;
} catch (e) {
errorDiv.innerText = `Error: ${e.message}`;
console.error(e);
}
}
function generateOneMoreData() {
const errorDiv = document.getElementById('error');
try {
// Get input values
if (ohlcvGenerator == null) {
throw new Error('OHLCV generator has not been created');
}
// Generate new data
let data = [];
for (let i = 0; i < 1; i++) {
data.push(ohlcvGenerator.next());
}
// Prepare chart data
candleData = [...candleData, ...data.map(d => ({
time: Math.floor(d.timestamp / 1000),
open: d.open,
high: d.high,
low: d.low,
close: d.close
}))];
volumeData = [...volumeData, ...data.map(d => ({
time: Math.floor(d.timestamp / 1000),
value: d.volume,
color: d.close > d.open ? 'rgba(0, 150, 136, 0.8)' : 'rgba(255, 82, 82, 0.8)'
}))];
candleData = candleData.slice(-5000);
volumeData = volumeData.slice(-5000);
// Update chart
candleSeries.setData(candleData);
volumeSeries.setData(volumeData);
} catch (e) {
errorDiv.innerText = `Error: ${e.message}`;
console.error(e);
}
}
// function clearPreloadedData() {
// document.getElementById('preloadedDataText').value = '';
// }
function loadFromFile() {
const input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = event => {
const text = event.target.result.trim();
const preloadedDataText = document.getElementById('preloadedDataText');
// preloadedDataText.value = preloadedDataText.value.concat((preloadedDataText.value.length > 0 ? '\n\n' : '').concat(text));
preloadedDataText.value = text;
preloadedDataChanged = true;
};
reader.readAsText(file);
}
};
document.body.appendChild(input);
input.click();
document.body.removeChild(input);
}
function loadFromBinance() {
const preloadedDataText = document.getElementById('preloadedDataText');
const timeframe = document.getElementById('timeframe').value;
let fullSymbol = prompt('(spot|swap):symbol[:1000[:YYYY-mm-dd]]', 'spot:btcusdt');
if (!fullSymbol) {
return;
}
let ds = fullSymbol.split(':');
if (ds.length < 2) {
return;
}
let contractType = ds[0].trim();
let symbol = ds[1].trim();
let cnt = (ds[2] || '1000').trim();
let endTime = ds[3] ? new Date(ds[3]).getTime() : Date.now();
let line = '';
if (contractType == 'spot') {
line = 'https://api.binance.com/api/v3/klines?symbol=' + symbol.toUpperCase();
}
if (contractType == 'swap') {
line = 'https://fapi.binance.com/fapi/v1/continuousKlines?contracttype=PERPETUAL&pair=' + symbol.toUpperCase();
}
if (!line || !symbol) {
return;
}
line += '&interval=' + timeframe + '&endTime=' + endTime + '&limit=' + cnt;
let request = fetch(line, {
method: 'get',
credentials: 'same-origin'
}).then(async function(response) {
return response.json();
}).then((arg) => {
let inputData = [];
for (let x of arg) {
const timestamp = x[0];
const open = x[1];
const high = x[2];
const low = x[3];
const close = x[4];
const volume = x[5];
inputData.push(`${timestamp};${open};${high};${low};${close};${volume}`);
}
preloadedDataText.value = inputData.join('\n');
})
}
function resizeChart() {
const width = chartContainer.clientWidth;
const height = chartContainer.clientHeight;
chart.applyOptions({
width: width,
height: height
});
}
window.addEventListener('resize', resizeChart);
// Initial chart render
resizeChart();
updateChart();
// Add event listener for regeneration
document.getElementById('regenerateBtn').addEventListener('click', updateChart);
document.getElementById('oneStepBtn').addEventListener('click', generateOneMoreData);
// document.getElementById('clearBtn').addEventListener('click', clearPreloadedData);
document.getElementById('fileBtn').addEventListener('click', loadFromFile);
document.getElementById('binanceBtn').addEventListener('click', loadFromBinance);
document.getElementById('preloadedDataToggle').addEventListener('change', () => { preloadedDataChanged = true; });
document.getElementById('preloadedDataText').addEventListener('change', () => { preloadedDataChanged = true; });
let intervalId = null;
function startAutoGenerate() {
const intervalSeconds = parseFloat(document.getElementById('intervalSeconds').value) * 1000;
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(generateOneMoreData, intervalSeconds);
}
function stopAutoGenerate() {
if (intervalId) clearInterval(intervalId);
intervalId = null;
}
document.getElementById('autoGenerate').addEventListener('change', function() {
if (this.checked) {
startAutoGenerate();
} else {
stopAutoGenerate();
}
});
document.getElementById('intervalSeconds').addEventListener('change', function() {
if (document.getElementById('autoGenerate').checked) {
startAutoGenerate();
}
});
</script>
</body>
</html>