I followed Metatrader5 python documentation and this answer in stack overflow
I try to open a sell position:
JavaScriptx79791import MetaTrader5 as mt5
2
3
4ea_magic_number = 9986989 # if you want to give every bot a unique identifier
5
6def get_info(symbol):
7'''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5symbolinfo_py
8'''
9# get symbol properties
10info=mt5.symbol_info(symbol)
11return info
12
13def open_trade(action, symbol, lot, sl_points, tp_points, deviation):
14'''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py
15'''
16# prepare the buy request structure
17symbol_info = get_info(symbol)
18
19if action == 'buy':
20trade_type = mt5.ORDER_TYPE_BUY
21price = mt5.symbol_info_tick(symbol).ask
22elif action =='sell':
23trade_type = mt5.ORDER_TYPE_SELL
24price = mt5.symbol_info_tick(symbol).bid
25point = mt5.symbol_info(symbol).point
26
27buy_request = {
28"action": mt5.TRADE_ACTION_DEAL,
29"symbol": symbol,
30"volume": lot,
31"type": trade_type,
32"price": price,
33"sl": price - sl_points * point,
34"tp": price + tp_points * point,
35"deviation": deviation,
36"magic": ea_magic_number,
37"comment": "sent by python",
38"type_time": mt5.ORDER_TIME_GTC, # good till cancelled
39"type_filling": mt5.ORDER_FILLING_RETURN,
40}
41# send a trading request
42result = mt5.order_send(buy_request)
43return result, buy_request
44
45def close_trade(action, buy_request, result, deviation):
46'''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py
47'''
48# create a close request
49symbol = buy_request['symbol']
50if action == 'buy':
51trade_type = mt5.ORDER_TYPE_BUY
52price = mt5.symbol_info_tick(symbol).ask
53elif action =='sell':
54trade_type = mt5.ORDER_TYPE_SELL
55price = mt5.symbol_info_tick(symbol).bid
56position_id=result.order
57lot = buy_request['volume']
58
59close_request={
60"action": mt5.TRADE_ACTION_DEAL,
61"symbol": symbol,
62"volume": lot,
63"type": mt5.ORDER_TYPE_SELL,
64"position": position_id,
65"price": price,
66"deviation": deviation,
67"magic": ea_magic_number,
68"comment": "python script close",
69"type_time": mt5.ORDER_TIME_GTC, # good till cancelled
70"type_filling": mt5.ORDER_FILLING_RETURN,
71}
72# send a close request
73result=mt5.order_send(close_request)
74
75
76# This is how I would execute the order
77result, buy_request = open_trade('buy', 'USDJPY', 0.1, 50, 50, 10)
78close_trade('sell', buy_request, result, 10)
79
Nothing happens and there is no reaction in applications terminal. I also check Trade and History section in Metatrader5 to find some related information but I find out nothing.
how can I monitor the logs in Metatrader5 to debug the code and resolve the problem?
Advertisement
Answer
In MetaTrader algo trading must be ON in order to make a buy/sell position.