使用Python + MetaTrader5库(适合自动化交易)平仓MT5 二分之一订单

| 发表于 2025-7-27 03:27:18 | 显示全部楼层 |复制链接
  1. import MetaTrader5 as mt5
  2. if not mt5.initialize():
  3.     print("MT5初始化失败")
  4.     quit()
  5. positions = mt5.positions_get()
  6. total_volume = sum(pos.volume for pos in positions)
  7. close_volume = total_volume * 0.5
  8. for pos in positions:
  9.     if close_volume <= 0:
  10.         break
  11.    
  12.     if pos.volume >= close_volume:
  13.         request = {
  14.             "action": mt5.TRADE_ACTION_DEAL,
  15.             "position": pos.ticket,
  16.             "symbol": pos.symbol,
  17.             "volume": close_volume,
  18.             "type": mt5.ORDER_TYPE_SELL if pos.type == mt5.ORDER_TYPE_BUY else mt5.ORDER_TYPE_BUY,
  19.             "price": mt5.symbol_info_tick(pos.symbol).ask if pos.type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(pos.symbol).bid,
  20.             "deviation": 10,
  21.         }
  22.         mt5.order_send(request)
  23.         break
  24.     else:
  25.         request = {
  26.             "action": mt5.TRADE_ACTION_DEAL,
  27.             "position": pos.ticket,
  28.             "symbol": pos.symbol,
  29.             "volume": pos.volume,
  30.             "type": mt5.ORDER_TYPE_SELL if pos.type == mt5.ORDER_TYPE_BUY else mt5.ORDER_TYPE_BUY,
  31.             "price": mt5.symbol_info_tick(pos.symbol).ask if pos.type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(pos.symbol).bid,
  32.             "deviation": 10,
  33.         }
  34.         mt5.order_send(request)
  35.         close_volume -= pos.volume
  36. mt5.shutdown()
复制代码
举报

评论 使用道具

精彩评论3

xqs1314
D
| 发表于 2026-3-1 23:37:11 | 显示全部楼层
感谢分享,很大收获@@
举报

点赞 评论 使用道具

sanwich
D
| 发表于 2026-3-2 12:28:24 | 显示全部楼层
平部分仓 搞起来不好看日记记录。我试过平三分之一仓,后面去对数据查问题的时候费脑
举报

点赞 评论 使用道具

xinhua123
DDD
| 发表于 前天 01:15 | 显示全部楼层
来学习了
举报

点赞 评论 使用道具

发新帖
EA交易
您需要登录后才可以评论 登录 | 立即注册