MT5通过Python提交买入订单返回None问题求助
MT5 Python下单返回None问题排查
核心错误点
- 参数传递错误:调用
crea_ordine时第一个参数传的是tick(行情tick对象),但函数定义里的simbolo参数需要的是品种字符串(比如"NDA_CFD.DE"),这会直接导致订单请求无效,返回None。
其他潜在问题及修复方案
修正参数传递
把下单调用改成:crea_ordine(symbol, lot, ordine_acquisto, buy_price, buy_sl, buy_tp)对齐止损止盈的精度
MT5要求止损、止盈价格必须匹配品种的小数位数精度,需用round函数处理:# 获取品种小数位数 digits = mt5.symbol_info(symbol).digits buy_sl = round(buy_price*(1-psl), digits) buy_tp = round(buy_price*(1+ptp), digits)添加错误排查逻辑
当order_send返回None时,调用mt5.last_error()获取具体错误信息,这是排查MT5交易问题的关键:
修改crea_ordine函数:def crea_ordine(simbolo, quantita, tipo_ordine, prezzo, stop_loss, take_profit): request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": simbolo, "volume": quantita, "type": tipo_ordine, "price": prezzo, "sl": stop_loss, "tp": take_profit, "deviation": deviation, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC, } result = mt5.order_send(request) if result is None: print("下单失败,错误信息:", mt5.last_error()) else: print(result)确认MT5连接状态
在代码开头添加连接检查,确保Python与MT5成功建立连接:if not mt5.initialize(): print("MT5初始化失败,错误代码:", mt5.last_error()) quit()
完整修正后的代码片段
import MetaTrader5 as mt5 # 初始化MT5连接 if not mt5.initialize(): print("MT5初始化失败,错误代码:", mt5.last_error()) quit() symbol = "NDA_CFD.DE" lot = 1.0 tick = mt5.symbol_info_tick(symbol) if tick is None: print(f"获取{symbol}行情失败,错误信息:", mt5.last_error()) mt5.shutdown() quit() buy_price = tick.ask sell_price = tick.bid symbol_info = mt5.symbol_info(symbol) point = symbol_info.point digits = symbol_info.digits psl = 0.05 ptp = 0.10 # 对齐止损止盈精度 buy_sl = round(buy_price*(1-psl), digits) buy_tp = round(buy_price*(1+ptp), digits) sell_sl = round(sell_price*(1+psl), digits) sell_tp = round(sell_price*(1-ptp), digits) deviation = 10 print ('Ask price', tick.ask) ordine_acquisto = mt5.ORDER_TYPE_BUY ordine_vendita = mt5.ORDER_TYPE_SELL def crea_ordine(simbolo, quantita, tipo_ordine, prezzo, stop_loss, take_profit): request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": simbolo, "volume": quantita, "type": tipo_ordine, "price": prezzo, "sl": stop_loss, "tp": take_profit, "deviation": deviation, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC, } result = mt5.order_send(request) if result is None: print("下单失败,错误信息:", mt5.last_error()) else: print(result) # 调用下单函数,修正参数 crea_ordine(symbol, lot, ordine_acquisto, buy_price, buy_sl, buy_tp) # 关闭MT5连接 mt5.shutdown()
内容的提问来源于stack exchange,提问作者Denis Dal Soler
相关产品推荐
相关产品推荐

