在 GitHub 上查看

BADX ADX 布林带策略

概述

该策略按照 MetaTrader 平台上的 BADX 专家顾问在 StockSharp 高阶 API 中实现。策略结合 平均趋向指数(ADX)布林带 来捕捉区间震荡行情:当 ADX 低于设定阈值且价格触碰外侧带时,系统逆势入场,预期价格回归均值。止损、止盈以及可选的跟踪止损均由 StartProtection 自动管理。

工作原理

  1. 订阅设定的蜡烛序列,并通过高阶绑定同时驱动 AverageDirectionalIndexBollingerBands 指标。
  2. 在每根已完成蜡烛上,回调会收到 ADX 数值以及布林带的上轨和下轨。
  3. 当 ADX 低于 AdxLevel 时视为盘整环境:
    • 若收盘价低于下轨且当前无持仓,则以市价买入。
    • 若收盘价高于上轨且当前无持仓,则以市价卖出。
  4. 风险参数会把“点”距离转换为绝对价格偏移。止损、止盈和跟踪止损(如启用)会在进场后立即通过保护管理器设置。
  5. 任意时刻仅允许存在一个持仓,退出由保护性订单或跟踪止损触发。

参数

  • CandleType (DataType): 指标计算使用的时间框架,默认为 15 分钟。
  • AdxPeriod (int): ADX 平滑周期,默认 30。
  • AdxLevel (decimal): 判定盘整的 ADX 上限阈值,默认 20。
  • BollingerPeriod (int): 布林带均线周期,默认 10。
  • BollingerDeviation (decimal): 布林带标准差倍数,默认 1.5。
  • StopLossPips (decimal): 止损距离(单位:点),默认 50。
  • TakeProfitPips (decimal): 止盈距离(单位:点),默认 50。
  • TrailingStopPips (decimal): 跟踪止损距离(单位:点),默认 5。
  • TrailingStepPips (decimal): 调整跟踪止损前所需的最小盈利(单位:点),默认 5。

使用方法

  1. 将策略附加到目标证券,并根据需要调整参数。
  2. 启动策略后会自动订阅蜡烛数据、初始化指标并设置保护性订单。
  3. 在支持图表的终端中可以同时观察蜡烛、布林带以及成交轨迹。
  4. 根据品种波动率或个人偏好调整止损、止盈及跟踪参数。

说明

  • 仅处理已完成的蜡烛,避免提前入场。
  • “点”大小依据证券的 PriceStep 计算;当报价有 3 或 5 位小数时,点值会额外乘以 10,以匹配原始 EA 的处理方式。
  • 默认将 Volume 设为 1,可按需修改基类的 Volume 属性以匹配期望手数。
  • 源码中的注释全部使用英文,遵循仓库要求。
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>
/// BADX ADX Bollinger strategy using EMA crossover.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class BadxAdxBollingerStrategy : 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 BadxAdxBollingerStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).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;
	}
}