-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathPytrader_API_V4_01.py
3149 lines (2608 loc) · 109 KB
/
Pytrader_API_V4_01.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_02
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['01101'] = 'Undefined check terminal connection error'
ERROR_DICT['01201'] = 'Undefined check MT type error'
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['02002'] = 'Unknown instrument for broker'
ERROR_DICT['02003'] = 'Unknown instrument for broker'
ERROR_DICT['02004'] = 'Time out error'
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 / placing order'
ERROR_DICT['07011'] = 'Netting account, no opposite orders allowed'
ERROR_DICT['07101'] = 'Trading not allowed'
ERROR_DICT['07102'] = 'Position not found'
ERROR_DICT['07201'] = 'Trading not allowed'
ERROR_DICT['07202'] = 'Position not found'
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['07401'] = 'Trading not allowed, check MT terminal settings'
ERROR_DICT['07402'] = 'Error check number'
ERROR_DICT['07403'] = 'Position not found'
ERROR_DICT['07404'] = 'Opposite position not found'
ERROR_DICT['07405'] = 'Both position of same type'
ERROR_DICT['07501'] = 'Trading not allowed'
ERROR_DICT['07502'] = 'Position not found'
ERROR_DICT['07503'] = 'Invalid SL value'
ERROR_DICT['07504'] = 'Invalid TP value'
ERROR_DICT['07505'] = 'Probably SL or TP new value equals old value'
ERROR_DICT['07601'] = 'Trading not allowed'
ERROR_DICT['07602'] = 'Order not found'
ERROR_DICT['07603'] = 'Invalid SL value'
ERROR_DICT['07604'] = 'Invalid TP value'
ERROR_DICT['07605'] = 'Probably SL or TP new value equals old value'
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 not found'
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):
"""
Initialize the Pytrader_API object.
Attributes:
socket_error (int): the error code for socket errors
socket_error_message (str): the error message for socket errors
order_return_message (str): the return message for orders
order_error (int): the error code for order errors
connected (bool): if the socket connection is established
timeout (bool): if the socket connection timed out
command_OK (bool): if the last command was OK
command_return_error (str): the error message for the last command
debug (bool): if debug mode is on
version (str): the version of the API
max_bars (int): the maximum number of bars that can be retrieved
max_ticks (int): the maximum number of ticks that can be retrieved
timeout_value (int): the time out value for socket communication
instrument_conversion_list (dict): a dictionary with the instrument conversion list
instrument_name_broker (str): the name of the instrument in the broker
instrument_name_universal (str): the name of the instrument in the universal API
date_from (datetime): the start date for retrieving data
date_to (datetime): the end date for retrieving data
instrument (str): the name of the instrument
license (str): the license type
invert_array (bool): if the array should be inverted
authorization_code (str): the authorization code
"""
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 = 'V4.01ca'
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
):
"""
Sets the timeout value for socket communication with an MT4 or MT5 EA/Bot.
Args:
timeout_in_seconds (int): The timeout duration in seconds.
Returns:
None
"""
# Store the timeout value
self.timeout_value = timeout_in_seconds
# Set the socket's timeout to the specified value
self.sock.settimeout(self.timeout_value)
# Set the socket to blocking mode
self.sock.setblocking(1)
return
def Disconnect(self):
"""
Closes the socket connection to a MT4 or MT5 EA bot.
This method closes the socket connection to a MT4 or MT5 EA bot.
After this method is called, the socket connection is closed and the
connection status is set to False.
Args:
None
Returns:
bool: True if the connection is closed, False otherwise
"""
# Close the socket connection
self.sock.close()
# Set the connection status to False
self.connected = False
# Return True if the connection is closed
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.
This method connects to a MT4 or MT5 EA/Bot. The connection is
established by creating a socket object and connecting to the
specified server and port. The method returns True if the
connection is established, False otherwise.
Args:
server (str): The server IP address, like -> '127.0.0.1', '192.168.5.1'
port (int): The port number
instrument_lookup (dict): A dictionairy with general instrument names and broker intrument names
authorization_code (str): The 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
"""
# Create a socket object
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set the socket to blocking mode
self.sock.setblocking(1)
# Store the port number
self.port = port
# Store the server IP address
self.server = server
# Store the instrument conversion list
self.instrument_conversion_list = instrument_lookup
# Store the authorization code
self.authorization_code = authorization_code
# Check if the instrument conversion list is empty
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:
# Connect to the server
self.sock.connect((self.server, self.port))
try:
# Receive data from the server
data_received = self.sock.recv(1000000)
# Set the connection status to True
self.connected = True
# Set the socket error to 0
self.socket_error = 0
# Set the socket error message to empty
self.socket_error_message = ''
# Return True if the connection is established
return True
except socket.error as msg:
# Set the socket error to 100 if the connection could not be established
self.socket_error = 100
# Set the socket error message
self.socket_error_message = 'Could not connect to server.'
# Set the connection status to False
self.connected = False
# Return False if the connection could not be established
return False
except socket.error as msg:
# Print an error message if the connection could not be established
print(
"Couldnt connect with the socket-server: %self.sock\n terminating program" %
msg)
# Set the connection status to False
self.connected = False
# Set the socket error to 101
self.socket_error = 101
# Set the socket error message
self.socket_error_message = 'Could not connect to server.'
# Return False if the connection could not be established
return False
def Check_connection(self) -> bool:
"""
Checks if connection with MT terminal/Ea bot is still active.
This function can be used to check if the connection with the EA is still active.
Args:
None
Returns:
bool: True if connection is active, False otherwise
"""
# Set the command to check if the connection with the MT terminal/Ea bot is still active
self.command = 'F000^1^'
# Initialize the command return error
self.command_return_error = ''
# Send the command to the EA
ok, dataString = self.send_command(self.command)
try:
# Check if the command is OK
if (ok == False):
# If the command is not OK, set the command_OK to False and return False
self.command_OK = False
return False
# Split the data received into parts
x = dataString.split('^')
# Check if the connection is active
if x[1] == 'OK':
# If the connection is active, set the timeout to False, set the command_OK to True and return True
self.timeout = False
self.command_OK = True
return True
else:
# If the connection is not active, set the timeout to True, set the error message and return False
self.timeout = True
self.command_return_error = ERROR_DICT['99900']
self.command_OK = True
return False
except:
# If an error occurs, set the error message, set the command_OK to False and return False
self.command_return_error = ERROR_DICT['00001']
self.command_OK = False
return False
def Check_terminal_server_connection(self) -> bool:
"""
Checks if MT4/5 terminal connected to broker.
This function checks if the MT4/5 terminal is connected to the broker.
Args:
None
Returns:
bool: True if connected, False otherwise
"""
# Set the command to check if the terminal is connected to the broker
self.command = 'F011^1^'
# Initialize the command return error
self.command_return_error = ''
# Send the command to the EA
ok, dataString = self.send_command(self.command)
try:
# Check if the command is OK
if (ok == False):
# If the command is not OK, set the command_OK to False and return False
self.command_OK = False
return False
# Split the data received into parts
x = dataString.split('^')
# Check if the terminal is connected to the broker
if x[2] == 'OK':
# If the terminal is connected, set the timeout to False and return True
self.timeout = False
self.command_OK = True
return True
else:
# If the terminal is not connected, set the timeout to False, set the error message and return False
self.timeout = False
self.command_return_error = ERROR_DICT['99900']
self.command_OK = True
return False
except:
# If an error occurs, set the error message and return False
self.command_return_error = ERROR_DICT['01101']
self.command_OK = False
return False
def Check_terminal_type(self) -> str:
"""
Checks for MT4 or MT5 terminal.
This function will check whether the terminal is MT4 or MT5.
Args:
None
Returns:
string: if function for MT4 terminal answer would be 'MT4', for MT5 terminal 'MT5'
"""
# Set the command to check the terminal type
self.command = 'F012^1^'
# Initialize the command return error
self.command_return_error = ''
# Send the command to the EA
ok, dataString = self.send_command(self.command)
try:
# Check if the command is OK
if (ok == False):
# If the command is not OK, set the command_OK to False and return False
self.command_OK = False
return False
# Split the data received into parts
x = dataString.split('^')
# Check if the terminal is MT4 or MT5
if x[3] == 'MT4':
# If the terminal is MT4, set the timeout to False and return 'MT4'
self.timeout = False
self.command_OK = True
return 'MT4'
elif x[3] == 'MT5':
# If the terminal is MT5, set the timeout to False and return 'MT5'
self.timeout = False
self.command_OK = True
return 'MT5'
else:
# If the terminal type is unknown, set the timeout to False, set the error message and return False
self.timeout = False
self.command_return_error = ERROR_DICT['99900']
self.command_OK = True
return False
except:
# If an error occurs, set the error message and return False
self.command_return_error = ERROR_DICT['01201']
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 from MetaTrader 5.
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
If the command fails, returns None.
"""
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
# Create a dictionary to store the information
returnDict = {}
del x[0:2]
x.pop(-1)
# Add the information to the dictionary
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
"""
# Reset the command return error
self.command_return_error = ''
# Send the command
ok, dataString = self.send_command('F002^1^')
if (ok == False):
# If the command fails, set the command_OK flag to False
self.command_OK = False
return None
if self.debug:
# Print the data string if in debug mode
print(dataString)
# Split the data string
x = dataString.split('^')
if x[0] != 'F002':
# If the command fails, set the command return error
self.command_return_error = ERROR_DICT['99900']
self.command_OK = False
return None
# Create a dictionary to store the information
returnDict = {}
# Delete the first two elements of the list and the last element
del x[0:2]
x.pop(-1)
# Add the information to the dictionary
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])
# Set the command_OK flag to True
self.command_OK = True
# Return the dictionary
return returnDict
def Check_license(self) -> bool:
"""
Checks for a valid license.
This function sends a command to check the license status and returns
whether the license is valid or if it's a demo.
Returns:
bool: True if licensed, False if Demo.
"""
# Set initial license status to 'Demo'
self.license = 'Demo'
# Create the command to check the license
self.command = 'F006^1^'
# Initialize the command return error
self.command_return_error = ''
# Send the command to check the license
ok, dataString = self.send_command(self.command)
# If the command fails, set command_OK to False and return None
if not ok:
self.command_OK = False
return None
# Print the data string if in debug mode
if self.debug:
print(dataString)
# Split the data string into components
x = dataString.split('^')
# Verify the command response
if x[0] != 'F006':
# Set error message and command_OK flag if response is incorrect
self.command_return_error = ERROR_DICT['99901']
self.command_OK = False
return None
# Update license status based on response
self.license = str(x[3])
# Return False if license is 'Demo', otherwise return True
if self.license == 'Demo':
return False
return True
def Check_trading_allowed(self,
instrument: str = 'EURUSD') -> bool:
"""
Check for trading allowed for specified symbol.
Args:
instrument: Instrument to check
Returns:
bool: True or False. True=allowed, False=not allowed
"""
# Get the broker instrument name
self.instrument_name_universal = instrument.upper()
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
# Create the command to check for trading allowed
self.command = 'F008^2^' + self.instrument + '^'
# Initialize the command return error
self.command_return_error = ''
# Send the command to check for trading allowed
ok, dataString = self.send_command(self.command)
# If the command fails, set command_OK to False and return None
if not ok:
self.command_OK = False
return None
# Print the data string if in debug mode
if self.debug:
print(dataString)
# Split the data string into components
x = dataString.split('^')
# Verify the command response
if x[0] != 'F008':
# Set error message and command_OK flag if response is incorrect
self.command_return_error = ERROR_DICT['99901']
self.command_OK = False
return None
# Return False if trading is not allowed, otherwise return True
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 normally the 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
"""
# Set the invert_array attribute to the passed value
self.invert_array = asc_desc
# Return True to indicate success
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 (datetime): start date
date_to (datetime): end date
Returns:
pd.DataFrame: DataFrame 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 pd.DataFrame([result])
else:
return pd.DataFrame()
def Get_instrument_info(self,
instrument: str = 'EURUSD') -> dict:
"""
Retrieves instrument information.
Args:
instrument (str): instrument name
Returns:
dict: Dictionary with:
instrument (str): instrument name
digits (int): number of decimal places
max_lotsize (float): maximum lot size
min_lotsize (float): minimum lot size
lot_step (float): step size for lot size
point (float): point value
tick_size (float): tick size
tick_value (float): tick value
swap_long (float): swap value for long positions
swap_short (float): swap value for short positions
stop_level (int): stop level for SL and TP distance
contract_size (float): contract size
"""
# Initialize the command return error
self.command_return_error = ''
# Convert the instrument name to uppercase and get the broker instrument name
self.instrument_name_universal = instrument.upper()
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
# Check if the instrument is in the broker list
if (self.instrument == 'none' or self.instrument is None):
self.command_return_error = 'Instrument not in broker list'
self.command_OK = False
return None
# Create the command to retrieve instrument info
self.command = 'F003^2^' + self.instrument + '^'
# Send the command and get the response
ok, dataString = self.send_command(self.command)
# If the command fails, set command_OK to False and return None
if not ok:
self.command_OK = False
return None
# Print the data string if in debug mode
if self.debug:
print(dataString)
# Split the data string into components
x = dataString.split('^')
# Verify the command response
if x[0] != 'F003':
self.command_return_error = ERROR_DICT[str(x[3])]
self.command_OK = False
return None
# Create a dictionary to store the results
returnDict = {}
del x[0:2] # Remove command identifier and redundant info
x.pop(-1) # Remove trailing empty element
# Populate the dictionary with instrument information
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])
returnDict['contract_size'] = float(x[10])
# Set the command_OK flag to True
self.command_OK = True
# Return the dictionary with instrument information
return returnDict
def Check_instrument(self,
instrument: str = 'EURUSD') -> str:
"""
Check if instrument known / market watch at broker.
Args:
instrument: instrument name
Returns:
tuple: (bool, str)
"""
# Set the instrument name to the universal name
self.instrument_name_universal = instrument.upper()
# Map the instrument name to the broker instrument name
self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)
# If the instrument is not in the broker list
if (self.instrument == 'none' or self.instrument == None):
# Set the error message
self.command_return_error = 'Instrument not in list'
# Set the command status to False
self.command_OK = False
# Return False and the error message
return False, 'Instrument not in list'
# Build the command string
self.command = 'F004^2^' + self.instrument + '^'
# Send the command and get the response
ok, dataString = self.send_command(self.command)
# If something went wrong
if not ok:
# Set the command status to False
self.command_OK = False
# Return False and the error message
return False, 'Error'
# If the debug flag is set
if self.debug:
# Print the response string
print(dataString)
# Split the response string into a list
x = dataString.split('^')
# If the command was not successful
if x[0] != 'F004':
# Set the error message
self.command_return_error = ERROR_DICT[str(x[3])]
# Set the command status to False
self.command_OK = False
# Return False and the error message
return False, str(x[2])
# Everything went well
# Return True and the result
return True, str(x[2])
def Get_instruments(self) ->list:
"""
Retrieves broker market instruments list, filtered by instrument list.
Args:
None
Returns:
List: All market symbols as universal instrument names
"""
self.command_return_error = ''
# Build the command string
self.command = 'F007^2^'
# Send the command and get the response
ok, dataString = self.send_command(self.command)
# If something went wrong
if not ok:
# Set the command status to False
self.command_OK = False
# Return None
return None
# If the debug flag is set
if self.debug:
# Print the response string
print(dataString)
return_list = []
# Split the response string into a list
x = dataString.split('^')
# If the command was not successful
if x[0] != 'F007':
# Set the error message
self.command_return_error = ERROR_DICT[x[3]]
# Set the command status to False
self.command_OK = False
# Return None
return return_list
# Remove the first two items, which are the command and the result
del x[0:2]
# Remove the last item, which is the end of the string
x.pop(-1)
# Loop through the list
for item in range(0, len(x)):
# Get the instrument name
_instrument = str(x[item])
# Get the universal instrument name
instrument = self.get_universal_instrument_name(_instrument)
# If the universal instrument name is valid
if (instrument != None):
# Add it to the list
return_list.append(instrument)
# Return the list
return return_list
def Get_broker_instrument_names(self) -> list:
"""
Retrieves broker instrument names in Market Watch, so not the universal names.
Returns:
List: All market symbols as broker instrument names in Market Watch
"""