设为首页 收藏本站 切换语言 切换语言

自动止盈止损MT5自动止盈止损EA开发(内含源码)

| 发表于 2025-8-6 20:00:08 | 显示全部楼层 |复制链接
# MT5自动止盈止损EA开发(含ATR动态设置)
图片内容仅供参考!
## EA基础架构设计

本EA旨在为MT5平台开发一个智能化的自动止盈止损系统,结合传统固定点数方法和动态ATR指标,实现风险管理的自动化与优化。以下是完整的MQL5实现方案。

### 核心功能模块

  1. ```mql5
  2. //+------------------------------------------------------------------+
  3. //| Expert initialization function                                   |
  4. //+------------------------------------------------------------------+
  5. input int ATR_Period = 14;                 // ATR计算周期
  6. input double ATR_Multiplier = 2.0;         // ATR倍数因子
  7. input bool Use_Fixed_TP_SL = true;         // 启用固定止盈止损
  8. input int Fixed_TP_Pips = 50;              // 固定止盈点数
  9. input int Fixed_SL_Pips = 30;              // 固定止损点数
  10. input double Risk_Percent = 1.0;           // 风险百分比(账户比例)
  11. input bool Use_Trailing_Stop = true;       // 启用移动止损
  12. input int Trailing_Stop_Distance = 20;     // 移动止损距离(点)
  13. input int Trailing_Step = 5;               // 移动步长(点)
  14. int OnInit()
  15. {
  16.    // 检查输入参数有效性
  17.    if(ATR_Period <= 0 || ATR_Multiplier <= 0 || Risk_Percent <= 0)
  18.    {
  19.       Print("参数错误: 周期和乘数必须大于0");
  20.       return(INIT_PARAMETERS_INCORRECT);
  21.    }
  22.    // 设置定时器,每秒检查一次
  23.    EventSetTimer(1);
  24.    return(INIT_SUCCEEDED);
  25. }
  26. void OnDeinit(const int reason)
  27. {
  28.    EventKillTimer();
  29. }
  30. ```
  31. ### 订单处理逻辑
  32. ```mql5
  33. void OnTick()
  34. {
  35.    // 只对新订单设置止盈止损
  36.    if(IsNewBar())
  37.    {
  38.       SetStopLossTakeProfit();
  39.    }
  40.    // 移动止损逻辑
  41.    if(Use_Trailing_Stop)
  42.    {
  43.       TrailingStopManagement();
  44.    }
  45. }
  46. bool IsNewBar()
  47. {
  48.    static datetime lastBarTime = 0;
  49.    datetime currentBarTime = iTime(_Symbol, _Period, 0);
  50.    if(lastBarTime != currentBarTime)
  51.    {
  52.       lastBarTime = currentBarTime;
  53.       return true;
  54.    }
  55.    return false;
  56. }
  57. ```
  58. ## ATR动态止盈止损实现
  59. ### ATR计算模块
  60. ```mql5
  61. double CalculateATRValue()
  62. {
  63.    double atr = iATR(_Symbol, _Period, ATR_Period, 0);
  64.    return atr / _Point; // 转换为点数
  65. }
  66. void SetStopLossTakeProfit()
  67. {
  68.    double atrValue = CalculateATRValue();
  69.    double atrSL = atrValue * ATR_Multiplier;
  70.    double atrTP = atrValue * ATR_Multiplier * 2; // 通常止盈是止损的2倍
  71.    for(int i = OrdersTotal()-1; i >= 0; i--)
  72.    {
  73.       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
  74.       {
  75.          if(OrderSymbol() == _Symbol && OrderMagicNumber() == ExpertMagicNumber)
  76.          {
  77.             // 跳过已设置止盈止损的订单
  78.             if(OrderStopLoss() != 0 || OrderTakeProfit() != 0) continue;
  79.             double newSl = 0, newTp = 0;
  80.             double point = _Point;
  81.             if(Use_Fixed_TP_SL)
  82.             {
  83.                if(OrderType() == OP_BUY)
  84.                {
  85.                   newSl = OrderOpenPrice() - Fixed_SL_Pips * point;
  86.                   newTp = OrderOpenPrice() + Fixed_TP_Pips * point;
  87.                }
  88.                else if(OrderType() == OP_SELL)
  89.                {
  90.                   newSl = OrderOpenPrice() + Fixed_SL_Pips * point;
  91.                   newTp = OrderOpenPrice() - Fixed_TP_Pips * point;
  92.                }
  93.             }
  94.             else // 使用ATR动态设置
  95.             {
  96.                if(OrderType() == OP_BUY)
  97.                {
  98.                   newSl = OrderOpenPrice() - atrSL * point;
  99.                   newTp = OrderOpenPrice() + atrTP * point;
  100.                }
  101.                else if(OrderType() == OP_SELL)
  102.                {
  103.                   newSl = OrderOpenPrice() + atrSL * point;
  104.                   newTp = OrderOpenPrice() - atrTP * point;
  105.                }
  106.             }
  107.             // 计算合适的手数基于风险百分比
  108.             double lotSize = CalculateLotSize(newSl);
  109.             // 修改订单设置止盈止损
  110.             if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSl, newTp, 0, clrNONE))
  111.             {
  112.                Print("订单修改失败,错误代码: ", GetLastError());
  113.             }
  114.          }
  115.       }
  116.    }
  117. }
  118. ```
  119. ### 智能手数计算
  120. ```mql5
  121. double CalculateLotSize(double stopLossPrice)
  122. {
  123.    double accountBalance = AccountBalance();
  124.    double riskAmount = accountBalance * Risk_Percent / 100.0;
  125.    double pointValue = MarketInfo(_Symbol, MODE_TICKVALUE);
  126.    if(OrderType() == OP_BUY)
  127.    {
  128.       double slPoints = (OrderOpenPrice() - stopLossPrice) / _Point;
  129.       double lotSize = riskAmount / (slPoints * pointValue);
  130.       return NormalizeDouble(lotSize, 2);
  131.    }
  132.    else if(OrderType() == OP_SELL)
  133.    {
  134.       double slPoints = (stopLossPrice - OrderOpenPrice()) / _Point;
  135.       double lotSize = riskAmount / (slPoints * pointValue);
  136.       return NormalizeDouble(lotSize, 2);
  137.    }
  138.    return 0.1; // 默认手数
  139. }
  140. ```
  141. ## 移动止损优化模块
  142. ```mql5
  143. void TrailingStopManagement()
  144. {
  145.    for(int i = OrdersTotal()-1; i >= 0; i--)
  146.    {
  147.       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
  148.       {
  149.          if(OrderSymbol() == _Symbol && OrderMagicNumber() == ExpertMagicNumber)
  150.          {
  151.             double newSl = 0;
  152.             double point = _Point;
  153.             double currentStop = OrderStopLoss();
  154.             if(OrderType() == OP_BUY)
  155.             {
  156.                double distance = (Bid - OrderOpenPrice()) / point;
  157.                if(distance > Trailing_Stop_Distance)
  158.                {
  159.                   newSl = Bid - Trailing_Stop_Distance * point;
  160.                   if(currentStop == 0 || newSl > currentStop)
  161.                   {
  162.                      if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSl, OrderTakeProfit(), 0, clrNONE))
  163.                      {
  164.                         Print("移动止损修改失败,错误代码: ", GetLastError());
  165.                      }
  166.                   }
  167.                }
  168.             }
  169.             else if(OrderType() == OP_SELL)
  170.             {
  171.                double distance = (OrderOpenPrice() - Ask) / point;
  172.                if(distance > Trailing_Stop_Distance)
  173.                {
  174.                   newSl = Ask + Trailing_Stop_Distance * point;
  175.                   if(currentStop == 0 || newSl < currentStop)
  176.                   {
  177.                      if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSl, OrderTakeProfit(), 0, clrNONE))
  178.                      {
  179.                         Print("移动止损修改失败,错误代码: ", GetLastError());
  180.                      }
  181.                   }
  182.                }
  183.             }
  184.          }
  185.       }
  186.    }
  187. }
  188. ```
  189. ## 参数优化与高级功能
  190. ### 多时间框架ATR
  191. ```mql5
  192. input ENUM_TIMEFRAMES Higher_TF_ATR = PERIOD_H1; // 高阶ATR时间框架
  193. input bool Use_Multi_TF_ATR = false;             // 启用多时间框架ATR
  194. double GetMultiTimeFrameATR()
  195. {
  196.    if(Use_Multi_TF_ATR)
  197.    {
  198.       double higherTFATR = iATR(_Symbol, Higher_TF_ATR, ATR_Period, 0);
  199.       double currentTFATR = iATR(_Symbol, _Period, ATR_Period, 0);
  200.       return (higherTFATR + currentTFATR) / 2.0 / _Point;
  201.    }
  202.    return CalculateATRValue();
  203. }
  204. ```
  205. ### 动态风险调整
  206. ```mql5
  207. input bool Use_Dynamic_Risk = true;       // 启用动态风险调整
  208. input int Equity_Threshold_1 = 5000;      // 净值阈值1(USD)
  209. input int Equity_Threshold_2 = 10000;     // 净值阈值2(USD)
  210. input double Risk_Percent_1 = 2.0;        // 风险百分比1
  211. input double Risk_Percent_2 = 1.5;        // 风险百分比2
  212. input double Risk_Percent_3 = 1.0;        // 风险百分比3
  213. double GetDynamicRiskPercent()
  214. {
  215.    if(!Use_Dynamic_Risk) return Risk_Percent;
  216.    double equity = AccountEquity();
  217.    if(equity < Equity_Threshold_1) return Risk_Percent_1;
  218.    else if(equity >= Equity_Threshold_1 && equity < Equity_Threshold_2) return Risk_Percent_2;
  219.    else return Risk_Percent_3;
  220. }
  221. ```
  222. ### 价格波动性过滤
  223. ```mql5
  224. input bool Use_Volatility_Filter = true;  // 启用波动性过滤
  225. input double High_Volatility_Level = 1.5; // 高波动性阈值(相对于平均ATR)
  226. bool IsNormalVolatility()
  227. {
  228.    if(!Use_Volatility_Filter) return true;
  229.    double currentATR = CalculateATRValue();
  230.    double avgATR = iATR(_Symbol, _Period, ATR_Period*3, 0) / _Point;
  231.    return currentATR <= avgATR * High_Volatility_Level;
  232. }
  233. ``
复制代码
`

