问题描述
我有这段代码用于更改MetaTrader 5中一个或多个未平仓订单的止损。运行此代码时,即使我的编译器打印该代码也不会发生任何错误。我已经进行了谈判,所以我不确定问题出在哪里。
以下是源代码:
def sl_change(ticket,SL,TP,pair,p_open,volume,o_type):
order_request = {
'action': mt5.TradE_ACTION_SLTP,'ticket': ticket,'type': o_type,'price_open': p_open,'volume': volume,'sl': SL,'tp': TP,'symbol': pair,'deviation': 20,"magic": ea_magic_number,"comment": "sent by python","type_time": mt5.ORDER_TIME_GTC,# good till cancelled
'type_filling': mt5.ORDER_FILLING_FOK,"type_filling": mt5.ORDER_FILLING_RETURN,}
result = mt5.order_check(order_request)
return result,order_request
pair = 'AUDUSD'
SL = 0.7101
positions = mt5.positions_get(symbol=pair)
ordernum = len(positions)
for i in range(0,ordernum):
position = positions[i]
ticket = position.ticket
TP = position.tp
volume = position.volume
o_type = position.type
p_open = position.price_open
print(positions)
time.sleep(5)
sl_change(ticket,o_type)
当我用order_send替换order_check时,仍然没有任何反应。
解决方法
这对我有用,现在它是示例代码,如果您不明白输入,请回答我,我可以为您提供更多信息
def changeslpl(ticket,pair,pos_type,SL,tp,ea_magic_number,volume,p_open):
request = {
"action": mt5.TRADE_ACTION_SLTP,"symbol": pair,"volume": volume,"type": pos_type,"position": ticket,"price_open": p_open,"sl": SL,"tp": tp,"deviation": 20,"magic": ea_magic_number,"comment": "python script open","type_time": mt5.ORDER_TIME_GTC,"type_filling": mt5.ORDER_FILLING_FOK,"ENUM_ORDER_STATE": mt5.ORDER_FILLING_RETURN,}
#// perform the check and display the result 'as is'
result = mt5.order_send(request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print("4. order_send failed,retcode={}".format(result.retcode))
print(" result",result)
,
您应该反转您的订单类型。如果是 mt5.ORDER_TYPE_BUY
,SL/TP 修改请求应该是 mt5.ORDER_TYPE_SELL
# This is what is important to you!
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
#importance ends here.
sltp_request = {
"action": mt5.TRADE_ACTION_SLTP,"symbol": symbol,"volume": float(volume),"type": order_type,"position": deal_id,"sl": sl,"price": price,"magic": 234000,"comment": "Change stop loss","type_filling": mt5.ORDER_FILLING_IOC,}
result = mt5.order_send(sltp_request)