[英]Changing stoploss in metatrader5 with python using Metatrader5 library and nothing happens
我有这段代码用于更改 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, SL, TP, pair, p_open, volume, 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_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(sltp_request)
我发现了为什么我们会面临这个问题。
当您第一次执行交易时,请注意STOP_LOSS
始终等于例如与价格相差 500 点,但现在您要修改止损。
所以 500 点 +/- current_price = 例如 138.500 == 我们的 STOP_LOSS
这里的技巧是您将价格设置为 STOP_LOSS,而不是 POINTS。
所以新的请求将是:
request = { 'action': mt5.TRADE_ACTION_SLTP, 'position': position.ticket, 'sl': 139.000, }
现在你终于要开始做某事了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.