-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBot.py
More file actions
245 lines (208 loc) · 8.4 KB
/
Bot.py
File metadata and controls
245 lines (208 loc) · 8.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
####################################################
#Import section#
####################################################
import MetaTrader5 as mt5
import matplotlib.pyplot as plt
from MoneyManagement_NauzerBalsara import RiskOfRuin as ror
import time
from datetime import datetime
# import pytz module for working with time zone
import pytz
# import the 'pandas' module for displaying data obtained in the tabular form
import pandas as pd
pd.set_option('display.max_columns', 500) # number of columns to be displayed
pd.set_option('display.width', 1500) # max table width to display
from statistics import stdev
import numpy as np
from Indicators import WilliamPercentageRange as WPR
####################################################
#Global Variables section#
####################################################
#constants
lotDimension=100000 #
#variables set at initialization
balance=0
oldBalance=0
leverage=0
rates=[]
last_time=0
#variables that must be set after backtesting
successProbability=0.33
historicalReturns=[0.00, - 1.20, - 7.50, 0.00, - 1.20, - 10.80, 0.00, - 1.20, 92.40, 0.00, - 1.20, - 28.50, 0.00, - 1.20, - 15.90, 0.00, - 1.20, - 5.40, 0.00, - 1.20, - 5.10, 0.00, - 1.20, 1.50, 0.00, - 1.20, - 20.85, 0.00, - 1.20, - 21.15, 0.00, - 1.20, - 25.05, 0.00, - 1.20, 117.60, 0.00, - 1.20, - 7.50, 0.00, - 1.20, 57.60, 0.00, - 1.20, - 9.00, 0.00, - 1.20, 67.80, 0.00, - 1.20, - 26.10, 0.00, - 1.20, - 30.15, 0.00, - 1.20, - 23.40, 0.00, - 1.20, 76.50, 0.00, - 1.20, 70.80, 0.00, - 1.20, - 28.80, 0.00, - 1.20, - 34.95, 0.00, - 1.20, 93.90, ]
#variables to be optimized
payoffRatio=2.5
lotSize=0.2
####################################################
#Generic Functions section#
####################################################
def InitializeMetaTrader5():
print("====================================================================================")
# establish MetaTrader 5 connection
if not mt5.initialize():
print("The initialization of MetaTrader5 failed, error code =",mt5.last_error())
quit()
#login data
account=***********
passwd="********"
tradingServer="AdmiralMarkets-Demo"
authorized=mt5.login(login=account, password=passwd, server=tradingServer)
if authorized:
# display trading account data in the form of a list
print("Show the account infos:")
account_info_dict = mt5.account_info()._asdict()
for prop in account_info_dict:
print(" {}={}".format(prop, account_info_dict[prop]))
else:
print("Failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))
quit()
print()
def DisplayTerminalInfos():
print("====================================================================================")
# display data on MetaTrader 5 version
print(mt5.version())
# display info on the terminal settings and status
terminal_info=mt5.terminal_info()
if terminal_info is not None:
terminal_info_dict = mt5.terminal_info()._asdict()
# # display data in the form of a list
# print("Show terminal_info()._asdict():")
# for prop in terminal_info_dict:
# print(" {}={}".format(prop, terminal_info_dict[prop]))
# print()
# convert the dictionary into DataFrame and print
df=pd.DataFrame(list(terminal_info_dict.items()),columns=['property','value'])
print("The terminal infos are :")
print(df)
else:
print("Failed to get the terminal infos, error code: {}".format(mt5.last_error()))
quit()
print()
def GetRates():
print("====================================================================================")
# get 10 EURUSD D1 bars from the current day
global rates
rates = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_M1, 0, 20)
if rates is not None:
# create DataFrame out of the obtained data
rates_frame = pd.DataFrame(rates)
# convert time in seconds into the datetime format
rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s')
# display data
print("\nDisplay dataframe with data")
print(rates_frame)
plt.plot(rates_frame['time'],rates['close'])
plt.ylabel('close price')
plt.xlabel('time')
plt.title('EURUSD last 10 close prices')
plt.show()
else:
print("Error on getting the rates, error code: {}".format(mt5.last_error()))
quit()
print()
def GetAccountBalance():
balance=mt5.account_info()._asdict()['balance']
if balance != 0:
print("The balance is {}.".format(balance))
else:
print("Error on getting the balance, error code: {}".format(mt5.last_error()))
return balance
def GetAccountLeverage():
leverage=mt5.account_info()._asdict()['leverage']
if leverage != 0:
print("The leverage is {}.".format(leverage))
else:
print("Error on getting the leverage, error code: {}".format(mt5.last_error()))
return leverage
def GetBuyPrice():
# display the last EURUSD tick
ask=mt5.symbol_info_tick("EURUSD")._asdict()['ask']
if ask != 0:
print("The ask is {}.".format(leverage))
else:
print("Error on getting the ask, error code: {}".format(mt5.last_error()))
return ask
return
####################################################
#Bot Functions section#
####################################################
def InitializeTheMoneyBot():
#initialize the comunication with MetaTrader5
InitializeMetaTrader5()
DisplayTerminalInfos()
#get the rates(Bars) from MetaTrader5
rates=GetRates()
#initialize other data
#1. balance
global balance
global oldBalance
balance=GetAccountBalance()
oldBalance=balance
#2. leverage
global leverage
leverage=GetAccountLeverage()
def CalculateMoneyManagementIndicators():
#Ask if I want to calculate:
#1. RiskOfRuin
answer=input("Calculate RiskOfRuin?(Y/N)")
if answer in ['Y','y']:
roundsOfTesting=100000
buyPrice=GetBuyPrice();
unitsOfCapital=(balance*leverage)/(lotSize*lotDimension*buyPrice)
print("The units of capital are {}.".format(unitsOfCapital))
riskOfRuin=ror.calculateRiskOfRuin(successProbability,payoffRatio,unitsOfCapital,roundsOfTesting)
print("The RiskOfRuin with the current strategy is {}.".format(riskOfRuin))
# #2. Volatility of historical returns
answer=input("Calculate Volatility of historical returns?(Y/N)")
if answer in ['Y','y']:
volatilityOfReturns=stdev(historicalReturns)
print("The Volatility of historical returns with the current strategy is {}.".format(volatilityOfReturns))
#3. Profitability index
answer=input("Profitability index?(Y/N)")
if answer in ['Y','y']:
profitabilityIndex=successProbability/(1-successProbability)*payoffRatio
if profitabilityIndex >= 2 and profitabilityIndex < 3 :
print("The Profitability index with the current strategy is {} and that is GOOD.".format(profitabilityIndex))
elif profitabilityIndex >= 3:
print("The Profitability index with the current strategy is {} and that is EXCELENT.".format(profitabilityIndex))
else :
print("The Profitability index with the current strategy is {} and that is BAD.".format(profitabilityIndex))
def isNewBar():
global last_time
global rates
lastbar=mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_M1, 0, 1)
#print(lastbar['time'])
if last_time == 0:
last_time=lastbar['time']
return False
if last_time<lastbar['time'] :
last_time=lastbar['time']
rates=np.append(rates,lastbar)
return True
return False
####################################################
#Main section#
####################################################
################
#Initialization#
################
InitializeTheMoneyBot()
#CalculateMoneyManagementIndicators()
######
#Loop#
######
while 1:
if isNewBar() :
print("New bar")
#Implement the strategy
positions_total=mt5.positions_total()
if positions_total != 0:
wpr=WPR.calculate(rates,14)
print("wpr={}".format(wpr))
input("Asteapta")
if positions_total == 0:
macd=MACD.calculate(rates,14,24,9)
#else:
#print("Old bar")
#time.sleep(30)
mt5.shutdown()
quit()