Ver no GitHub

ColorMETRO Stochastic Strategy

This strategy is a C# port of the MQL5 expert exp_colormetro_stochastic.mq5. It replaces the original ColorMETRO Stochastic indicator with the built-in StochasticOscillator from StockSharp and trades on crossover events.

Logic

  • Subscribes to 8-hour candles by default (configurable).
  • Calculates the Stochastic oscillator with parameters:
    • %K period (KPeriod)
    • %D period (DPeriod)
    • Additional smoothing (Slowing)
  • Stores previous %K and %D values to detect crossovers.
  • Buy when %K crosses above %D.
  • Sell when %K crosses below %D.
  • Applies a simple 2% stop-loss and take-profit via StartProtection.

Parameters

Name Description
KPeriod Lookback for %K line (default 5).
DPeriod Smoothing period for %D line (default 3).
Slowing Additional smoothing value (default 3).
CandleType Timeframe of candles, default 8 hours.

Notes

The original MQL version used a custom ColorMETRO Stochastic indicator with fast and slow step lines. This port approximates its signals using the standard Stochastic oscillator.

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>
/// ColorMETRO Stochastic crossover strategy based on the Stochastic Oscillator.
/// Generates market entries when %K crosses %D.
/// </summary>
public class ColorMetroStochasticStrategy : Strategy
{
	private readonly StrategyParam<int> _kPeriod;
	private readonly StrategyParam<int> _dPeriod;
	private readonly StrategyParam<int> _slowing;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevK;
	private decimal? _prevD;

	/// <summary>
	/// %K calculation period.
	/// </summary>
	public int KPeriod
	{
		get => _kPeriod.Value;
		set => _kPeriod.Value = value;
	}

	/// <summary>
	/// %D smoothing period.
	/// </summary>
	public int DPeriod
	{
		get => _dPeriod.Value;
		set => _dPeriod.Value = value;
	}

	/// <summary>
	/// Additional smoothing value.
	/// </summary>
	public int Slowing
	{
		get => _slowing.Value;
		set => _slowing.Value = value;
	}

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

	/// <summary>
	/// Initializes a new instance of the strategy.
	/// </summary>
	public ColorMetroStochasticStrategy()
	{
		_kPeriod = Param(nameof(KPeriod), 5)
			.SetGreaterThanZero()
			.SetDisplay("K Period", "K calculation period", "Indicator")
			.SetOptimize(3, 15, 1);

		_dPeriod = Param(nameof(DPeriod), 3)
			.SetGreaterThanZero()
			.SetDisplay("D Period", "D smoothing period", "Indicator")
			.SetOptimize(2, 10, 1);

		_slowing = Param(nameof(Slowing), 3)
			.SetGreaterThanZero()
			.SetDisplay("Slowing", "Additional smoothing", "Indicator")
			.SetOptimize(1, 5, 1);

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevK = null;
		_prevD = null;
	}

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

		_prevK = null;
		_prevD = null;

		var stoch = new StochasticOscillator();
		stoch.K.Length = KPeriod;
		stoch.D.Length = DPeriod;

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(stoch, ProcessCandle)
			.Start();

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

		StartProtection(
			takeProfit: new Unit(2, UnitTypes.Percent),
			stopLoss: new Unit(2, UnitTypes.Percent));
	}

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var stoch = (IStochasticOscillatorValue)stochValue;

		if (stoch.K is not decimal k || stoch.D is not decimal d)
			return;

		if (_prevK is decimal prevK && _prevD is decimal prevD)
		{
			// Bullish crossover: %K rises above %D
			if (prevK <= prevD && k > d && Position <= 0)
				BuyMarket();

			// Bearish crossover: %K falls below %D
			else if (prevK >= prevD && k < d && Position >= 0)
				SellMarket();
		}

		_prevK = k;
		_prevD = d;
	}
}