-
Notifications
You must be signed in to change notification settings - Fork 398
/
Capitulo_09_MT5.py
219 lines (169 loc) · 6.9 KB
/
Capitulo_09_MT5.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
import warnings
from datetime import datetime
import pandas as pd
import MetaTrader5 as mt5
warnings.filterwarnings("ignore")
mt5.initialize()
class MT5:
def get_data(symbol, n, timeframe=mt5.TIMEFRAME_D1):
""" Función para importar los datos del símbolo elegido"""
# Inicializamos la conexión si no estaba activa
mt5.initialize()
# Current date extract
utc_from = datetime.now()
# Import the data into a tuple
rates = mt5.copy_rates_from(symbol, timeframe, utc_from, n)
# Tuple to dataframe
rates_frame = pd.DataFrame(rates)
# Convert time in seconds into the datetime format
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
# Convert the column "time" in the right format
rates_frame['time'] = pd.to_datetime(rates_frame['time'], format='%Y-%m-%d')
# Set column time as the index of the dataframe
rates_frame = rates_frame.set_index('time')
return rates_frame
def orders(symbol, lot, buy=True, id_position=None):
""" Enviamos las órdenes """
# Inicializamos la conexión si no estaba activa
if mt5.initialize() == False:
mt5.initialize()
# Get filling mode
filling_mode = mt5.symbol_info(symbol).filling_mode - 1
# Take ask price
ask_price = mt5.symbol_info_tick(symbol).ask
# Take bid price
bid_price = mt5.symbol_info_tick(symbol).bid
# Take the point of the asset
point = mt5.symbol_info(symbol).point
deviation = 20 # mt5.getSlippage(symbol)
# **************************** Open a trade *****************************
if id_position == None:
# Buy order Parameters
if buy:
type_trade = mt5.ORDER_TYPE_BUY
sl = ask_price*(1-0.01)
tp = ask_price*(1+0.01)
price = ask_price
# Sell order Parameters
else:
type_trade = mt5.ORDER_TYPE_SELL
sl = bid_price*(1+0.01)
tp = bid_price*(1-0.01)
price = bid_price
# Open the trade
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": type_trade,
"price": price,
"deviation": deviation,
"sl": sl,
"tp": tp,
"magic": 234000,
"comment": "python script order",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": filling_mode,
}
# send a trading request
result = mt5.order_send(request)
result_comment = result.comment
# **************************** Close a trade *****************************
else:
# Buy order Parameters
if buy:
type_trade = mt5.ORDER_TYPE_SELL
price = bid_price
# Sell order Parameters
else:
type_trade = mt5.ORDER_TYPE_BUY
price = ask_price
# Close the trade
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": type_trade,
"position": id_position,
"price": price,
"deviation": deviation,
"magic": 234000,
"comment": "python script order",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": filling_mode,
}
# send a trading request
result = mt5.order_send(request)
result_comment = result.comment
return result.comment
def resume():
""" Return the current positions. Position=0 --> Buy """
# Initialize the connection if there is not
mt5.initialize()
# Define the name of the columns that we will create
columns = ["ticket", "position", "symbol", "volume"]
# Go take the current open trades
current = mt5.positions_get()
# Create a empty dataframe
summary = pd.DataFrame()
# Loop to add each row in dataframe
# (Can be ameliorate using of list of list)
for element in current:
element_pandas = pd.DataFrame([element.ticket,
element.type,
element.symbol,
element.volume],
index=columns).transpose()
summary = pd.concat((summary, element_pandas), axis=0)
return summary
def run(symbol, long, short, lot):
# Inicializamos la conexión si no estaba activa
if mt5.initialize() == False:
mt5.initialize()
# Choose your symbol
print("------------------------------------------------------------------")
print("Date: ", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
print("SYMBOL:", symbol)
# Initialize the device
current_open_positions = MT5.resume()
# Buy or sell
print(f"BUY: {long} \t SHORT: {short}")
""" Close trade eventually """
# Extraction type trade
try:
position = current_open_positions.loc[current_open_positions["symbol"]==symbol].values[0][1]
identifier = current_open_positions.loc[current_open_positions["symbol"]==symbol].values[0][0]
except:
position= None
identifier = None
print(f"POSITION: {position} \t ID: {identifier}")
# Close trades
if long==True and position==0:
long=False
elif long==False and position==0:
res = MT5.orders(symbol, lot, buy=True, id_position=identifier)
print(f"CLOSE LONG TRADE: {res}")
elif short==True and position ==1:
short=False
elif short == False and position == 1:
res = MT5.orders(symbol, lot, buy=False, id_position=identifier)
print(f"CLOSE SHORT TRADE: {res}")
else:
pass
""" Buy or short """
if long==True:
res = MT5.orders(symbol, lot, buy=True, id_position=None)
print(f"OPEN LONG TRADE: {res}")
if short==True:
res = MT5.orders(symbol, lot, buy=False, id_position=None)
print(f"OPEN SHORT TRADE: {res}")
print("------------------------------------------------------------------")
def close_all_night():
result = MT5.resume()
for i in range(len(result)):
before = mt5.account_info().balance
row = result.iloc[0+i:1+i,:]
if row["position"][0]==0:
res = MT5.orders(row["symbol"][0], row["volume"][0], buy=True, id_position=row["ticket"][0])
else:
res = MT5.orders(row["symbol"][0], row["volume"][0], buy=False, id_position=row["ticket"][0])