Ver no GitHub

N Candles Strategy

The N Candles strategy replicates the MQL expert advisor that enters a trade when a configurable number of consecutive candles share the same direction. Once the most recent N finished candles are all bullish, the strategy sends a market buy order. When all are bearish, it sends a market sell order. No exit logic is included; the position must be managed externally or by additional strategies.

Overview

  • Market Regime: Works best in markets that exhibit short momentum bursts.
  • Instruments: Any instrument supporting continuous trading (FX, futures, crypto).
  • Timeframes: Configurable; default is 1-hour candles.
  • Order Types: Market orders without protective stops or targets.

How It Works

  1. On every finished candle the strategy evaluates the last N candles.
  2. If every candle in that window is bullish, it issues a buy market order with the configured volume.
  3. If every candle is bearish, it issues a sell market order.
  4. Doji candles (equal open and close) reset the count and suppress trading until a new streak forms.
  5. The strategy does not manage open positions; repeated signals add to the existing direction on netting accounts.

Parameters

  • Consecutive Candles: Number of identical candles required before placing an order.
  • Volume: Market order size sent on each signal.
  • Candle Type: Candle series used for streak detection (timeframe or custom candle type).

Usage Notes

  • Because the strategy lacks stops or exits, combine it with manual management, protective strategies, or portfolio risk controls.
  • On highly volatile markets consider lowering the candle count or timeframe to capture faster streaks.
  • Excessive consecutive streaks can accumulate large positions; monitor leverage and account limits.
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>
/// Trades in the direction of consecutive candles of the same color.
/// </summary>
public class NCandlesStrategy : Strategy
{
	private readonly StrategyParam<int> _consecutiveCandles;
	private readonly StrategyParam<DataType> _candleType;

	private int _currentDirection;
	private int _streakLength;

	/// <summary>
	/// Number of identical candles that must appear in a row to trigger an order.
	/// </summary>
	public int ConsecutiveCandles
	{
		get => _consecutiveCandles.Value;
		set => _consecutiveCandles.Value = value;
	}


	/// <summary>
	/// The type of candles used for analysis.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the strategy.
	/// </summary>
	public NCandlesStrategy()
	{
		_consecutiveCandles = Param(nameof(ConsecutiveCandles), 4)
			.SetGreaterThanZero()
			.SetDisplay("Consecutive Candles", "Number of identical candles required", "General")
			
			.SetOptimize(2, 6, 1);


		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Candles to analyze", "General");
	}

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

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

		_currentDirection = 0;
		_streakLength = 0;
	}

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

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

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

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

		var direction = 0;

		if (candle.ClosePrice > candle.OpenPrice)
		{
			direction = 1;
		}
		else if (candle.ClosePrice < candle.OpenPrice)
		{
			direction = -1;
		}
		else
		{
			// Doji candle breaks the streak just like in the original expert.
			_currentDirection = 0;
			_streakLength = 0;
			return;
		}

		if (direction == _currentDirection)
		{
			_streakLength = Math.Min(_streakLength + 1, ConsecutiveCandles);
		}
		else
		{
			_currentDirection = direction;
			_streakLength = 1;
		}

		if (_streakLength < ConsecutiveCandles)
			return;

		if (direction > 0 && Position <= 0)
		{
			BuyMarket();
		}
		else if (direction < 0 && Position >= 0)
		{
			SellMarket();
		}
	}
}