-
Notifications
You must be signed in to change notification settings - Fork 23
/
Pytrader_API_V3_02.py
2257 lines (1917 loc) · 76.5 KB
/
Pytrader_API_V3_02.py
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
# Pytrader API for MT4 and MT5
# Version V3_01
import socket
import numpy as np
import pandas as pd
from datetime import datetime
import pytz
import io
TZ_SERVER = 'Europe/Tallinn' # EET
TZ_LOCAL = 'Europe/Budapest'
TZ_UTC = 'UTC'
ERROR_DICT = {}
ERROR_DICT['00001'] = 'Undefined check connection error'
ERROR_DICT['00101'] = 'IP address error'
ERROR_DICT['00102'] = 'Port number error'
ERROR_DICT['00103'] = 'Connection error with license EA'
ERROR_DICT['00104'] = 'Undefined answer from license EA'
ERROR_DICT['00301'] = 'Unknown instrument for broker'
ERROR_DICT['00302'] = 'Instrument not in demo'
ERROR_DICT['00304'] = 'Unknown instrument for broker'
ERROR_DICT['00401'] = 'Instrument not in demo'
ERROR_DICT['00402'] = 'Instrument not exists for broker'
ERROR_DICT['00501'] = 'No instrument defined/configured'
ERROR_DICT['02001'] = 'Instrument not in demo'
ERROR_DICT['02004'] = 'Unknown instrument for broker'
ERROR_DICT['02003'] = 'Unknown instrument for broker'
ERROR_DICT['02101'] = 'Instrument not in demo'
ERROR_DICT['02102'] = 'No ticks'
ERROR_DICT['02103'] = 'Not imlemented in MT4'
ERROR_DICT['04101'] = 'Instrument not in demo'
ERROR_DICT['04102'] = 'Wrong/unknown time frame'
ERROR_DICT['04103'] = 'No records'
ERROR_DICT['04104'] = 'Undefined error'
ERROR_DICT['04105'] = 'Unknown instrument for broker'
ERROR_DICT['04201'] = 'Instrument not in demo'
ERROR_DICT['04202'] = 'Wrong/unknown time frame'
ERROR_DICT['04203'] = 'No records'
ERROR_DICT['04204'] = 'Unknown instrument for broker'
ERROR_DICT['04501'] = 'Instrument not in demo'
ERROR_DICT['04502'] = 'Wrong/unknown time frame'
ERROR_DICT['04503'] = 'No records'
ERROR_DICT['04504'] = 'Missing market instrument'
ERROR_DICT['06201'] = 'Wrong time window'
ERROR_DICT['06401'] = 'Wrong time window'
ERROR_DICT['07001'] = 'Trading not allowed, check MT terminal settings'
ERROR_DICT['07002'] = 'Instrument not in demo'
ERROR_DICT['07003'] = 'Instrument not in market watch'
ERROR_DICT['07004'] = 'Instrument not known for broker'
ERROR_DICT['07005'] = 'Unknown order type'
ERROR_DICT['07006'] = 'Wrong SL value'
ERROR_DICT['07007'] = 'Wrong TP value'
ERROR_DICT['07008'] = 'Wrong volume value'
ERROR_DICT['07009'] = 'Error opening market order'
ERROR_DICT['07010'] = 'Error opening pending order'
ERROR_DICT['07011'] = 'Unknown instrument for broker'
ERROR_DICT['07101'] = 'Trading not allowed'
ERROR_DICT['07102'] = 'Position not found/error'
ERROR_DICT['07201'] = 'Trading not allowed'
ERROR_DICT['07202'] = 'Position not found/error'
ERROR_DICT['07203'] = 'Wrong volume'
ERROR_DICT['07204'] = 'Error in partial close'
ERROR_DICT['07301'] = 'Trading not allowed'
ERROR_DICT['07302'] = 'Error in delete'
ERROR_DICT['07501'] = 'Trading not allowed'
ERROR_DICT['07502'] = 'Position not open'
ERROR_DICT['07503'] = 'Error in modify'
ERROR_DICT['07601'] = 'Trading not allowed'
ERROR_DICT['07602'] = 'Position not open'
ERROR_DICT['07603'] = 'Error in modify'
ERROR_DICT['07701'] = 'Trading not allowed'
ERROR_DICT['07702'] = 'Position not open'
ERROR_DICT['07703'] = 'Error in modify'
ERROR_DICT['07801'] = 'Trading not allowed'
ERROR_DICT['07802'] = 'Position not open'
ERROR_DICT['07803'] = 'Error in modify'
ERROR_DICT['07901'] = 'Trading not allowed'
ERROR_DICT['07902'] = 'Instrument not in demo'
ERROR_DICT['07903'] = 'Order does not exist'
ERROR_DICT['07904'] = 'Wrong order type'
ERROR_DICT['07905'] = 'Wrong price'
ERROR_DICT['07906'] = 'Wrong TP value'
ERROR_DICT['07907'] = 'Wrong SL value'
ERROR_DICT['07908'] = 'Check error code'
ERROR_DICT['07909'] = 'Something wrong'
ERROR_DICT['08101'] = 'Unknown global variable'
ERROR_DICT['08201'] = 'Log file not existing'
ERROR_DICT['08202'] = 'Log file empty'
ERROR_DICT['08203'] = 'Error in reading log file'
ERROR_DICT['08204'] = 'Function not implemented'
ERROR_DICT['09101'] = 'Trading not allowed'
ERROR_DICT['09102'] = 'Unknown instrument for broker'
ERROR_DICT['09103'] = 'Function not implemented'
ERROR_DICT['99900'] = 'Wrong authorizaton code'
ERROR_DICT['99901'] = 'Undefined error'
ERROR_DICT['99999'] = 'Dummy'
class Pytrader_API:
def __init__(self):
self.socket_error: int = 0
self.socket_error_message: str = ''
self.order_return_message: str = ''
self.order_error: int = 0
self.connected: bool = False
self.timeout: bool = False
self.command_OK: bool = False
self.command_return_error: str = ''
self.debug: bool = False
self.version: str = 'V3.02'
self.max_bars: int = 5000
self.max_ticks: int = 5000
self.timeout_value: int = 60
self.instrument_conversion_list: dict = {}
self.instrument_name_broker: str = ''
self.instrument_name_universal: str = ''
self.date_from: datetime = '2000/01/01, 00:00:00'
self.date_to: datetime = datetime.now()
self.instrument: str = ''
self.license = 'Demo'
self.invert_array = False
self.authorization_code: str = 'None'
def Set_timeout(self,
timeout_in_seconds: int = 60
):
"""
Set time out value for socket communication with MT4 or MT5 EA/Bot.
Args:
timeout_in_seconds: the time out value
Returns:
None
"""
self.timeout_value = timeout_in_seconds
self.sock.settimeout(self.timeout_value)
self.sock.setblocking(1)
return
def Disconnect(self):
"""
Closes the socket connection to a MT4 or MT5 EA bot.
Args:
None
Returns:
bool: True or False
"""
self.sock.close()
return True
def Connect(self,
server: str = '',
port: int = 2345,
instrument_lookup: dict = [],
authorization_code: str = 'None') -> bool:
"""
Connects to a MT4 or MT5 EA/Bot.
Args:
server: Server IP address, like -> '127.0.0.1', '192.168.5.1'
port: port number
instrument_lookup: dictionairy with general instrument names and broker intrument names
authorization_code: authorization code, this can be used as extra security. The code has also to be set in the EA's
Returns:
bool: True or False
"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setblocking(1)
self.port = port
self.server = server
self.instrument_conversion_list = instrument_lookup
self.authorization_code = authorization_code
if (len(self.instrument_conversion_list) == 0):
print('Broker Instrument list not available or empty')
self.socket_error_message = 'Broker Instrument list not available'
return False
try:
self.sock.connect((self.server, self.port))
try:
data_received = self.sock.recv(1000000)
self.connected = True
self.socket_error = 0
self.socket_error_message = ''
return True
except socket.error as msg:
self.socket_error = 100
self.socket_error_message = 'Could not connect to server.'
self.connected = False
return False
except socket.error as msg:
print(
"Couldnt connect with the socket-server: %self.sock\n terminating program" %
msg)
self.connected = False
self.socket_error = 101
self.socket_error_message = 'Could not connect to server.'
return False
def Check_connection(self) -> bool:
"""
Checks if connection with MT terminal/Ea bot is still active.
Args:
None
Returns:
bool: True or False
"""
self.command = 'F000^1^'
self.command_return_error = ''
ok, dataString = self.send_command(self.command)
try:
if (ok == False):
self.command_OK = False
return False
x = dataString.split('^')
if x[1] == 'OK':
self.timeout = True
self.command_OK = True
return True
else:
self.timeout = False
self.command_return_error = ERROR_DICT['99900']
self.command_OK = True
return False
except:
self.command_return_error = ERROR_DICT['00001']
self.command_OK = False
return False
@property
def IsConnected(self) -> bool:
"""Returns connection status.
Returns:
bool: True or False
"""
return self.connected
def Get_static_account_info(self) -> dict:
"""
Retrieves static account information.
Returns: Dictionary with:
Account name,
Account number,
Account currency,
Account type,
Account leverage,
Account trading allowed,
Account maximum number of pending orders,
Account margin call percentage,
Account close open trades margin percentage
Account company
"""
self.command_return_error = ''
ok, dataString = self.send_command('F001^1^')
if (ok == False):
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F001':
self.command_return_error = ERROR_DICT['99900']
self.command_OK = False
return None
returnDict = {}
del x[0:2]
x.pop(-1)
returnDict['name'] = str(x[0])
returnDict['login'] = str(x[1])
returnDict['currency'] = str(x[2])
returnDict['type'] = str(x[3])
returnDict['leverage'] = int(x[4])
returnDict['trade_allowed'] = bool(x[5])
returnDict['limit_orders'] = int(x[6])
returnDict['margin_call'] = float(x[7])
returnDict['margin_close'] = float(x[8])
returnDict['company'] = str(x[9])
self.command_OK = True
return returnDict
def Get_dynamic_account_info(self) -> dict:
"""
Retrieves dynamic account information.
Returns: Dictionary with:
Account balance,
Account equity,
Account profit,
Account margin,
Account margin level,
Account margin free
"""
self.command_return_error = ''
ok, dataString = self.send_command('F002^1^')
if (ok == False):
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F002':
self.command_return_error = ERROR_DICT['99900']
self.command_OK = False
return None
returnDict = {}
del x[0:2]
x.pop(-1)
returnDict['balance'] = float(x[0])
returnDict['equity'] = float(x[1])
returnDict['profit'] = float(x[2])
returnDict['margin'] = float(x[3])
returnDict['margin_level'] = float(x[4])
returnDict['margin_free'] = float(x[5])
self.command_OK = True
return returnDict
def Check_license(self) -> bool:
"""
Check for license.
Returns:
bool: True or False. True=licensed, False=Demo
"""
self.license = 'Demo'
self.command = 'F006^1^'
self.command_return_error = ''
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F006':
self.command_return_error = ERROR_DICT['99901']
self.command_OK = False
return None
self.license = str(x[3])
if (self.license == 'Demo'):
return False
return True
def Check_trading_allowed(self,
instrument = 'EURUSD') -> bool:
"""
Check for trading allowed for specified symbol.
Returns:
bool: True or False. True=allowed, False=not allowed
"""
self.command = 'F008^2^' + instrument + '^'
self.command_return_error = ''
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F008':
self.command_return_error = ERROR_DICT['99901']
self.command_OK = False
return None
if (str(x[2]) == 'NOK'):
return False
return True
def Set_bar_date_asc_desc(self,
asc_desc: bool = False) -> bool:
"""
Sets first row of array as first bar or as last bar
In MT4/5 element[0] of an array is normaliter actual bar/candle
Depending on the math you want to apply, this has to be the opposite
Args:
asc_dec: True = row[0] is oldest bar
False = row[0] is latest bar
Returns:
bool: True or False
"""
self.invert_array = asc_desc
return True
def Get_PnL(self,
date_from: datetime = datetime(2021, 3, 1, tzinfo = pytz.timezone("Etc/UTC")),
date_to: datetime = datetime.now()) -> pd.DataFrame:
'''
Retrieves profit loss info.
Args:
date_from: start date
date_to: end date
Returns: Dictionary with:
realized_profit profit of all closed positions
unrealized_profit profit of all open positions
buy_profit profit of closed buy positions
sell_profit profit of closed sell positions
positions_in_profit number of profit positions
positions in loss number of loss positions
volume_in_profit total volume of positions in profit
volume_in_loss total volume of positions in loss
'''
total_profit = 0.0
buy_profit = 0.0
sell_profit = 0.0
trades_in_loss = 0
trades_in_profit = 0
volume_in_loss = 0.0
volume_in_profit = 0.0
commission_in_loss = 0.0
commission_in_profit = 0.0
swap_in_loss = 0.0
swap_in_profit = 0.0
unrealized_profit = 0.0
# retrieve closed positions
closed_positions = self.Get_closed_positions_within_window(date_from, date_to)
if type(closed_positions) == pd.DataFrame:
for position in closed_positions.itertuples():
profit = position.profit + position.commission + position.swap
total_profit = total_profit + profit
if (profit > 0.0):
trades_in_profit = trades_in_profit + 1
volume_in_profit = volume_in_profit + position.volume
commission_in_profit = commission_in_profit + position.commission
swap_in_profit = swap_in_profit + position.swap
else:
trades_in_loss = trades_in_loss + 1
volume_in_loss = volume_in_loss + position.volume
commission_in_loss = commission_in_loss + position.commission
swap_in_loss = swap_in_loss + position.swap
if (position.position_type == 'sell'):
sell_profit = sell_profit + profit
if (position.position_type == 'buy'):
buy_profit = buy_profit + profit
# retrieve dynamic account info
dynamic_info = self.Get_dynamic_account_info()
unrealized_profit = dynamic_info['equity'] - dynamic_info['balance']
result = {}
result['realized_profit'] = total_profit
result['unrealized_profit'] = unrealized_profit
result['buy_profit'] = buy_profit
result['sell_profit'] = sell_profit
result['positions_in_profit'] = trades_in_profit
result['positions_in_loss'] = trades_in_loss
result['volume_in_profit'] = volume_in_profit
result['volume_in_loss'] = volume_in_loss
return result
else:
return pd.DataFrame()
def Get_instrument_info(self,
instrument: str = 'EURUSD') -> dict:
"""
Retrieves instrument information.
Args:
instrument: instrument name
Returns: Dictionary with:
instrument,
digits,
max_lotsize,
min_lotsize,
lot_step,
point,
tick_size,
tick_value
swap_long
swap_short
stop_level for sl and tp distance
"""
self.command_return_error = ''
self.instrument_name_universal = instrument.upper()
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
if (self.instrument == 'none' or self.instrument == None):
self.command_return_error = 'Instrument not in broker list'
self.command_OK = False
return None
self.command = 'F003^2^' + self.instrument + '^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F003':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return None
returnDict = {}
del x[0:2]
x.pop(-1)
returnDict['instrument'] = str(self.instrument_name_universal)
returnDict['digits'] = int(x[0])
returnDict['max_lotsize'] = float(x[1])
returnDict['min_lotsize'] = float(x[2])
returnDict['lot_step'] = float(x[3])
returnDict['point'] = float(x[4])
returnDict['tick_size'] = float(x[5])
returnDict['tick_value'] = float(x[6])
returnDict['swap_long'] = float(x[7])
returnDict['swap_short'] = float(x[8])
returnDict['stop_level'] = int(x[9])
self.command_OK = True
return returnDict
def Check_instrument(self,
instrument: str = 'EURUSD') -> str:
"""
Check if instrument known / market watch at broker.
Args:
instrument: instrument name
Returns:
bool: True or False
"""
self.instrument_name_universal = instrument.upper()
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
if (self.instrument == 'none' or self.instrument == None):
self.command_return_error = 'Instrument not in list'
self.command_OK = False
return None
self.command = 'F004^2^' + self.instrument + '^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return False, 'Error'
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F004':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return False, str(x[2])
return True, str(x[2])
def Get_instruments(self) ->list:
"""
Retrieves broker market instruments list.
Args:
None
Returns:
List: All market symbols as universal instrument names
"""
self.command_return_error = ''
self.command = 'F007^2^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
# analyze the answer
return_list = []
x = dataString.split('^')
if x[0] != 'F007':
self.command_return_error = ERROR_DICT[x[3]]
self.command_OK = False
return return_list
del x[0:2]
x.pop(-1)
for item in range(0, len(x)):
_instrument = str(x[item])
instrument = self.get_universal_instrument_name(_instrument)
if (instrument != None):
return_list.append(instrument)
return return_list
def Get_broker_server_time(self) -> datetime:
"""
Retrieves broker server time.
Args:
None
Returns:
datetime: Boker time
"""
self.command_return_error = ''
self.command = 'F005^1^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F005':
self.command_return_error = ERROR_DICT[x[3]]
self.command_OK = False
return None
del x[0:2]
x.pop(-1)
y = x[0].split('-')
d = datetime(int(y[0]), int(y[1]), int(y[2]),
int(y[3]), int(y[4]), int(y[5]))
return d
def Get_last_tick_info(self,
instrument: str = 'EURUSD') -> dict:
"""
Retrieves instrument last tick data.
Args:
instrument: instrument name
Returns: Dictionary with:
instrument name,
date,
ask,
bid,
last deal price,
volume
spread, in points
date_in_ms
"""
self.command_return_error = ''
self.instrument_name_universal = instrument.upper()
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
if (self.instrument == 'none' or self.instrument == None):
self.command_return_error = 'Instrument not in broker list'
self.command_OK = False
return None
ok, dataString = self.send_command('F020^2^' + self.instrument + '^')
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if x[0] != 'F020':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return None
returnDict = {}
del x[0:2]
x.pop(-1)
returnDict['instrument'] = str(self.instrument_name_universal)
returnDict['date'] = int(x[0])
returnDict['ask'] = float(x[1])
returnDict['bid'] = float(x[2])
returnDict['last'] = float(x[3])
returnDict['volume'] = int(x[4])
returnDict['spread'] = float(x[5])
returnDict['date_in_ms'] = int(x[6])
self.command_OK = True
return returnDict
def Get_last_x_ticks_from_now(self,
instrument: str = 'EURUSD',
nbrofticks: int = 2000) -> np.array:
"""
Retrieves last x ticks from an instrument.
Args:
instrument: instrument name
nbrofticks: number of ticks to retriev
Returns: numpy array with:
date,
ask,
bid,
last volume,
volume
"""
self.command_return_error = ''
self.instrument_name_universal = instrument.upper()
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
if (self.instrument == 'none' or self.instrument == None):
self.command_return_error = 'Instrument not in broker list'
self.command_OK = False
return None
self.nbrofticks = nbrofticks
dt = np.dtype([('date', np.int64), ('ask', np.float64), ('bid', np.float64), ('last', np.float64), ('volume', np.int32)])
ticks = np.zeros(nbrofticks, dtype=dt)
if (self.nbrofticks > self.max_ticks):
iloop = self.nbrofticks // self.max_ticks
itail = self.nbrofticks % self.max_ticks
for index in range(0, iloop):
self.command = 'F021^4^' + self.instrument + '^' + str(index * self.max_ticks) + '^' + str(self.max_ticks) + '^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
print('')
print(len(dataString))
x = dataString.split('^')
if str(x[0]) != 'F021':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return None
del x[0:2]
x.pop(-1)
for value in range(0, len(x)):
y = x[value].split('$')
ticks[value + index * self.max_ticks][0] = int(y[0])
ticks[value + index * self.max_ticks][1] = float(y[1])
ticks[value + index * self.max_ticks][2] = float(y[2])
ticks[value + index * self.max_ticks][3] = float(y[3])
ticks[value + index * self.max_ticks][4] = int(y[4])
if (len(x) < self.max_ticks):
ticks = np.sort(ticks[ticks[:]['date']!=0])
self.command_OK = True
if (self.invert_array == True):
ticks = np.flipud(ticks)
return ticks
if (itail == 0):
ticks = np.sort(ticks[ticks[:]['date']!=0])
self.command_OK = True
return ticks
if (itail > 0):
self.command = 'F021^4^' + self.instrument + '^' + str(iloop * self.max_ticks) + '^' + str(itail) + '^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
print('')
print(len(dataString))
x = dataString.split('^')
if str(x[0]) != 'F021':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return None
del x[0:2]
x.pop(-1)
for value in range(0, len(x)):
y = x[value].split('$')
ticks[value + iloop * self.max_ticks][0] = int(y[0])
ticks[value + iloop * self.max_ticks][1] = float(y[1])
ticks[value + iloop * self.max_ticks][2] = float(y[2])
ticks[value + iloop * self.max_ticks][3] = float(y[3])
ticks[value + iloop * self.max_ticks][4] = int(y[4])
self.command_OK = True
ticks = np.sort(ticks[ticks[:]['date']!=0])
if (self.invert_array == True):
ticks = np.flipud(ticks)
return ticks
else:
self.command = 'F021^4^' + self.instrument + '^' + str(0) + '^' + str(self.nbrofticks) + '^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
print('')
print(len(dataString))
x = dataString.split('^')
if str(x[0]) != 'F021':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return None
del x[0:2]
x.pop(-1)
for value in range(0, len(x)):
y = x[value].split('$')
ticks[value][0] = int(y[0])
ticks[value][1] = float(y[1])
ticks[value][2] = float(y[2])
ticks[value][3] = float(y[3])
ticks[value][4] = int(y[4])
self.command_OK = True
ticks = np.sort(ticks[ticks[:]['date']!=0])
if (self.invert_array == True):
ticks = np.flipud(ticks)
#return ticks
return ticks[:len(x)]
def Get_actual_bar_info(self,
instrument: str = 'EURUSD',
timeframe: int = 16408) -> dict:
"""
Retrieves instrument last actual data.
Args:
instrument: instrument name
timeframe: time frame like H1, H4
Returns: Dictionary with:
instrument name,
date,
open,
high,
low,
close,
volume,
"""
self.command_return_error = ''
self.instrument_name_universal = instrument.upper()
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
if (self.instrument == 'none' or self.instrument == None):
self.command_return_error = 'Instrument not in broker list'
self.command_OK = False
return None
self.command = 'F041^3^' + self.instrument + '^' + str(timeframe) + '^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if str(x[0]) != 'F041':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return None
del x[0:2]
x.pop(-1)
returnDict = {}
returnDict['instrument'] = str(self.instrument_name_universal)
returnDict['date'] = int(x[0])
returnDict['open'] = float(x[1])
returnDict['high'] = float(x[2])
returnDict['low'] = float(x[3])
returnDict['close'] = float(x[4])
returnDict['volume'] = int(x[5])
self.command_OK = True
return returnDict
def Get_specific_bar(self,
instrument_list: list = ['EURUSD', 'GBPUSD'],
specific_bar_index: int = 1,
timeframe: int = 16408) -> dict:
"""
Retrieves instrument data(d, o, h, l, c, v) of one bar(index) for the instruments in the list.
Args:
instrument: instrument name
specific_bar_index: the specific bar (0 = actual bar)
timeframe: time frame like H1, H4
Returns: Dictionary with: {instrument:{instrument data}}
instrument name,
[date,
open,
high,
low,
close,
volume]
"""
self.command_return_error = ''
# compose MT5 command string
self.command = 'F045^3^'
for index in range (0, len(instrument_list), 1):
_instr = self.get_broker_instrument_name(instrument_list[index].upper())
if (self.instrument == 'none' or self.instrument == None):
self.command_return_error = 'Instrument not in broker list'
self.command_OK = False
return None
self.command = self.command + _instr + '$'
self.command = self.command + '^' + str(specific_bar_index) + '^' + str(timeframe) + '^'
ok, dataString = self.send_command(self.command)
if not ok:
self.command_OK = False
return None
if self.debug:
print(dataString)
x = dataString.split('^')
if str(x[0]) != 'F045':
self.command_return_error = str(x[2])
self.command_OK = False
return None
del x[0:2]
x.pop(-1)
result = {}
for value in range(0, len(x)):
y = x[value].split('$')
symbol_result = {}
symbol = str(y[0])
symbol_result['date'] = int(y[1])
symbol_result['open'] = float(y[2])
symbol_result['high'] = float(y[3])