GitHub で見る

MAクロスメソッドPriceMode戦略

概要

MA Cross Method PriceMode 戦略は、MetaTrader 4 エキスパート「MA_cross_Method_PriceMode」の直接の StockSharp 移植です。構成可能な 2 つの移動平均を組み合わせ、高速平均が低速平均を横切るたびに反応します。どちらの行も、元の MetaTrader 入力: 期間、平滑化方法 (SMA、EMA、SMMA、LWMA)、適用価格 (終値、始値、高値、安値、中央値、代表値、加重値)、および水平シフトを公開します。この戦略は、定期的な時間ベースのローソク足を提供するあらゆる商品で機能します。

インジケーター

  • 高速移動平均 – 設定可能な長さ、方法、価格ソース。 MetaTrader シフト パラメータは、完了したインジケーター値をバッファリングし、値 FirstShift バーを読み取ることによって再現されます。
  • 低速移動平均 – バッファリングを介した同じシフトエミュレーションを使用した構成可能な長さ、方法、および価格ソース。

取引ロジック

  1. この戦略は、選択されたキャンドル タイプをサブスクライブし、バー内再描画を避けるために完成したキャンドルのみを処理します。
  2. 閉じたバーごとに、両方の移動平均にそれぞれの適用価格を入力します。
  3. 両方の平均から最終値が生成されると、ストラテジーは次の 2 つの条件を評価します。
    • 強気クロス – 前のバーでは速い MA が遅い MA よりも下か同じでしたが、現在のバーでは遅い MA よりも上に移動しました。
    • 弱気クロス – 前の足では速い MA が遅い MA よりも上か同じでしたが、現在の足では遅い MA より下に移動します。
  4. 強気のクロスでは、戦略は OrderVolume 枚の契約を買います。ショートポジションがオープンしている場合、ショートポジションをカバーし、新しいロングエクスポージャーを確立するために注文サイズが自動的に増加します。
  5. 弱気クロスでは、戦略は OrderVolume 枚の契約を売ります。ロングポジションがオープンしている場合は、ショートを確立する前に注文サイズを増やしてクローズします。
  6. StartProtection() は、必要に応じて StockSharp 保護モジュール (ストップロスや損益分岐点アシスタントなど) を追加できるように呼び出されます。

パラメーター

名前 説明 デフォルト
FirstPeriod 高速移動平均の期間。 3
SecondPeriod ゆっくりとした移動平均の期間。 13
FirstMethod 高速移動平均に使用される平滑化方法 (SimpleExponentialSmoothedLinearWeighted)。 Simple
SecondMethod 低速移動平均に使用される平滑化方法。 LinearWeighted
FirstPriceMode 高速移動平均に適用される価格(CloseOpenHighLowMedianTypicalWeighted)。 Close
SecondPriceMode 低速移動平均に適用される価格。 Median
FirstShift 高速移動平均に適用される水平シフト (バー単位)。 0
SecondShift 低速移動平均に適用される水平シフト (バー単位)。 0
OrderVolume 新しいポジションに使用される基本注文量。 0.1
CandleType 戦略によって処理されるローソク足のタイプ/タイムフレーム。 5分キャンドル

MQL バージョンとの違い

  • MetaTrader 注文の反復 (OrdersTotalOrderSelectOrderClose) は、StockSharp Strategy.Position プロパティの直接使用と、必要に応じて逆エクスポージャに合わせてサイズ設定された成行注文に置き換えられます。
  • MetaTrader の「新しいバー」フラグは必要ありません。ProcessCandle は完成したローソク足ごとに 1 回だけ実行され、ティックレベルのポーリングなしでバーごとに 1 回の同じ動作が保証されます。
  • MA シフト処理は、各平均の最後の shift + 2 値を保持するコンパクトなバッファーを使用して実装されています。これにより、禁止されたインジケーターの後方参照 (GetValue) に依存せずにインジケーターの変位が反映されます。
  • この戦略はブローカーに依存しません。リスク管理ヘルパーは、固定の MetaTrader stop/limit 引数の代わりに、StartProtection() を介して接続できます。

