GitHub で見る

Dynamic Averaging戦略

概要

Dynamic AveragingはMetaTrader 5エキスパートアドバイザー「Dynamic averaging.mq5」(ID 23319)の直接移植版です。この戦略は、標準偏差に基づくボラティリティフィルターと高速Stochasticオシレーターを組み合わせています。市場のボラティリティがその移動平均を下回っている間のみ取引が許可され、Stochasticの反転がより信頼性の高いコンソリデーション中のエントリーを強制します。

パラメーター

  • TradeVolume – 各新規エントリーの注文サイズ。損失シーケンス後に自動的に倍増し、利益シーケンス後にリセットされます。
  • MinimumProfit – すべてのオープンポジションを閉じる浮動利益(口座通貨)の閾値。
  • SlidingWindowDays – 標準偏差値を平均化してボラティリティベースラインを構築するために使用するカレンダー日数。
  • StochasticKPeriod – %K計算のバー数。
  • StochasticDPeriod – %Dラインの平滑化長。
  • StochasticSlowPeriod – Stochasticオシレーターの最終減速期間。
  • StdDevPeriod – 標準偏差インジケーターのルックバック期間。
  • CandleType – 計算のためのソースローソク足(デフォルト:15分足時間軸)。

トレードルール

  1. 戦略は完成したローソク足のみで動作します。各バークローズでStochasticとボラティリティフィルターがSubscribeCandles().BindExを介して更新されます。
  2. StandardDeviation(StdDevPeriod)を使用して市場のボラティリティを計算し、最後のSlidingWindowDays分のバーにわたるSimpleMovingAverageで計算された平均ボラティリティと比較します。
  3. 現在の標準偏差が移動平均より上の場合、そのバーはスキップされます。
  4. ボラティリティが低い場合:
    • %Kが25未満で、前の2つの%K値の傾きが正(最後の値から2バー前の値を引いたもの)の場合、ロングエントリー。
    • %Kが75超で、前の2つの%K値の傾きが負の場合、ショートエントリー。
  5. ポジションは反対側をフラットにするのに十分なボリュームと新しいTradeVolumeエクスポージャーを送ることで反転されます。
  6. オープンポジションの浮動PnLがMinimumProfitを超えると、戦略は即座に市場を出ます。

ポジションサイジングと回復

  • 初期注文サイズはTradeVolumeと同じです。
  • ポジションをクローズした後、実現PnLの変化が検査されます。
    • 損失は次の取引サイズを倍増させ(マーチンゲールステップ)、元のEAの動作を再現します。
    • 利益またはブレークイーブンはサイズをベースTradeVolumeにリセットします。

実装の詳細

  • ローソク足、Stochasticおよび標準偏差の値はBindExを使用した高レベルAPIを通じて処理され、手動バッファ管理を回避します。
  • スライディングボラティリティウィンドウは、利用可能な場合はローソク足の時間軸を使用してカレンダー日数をバーカウントに変換します。
  • 浮動利益管理は現在のローソク足クローズとPositionAvgPriceに依存し、オープンポジション利益のみを合計するMQL実装と一致します。
  • すべてのコードコメントは英語で記述されており、タスク要件に従いPythonバージョンは提供されていません。
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;

public class DynamicAveragingStrategy : 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 DynamicAveragingStrategy()
	{
		_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;
	}
}