View on GitHub

Color JSatl Digit Strategy

This strategy converts the MQL5 expert "Exp_ColorJSatl_Digit" into StockSharp. It digitizes the slope of the Jurik Moving Average (JMA) to classify each bar as up or down. A shift from state 0 to 1 marks an emerging uptrend, while a change from 1 to 0 signals a downtrend.

The algorithm subscribes to candles of a chosen timeframe and binds a JMA indicator. When the JMA turns upward the strategy opens a long position and closes any short. When the JMA turns downward it opens a short and closes any long. The optional DirectMode parameter inverts the signals to trade counter-trend.

Positions are protected by percentage-based stop loss and take profit levels. All parameters are defined through StrategyParam and can be optimized.

Details

  • Entry Criteria
    • Long: JMA turns upward (prev > prevPrev && current >= prev) and DirectMode is true. In reverse mode a downward turn opens the long.
    • Short: JMA turns downward (prev < prevPrev && current <= prev) and DirectMode is true. In reverse mode an upward turn opens the short.
  • Exit Criteria: Opposite signal triggers an immediate market order in the other direction. Protective orders may also exit positions.
  • Stops: Percentage stop loss and take profit via StartProtection.
  • Default Values
    • JMA Length = 30
    • Candle Type = 4-hour candles
    • Stop Loss % = 1
    • Take Profit % = 2
    • Direct Mode = true
  • Filters
    • Category: Trend following
    • Direction: Both (reversible)
    • Indicators: Jurik Moving Average
    • Stops: Yes
    • Complexity: Medium
    • Timeframe: Medium-term
    • Seasonality: No
    • Neural networks: No
    • Divergence: No
    • Risk level: Moderate
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>
/// Trend-following strategy based on the slope of Jurik Moving Average.
/// Opens long when the JMA turns up and short when it turns down.
/// </summary>
public class ColorJsatlDigitStrategy : Strategy
{
	private readonly StrategyParam<int> _jmaLength;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<bool> _directMode;
	private readonly StrategyParam<decimal> _stopLoss;
	private readonly StrategyParam<decimal> _takeProfit;

	private decimal? _prevJma;
	private decimal? _prevPrevJma;

	/// <summary>
	/// JMA period length.
	/// </summary>
	public int JmaLength
	{
		get => _jmaLength.Value;
		set => _jmaLength.Value = value;
	}

	/// <summary>
	/// Candle type used for calculations.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Trade in direction of the signal.
	/// </summary>
	public bool DirectMode
	{
		get => _directMode.Value;
		set => _directMode.Value = value;
	}

	/// <summary>
	/// Stop loss percent.
	/// </summary>
	public decimal StopLoss
	{
		get => _stopLoss.Value;
		set => _stopLoss.Value = value;
	}

	/// <summary>
	/// Take profit percent.
	/// </summary>
	public decimal TakeProfit
	{
		get => _takeProfit.Value;
		set => _takeProfit.Value = value;
	}

	public ColorJsatlDigitStrategy()
	{
		_jmaLength = Param(nameof(JmaLength), 30)
			.SetGreaterThanZero()
			.SetDisplay("JMA Length", "JMA period length", "Parameters")
			
			.SetOptimize(10, 60, 5);

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Indicator timeframe", "Parameters");

		_directMode = Param(nameof(DirectMode), true)
			.SetDisplay("Direct Mode", "Trade in direction of signal", "Parameters");

		_stopLoss = Param(nameof(StopLoss), 1m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss %", "Stop loss percent", "Risk Management")
			
			.SetOptimize(0.5m, 5m, 0.5m);

		_takeProfit = Param(nameof(TakeProfit), 2m)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit %", "Take profit percent", "Risk Management")
			
			.SetOptimize(1m, 10m, 1m);
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

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

		_prevJma = null;
		_prevPrevJma = null;
	}

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

		_prevJma = null;
		_prevPrevJma = null;

		var jma = new JurikMovingAverage { Length = JmaLength };

		var sub = SubscribeCandles(CandleType);
		sub.Bind(jma, ProcessCandle).Start();

		StartProtection(
			takeProfit: new Unit(TakeProfit * 100m, UnitTypes.Percent),
			stopLoss: new Unit(StopLoss * 100m, UnitTypes.Percent));
	}

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

		if (!IsFormedAndOnlineAndAllowTrading())
		{
			_prevPrevJma = _prevJma;
			_prevJma = jmaValue;
			return;
		}

		if (_prevJma is decimal prev && _prevPrevJma is decimal prev2)
		{
			var turnUp = prev > prev2 && jmaValue >= prev;
			var turnDown = prev < prev2 && jmaValue <= prev;

			if (DirectMode)
			{
				if (turnUp && Position <= 0)
					BuyMarket();
				else if (turnDown && Position >= 0)
					SellMarket();
			}
			else
			{
				if (turnDown && Position <= 0)
					BuyMarket();
				else if (turnUp && Position >= 0)
					SellMarket();
			}
		}

		_prevPrevJma = _prevJma;
		_prevJma = jmaValue;
	}
}