/
GetDataFromMt5.py
162 lines (141 loc) · 5.26 KB
/
GetDataFromMt5.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
import MetaTrader5 as mt5
from datetime import datetime
import pandas as pd
import time
import schedule
import pytz
import talib as ta
import numpy as np
def connect(account):
account = int(account)
mt5.initialize()
authorized=mt5.login(account)
if authorized:
print("Connected: Connecting to MT5 Client")
else:
print("Failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))
def open_position(pair, order_type, size, tp_distance=None, stop_distance=None):
symbol_info = mt5.symbol_info(pair)
if symbol_info is None:
print(f"{pair} not found")
return
if not symbol_info.visible:
print(f"{pair} is not visible, trying to switch on")
if not mt5.symbol_select(pair, True):
print(f"symbol_select({pair}) failed, exit")
return
print(f"{pair} found!")
point = symbol_info.point
volume_step = symbol_info.volume_step
if(order_type == "BUY"):
order = mt5.ORDER_TYPE_BUY
price = mt5.symbol_info_tick(pair).ask
if (stop_distance):
sl = price - (stop_distance * point)
if(tp_distance):
tp = price + (tp_distance * point)
if(order_type == "SELL"):
order = mt5.ORDER_TYPE_SELL
price = mt5.symbol_info_tick(pair).bid
if (stop_distance):
sl = price + (stop_distance * point)
if(tp_distance):
tp = price - (tp_distance * point)
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": pair,
"volume": float(size),
"type": order,
"price": price,
"sl": sl,
"tp": tp,
"magic": 234000,
"comment": "",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print("Failed to send order :(")
else:
print("Order successfully placed!")
def positions_get(symbol=None):
if(symbol is None):
res = mt5.positions_get()
else:
res = mt5.positions_get(symbol=symbol)
if(res is not None and res != ()):
df = pd.DataFrame(list(res), columns=res[0]._asdict().keys())
df["time"] = pd.to_datetime(df["time"], unit="s")
return df
return pd.DataFrame()
def close_position(deal_id):
open_positions = positions_get()
open_positions = open_positions[open_positions["ticket"] == deal_id]
order_type = open_positions["type"][0]
symbol = open_positions["symbol"][0]
volume = open_positions["volume"][0]
if(order_type == mt5.ORDER_TYPE_BUY):
order_type = mt5.ORDER_TYPE_SELL
price = mt5.symbol_info_tick(symbol).bid
else:
order_type = mt5.ORDER_TYPE_BUY
price = mt5.symbol_info_tick(symbol).ask
close_request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": float(volume),
"type": order_type,
"position": deal_id,
"price": price,
"magic": 234000,
"comment": "Close trade",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(close_request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print("Failed to close order :(")
else:
print("Order successfully closed!")
def close_positions_by_symbol(symbol):
open_positions = positions_get(symbol)
open_positions["ticket"].apply(lambda x: close_position(x))
def live_trading():
schedule.every().hour.at(":00").do(run_trader, mt5.TIMEFRAME_M15)
schedule.every().hour.at(":15").do(run_trader, mt5.TIMEFRAME_M15)
schedule.every().hour.at(":30").do(run_trader, mt5.TIMEFRAME_M15)
schedule.every().hour.at(":45").do(run_trader, mt5.TIMEFRAME_M15)
while True:
schedule.run_pending()
time.sleep(1)
def run_trader(time_frame):
print(f"Running trader at {datetime.now()}")
connect(41464506)
pair_data = get_data(time_frame)
check_trades(time_frame, pair_data)
def get_data(time_frame):
pairs = ["EURUSD", "USDCAD"]
pair_data = dict()
for pair in pairs:
utc_from = datetime(2021, 1, 1, tzinfo=pytz.timezone('Europe/Athens'))
date_to = datetime.now().astimezone(pytz.timezone("Europe/Athens"))
date_to = datetime(date_to.year, date_to.month, date_to.day, hour=date_to.hour, minute=date_to.minute)
rates = mt5.copy_rates_range(pair, time_frame, utc_from, date_to)
rates_frame = pd.DataFrame(rates, columns = ['time', 'open', 'high', 'low', 'close', 'tick_volume', 'spread', 'real_volume'])
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
rates_frame.drop(rates_frame.tail(1).index, inplace = True)
pair_data[pair] = rates_frame
print(pair_data[pair])
return pair_data
def check_trades(time_frame, pair_data):
for pair, data in pair_data.items():
data["SMA"] = ta.SMA(data["close"], 10)
data["EMA"] = ta.EMA(data["close"], 50)
last_row = data.tail(1)
for index, last in last_row.iterrows():
if(last["close"] > last["EMA"] and last["close"] < last["SMA"]):
open_position(pair, "BUY", 1, 300, 100)
if __name__ == "__main__":
#live_trading()
run_trader(mt5.TIMEFRAME_M15)