View on GitHub

MLTrendE Strategy

This strategy trades in the direction of a weighted moving average (WMA) and optionally pyramids positions when price moves favorably.

Logic

  • Calculate a WMA of the selected candle series.
  • If no position is open:
    • Trade type 0: open a long position when the close price is above the WMA, or a short position when it is below.
    • Trade type 1: always open a long position.
    • Trade type 2: always open a short position.
  • When a position is open and reaches the specified profit target, add another trade with scaled volume.
  • Once the maximum number of trades is reached, the entire position is closed at the next profit target.

Parameters

  • Volume – base trade volume.
  • Multiplier1 – volume multiplier for the second trade.
  • Multiplier2 – volume multiplier for the third trade.
  • TakeProfit – profit in price units required to scale or close.
  • Map – period of the weighted moving average.
  • MaxTrades – maximum number of consecutive trades.
  • TradeType – 0 trend following, 1 force long, 2 force short.
  • CandleType – timeframe of the analyzed candles.

Notes

The strategy uses only completed candles and market orders. It does not manage stops or risk; use account protection if needed.

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;
	}
}