使用上の注意

  • 元の時間枠 (M5 や H1 など) と一致するローソク足の期間を選択します。カスタムの時間枠は、戦略パラメータの CandleType を編集することで指定できます。
  • FirstShift または SecondShift を正の値に設定すると、MetaTrader の水平シフト入力と同様に、完了したバーの数だけ効果的なクロスオーバーが遅れます。
  • Weighted 価格モードは、MetaTrader の (High + Low + 2 * Close) / 4 式を再現します。中央値モードと標準モードは、標準の (High + Low) / 2 および (High + Low + Close) / 3 の定義に従います。
  • すべての注文は成行注文であるため、アカウント構成が要求されたボリュームとスリッページを許容できることを確認してください。
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Moving average crossover strategy converted from the MetaTrader script "MA_cross_Method_PriceMode".
/// Allows selecting the smoothing method, applied price and horizontal shift for each average.
/// </summary>
public class MaCrossMethodPriceModeStrategy : Strategy
{
	private readonly StrategyParam<int> _firstPeriod;
	private readonly StrategyParam<int> _secondPeriod;
	private readonly StrategyParam<MaMethods> _firstMethod;
	private readonly StrategyParam<MaMethods> _secondMethod;
	private readonly StrategyParam<AppliedPriceModes> _firstPriceMode;
	private readonly StrategyParam<AppliedPriceModes> _secondPriceMode;
	private readonly StrategyParam<int> _firstShift;
	private readonly StrategyParam<int> _secondShift;
	private readonly StrategyParam<decimal> _orderVolume;
	private readonly StrategyParam<DataType> _candleType;

	private DecimalLengthIndicator _firstMa = null!;
	private DecimalLengthIndicator _secondMa = null!;

	private readonly List<decimal> _firstValues = new();
	private readonly List<decimal> _secondValues = new();

	/// <summary>
	/// Initializes a new instance of <see cref="MaCrossMethodPriceModeStrategy"/>.
	/// </summary>
	public MaCrossMethodPriceModeStrategy()
	{
		_firstPeriod = Param(nameof(FirstPeriod), 3)
			.SetGreaterThanZero()
			.SetDisplay("Fast MA Period", "Length of the first moving average.", "Indicators")
			
			.SetOptimize(2, 50, 1);

		_secondPeriod = Param(nameof(SecondPeriod), 13)
			.SetGreaterThanZero()
			.SetDisplay("Slow MA Period", "Length of the second moving average.", "Indicators")
			
			.SetOptimize(5, 100, 1);

		_firstMethod = Param(nameof(FirstMethod), MaMethods.Simple)
			.SetDisplay("Fast MA Method", "Smoothing method applied to the first moving average.", "Indicators")
			;

		_secondMethod = Param(nameof(SecondMethod), MaMethods.LinearWeighted)
			.SetDisplay("Slow MA Method", "Smoothing method applied to the second moving average.", "Indicators")
			;

		_firstPriceMode = Param(nameof(FirstPriceMode), AppliedPriceModes.Close)
			.SetDisplay("Fast MA Price", "Price source used for the first moving average.", "Indicators")
			;

		_secondPriceMode = Param(nameof(SecondPriceMode), AppliedPriceModes.Median)
			.SetDisplay("Slow MA Price", "Price source used for the second moving average.", "Indicators")
			;

		_firstShift = Param(nameof(FirstShift), 0)
			.SetNotNegative()
			.SetDisplay("Fast MA Shift", "Horizontal shift (in bars) applied to the first moving average.", "Indicators");

		_secondShift = Param(nameof(SecondShift), 0)
			.SetNotNegative()
			.SetDisplay("Slow MA Shift", "Horizontal shift (in bars) applied to the second moving average.", "Indicators");

		_orderVolume = Param(nameof(OrderVolume), 0.1m)
			.SetGreaterThanZero()
			.SetDisplay("Order Volume", "Base order volume used for new entries.", "Trading")
			;

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe used for price processing.", "General");
	}

	/// <summary>
	/// Period of the first moving average.
	/// </summary>
	public int FirstPeriod
	{
		get => _firstPeriod.Value;
		set => _firstPeriod.Value = value;
	}

	/// <summary>
	/// Period of the second moving average.
	/// </summary>
	public int SecondPeriod
	{
		get => _secondPeriod.Value;
		set => _secondPeriod.Value = value;
	}

	/// <summary>
	/// Smoothing method applied to the first moving average.
	/// </summary>
	public MaMethods FirstMethod
	{
		get => _firstMethod.Value;
		set => _firstMethod.Value = value;
	}

	/// <summary>
	/// Smoothing method applied to the second moving average.
	/// </summary>
	public MaMethods SecondMethod
	{
		get => _secondMethod.Value;
		set => _secondMethod.Value = value;
	}

	/// <summary>
	/// Applied price mode for the first moving average.
	/// </summary>
	public AppliedPriceModes FirstPriceMode
	{
		get => _firstPriceMode.Value;
		set => _firstPriceMode.Value = value;
	}

	/// <summary>
	/// Applied price mode for the second moving average.
	/// </summary>
	public AppliedPriceModes SecondPriceMode
	{
		get => _secondPriceMode.Value;
		set => _secondPriceMode.Value = value;
	}

	/// <summary>
	/// Shift (in bars) applied to the first moving average values.
	/// </summary>
	public int FirstShift
	{
		get => _firstShift.Value;
		set => _firstShift.Value = value;
	}

	/// <summary>
	/// Shift (in bars) applied to the second moving average values.
	/// </summary>
	public int SecondShift
	{
		get => _secondShift.Value;
		set => _secondShift.Value = value;
	}

