-
Notifications
You must be signed in to change notification settings - Fork 13
/
tse.js
1771 lines (1540 loc) · 62.2 KB
/
tse.js
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function () {
const isNode = (function(){return typeof global!=='undefined'&&this===global})();
const isBrowser = (function(){return typeof window!=='undefined'&&this===window})();
const fetch = isNode ? require('node-fetch') : isBrowser ? window.fetch : undefined;
const Decimal = isNode ? require('decimal.js') : isBrowser ? window.Decimal : undefined;
const jalaali = isNode ? require('jalaali-js') : isBrowser ? window.jalaali : undefined;
if (isBrowser) {
if (!Decimal) throw new Error('Cannot find required dependency: Decimal');
if (!localforage) throw new Error('Cannot find required dependency: localforage');
}
Decimal.set({ precision: 40, rounding: Decimal.ROUND_HALF_EVEN });
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// storage
const storage = (function () {
let instance;
if (isNode) {
const { readFileSync: read, writeFileSync: write, existsSync: exists, mkdirSync: mkdir, statSync: stat, readdirSync: readdir } = require('fs');
const { join } = require('path');
const { gzip, gunzip } = require('zlib');
let datadir;
const home = require('os').homedir();
const defaultdir = join(home, 'tse-cache');
const tracker = join(home, '.tse');
if ( exists(tracker) ) {
datadir = read(tracker, 'utf8');
try { stat(datadir).isDirectory(); } catch { datadir = defaultdir; }
} else {
datadir = defaultdir;
if ( !exists(datadir) ) mkdir(datadir, {recursive: true});
write(tracker, datadir);
}
const getItem = (key) => {
key = key.replace('tse.', '');
const dir = key.startsWith('prices.') ? join(datadir, 'prices') : datadir;
const file = join(dir, `${key}.csv`);
if ( !exists(file) ) write(file, '');
return read(file, 'utf8');
};
const setItem = (key, value) => {
key = key.replace('tse.', '');
const dir = key.startsWith('prices.') ? join(datadir, 'prices') : datadir;
write(join(dir, `${key}.csv`), value);
};
const getItemAsync = (key, zip=false) => new Promise((done, fail) => {
key = key.replace('tse.', '');
const dir = key.startsWith('prices.') ? join(datadir, 'prices') : datadir;
const file = join(dir, `${key}.csv` + (zip?'.gz':''));
if ( !exists(file) ) {
write(file, '');
done('');
return;
}
const content = read(file, zip?undefined:'utf8');
done(zip ? gunzip(content).toString() : content);
});
const setItemAsync = (key, value, zip=false) => new Promise((done, fail) => {
key = key.replace('tse.', '');
let dir = datadir;
if ( key.startsWith('prices.') ) {
dir = join(datadir, 'prices');
key = key.replace('prices.', '');
}
const file = join(dir, `${key}.csv` + (zip?'.gz':''));
write(file, zip ? gzip(value) : value);
done();
});
const getItems = async function (selins=new Set(), result={}) {
const d = join(datadir, 'prices');
if (!exists(d)) mkdir(d);
for (const i of readdir(d)) {
const key = i.replace('.csv','');
if ( !selins.has(key) ) continue;
result[key] = read(join(d,i),'utf8');
}
};
const itdGetItems = async function (selins=new Set(), full=false) {
const d = join(datadir, 'intraday');
if (!exists(d)) mkdir(d);
const dirs = readdir(d).filter( i => stat(join(d,i)).isDirectory() && selins.has(i) );
let result;
if (full) {
result = dirs.map(i => {
const files = readdir(join(d,i)).map(j => {
const z = j.slice(-3) === '.gz';
return [ z ? j.slice(0,-3) : j, read(join(d,i,j), z ? null : 'utf8') ];
});
return [ i, Object.fromEntries(files) ];
});
} else {
result = dirs.map(i => {
const files = readdir(join(d,i)).map(j => {
const z = j.slice(-3) === '.gz';
return [z ? j.slice(0,-3) : j, true];
});
return [ i, Object.fromEntries(files) ];
});
}
return Object.fromEntries(result);
};
const itdSetItem = async function (key, obj) {
key = key.replace('tse.', '');
const d = join(datadir, 'intraday');
const dir = join(d, key);
if ( !exists(dir) ) mkdir(dir);
Object.keys(obj).forEach(k => {
const cont = obj[k];
const filename = k + (cont==='N/A'?'':'.gz');
write(join(dir, filename), obj[k]);
});
};
instance = {
getItem, setItem, getItemAsync, setItemAsync, getItems,
get CACHE_DIR() { return datadir; },
set CACHE_DIR(newdir) {
if (typeof newdir === 'string') {
if ( !exists(newdir) ) mkdir(newdir, {recursive: true});
if ( stat(newdir).isDirectory() ) {
datadir = newdir;
write(tracker, datadir);
}
}
},
itd: {
getItems: itdGetItems,
setItem: itdSetItem
}
};
} else if (isBrowser) {
const pako = window.pako || undefined;
const cpstore = localforage.createInstance({name: 'tse.prices'});
const getItemAsync = async (key, zip=false) => {
let store = localforage;
if ( key.startsWith('tse.prices.') ) {
key = key.replace('prices.', '');
store = cpstore;
}
const v = await store.getItem(key);
if (!v) return '';
if (!pako) return v;
return zip ? pako.ungzip(v, {to: 'string'}) : v;
};
const setItemAsync = async (key, value, zip=false) => {
let store = localforage;
if ( key.startsWith('tse.prices.') ) {
key = key.replace('tse.prices.', '');
store = cpstore;
}
if (!pako) {
await store.setItem(key, value);
return;
}
const rdy = zip ? pako.gzip(value) : value;
await store.setItem(key, rdy);
};
const getItems = async function (selins=new Set(), result={}) {
await cpstore.iterate((val, key) => {
let k = key.replace('tse.', '');
if (selins.has(k)) result[k] = val;
});
};
const itdstore = localforage.createInstance({name: 'tse.intraday'});
const itdGetItems = async function (selins=new Set(), full=false) {
const result = {};
if (full) {
await itdstore.iterate((val, key) => {
if (selins.has(key)) result[key] = val;
});
} else {
await itdstore.iterate((val, key) => {
if (selins.has(key)) result[key] = Object.keys(val).reduce((r,k) => (r[k] = true, r), {});
});
}
return result;
};
const itdSetItem = async (key, value, zip=false) => {
if (!pako) {
await itdstore.setItem(key, value);
return;
}
const rdy = zip ? pako.gzip(value) : value;
await itdstore.setItem(key, rdy);
};
instance = {
getItem: (key) => localStorage.getItem(key) || '',
setItem: (key, value) => localStorage.setItem(key, value),
getItemAsync,
setItemAsync,
getItems,
itd: {
getItems: itdGetItems,
setItem: itdSetItem
}
};
}
return instance;
})();
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// request
let API_URL = 'http://service.tsetmc.com/tsev2/data/TseClient2.aspx';
const rq = {
Instrument(DEven) {
const params = {
t: 'Instrument',
a: ''+DEven
};
return this.makeRequest(params);
},
InstrumentAndShare(DEven, LastID=0) {
const params = {
t: 'InstrumentAndShare',
a: ''+DEven,
a2: ''+LastID
};
return this.makeRequest(params);
},
LastPossibleDeven() {
const params = {
t: 'LastPossibleDeven'
};
return this.makeRequest(params);
},
ClosingPrices(insCodes) {
const params = {
t: 'ClosingPrices',
a: ''+insCodes
};
return this.makeRequest(params);
},
makeRequest(params) {
const url = new URL(API_URL);
url.search = new URLSearchParams(params).toString();
return new Promise((resolve, reject) => {
fetch(url).then(async res => {
res.status === 200 ? resolve(await res.text()) : reject(res.status +' '+ res.statusText);
}).catch(err => reject(err));
});
}
};
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// structs
class ClosingPrice {
constructor(_row='') {
const row = _row.split(',');
if (row.length !== 11) throw new Error('Invalid ClosingPrice data!');
this.InsCode = row[0]; // int64
this.DEven = row[1]; // int32 (the rest are all decimal)
this.PClosing = row[2]; // close
this.PDrCotVal = row[3]; // last
this.ZTotTran = row[4]; // count
this.QTotTran5J = row[5]; // volume
this.QTotCap = row[6]; // price
this.PriceMin = row[7]; // low
this.PriceMax = row[8]; // high
this.PriceYesterday = row[9]; // yesterday
this.PriceFirst = row[10]; // open
}
}
const cols = ['date','dateshamsi','open','high','low','last','close','vol','count','value','yesterday','symbol','name','namelatin','companycode'];
const colsFa = ['تاریخ میلادی','تاریخ شمسی','اولین قیمت','بیشترین قیمت','کمترین قیمت','آخرین قیمت','قیمت پایانی','حجم معاملات','تعداد معاملات','ارزش معاملات','قیمت پایانی دیروز','نماد','نام','نام لاتین','کد شرکت',];
class Column {
constructor(row=[]) {
const len = row.length;
if (len > 2 || len < 1) throw new Error('Invalid Column data!');
this.name = cols[ row[0] ];
this.fname = colsFa[ row[0] ];
this.header = row[1];
}
}
class Instrument {
constructor(_row='') {
const row = _row.split(',');
if ( ![18,19].includes(row.length) ) throw new Error('Invalid Instrument data!');
// unspecified ones are all string
this.InsCode = row[0]; // int64 (long)
this.InstrumentID = row[1];
this.LatinSymbol = row[2];
this.LatinName = row[3];
this.CompanyCode = row[4];
this.Symbol = cleanFa(row[5]).trim();
this.Name = row[6];
this.CIsin = row[7];
this.DEven = row[8]; // int32 (int)
this.Flow = row[9]; // 0,1,2,3,4,5,6,7 بازار byte
this.LSoc30 = row[10]; // نام 30 رقمي فارسي شرکت
this.CGdSVal = row[11]; // A,I,O نوع نماد
this.CGrValCot = row[12]; // 00,11,1A,...25 کد گروه نماد
this.YMarNSC = row[13]; // NO,OL,BK,BY,ID,UI کد بازار
this.CComVal = row[14]; // 1,3,4,5,6,7,8,9 کد تابلو
this.CSecVal = row[15]; // []62 کد گروه صنعت
this.CSoSecVal = row[16]; // []177 کد زير گروه صنعت
this.YVal = row[17]; // string نوع نماد
if (row[18]) {
this.SymbolOriginal = cleanFa(row[18]).trim();
}
}
}
class InstrumentITD {
constructor(_row='') {
const row = _row.split(',');
if (row.length !== 11) throw new Error('Invalid InstrumentITD data!');
this.InsCode = row[0];
this.LVal30 = cleanFa(row[1]); // نام 30 رقمي فارسي نماد
this.LVal18AFC = cleanFa(row[2]); // کد 18 رقمي فارسي نماد
this.FlowTitle = cleanFa(row[3]);
this.CGrValCotTitle = cleanFa(row[4]);
this.Flow = row[5];
this.CGrValCot = row[6];
this.CIsin = row[7];
this.InstrumentID = row[8];
this.ZTitad = row[9]; // تعداد سھام
this.BaseVol = row[10]; // حجم مبنا
}
}
class Share {
constructor(_row='') {
const row = _row.split(',');
if (row.length !== 5) throw new Error('Invalid Share data!');
this.Idn = row[0]; // long
this.InsCode = row[1]; // long
this.DEven = row[2]; // int
this.NumberOfShareNew = parseInt( row[3] ); // Decimal
this.NumberOfShareOld = parseInt( row[4] ); // Decimal
}
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// utils
function parseInstruments(struct=false, arr=false, structKey='InsCode', itd=false) {
let rows = storage.getItem('tse.instruments'+(itd?'.intraday':''));
rows = rows ? rows.split('\n') : [];
const instruments = arr ? [] : {};
const Struct = itd ? InstrumentITD : Instrument;
for (const row of rows) {
const item = struct ? new Struct(row) : row;
if (arr) {
instruments.push(item);
} else {
const key = struct ? item[structKey] : row.split(',', 1)[0];
instruments[key] = item;
}
}
return instruments;
}
function parseShares(struct=false, arr=true) {
let rows = storage.getItem('tse.shares');
rows = rows ? rows.split('\n') : [];
const shares = arr ? [] : {};
for (const row of rows) {
const item = struct ? new Share(row) : row;
if (arr) {
shares.push(item);
} else {
const key = struct ? item.InsCode : row.split(',', 2)[1];
if (!shares[key]) shares[key] = [];
shares[key].push(item);
}
}
return shares;
}
function dateToStr(d) {
return d.getFullYear()*10000 + (d.getMonth()+1)*100 + d.getDate() + '';
}
function strToDate(s) {
return new Date( +s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8) );
}
function cleanFa(str) {
return str
// .replace(/[\u200B-\u200D\uFEFF]/g, ' ')
.replace(/\u200B/g, '') // zero-width space
.replace(/\s?\u200C\s?/g, ' ') // zero-width non-joiner
.replace(/\u200D/g, '') // zero-width joiner
.replace(/\uFEFF/g, '') // zero-width no-break space
.replace(/ك/g, 'ک')
.replace(/ي/g, 'ی');
}
function gregToShamsi(s) {
const { jy, jm, jd } = jalaali.toJalaali(+s.slice(0,4), +s.slice(4,6), +s.slice(6,8));
return (jy*10000) + (jm*100) + jd + '';
}
function shamsiToGreg(s) {
const { gy, gm, gd } = jalaali.toGregorian(+s.slice(0,4), +s.slice(4,6), +s.slice(6,8));
return (gy*10000) + (gm*100) + gd + '';
}
function dayDiff(s1, s2) {
const date1 = +new Date(+s1.slice(0,4), +s1.slice(4,6)-1, +s1.slice(6,8));
const date2 = +new Date(+s2.slice(0,4), +s2.slice(4,6)-1, +s2.slice(6,8));
const diffTime = Math.abs(date2 - date1);
const msPerDay = (1000 * 60 * 60 * 24);
const diffDays = Math.ceil(diffTime / msPerDay);
return diffDays;
}
function splitArr(arr, size){
return arr
.map( (v, i) => i % size === 0 ? arr.slice(i, i+size) : undefined )
.filter(i => i);
}
function isObj(v) {
return Object.prototype.toString.call(v) === '[object Object]';
}
function isPosIntOrZero(n) {
return Number.isInteger(n) && n >= 0;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
let UPDATE_INTERVAL = 1;
let PRICES_UPDATE_CHUNK = 50;
let PRICES_UPDATE_CHUNK_DELAY = 300;
let PRICES_UPDATE_RETRY_COUNT = 3;
let PRICES_UPDATE_RETRY_DELAY = 1000;
const PRICES_UPDATE_POLLING_CYCLE = 1000 / 5; // 5 times per second
const TRADING_SESSION_END_HOUR = 16;
const SYMBOL_RENAME_STRING = '-ق';
const MERGED_SYMBOL_CONTENT = 'merged';
const defaultSettings = {
columns: [0,2,3,4,5,6,7,8,9],
adjustPrices: 0,
getAdjustInfo: false,
getAdjustInfoOnly: false,
daysWithoutTrade: false,
startDate: '20010321',
mergeSimilarSymbols: true,
cache: true,
csv: false,
csvHeaders: true,
csvDelimiter: ',',
onprogress: undefined,
progressTotal: 100,
debugMergeSimilarSymbols: false,
};
let lastdevens = {};
let storedPrices = {};
function adjust(cond, closingPrices, shares, getInfo, getInfoOnly) {
const cp = closingPrices;
const len = closingPrices.length;
const shouldGetInfo = getInfo || getInfoOnly;
const adjustedClosingPrices = [];
const info = {events: [], validGPLRatio: undefined};
let res = {
prices: getInfoOnly ? undefined : cp,
info: shouldGetInfo ? info : undefined,
};
if ( (cond === 1 || cond === 2 || shouldGetInfo) && len > 1 ) {
let gaps = new Decimal('0.0');
let coef = new Decimal('1.0');
adjustedClosingPrices.push( cp[len-1] );
if (cond === 1 || shouldGetInfo) {
for (let i=len-2; i>=0; i-=1) {
const [curr, next] = [ cp[i], cp[i+1] ];
if (!Decimal(curr.PClosing).eq(next.PriceYesterday) && curr.InsCode === next.InsCode) {
gaps = gaps.plus(1);
}
}
}
const gapsToLifespanRatio = gaps.div(len);
const hasValidRatio = gapsToLifespanRatio.lt('0.08');
info.validGPLRatio = hasValidRatio;
if ( (cond === 1 && hasValidRatio) || cond === 2 || shouldGetInfo ) {
for (let i=len-2; i>=0; i-=1) {
const [curr, next] = [ cp[i], cp[i+1] ];
const pricesDontMatch = !Decimal(curr.PClosing).eq(next.PriceYesterday) && curr.InsCode === next.InsCode;
const targetShare = shares.get(next.DEven);
if (shouldGetInfo && pricesDontMatch && (hasValidRatio || targetShare)) {// halt event
const adjustEvent = {};
const priceBeforeEvent = curr.PClosing;
const priceAfterEvent = next.PriceYesterday;
const dateBeforeEvent = curr.DEven;
let date = dateBeforeEvent;
if (targetShare) {// capital increase event
const {NumberOfShareOld: oldShares, NumberOfShareNew: newShares} = targetShare;
const increasePct = Decimal(newShares).sub(oldShares).div(oldShares);
adjustEvent.type = 'capital increase';
adjustEvent.increasePct = increasePct.toString();
adjustEvent.oldShares = ''+oldShares;
adjustEvent.newShares = ''+newShares;
//const {DEven: eventDate} = targetShare;
//date = eventDate; // alternative date to use, but results in less accurate external price adjustment
} else {// dividend event
const dividend = Decimal(priceBeforeEvent).sub(priceAfterEvent);
adjustEvent.type = 'dividend';
adjustEvent.dividend = dividend.toString();
}
adjustEvent.priceBeforeEvent = priceBeforeEvent;
adjustEvent.priceAfterEvent = priceAfterEvent;
adjustEvent.date = date;
info.events.push(adjustEvent);
}
if (getInfoOnly) continue;
if (cond === 1 && pricesDontMatch) {
coef = coef.times(next.PriceYesterday).div(curr.PClosing);
} else if (cond === 2 && pricesDontMatch && targetShare) {
const oldShares = targetShare.NumberOfShareOld;
const newShares = targetShare.NumberOfShareNew;
coef = coef.times(oldShares).div(newShares);
}
let
close = coef.times(curr.PClosing).toDecimalPlaces(2).toFixed(2),
last = coef.times(curr.PDrCotVal).toDecimalPlaces(2).toFixed(2),
low = coef.times(curr.PriceMin).toDecimalPlaces(0).toString(),
high = coef.times(curr.PriceMax).toDecimalPlaces(0).toString(),
yday = coef.times(curr.PriceYesterday).toDecimalPlaces(0).toString(),
first = coef.times(curr.PriceFirst).toDecimalPlaces(2).toFixed(2);
// note: the `toFixed()` calls are necessary and not redundant
const adjustedClosingPrice = {
InsCode: curr.InsCode,
DEven: curr.DEven,
PClosing: close, // close
PDrCotVal: last, // last
ZTotTran: curr.ZTotTran,
QTotTran5J: curr.QTotTran5J,
QTotCap: curr.QTotCap,
PriceMin: low, // low
PriceMax: high, // high
PriceYesterday: yday, // yesterday
PriceFirst: first // first
};
adjustedClosingPrices.push(adjustedClosingPrice);
}
adjustedClosingPrices.reverse();
res = {
prices: getInfoOnly ? undefined : adjustedClosingPrices,
info: shouldGetInfo ? info : undefined,
};
}
}
return res;
}
function getCell(columnName, instrument, closingPrice) {
const c = columnName;
const str =
c === 'date' ? closingPrice.DEven :
c === 'dateshamsi' ? jalaali && gregToShamsi(closingPrice.DEven) :
c === 'open' ? closingPrice.PriceFirst :
c === 'high' ? closingPrice.PriceMax :
c === 'low' ? closingPrice.PriceMin :
c === 'last' ? closingPrice.PDrCotVal :
c === 'close' ? closingPrice.PClosing :
c === 'vol' ? closingPrice.QTotTran5J :
c === 'count' ? closingPrice.ZTotTran :
c === 'value' ? closingPrice.QTotCap:
c === 'yesterday' ? closingPrice.PriceYesterday :
c === 'symbol' ? instrument.Symbol :
c === 'name' ? instrument.Name :
c === 'namelatin' ? instrument.LatinName :
c === 'companycode' ? instrument.CompanyCode : '';
return str;
}
function shouldUpdate(deven='', lastPossibleDeven) {
if (!deven || deven === '0') return true; // first time (never updated before)
const today = new Date();
const todayDeven = dateToStr(today);
const daysPassed = dayDiff(lastPossibleDeven, deven);
const inWeekend = [4,5].includes( today.getDay() );
const lastUpdateWeekday = strToDate(lastPossibleDeven).getDay();
const result = (
daysPassed >= UPDATE_INTERVAL &&
(todayDeven === lastPossibleDeven ? today.getHours() > TRADING_SESSION_END_HOUR : true) && // w8 until end of trading session
!(
// no update needed if: we are in weekend but ONLY if last time we updated was on last day (wednesday) of THIS week
inWeekend &&
lastUpdateWeekday !== 3 && // not wednesday
daysPassed <= 3 // and wednesday of this week
)
);
return result;
}
async function getLastPossibleDevens() {
let NO, ID; // normalMarket, indexMarket
const stored = storage.getItem('tse.lastPossibleDevens');
if (stored) [NO, ID] = stored.split(',');
const today = dateToStr(new Date());
const lastUpdate = storage.getItem('tse.lastLPDUpdate');
if (+today <= lastUpdate) return [NO, ID];
if ( !stored || shouldUpdate(today, NO) || shouldUpdate(today, ID) ) {
let error;
const res = await rq.LastPossibleDeven().catch(err => error = err);
if (error) return { title: 'Failed request: LastPossibleDeven', detail: error };
if ( !/^\d{8};\d{8}$/.test(res) ) return { title: 'Invalid server response: LastPossibleDeven' };
const splits = res.split(';');
storage.setItem('tse.lastPossibleDevens', splits.join(','));
storage.setItem('tse.lastLPDUpdate', today);
[NO, ID] = splits;
}
return [NO, ID];
}
async function updateInstruments() {
const lastUpdate = +storage.getItem('tse.lastInstrumentUpdate');
const today = new Date();
const todayDeven = +dateToStr(today);
if (lastUpdate && (todayDeven <= lastUpdate || today.getHours() <= TRADING_SESSION_END_HOUR)) return;
let lastId;
let currentShares;
if (!lastUpdate) {
lastId = 0;
} else {
currentShares = parseShares();
const shareIds = currentShares.map(i => +i.split(',',1)[0]);
lastId = Math.max(...shareIds);
}
let error;
const res = await rq.InstrumentAndShare(todayDeven, lastId).catch(err => error = err);
if (error) return { title: 'Failed request: InstrumentAndShare', detail: error };
let shares = res.split('@')[1];
error = 0;
let instruments = await rq.Instrument(0).catch(err => error = err);
if (error) return { title: 'Failed request: Instrument', detail: error };
// if (instruments === '*') console.warn('Cannot update during trading session hours.');
// if (instruments === '') console.warn('Already updated: ', 'Instruments');
// if (shares === '') console.warn('Already updated: ', 'Shares');
if (instruments !== '' && instruments !== '*') {
let rows = instruments.split(';').map(i=> i.split(','));
let _rows = [...rows.map(i=> (i=[...i], i[5]=cleanFa(i[5]).trim(), i))];
let dups = [...new Set(
_rows.map(i=> i[5]) // symbols
.filter((v,i,a) => a.indexOf(v) !== i) // duplicate symbols (unique)
)].map(i => _rows.filter(j=> j[5] === i)); // duplicate items
let code_idx = new Map(rows.map((i,j) => [i[0], j]));
for (let dup of dups) {
let dupSorted = dup.sort((a,b) => +b[8] - a[8]);
dupSorted.forEach((i,j) => {
let oj = code_idx.get(i[0]);
let origsym = rows[oj][5];
if (j > 0) {
let postfix = SYMBOL_RENAME_STRING + (j+1);
i.push(origsym);
i[5] = origsym.trim() + postfix;
} else {
i[5] = origsym;
}
});
}
dups.flat().forEach(i => {
let j = code_idx.get(i[0]);
rows[j] = i;
});
instruments = rows;
code_idx = undefined;
_rows = undefined;
rows = undefined;
instruments = instruments.map(i=>i.join(',')).join('\n');
storage.setItem('tse.instruments', instruments);
}
if (shares !== '') {
if (currentShares && currentShares.length) {
shares = currentShares.concat( shares.split(';') ).join('\n');
} else {
shares = shares.replace(/;/g, '\n');
}
storage.setItem('tse.shares', shares);
}
if ((instruments !== '' && instruments !== '*') || shares !== '') {
storage.setItem('tse.lastInstrumentUpdate', ''+todayDeven);
}
}
const pricesUpdateManager = (function () {
let total = 0;
let succs = [];
let fails = [];
let retries = 0;
let retrychunks = [];
let timeouts = new Map();
let qeudRetry;
let resolve;
let writing = [];
let pf, pn, ptot, pSR, pR;
let shouldCache;
let lastPossibleDeven;
function poll() {
if (timeouts.size > 0 || qeudRetry) {
setTimeout(poll, PRICES_UPDATE_POLLING_CYCLE);
return;
}
if (succs.length === total || retries >= PRICES_UPDATE_RETRY_COUNT) {
const _succs = [...succs];
const _fails = [...fails];
succs = [];
fails = [];
Promise.all(writing).then(() => {
writing = [];
resolve({succs: _succs, fails: _fails, pn});
});
return;
}
if (retrychunks.length) {
const inscodes = new Set(retrychunks.flat().map(i => i[0]));
fails = fails.filter(i => !inscodes.has(i));
retries++;
qeudRetry = setTimeout(batch, PRICES_UPDATE_RETRY_DELAY, retrychunks);
retrychunks = [];
setTimeout(poll, PRICES_UPDATE_RETRY_DELAY);
}
}
function onresult(response, chunk, id) {
const inscodes = new Set(chunk.map(([insCode]) => insCode));
if ( typeof response === 'string' && (/^[\d.,;@-]+$/.test(response) || response === '') ) {
const res = response.replace(/;/g, '\n').split('@').map((v,i)=> [chunk[i][0], v]);
for (const [inscode, newdata] of res) {
succs.push(inscode);
if (newdata) {
const olddata = storedPrices[inscode];
const data = olddata ? olddata+'\n'+newdata : newdata;
storedPrices[inscode] = data;
lastdevens[inscode] = newdata.split('\n').slice(-1)[0].split(',',2)[1];
writing.push( shouldCache && storage.setItemAsync('tse.prices.'+inscode, data) );
} else {
lastdevens[inscode] = lastPossibleDeven;
}
}
fails = fails.filter(i => !inscodes.has(i));
if (pf) {
const filled = pSR.div(PRICES_UPDATE_RETRY_COUNT + 2).mul(retries + 1);
pf(pn= +Decimal(pn).plus( pSR.sub(filled) ) );
}
} else {
fails.push(...inscodes);
retrychunks.push(chunk);
}
timeouts.delete(id);
}
function request(chunk=[], id) {
const insCodes = chunk.map(i => i.join(',')).join(';');
rq.ClosingPrices(insCodes)
.then( r => onresult(r, chunk, id) )
.catch( () => onresult(undefined, chunk, id) );
if (pf) pf(pn= +Decimal(pn).plus(pR) );
}
function batch(chunks=[]) {
if (qeudRetry) qeudRetry = undefined;
const ids = chunks.map((v,i) => 'a'+i);
for (let i=0, delay=0, n=chunks.length; i<n; i++, delay+=PRICES_UPDATE_CHUNK_DELAY) {
const id = ids[i];
const t = setTimeout(request, delay, chunks[i], id);
timeouts.set(id, t);
}
}
function start(updateNeeded=[], _shouldCache, _lastPossibleDeven, po={}) {
shouldCache = _shouldCache;
lastPossibleDeven = _lastPossibleDeven;
({ pf, pn, ptot } = po);
total = updateNeeded.length;
pSR = ptot.div( Math.ceil(Decimal(total).div(PRICES_UPDATE_CHUNK)) ); // each successful request: ( ptot / Math.ceil(total / PRICES_UPDATE_CHUNK) )
pR = pSR.div(PRICES_UPDATE_RETRY_COUNT + 2); // each request: pSR / (PRICES_UPDATE_RETRY_COUNT + 2)
succs = [];
fails = [];
retries = 0;
retrychunks = [];
timeouts = new Map();
qeudRetry = undefined;
const chunks = splitArr(updateNeeded, PRICES_UPDATE_CHUNK);
batch(chunks);
poll();
return new Promise(r => resolve = r);
}
return start;
})();
async function updatePrices(selection=[], shouldCache, {pf, pn, ptot}={}) {
lastdevens = storage.getItem('tse.inscode_lastdeven');
let inscodes = new Set();
if (lastdevens) {
const ents = lastdevens.split('\n').map(i=>i.split(','));
lastdevens = Object.fromEntries(ents);
inscodes = new Set( Object.keys(lastdevens) );
} else {
lastdevens = {};
}
let result = { succs: [], fails: [], error: undefined, pn };
const pfin = +Decimal(pn).plus(ptot);
const lastPossibleDevens = await getLastPossibleDevens();
if (isObj(lastPossibleDevens)) {
result.error = lastPossibleDevens;
if (pf) pf(pn= pfin);
return result;
}
const [lpdNO, lpdID] = lastPossibleDevens;
const { startDate: firstPossibleDeven } = defaultSettings;
const toUpdate = selection.map(instrument => {
const { InsCode: inscode, YMarNSC: market } = instrument;
const isNotNormalMarkets = market === 'NO' ? 0 : 1;
if ( !inscodes.has(inscode) ) { // doesn't have data
return [inscode, firstPossibleDeven, isNotNormalMarkets];
} else { // has data
const lastdeven = lastdevens[inscode];
const lastPossibleDeven =
market !== 'NO' ? lpdID :
market !== 'ID' ? lpdNO :
lpdNO;
if (!lastdeven) return; // but expired symbol
if ( shouldUpdate(lastdeven, lastPossibleDeven) ) { // but outdated
return [inscode, lastdeven, isNotNormalMarkets];
}
}
}).filter(i=>i);
if (pf) pf(pn= +Decimal(pn).plus( ptot.mul(0.01) ) );
const selins = new Set(selection.map(i => i.InsCode));
const storedins = new Set(Object.keys(storedPrices));
if ( !storedins.size || [...selins].find(i => !storedins.has(i)) ) {
await storage.getItems(selins, storedPrices);
}
if (pf) pf(pn= +Decimal(pn).plus( ptot.mul(0.01) ) );
if (toUpdate.length) {
const managerResult = await pricesUpdateManager(toUpdate, shouldCache, lpdNO, { pf, pn, ptot: ptot.sub(ptot.mul(0.02)) });
const { succs, fails } = managerResult;
({ pn } = managerResult);
if (succs.length && shouldCache) {
const str = Object.keys(lastdevens).map(k => [k, lastdevens[k]].join(',')).join('\n');
storage.setItem('tse.inscode_lastdeven', str);
}
result = { succs, fails };
}
if (pf && pn !== pfin) pf(pn=pfin);
result.pn = pn;
return result;
}
async function getPrices(symbols=[], _settings={}) {
if (!symbols.length) return;
const settings = {...defaultSettings, ..._settings};
const result = { data: [], error: undefined };
let { onprogress: pf, progressTotal: ptot } = settings;
if (typeof pf !== 'function') pf = undefined;
if (typeof ptot !== 'number') ptot = defaultSettings.progressTotal;
let pn = 0;
ptot = Decimal(ptot);
const err = await updateInstruments();
if (pf) pf(pn= +Decimal(pn).plus( ptot.mul(0.01) ) );
if (err) {
const { title, detail } = err;
result.error = { code: 1, title, detail };
if (pf) pf(+ptot);
return result;
}
const instruments = parseInstruments(true, undefined, 'Symbol');
const selection = symbols.map(i => instruments[i]);
const notFounds = symbols.filter((v,i) => !selection[i]);
if (pf) pf(pn= +Decimal(pn).plus( ptot.mul(0.01) ) );
if (notFounds.length) {
result.error = { code: 2, title: 'Incorrect Symbol', symbols: notFounds };
if (pf) pf(+ptot);
return result;
}
const { mergeSimilarSymbols } = settings;
let merges = new Map();
let extrasIndex = -1;
if (mergeSimilarSymbols) {
const syms = Object.keys(instruments);
const ins = syms.map(k => instruments[k]);
const roots = new Set(ins.filter(i => i.SymbolOriginal).map(i => i.SymbolOriginal));
const regx = new RegExp(SYMBOL_RENAME_STRING+'(\\d+)');
merges = new Map([...roots].map(i => [ i, [] ]));
ins.forEach((i, j) => {
const { SymbolOriginal: orig, Symbol: sym, InsCode: code } = i;
const renamedOrRoot = orig || sym;
if (!merges.has(renamedOrRoot)) return;
merges.get(renamedOrRoot).push({ sym, code, order: orig ? +sym.match(regx)[1] : 1 });
});
[...merges].forEach(([, v]) => v.sort((a,b) => a.order - b.order));
const selsyms = new Set(selection.map(i=> i.Symbol));
const extras = selection.map(({Symbol: sym}) => {
if (!merges.has(sym)) return;
let leafs = merges.get(sym).slice(1).map(i => i.sym);
leafs = leafs.filter(i => !selsyms.has(i));
const leafInss = leafs.map(sym => instruments[sym]);
return leafInss;
}).flat().filter(i=>i);
if (extras.length) {
extrasIndex = selection.length;
selection.push(...extras);
}
}
const updateResult = await updatePrices(selection, settings.cache, {pf, pn, ptot: ptot.mul(0.78)});
const { succs, fails, error } = updateResult;
({ pn } = updateResult);
if (error) {
const { title, detail } = error;
result.error = { code: 1, title, detail };
if (pf) pf(+ptot);
return result;
}
if (fails.length) {
const syms = Object.fromEntries( selection.map(i => [i.InsCode, i.Symbol]) );
result.error = { code: 3, title: 'Incomplete Price Update',
fails: fails.map(k => syms[k]),
succs: succs.map(k => syms[k])
};
const _fails = new Set(fails);
selection.forEach((v,i,a) => _fails.has(v.InsCode) ? a[i] = undefined : 0);
}
if (mergeSimilarSymbols && extrasIndex > -1) selection.splice(extrasIndex);
const columns = settings.columns.map(i => {
const row = !Array.isArray(i) ? [i] : i;
const column = new Column(row);
const finalHeader = column.header || column.name;
return { ...column, header: finalHeader };
});