## 中文参数设置指南

### 基础参数设置

1. **ATR参数组**
   - ATR计算周期(ATR_Period):推荐14-20周期,周期越长ATR越平滑
   - ATR倍数因子(ATR_Multiplier):1.5-3.0之间,决定止损幅度

2. **固定止盈止损组**
   - 启用固定止盈止损(Use_Fixed_TP_SL):true/false
   - 固定止盈点数(Fixed_TP_Pips):建议30-100点
   - 固定止损点数(Fixed_SL_Pips):建议20-50点

3. **风险管理组**
   - 风险百分比(Risk_Percent):建议0.5%-2%
   - 动态风险调整(Use_Dynamic_Risk):true/false
   - 各阶段风险百分比(Risk_Percent_1/2/3):随账户增长降低风险

### 高级功能设置

1. **移动止损组**
   - 启用移动止损(Use_Trailing_Stop):true/false
   - 移动止损距离(Trailing_Stop_Distance):建议15-30点
   - 移动步长(Trailing_Step):建议5-10点

2. **多时间框架ATR**
   - 启用多时间框架ATR(Use_Multi_TF_ATR):true/false
   - 高阶ATR时间框架(Higher_TF_ATR):比当前高一级的时间框架

3. **波动性过滤**
   - 启用波动性过滤(Use_Volatility_Filter):true/false
   - 高波动性阈值(High_Volatility_Level):1.3-2.0倍平均ATR