	/// <summary>
	/// Base order volume used for new positions.
	/// </summary>
	public decimal OrderVolume
	{
		get => _orderVolume.Value;
		set => _orderVolume.Value = value;
	}

	/// <summary>
	/// Candle type (timeframe) processed by the strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_firstMa = null!;
		_secondMa = null!;
		_firstValues.Clear();
		_secondValues.Clear();
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_firstMa = CreateMovingAverage(FirstMethod, FirstPeriod);
		_secondMa = CreateMovingAverage(SecondMethod, SecondPeriod);

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(_firstMa, _secondMa, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, _firstMa);
			DrawIndicator(area, _secondMa);
			DrawOwnTrades(area);
		}

		StartProtection(null, null);
	}

	private void ProcessCandle(ICandleMessage candle, decimal firstDecimal, decimal secondDecimal)
	{
		if (candle.State != CandleStates.Finished)
			return;

		UpdateBuffer(_firstValues, firstDecimal, FirstShift);
		UpdateBuffer(_secondValues, secondDecimal, SecondShift);

		if (!TryGetShiftedValues(_firstValues, FirstShift, out var firstCurrent, out var firstPrevious))
			return;

		if (!TryGetShiftedValues(_secondValues, SecondShift, out var secondCurrent, out _))
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var bullishCross = IsBullishCross(firstPrevious, firstCurrent, secondCurrent);
		var bearishCross = IsBearishCross(firstPrevious, firstCurrent, secondCurrent);

		if (bullishCross && OrderVolume > 0m && Position <= 0m)
		{
			var volumeToBuy = OrderVolume + (Position < 0m ? Math.Abs(Position) : 0m);
			BuyMarket(volumeToBuy);
		}
		else if (bearishCross && OrderVolume > 0m && Position >= 0m)
		{
			var volumeToSell = OrderVolume + (Position > 0m ? Position : 0m);
			SellMarket(volumeToSell);
		}
	}

	private static void UpdateBuffer(List<decimal> buffer, decimal value, int shift)
	{
		buffer.Add(value);

		var maxCount = Math.Max(shift + 2, 2);
		while (buffer.Count > maxCount)
		{
			buffer.RemoveAt(0);
		}
	}

	private static bool TryGetShiftedValues(IReadOnlyList<decimal> buffer, int shift, out decimal current, out decimal previous)
	{
		var currentIndex = buffer.Count - 1 - shift;
		var previousIndex = buffer.Count - 2 - shift;

		if (previousIndex < 0 || currentIndex < 0 || currentIndex >= buffer.Count)
		{
			current = default;
			previous = default;
			return false;
		}

		current = buffer[currentIndex];
		previous = buffer[previousIndex];
		return true;
	}

	private static bool IsBullishCross(decimal previousFast, decimal currentFast, decimal currentSlow)
	{
		return (previousFast <= currentSlow && currentFast > currentSlow)
			|| (previousFast < currentSlow && currentFast >= currentSlow);
	}

	private static bool IsBearishCross(decimal previousFast, decimal currentFast, decimal currentSlow)
	{
		return (previousFast >= currentSlow && currentFast < currentSlow)
			|| (previousFast > currentSlow && currentFast <= currentSlow);
	}

	private static decimal SelectPrice(ICandleMessage candle, AppliedPriceModes mode)
	{
		return mode switch
		{
			AppliedPriceModes.Close => candle.ClosePrice,
			AppliedPriceModes.Open => candle.OpenPrice,
			AppliedPriceModes.High => candle.HighPrice,
			AppliedPriceModes.Low => candle.LowPrice,
			AppliedPriceModes.Median => (candle.HighPrice + candle.LowPrice) / 2m,
			AppliedPriceModes.Typical => (candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 3m,
			AppliedPriceModes.Weighted => (candle.HighPrice + candle.LowPrice + (2m * candle.ClosePrice)) / 4m,
			_ => candle.ClosePrice
		};
	}

	private static DecimalLengthIndicator CreateMovingAverage(MaMethods method, int period)
	{
		return method switch
		{
			MaMethods.Simple => new SMA { Length = period },
			MaMethods.Exponential => new EMA { Length = period },
			MaMethods.Smoothed => new SmoothedMovingAverage { Length = period },
			MaMethods.LinearWeighted => new WeightedMovingAverage { Length = period },
			_ => new SMA { Length = period }
		};
	}

	/// <summary>
	/// Moving average smoothing methods that mirror the MetaTrader inputs.
	/// </summary>
	public enum MaMethods
	{
		Simple,
		Exponential,
		Smoothed,
		LinearWeighted
	}

	/// <summary>
	/// Applied price options equivalent to the MetaTrader constants.
	/// </summary>
	public enum AppliedPriceModes
	{
		Close,
		Open,
		High,
		Low,
		Median,
		Typical,
		Weighted
	}
}