-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjstrader_api_V1_01.js
2742 lines (2342 loc) · 99 KB
/
jstrader_api_V1_01.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
const net = require('net');
/**
* Custom error class for JstraderApi errors
* @extends Error
*/
class JsTraderApiError extends Error {
constructor(message, code) {
super(message);
this.name = 'JsTraderApiError';
this.code = code;
}
}
/**
* Error dictionary mapping error codes to their descriptions.
* @type {Object.<string, string>}
*/
const ERROR_DICT = {
'00001': 'Undefined check connection error',
'00101': 'IP address error',
'00102': 'Port number error',
'00103': 'Connection error with license EA',
'00104': 'Undefined answer from license EA',
'00301': 'Unknown instrument for broker',
'00302': 'Instrument not in demo',
'00304': 'Unknown instrument for broker',
'00401': 'Instrument not in demo',
'00402': 'Instrument not exists for broker',
'00501': 'No instrument defined/configured',
'01101': 'Undefined check terminal connection error',
'01201': 'Undefined check MT type error',
'02001': 'Instrument not in demo',
'02002': 'Unknown instrument for broker',
'02003': 'Unknown instrument for broker',
'02004': 'Time out error',
'04101': 'Instrument not in demo',
'04102': 'Wrong/unknown time frame',
'04103': 'No records',
'04104': 'Undefined error',
'04105': 'Unknown instrument for broker',
'04201': 'Instrument not in demo',
'04202': 'Wrong/unknown time frame',
'04204': 'Unknown instrument for broker',
'04501': 'Instrument not in demo',
'04502': 'Wrong/unknown time frame',
'04503': 'No records',
'04504': 'Missing market instrument',
'06201': 'Wrong time window',
'06401': 'Wrong time window',
'07001': 'Trading not allowed, check MT terminal settings',
'07002': 'Instrument not in demo',
'07003': 'Instrument not in market watch',
'07004': 'Instrument not known at broker',
'07005': 'Unknown order type',
'07006': 'Wrong SL value',
'07007': 'Wrong TP value',
'07008': 'Wrong volume value',
'07009': 'Error opening / placing order',
'07101': 'Trading not allowed',
'07102': 'Position not found/error',
'07201': 'Trading not allowed',
'07202': 'Position not found/error',
'07203': 'Wrong volume',
'07204': 'Error in partial close',
'07301': 'Trading not allowed',
'07302': 'Error in delete',
'07401': 'Trading not allowed, check MT terminal settings',
'07402': 'Error check number',
'07403': 'Position does not exist',
'07404': 'Opposite position does not exist',
'07405': 'Both position of same type',
'07501': 'Trading not allowed',
'07502': 'Position not open' ,
'07503': 'Error in modify',
'07601': 'Trading not allowed',
'07602': 'Position not open' ,
'07603': 'Error in modify',
'07701': 'Trading not allowed',
'07702': 'Position not open' ,
'07703': 'Error in modify',
'07801': 'Trading not allowed',
'07802': 'Position not open' ,
'07803': 'Error in modify',
'07901': 'Trading not allowed',
'07902': 'Instrument not in demo',
'07903': 'Order does not exist' ,
'07904': 'Wrong order type',
'07905': 'Wrong price',
'07906': 'Wrong TP value',
'07907': 'Wrong SL value',
'07908': 'Check error code',
'07909': 'Something wrong',
'08101': 'Unknown global variable',
'08201': 'Log file not existing',
'08202': 'Log file empty',
'08203': 'Error in reading log file',
'08204': 'Function not implemented',
'09101': 'Trading not allowed',
'09102': 'Unknown instrument for broker',
'09103': 'Function not implemented',
'99900': 'Wrong authorizaton code',
'99901': 'Undefined error',
'99999': 'Dummy'
};
/**
* jstrader API for MT4 and MT5
* @class
*/
class JsTraderApi {
constructor() {
this.sock = null;
this.socketError = 0;
this.socketErrorMessage = '';
this.orderReturnMessage = '';
this.orderError = 0;
this.connected = false;
this.timeout = false;
this.commandOK = false;
this.commandReturnError = '';
this.debug = false;
this.version = 'V1.01';
this.maxBars = 2000;
this.maxTicks = 2000;
this.timeoutValue = 10;
this.instrumentConversionList = {};
this.instrumentNameBroker = '';
this.instrumentNameUniversal = '';
this.dateFrom = new Date('2024-01-01T00:00:00Z');
this.dateTo = new Date();
this.instrument = '';
this.license = 'Demo';
this.invertArray = false;
this.authorizationCode = 'None';
}
/**
* Set timeout value for socket communication with MT4 or MT5 EA/Bot.
*
* @param {number} [timeoutInSeconds=60] - The timeout value in seconds.
*
* @returns {Promise<Object>} - List[]
* List[0] - bool: status, true or false
* List[1] - timeout value
* @throws {JsTraderApiError} If the socket is not initialized.
*/
Set_timeout(timeoutInSeconds = 5) {
this.timeoutValue = timeoutInSeconds;
if (this.sock) {
this.sock.setTimeout(this.timeoutValue * 1000);
return([true, timeoutInSeconds]);
} else {
throw new JsTraderApiError('Socket not initialized', 'SOCKET_NOT_INITIALIZED');
}
}
/**
* Connects to a MT4 or MT5 EA/Bot.
*
* @param {string} [server='127.0.0.1'] - Server IP address.
* @param {number} [port=1111] - Port number.
* @param {Object} [instrumentLookup={}] - Dictionary with universal instrument names and broker instrument names.
* Act as translation table.
* @param {string} [authorizationCode='None'] - Authorization code for extra security.
* @returns {Promise<Object>} - List[]
* List[0] - bool: status, true or false
* List[1] - string: server ip address
* @throws {JsTraderApiError} If connection fails or instrumentLookup list is empty.
*/
async connect(server = '127.0.0.1', port = 1111, instrumentLookup = {}, authorizationCode = 'None') {
this.sock = new net.Socket();
this.sock.setEncoding('utf8');
this.port = port;
this.server = server;
this.instrumentConversionList = instrumentLookup;
this.authorizationCode = authorizationCode;
if (Object.keys(this.instrumentConversionList).length === 0) {
throw new JsTraderApiError('Broker Instrument list not available or empty', 'EMPTY_INSTRUMENT_LIST');
}
return new Promise((resolve, reject) => {
const onError = (err) => {
this.sock.removeListener('error', onError);
this.sock.removeListener('connect', onConnected);
this.connected = false;
this.socketError = 101;
this.socketErrorMessage = 'Could not connect to server.';
reject(new JsTraderApiError(`Connection failed: ${err.message}`, 'CONNECTION_FAILED'));
};
const onConnected = () => {
this.sock.removeListener('error', onError);
this.sock.removeListener('connect', onConnected);
this.connected = true;
this.socketError = 0;
this.socketErrorMessage = '';
};
const onData = (data) => {
data = '';
this.sock.removeListener('data', onData);
resolve([true, server]);
};
this.sock.once('error', onError);
this.sock.once('connect', onConnected);
this.sock.once('data', onData);
this.sock.connect(this.port, this.server);
// Set a timeout for the command
setTimeout(() => {
this.sock.removeListener('data', onData);
this.sock.removeListener('error', onError);
this.sock.removeListener('error', onError);
this.socketErrorMessage = ERROR_DICT['00103'];
this.timeout = true;
reject(new JsTraderApiError('Command timed out, check server and port', 'COMMAND_TIMEOUT'));
}, this.timeoutValue * 1000);
});
}
/**
* Closes the socket connection to a MT4 or MT5 EA bot.
*
* @throws {JsTraderApiError} If the socket is not initialized or an error occurs during disconnection.
*/
disconnect() {
if (!this.sock) {
throw new JsTraderApiError('Socket not initialized', 'SOCKET_NOT_INITIALIZED');
}
try {
this.sock.destroy();
this.connected = false;
} catch (error) {
throw new JsTraderApiError(`Failed to disconnect: ${error.message}`, 'DISCONNECT_FAILED');
}
}
/**
* Checks if connection with MT terminal/EA bot is still active.
* @returns {Promise<boolean>}
* @throws {JsTraderApiError} If the connection check fails, f.i socket not initialized
*/
async Check_connection() {
const command = 'F000^1^';
this.commandReturnError = '';
try {
const [ok, dataString] = await this.sendCommand(command);
if (!ok) {
this.commandOK = false;
return false;
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[1] === 'OK') {
this.timeout = false;
this.commandOK = true;
return true;
} else {
this.timeout = true;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
return false;
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Connection check failed: ${error.message}`, 'CONNECTION_CHECK_FAILED');
}
}
/**
* Get broker server time.
*
* @returns {Promise<Object>} List[]
* List[0] = status, true or false
* List[1] = datetime: Boker time
* @throws {JsTraderApiError} If the connection fails.
*/
async Get_broker_server_time()
{
this.commandReturnError = '';
this.command = 'F005^1^';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to retrieve server broker time', 'SERVER_BROKER_TIME_RETRIEVAL_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F005') {
this.timeout = false;
this.command_OK = true;
const y = x[2].split('-');
const myDate = new Date();
myDate.setFullYear(parseInt(y[0]));
myDate.setMonth(parseInt(y[1])-1);
myDate.setDate(parseInt(y[2]));
myDate.setHours(parseInt(y[3]));
myDate.setMinutes(parseInt(y[4]));
myDate.setSeconds(parseInt(y[5]));
return([true, myDate]);
}
else {
this.timeout = true;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to retrieve broker server time: ${error.message}`, 'SERVER_BROKER_TIME_RETRIEVAL_FAILED');
}
}
/**
* Retrieves static account information.
*
* @returns {Promise<Object>} List[] - Account information.
* List[0] - bool: status, true or false
* List[1] - dict: {name, number, currency, type, leverage, trading_allowed, limit_orders, margin_call, margin_close, company }
* @throws {JsTraderApiError} If retrieval of account information fails.
*/
async Get_static_account_info() {
this.command = 'F001^1^';
this.commandReturnError = '';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to retrieve static account information', 'ACCOUNT_INFO_RETRIEVAL_FAILED');
}
const x = dataString.split('^');
if (this.debug) {
console.log(dataString);
}
if (x[0] === 'F001') {
this.timeout = false;
this.commandOK = true;
return [true, {
name: x[2],
login: x[3],
currency: x[4],
type: x[5],
leverage: x[6],
trade_allowed: x[7],
limit_orders: x[8],
margin_call: x[9],
margin_close: x[10],
company: x[11]}];
} else {
this.timeout = true;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to get account info: ${error.message}`, 'STATIC_ACCOUNT_INFO_RETRIEVAL_FAILED');
}
}
/**
* Retrieves dynamic account information.
*
* @returns {Promise<Object>} List[] - Account information.
* List[0] - bool: status, true or false
* List[1] - dict: {balance, equity, profit, margin, margin_level, margin_free }
* @throws {JsTraderApiError} If retrieval of account information fails.
*/
async Get_dynamic_account_info() {
const command = 'F002^1^';
this.commandReturnError = '';
try {
const [ok, dataString] = await this.sendCommand(command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to retrieve dynamic account information', 'DYNAMIC_ACCOUNT_INFO_RETRIEVAL_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F002') {
this.timeout = false;
this.commandOK = true;
return [true, {
balance: x[2],
equity: x[3],
profit: x[4],
margin: x[5],
margin_level: x[6],
margin_free: x[7],
}];
} else {
this.timeout = true;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to get account info: ${error.message}`, 'DYNAMIC_ACCOUNT_INFO_RETRIEVAL_FAILED');
}
}
/**
* Retrieve instrument info/parameters.
*
* @param {string} [instrumentName] - Name of instrument.
* @returns {Promise<Object>} - List[boolean, dict]
* List[0] - bool: status, true or false
* List[1] - dict: {instrument, digits, max_lotsize, min_lotsize, lot_step, point,
* tick_size, tick_value, swap_long, swap_short, stop_level, contract_size}
* @throws {JsTraderApiError} If retrieval of instrument information fails.
*/
async Get_instrument_info(instrumentName = 'EURUSD') {
this.instrumentNameUniversal = instrumentName;
const brokerName = this.instrumentConversionList[instrumentName.toUpperCase()];
if (!brokerName) {
throw new JsTraderApiError(`Instrument not found: ${this.instrumentNameUniversal}`, 'INSTRUMENT_NOT_FOUND');
}
this.instrumentNameBroker = brokerName;
this.commandReturnError = '';
this.command = 'F003^2^' + this.instrumentNameBroker + '^';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to retrieve instrument information', 'INSTRUMENT_INFO_RETRIEVAL_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F003') {
this.timeout = false;
this.command_OK = true;
return([true, {
instrument: this.instrumentNameUniversal,
digits: x[2],
max_lotsize: x[3],
min_lotsize: x[4],
lot_step: x[5],
point: x[6],
tick_size: x[7],
tick_value: x[8],
swap_long: x[9],
swap_short: x[10],
stop_level: x[11],
contract_size: x[12],
}]);
} else {
this.timeout = true;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
}
catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to get instrument info: ${error.message}`, 'INSTRUMENT_INFO_RETRIEVAL_FAILED');
}
}
/**
* Retrieve broker instrument names
*
* @returns {Promise<Object>} - List[boolean, string]
* List[0] - bool: status, true or false
* List[1] - []: List of broker instrument names
* @throws {JsTraderApiError} If connection fails.
*/
async Get_broker_instrument_names() {
this.command = 'F007^1^';
this.commandReturnError = '';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to retrieve broker instrument names', 'BROKER_INSTRUMENT_NAMES_RETRIEVAL_FAILED');
}
if (this.debug) {
console.log(dataString);
}
let returnList = [];
let x = dataString.split('^');
if (x[0] === 'F007') {
this.timeout = false;
this.commandOK = true;
x = x.slice(2, -1);
returnList = x.map(item => String(item));
/* for (let j = 0; j < x.length; j++) {
returnList.push(x[j]);
} */
return [true, returnList];
} else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to get broker instrument names: ${error.message}`, 'BROKER_INSTRUMENT_NAMES_RETRIEVAL_FAILED');
}
}
/**
* Check if instrument is in market watch.
*
* @param {string} [instrumentName] - Name of instrument.
* @returns {Promise<Object>} - List[boolean, dict]
* List[0] - bool: status, true or false
* List[1] - string: 'Market watch' or 'Not in market watch'
* @throws {JsTraderApiError} If connection fails.
*/
async Check_market_watch(instrumentName = 'EURUSD') {
this.instrumentNameUniversal = this.instrument;
const brokerName = this.instrumentConversionList[instrumentName.toUpperCase()];
if (!brokerName) {
throw new JsTraderApiError(`Instrument not found: ${this.instrumentNameUniversal}`, 'INSTRUMENT_NOT_FOUND');
}
this.instrumentNameBroker = brokerName;
this.commandReturnError = '';
this.command = 'F004^2^' + this.instrumentNameBroker + '^';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to check instrument market/no market', 'INSTRUMENT_MARKET_CHECK_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F004') {
this.timeout = false;
this.commandOK = true;
return [true, x[2]];
} else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to check instrument market/no market: ${error.message}`, 'INSTRUMENT_MARKET_CHECK_FAILED');
}
}
/**
* Check Mt4/MT5 license type
*
* @returns {Promise<Object>} - List[boolean, string]
* List[0] - bool: status, true or false
* List[1] - string: 'Demo' or 'Licensed'
* @throws {JsTraderApiError} If connection fails.
*/
async Check_license()
{
this.command = 'F006^1^';
this.commandReturnError = '';
this.license = 'Demo';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to check license', 'LICENSE_CHECK_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F006') {
this.timeout = false;
this.commandOK = true;
this.license = x[3 ]
return [true, x[3]];
} else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99901'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to check license: ${error.message}`, 'LICENSE_CHECK_FAILED');
}
}
/**
* Check if for instrument trading is allowed
*
* @param {string} [instrumentName] - Name of instrument.
* @returns {Promise<Object>} - List[boolean, dict]
* List[0] - bool: true or false
* List[1] - 'Allowed or 'Not allowed'
* @throws {JsTraderApiError} If connection fails.
*/
async Check_trading_allowed(instrumentName = 'EURUSD') {
this.commandReturnError = '';
this.instrumentNameBroker = instrumentName;
const brokerName = this.instrumentConversionList[instrumentName.toUpperCase()];
if (!brokerName) {
throw new JsTraderApiError(`Instrument not found: ${this.instrumentNameUniversal}`, 'INSTRUMENT_NOT_FOUND');
}
this.instrumentNameBroker = brokerName;
this.command = 'F008^2^' + this.instrumentNameBroker + '^';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to check trading allowed', 'TRADING_ALLOWED_CHECK_FAILED');
}
const x = dataString.split('^');
if (x[0] === 'F008') {
this.timeout = false;
this.commandOK = true;
return [true, x[2]];
} else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
}
catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to check trading allowed: ${error.message}`, 'TRADING_ALLOWED_CHECK_FAILED');
}
}
/**
* Check if MT terminal is connected to the broker server
*
* @returns {Promise<Object>} - List[boolean, string]
* List[0] - bool: status, true or false
* List[1] - string: 'Connected' or 'Not connected'
* @throws {JsTraderApiError} If connection fails.
*/
async Check_terminal_server_connection() {
this.command = 'F011^1^';
this.commandReturnError = '';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to check terminal connected to server', 'TERMINAL_CONNECTED_CHECK_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F011') {
this.timeout = false;
this.commandOK = true;
if (x[1] === '1') {
return([true, 'Connected']);
}
return [true, 'Not connected'];
//return [true, x[1]];
} else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to check terminal connected to server: ${error.message}`, 'TERMINAL_CONNECTED_CHECK_FAILED');
}
}
/**
* Check terminal type MT4 or MT5
*
* @returns {Promise<Object>} - List[boolean, string]
* List[0] - bool: status, true or false
* List[1] - string: MT4 or MT5
* @throws {JsTraderApiError} If connection fails.
*/
async Check_terminal_type() {
this.command = 'F012^1^';
this.commandReturnError = '';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to check terminal type', 'TERMINAL_TYPE_CHECK_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F012') {
this.timeout = false;
this.commandOK = true;
if (x[1] === '1') {
return([true, 'MT4']);
}
return [true, 'MT5'];
} else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to check terminal type: ${error.message}`, 'TERMINAL_TYPE_CHECK_FAILED');
}
}
/**
* Retrieve instrument last tick info.
*
* @param {string} [instrumentName] - Name of instrument.
* @returns {Promise<Object>} - List[boolean, dict]
* List[0] - bool: status, true or false
* List[1] - {instrument, date, ask, bid, lst, volume, spread, date_in_ms}
* @throws {JsTraderApiError} If connection fails or ....
*/
async Get_last_tick_info(instrumentName = 'EURUSD') {
this.commandReturnError = '';
this.instrumentNameUniversal = instrumentName;
const brokerName = this.instrumentConversionList[instrumentName.toUpperCase()];
if (!brokerName) {
throw new JsTraderApiError(`Instrument not found: ${this.instrumentNameUniversal}`, 'INSTRUMENT_NOT_FOUND');
}
this.instrumentNameBroker = brokerName;
this.command = 'F020^2^' + this.instrumentNameBroker + '^';
try {
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to get last tick info', 'LAST_TICK_INFO_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F020') {
this.timeout = false;
this.commandOK = true;
return [true, {
instrument: this.instrumentNameUniversal,
date: parseInt(x[2]),
ask: parseFloat(x[3]),
bid: parseFloat(x[4]),
last: parseFloat(x[5]),
volume: parseInt(x[6]),
spread: parseFloat(x[7]),
date_in_ms: parseInt(x[8])
}];
} else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
} catch (error) {
this.commandReturnError = ERROR_DICT['00001'];
this.commandOK = false;
throw new JsTraderApiError(`Failed to get last tick info: ${error.message}`, 'LAST_TICK_INFO_FAILED');
}
}
/**
* Retrieve instrument last x tick info.
* @param {string} [instrumentName] - Name of instrument.
* @param {number} [nbrOfTicks] - Number of ticks to retrieve.
* @returns {Promise<Object>} - List[boolean, List[{}]]
* List[0] - bool: status, true or false
* List[1] - [{dateInMs, ask, bid, last, volume, spread}{}....]
* @throws {JsTraderApiError} If connection fails or ....
*/
async Get_last_x_ticks_from_now(instrumentName = 'EURUSD', nbrOfTicks = 100) {
this.commandReturnError = '';
this.instrumentNameUniversal = instrumentName;
const brokerName = this.instrumentConversionList[instrumentName.toUpperCase()];
if (!brokerName) {
throw new JsTraderApiError(`Instrument not found: ${this.instrumentNameUniversal}`, 'INSTRUMENT_NOT_FOUND');
}
this.instrumentNameBroker = brokerName;
this.nbrOfTicks = nbrOfTicks;
//this.instrumentNameUniversal = instrumentName;
if (nbrOfTicks < 1) {
throw new JsTraderApiError(`NbrOfTicks < 1: ${nbrOfTicks}`, 'INVALID_NBR_OF_TICKS');
}
let iLoop = Math.floor(this.nbrOfTicks / this.maxTicks);
let iTail = this.nbrOfTicks - (this.maxTicks * iLoop);
try {
if (nbrOfTicks > this.maxTicks) {
//let iLoop = Math.floor(this.nbrOfTicks / this.maxTicks);
//let iTail = this.nbrOfTicks - (this.maxTicks * iLoop);
let allTicks = [];
for (let i = 0; i < iLoop; i++) {
this.command = 'F021^4^' + this.instrumentNameBroker + '^' + (i * this.maxTicks).toString() + '^' + this.maxTicks.toString() + '^';
const [ok, dataString] = await this.sendCommand(this.command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to get x tick info', 'X_TICK_INFO_FAILED');
}
if (this.debug) {
console.log(dataString);
}
let x = dataString.split('^');
if (x[0] === 'F021') {
this.timeout = false;
this.commandOK = true;
x = x.slice(2, -1);
let ticks = [];
for (let j = 0; j < x.length; j++) {
const y = x[j].split('$');
const newRow = {
//index: j + i * this.maxTicks,
dateInMs: parseInt(y[0]),
ask: parseFloat(y[1]),
bid: parseFloat(y[2]),
last: parseFloat(y[3]),
volume: parseInt(y[4])
};
ticks.push(newRow);
}
allTicks = allTicks.concat(ticks);
}
else {
this.timeout = false;
this.commandReturnError = ERROR_DICT['99900'];
this.commandOK = true;
throw new JsTraderApiError('Invalid response format', 'INVALID_RESPONSE_FORMAT');
}
}
if (iTail > 0) {
this.command = 'F021^4^' + this.instrumentNameBroker + '^' + (iLoop * this.maxTicks).toString() + '^' + iTail.toString() + '^';
const [ok, dataString] = await this.sendCommand(command);
if (!ok) {
this.commandOK = false;
throw new JsTraderApiError('Failed to get x tick info', 'X_TICK_INFO_FAILED');
}
if (this.debug) {
console.log(dataString);
}
const x = dataString.split('^');
if (x[0] === 'F021') {
this.timeout = false;
this.commandOK = true;
x = x.slice(2, -1);
let ticks = [];
for (let j = 0; j < x.length; j++) {
const y = x[j].split('$');
const newRow = {
//index: j + iLoop * this.maxTicks,
dateInMs: parseInt(y[0]),
ask: parseFloat(y[1]),
bid: parseFloat(y[2]),
last: parseFloat(y[3]),
volume: parseInt(y[4])
};
ticks.push(newRow);
}