I'm new and am trying to build a python bot for MT5. i tried to send a trade in MT5 over python, however it always returns "None".
I've input all the required information, could it be because of decimal error?
import os
from datetime import datetime
import MetaTrader5 as mt5
import requests
import datetime as dt # for dealing with times
import numpy as np
import json
import pandas as pd
import pytz
ea_magic_number = 9986989 # if you want to give every bot a unique identifier
def open_trade(action, symbol, lot, sl_points, tp_points, deviation):
'''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py
'''
# prepare the buy request structure
symbol_info = mt5.symbol_info(symbol)
if action == 'buy':
trade_type = mt5.ORDER_TYPE_BUY
price = mt5.symbol_info_tick(symbol).ask
elif action =='sell':
trade_type = mt5.ORDER_TYPE_SELL
price = mt5.symbol_info_tick(symbol).bid
point = mt5.symbol_info(symbol).point
action_request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": trade_type,
"price": price,
"sl": round(price - sl_points * point,5),
"tp": price + tp_points * point,
"deviation": deviation,
"magic": ea_magic_number,
"comment": "sent by python",
"type_time": mt5.ORDER_TIME_GTC, # good till cancelled
"type_filling": mt5.ORDER_FILLING_RETURN
}
# send a trading request
result = mt5.order_send(action_request)
return result, action_request
def close_trade(action, action_request, result, deviation):
'''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py
'''
# create a close request
symbol = action_request['symbol']
if action == 'buy':
trade_type = mt5.ORDER_TYPE_BUY
price = mt5.symbol_info_tick(symbol).ask
elif action =='sell':
trade_type = mt5.ORDER_TYPE_SELL
price = mt5.symbol_info_tick(symbol).bid
position_id=result.order
lot = action_request['volume']
action_request={
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": mt5.ORDER_TYPE_SELL,
"position": position_id,
"price": price,
"deviation": deviation,
"magic": ea_magic_number,
"comment": "python script close",
"type_time": mt5.ORDER_TIME_GTC, # good till cancelled
"type_filling": mt5.ORDER_FILLING_RETURN,
}
# send a close request
result=mt5.order_send(action_request)
currency_pair = "GBPUSD"
# establish connection to MetaTrader 5 terminal
if not mt5.initialize(login=31706337, server="MetaQuotes-Demo",password="mzhjm8hi"):
print("initialize() failed, error code =", mt5.last_error())
quit()
trade = open_trade('buy', currency_pair, 10, 500, 2000, 10)
print(trade)
Result: C:\Users\andyq\PycharmProjects\BinanceTrading\venv\Scripts\python.exe "C:/Users/andyq/PycharmProjects/BinanceTrading/data preparation.py"
(None, {'action': 1, 'symbol': 'GBPUSD', 'volume': 10, 'type': 0, 'price': 1.26224, 'sl': 1.25724, 'tp': 1.28224, 'deviation': 10, 'magic': 9986989, 'comment': 'sent by python', 'type_time': 0, 'type_filling': 2})
Process finished with exit code 0