GitHub で見る

MLTrendE戦略

この戦略は加重移動平均(WMA)の方向に取引し、価格が有利に動いた場合にオプションでポジションをピラミッド(追加)します。

ロジック

  • 選択したローソク足シリーズのWMAを計算します。
  • ポジションがない場合:
    • 取引タイプ0: 終値がWMAを上回る場合にロングポジション、下回る場合にショートポジションを開きます。
    • 取引タイプ1: 常にロングポジションを開きます。
    • 取引タイプ2: 常にショートポジションを開きます。
  • ポジションが開かれていて指定の利益目標に達した場合、スケールされたボリュームで別の取引を追加します。
  • 最大取引数に達したら、次の利益目標でポジション全体を決済します。

パラメーター

  • Volume – 基本取引ボリューム。
  • Multiplier1 – 2番目の取引のボリューム乗数。
  • Multiplier2 – 3番目の取引のボリューム乗数。
  • TakeProfit – スケールまたは決済に必要な価格単位での利益。
  • Map – 加重移動平均の期間。
  • MaxTrades – 連続取引の最大数。
  • TradeType – 0 トレンドフォロー、1 ロング強制、2 ショート強制。
  • CandleType – 分析するローソク足の時間軸。

注意事項

この戦略は完了したローソク足と成行注文のみを使用します。ストップやリスクは管理しません。必要に応じてアカウント保護を使用してください。

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>
/// Weighted moving average trend strategy.
/// Buys when close crosses above WMA, sells when below.
/// </summary>
public class MLTrendEStrategy : Strategy
{
	private readonly StrategyParam<int> _wmaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevClose;
	private decimal _prevWma;
	private bool _hasPrev;

	public int WmaPeriod { get => _wmaPeriod.Value; set => _wmaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public MLTrendEStrategy()
	{
		_wmaPeriod = Param(nameof(WmaPeriod), 34)
			.SetGreaterThanZero()
			.SetDisplay("WMA Length", "Weighted moving average period", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe for analysis", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevClose = 0;
		_prevWma = 0;
		_hasPrev = false;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var wma = new WeightedMovingAverage { Length = WmaPeriod };
		SubscribeCandles(CandleType).Bind(wma, ProcessCandle).Start();
	}

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

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevClose = close;
			_prevWma = wmaValue;
			_hasPrev = true;
			return;
		}

		// Cross above WMA
		if (_prevClose <= _prevWma && close > wmaValue && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Cross below WMA
		else if (_prevClose >= _prevWma && close < wmaValue && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevClose = close;
		_prevWma = wmaValue;
	}
}