### 优化建议

1. **针对不同货币对**
   - 高波动货币对(如GBP pairs):增大ATR乘数(2.5-3.0)和止损距离
   - 低波动货币对(如CHF pairs):减小ATR乘数(1.5-2.0)和止损距离

2. **针对不同时间框架**
   - 短线交易(H1以下):使用较小ATR乘数(1.5-2.0)
   - 中线交易(H4-D1):使用较大ATR乘数(2.0-3.0)

3. **针对市场状态**
   - 高波动市场:减小风险百分比至0.5%-1%
   - 低波动市场:可适当增加风险至1%-2%

## 实盘部署建议

1. **测试阶段**
   - 先在模拟账户运行2-4周
   - 测试不同参数组合的表现
   - 特别关注极端行情下的表现

2. **资金管理**
   - 初始实盘使用账户资金的10-20%
   - 盈利超过20%后提取本金
   - 采用金字塔加仓方式

3. **监控与调整**
   - 每周评估EA表现
   - 根据市场波动性调整ATR参数
   - 在重大经济事件前考虑暂停EA

4. **多策略组合**
   - 将此EA与趋势跟踪EA结合使用
   - 在不同货币对间分散配置
   - 使用不同参数设置创建多个EA实例

这个完整的MT5 EA实现了智能化的自动止盈止损功能,结合了固定点数法和动态ATR方法的优点,并加入了移动止损、多时间框架分析和波动性过滤等高级功能。通过合理设置中文参数,交易者可以根据自己的风险偏好和市场条件进行个性化配置,实现更科学的交易风险管理。
1.png
2.png
举报

评论 使用道具

精彩评论5

sunkist1788
D
| 发表于 2025-8-6 23:58:13 | 显示全部楼层
很厉害啊楼主
举报

点赞 评论 使用道具

对冲量化之神
D
| 发表于 2025-8-10 21:20:21 | 显示全部楼层
能不能赚钱
举报

点赞 评论 使用道具

xinhua123
DDD
| 发表于 2025-9-6 17:23:00 | 显示全部楼层
很好很好
举报

点赞 评论 使用道具

yangxiao
DD
| 发表于 2025-9-8 21:41:08 | 显示全部楼层
好不错哦。
举报

点赞 评论 使用道具

dy008524
D
| 发表于 2025-9-20 22:30:25 | 显示全部楼层
编写都是错误,不通过
举报

点赞 评论 使用道具

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

 简体中文国旗 简体中文
 繁體中文国旗 繁體中文
 English国旗 English(英语)
 日本語国旗 日本語(日语)
 Deutsch国旗 Deutsch(德语)
 Русский язык国旗 Русский язык(俄语)
 بالعربية国旗 بالعربية(阿拉伯语)
 Türkçe国旗 Türkçe(土耳其语)
 Português国旗 Português(葡萄牙语)
 ภาษาไทย国旗 ภาษาไทย(泰国语)
 한어国旗 한어(朝鲜语/韩语)
 Français国旗 Français(法语)
翻译