GitHub で見る

BADX ADX Bollinger戦略

概要

この戦略はStockSharp高レベルAPIを使用してMetaTraderのBADXエキスパートアドバイザーを再現します。Average Directional Index (ADX)Bollinger Bandsを組み合わせてレンジ相場を取引します: ADXが設定可能なしきい値を下回り、価格が外側のバンドに触れると、戦略は平均回帰を期待してその動きに逆張りします。ストップロス、テイクプロフィット、オプションのトレーリングストップを含むすべての保護注文はStartProtectionによって自動的に管理されます。

仕組み

  1. 設定されたローソク足シリーズを購読し、AverageDirectionalIndexBollingerBandsインジケーターの両方を高レベルバインディングを通じてフィードします。
  2. 完成した各ローソク足について、コールバックはADX値とBollingerの上部・下部エンベロープを受け取ります。
  3. ADXがAdxLevelを下回ると、市場はトレンドなしと見なされます:
    • 終値が下部バンドを下回り、オープンポジションがない場合、戦略は成行で買います。
    • 終値が上部バンドを上回り、オープンポジションがない場合、戦略は成行で売ります。
  4. リスク管理はpip距離を絶対価格オフセットに変換します。ストップロス、テイクプロフィット、トレーリングパラメーター(有効な場合)はエントリー直後に保護マネージャーを通じて適用されます。
  5. 一度に1つのポジションのみアクティブにできます。エグジットは保護注文またはトレーリングストップ調整を通じて発生します。

パラメーター

  • CandleType (DataType): インジケーター計算に使用する時間足。デフォルト: 15分足ローソク足。
  • AdxPeriod (int): ADXインジケーターの平均化期間。デフォルト: 30。
  • AdxLevel (decimal): レンジ相場として分類される最大ADX値。デフォルト: 20。
  • BollingerPeriod (int): Bollinger Bandsの移動平均期間。デフォルト: 10。
  • BollingerDeviation (decimal): Bollinger Bandsの標準偏差乗数。デフォルト: 1.5。
  • StopLossPips (decimal): pip単位のストップロス距離。デフォルト: 50。
  • TakeProfitPips (decimal): pip単位のテイクプロフィット距離。デフォルト: 50。
  • TrailingStopPips (decimal): pip単位のトレーリングストップ距離。デフォルト: 5。
  • TrailingStepPips (decimal): トレーリングストップが調整される前の最小価格改善(pip)。デフォルト: 5。

使用方法

  1. 戦略を商品に接続し、パラメーターを希望通りに設定します。
  2. 戦略を開始します。必要なローソク足ストリームを自動的に購読し、インジケーターを構築して保護注文を設定します。
  3. チャートエリアでトレードを監視します: プラットフォームがチャート表示をサポートしている場合、ローソク足、Bollinger Bands、約定注文が可視化されます。
  4. リスクパラメーター(ストップロス、テイクプロフィット、トレーリング距離)を商品のボラティリティまたは個人の設定に合わせて調整します。

メモ

  • 早期エントリーを避けるため、完成したローソク足のみが処理されます。
  • pip サイズは商品のPriceStepから導出されます; 商品が3または5桁の小数点を使用する場合、pipは10倍に調整され、元のエキスパートアドバイザーを模倣します。
  • 戦略はデフォルトでVolume1に保ちます。希望するトレードサイズに合わせて基底クラスの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;
	}
}