在 GitHub 上查看

Executer AC 策略

Executer AC 策略是 MetaTrader 5 版 "Executer AC" 专家的完整移植版本,核心依据 Bill Williams 的 Accelerator Oscillator (AC)。StockSharp 实现保持原脚本的交易逻辑,并提供参数化风险控制与可视化支持。

交易逻辑

策略只在所选周期的已完结 K 线上运行,并读取最近四个 AC 值:

  • AC[0]:最新收盘柱(对应原代码的 ac[1])。
  • AC[1]AC[2]AC[3]:更早的柱体,用于判断加速结构。

完整决策流程如下:

  1. 持仓管理
    • AC[0] < AC[1] 时视为多头动能衰减,平掉全部多单。
    • AC[0] > AC[1] 时视为空头动能衰减,平掉全部空单。
    • 启用移动止损:价格向有利方向运行超过 TrailingStop + TrailingStep(以点数计)后,将止损更新到最新收盘价减/加 TrailingStop 的位置。
  2. 无仓时的入场
    • 零轴上方的加速上涨AC[0] > 0AC[1] > 0AC[0] > AC[1] > AC[2],买入。
    • 零轴上方的加速下跌AC[0] > 0AC[1] > 0AC[0] < AC[1] < AC[2] < AC[3],卖出。
    • 零轴下方的加速上涨AC[0] < 0AC[1] < 0AC[0] > AC[1] > AC[2] > AC[3],买入。
    • 零轴下方的加速下跌AC[0] < 0AC[1] < 0AC[0] < AC[1] < AC[2],卖出。
    • 零轴交叉:从正转负(AC[0] > 0AC[1] < 0)视为新的多头信号;从负转正(AC[0] < 0AC[1] > 0)视为空头信号。

所有判断都在指标计算完成并允许交易后才执行。

风险控制

  • 止损与止盈:以点数为单位,自动按交易品种的最小价位变动转换为价格距离,数值为 0 表示关闭该功能。
  • 移动止损:与原脚本一致,当浮动盈利超过 TrailingStop + TrailingStep 点时,止损沿趋势方向移动,同时要求每次移动至少提高 TrailingStep 点的盈利空间。
  • 账户保护:调用 StartProtection(),利用 StockSharp 的保护机制防止连接异常导致的未预期风险。

参数说明

参数 含义
TradeVolume 下单数量,根据交易品种的最小手数和最大手数自动调整。
StopLossPips 止损距离(点),为 0 表示禁用。
TakeProfitPips 止盈距离(点),为 0 表示禁用。
TrailingStopPips 移动止损的基础距离(点)。
TrailingStepPips 每次收紧移动止损所需的额外盈利(点)。
CandleType 计算 AC 所使用的 K 线周期。

实现细节

  • 针对三位或五位小数的外汇品种,点值按 MetaTrader 的方式乘以 10,确保止损/止盈与原版一致。
  • 使用固定长度数组保存最近四个 AC 值,避免额外的集合操作,完全复制 ac[1]…ac[4] 的比较逻辑。
  • 在同一根 K 线内,一旦触发平仓逻辑,处理流程立即返回,不会继续执行新的开仓条件,与原 EA 的 return 行为保持一致。
  • 移动止损会同步更新内部状态和外部止损价位,效果等同于 MQL5 中的 PositionModify

使用建议

  1. 选择适合标的波动特征的时间框架(原策略常用于外汇的短周期)。
  2. 根据波动率调整止损、止盈与移动止损距离,避免过小的数值导致频繁出局。
  3. 如条件允许,可在经纪商端设置服务器止损以增强安全性。
  4. 多策略并行时,应注意整体仓位占用和账户风险敞口。
using System;
using System.Collections.Generic;

using Ecng.Common;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Executer AC strategy using EMA crossover.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class ExecuterAcStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public ExecuterAcStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 12).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
		_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };
		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
		if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}