Ver no GitHub

Stochastic Keltner Strategy

This strategy uses Stochastic Keltner indicators to generate signals. Long entry occurs when Stoch %K < 20 && Price < Keltner lower band (oversold at lower band). Short entry occurs when Stoch %K > 80 && Price > Keltner upper band (overbought at upper band). It is suitable for traders seeking opportunities in mixed markets.

Testing indicates an average annual return of about 61%. It performs best in the crypto market.

Details

  • Entry Criteria:
    • Long: Stoch %K < 20 && Price < Keltner lower band (oversold at lower band)
    • Short: Stoch %K > 80 && Price > Keltner upper band (overbought at upper band)
  • Long/Short: Both sides.
  • Exit Criteria:
    • Long: Exit long position when price returns to middle band
    • Short: Exit short position when price returns to middle band
  • Stops: Yes.
  • Default Values:
    • StochPeriod = 14
    • StochK = 3
    • StochD = 3
    • EmaPeriod = 20
    • KeltnerMultiplier = 2m
    • AtrPeriod = 14
    • AtrMultiplier = 2m
    • CandleType = TimeSpan.FromMinutes(5)
  • Filters:
    • Category: Mixed
    • Direction: Both
    • Indicators: Stochastic Keltner
    • Stops: Yes
    • Complexity: Intermediate
    • Timeframe: Intraday
    • Seasonality: No
    • Neural networks: No
    • Divergence: No
    • Risk Level: Medium
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>
/// Strategy based on Stochastic Oscillator and Keltner Channels indicators
/// </summary>
public class StochasticKeltnerStrategy : Strategy
{
	private readonly StrategyParam<int> _stochPeriod;
	private readonly StrategyParam<int> _stochK;
	private readonly StrategyParam<int> _stochD;
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<decimal> _keltnerMultiplier;
	private readonly StrategyParam<int> _atrPeriod;
	private readonly StrategyParam<decimal> _atrMultiplier;
	private readonly StrategyParam<int> _cooldownBars;
	private readonly StrategyParam<DataType> _candleType;
	private decimal _prevStochK;
	private int _cooldown;

	/// <summary>
	/// Stochastic period
	/// </summary>
	public int StochPeriod
	{
		get => _stochPeriod.Value;
		set => _stochPeriod.Value = value;
	}

	/// <summary>
	/// Stochastic %K smoothing period
	/// </summary>
	public int StochK
	{
		get => _stochK.Value;
		set => _stochK.Value = value;
	}

	/// <summary>
	/// Stochastic %D smoothing period
	/// </summary>
	public int StochD
	{
		get => _stochD.Value;
		set => _stochD.Value = value;
	}

	/// <summary>
	/// EMA period for Keltner Channel
	/// </summary>
	public int EmaPeriod
	{
		get => _emaPeriod.Value;
		set => _emaPeriod.Value = value;
	}

	/// <summary>
	/// Keltner Channel multiplier (k)
	/// </summary>
	public decimal KeltnerMultiplier
	{
		get => _keltnerMultiplier.Value;
		set => _keltnerMultiplier.Value = value;
	}

	/// <summary>
	/// ATR period for Keltner Channel and stop-loss
	/// </summary>
	public int AtrPeriod
	{
		get => _atrPeriod.Value;
		set => _atrPeriod.Value = value;
	}

	/// <summary>
	/// ATR multiplier for stop-loss
	/// </summary>
	public decimal AtrMultiplier
	{
		get => _atrMultiplier.Value;
		set => _atrMultiplier.Value = value;
	}

	/// <summary>
	/// Bars to wait between trades.
	/// </summary>
	public int CooldownBars
	{
		get => _cooldownBars.Value;
		set => _cooldownBars.Value = value;
	}

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

	/// <summary>
	/// Constructor
	/// </summary>
	public StochasticKeltnerStrategy()
	{
		_stochPeriod = Param(nameof(StochPeriod), 14)
			.SetRange(5, 30)
			.SetDisplay("Stoch Period", "Period for Stochastic Oscillator", "Stochastic")
			;

		_stochK = Param(nameof(StochK), 3)
			.SetRange(1, 10)
			.SetDisplay("Stoch %K", "Stochastic %K smoothing period", "Stochastic")
			;

		_stochD = Param(nameof(StochD), 3)
			.SetRange(1, 10)
			.SetDisplay("Stoch %D", "Stochastic %D smoothing period", "Stochastic")
			;

		_emaPeriod = Param(nameof(EmaPeriod), 20)
			.SetRange(10, 50)
			.SetDisplay("EMA Period", "EMA period for Keltner Channel", "Keltner")
			;

		_keltnerMultiplier = Param(nameof(KeltnerMultiplier), 2m)
			.SetRange(1m, 4m)
			.SetDisplay("K Multiplier", "Multiplier for Keltner Channel", "Keltner")
			;

		_atrPeriod = Param(nameof(AtrPeriod), 14)
			.SetRange(7, 28)
			.SetDisplay("ATR Period", "ATR period for Keltner Channel and stop-loss", "Risk Management")
			;

		_atrMultiplier = Param(nameof(AtrMultiplier), 2m)
			.SetRange(1m, 4m)
			.SetDisplay("ATR Multiplier", "Multiplier for ATR-based stop-loss", "Risk Management")
			;

		_cooldownBars = Param(nameof(CooldownBars), 40)
			.SetRange(1, 200)
			.SetDisplay("Cooldown Bars", "Bars between entries", "General");

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevStochK = 50m;
		_cooldown = 0;
	}

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

		// Initialize indicators
		var stochastic = new StochasticOscillator
		{
			K = { Length = StochPeriod },
			D = { Length = StochD },
		};

		var keltner = new KeltnerChannels
		{
			Length = EmaPeriod,
		};

		var atr = new AverageTrueRange { Length = AtrPeriod };

		// Create subscription and bind indicators
		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(keltner, stochastic, atr, ProcessIndicators)
			.Start();
		
		// Setup chart visualization if available
		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, keltner);
			DrawIndicator(area, stochastic);
			DrawOwnTrades(area);
		}
	}

	private void ProcessIndicators(ICandleMessage candle, IIndicatorValue keltnerValue, IIndicatorValue stochValue, IIndicatorValue atrValue)
	{
		// Skip unfinished candles
		if (candle.State != CandleStates.Finished)
			return;

		// Check if strategy is ready to trade
		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var price = candle.ClosePrice;

		var keltnerTyped = (KeltnerChannelsValue)keltnerValue;
		var upperBand = keltnerTyped.Upper;
		var lowerBand = keltnerTyped.Lower;
		var middleBand = keltnerTyped.Middle;

		// Trading logic:
		// Long: Stoch %K < 20 && Price < Keltner lower band (oversold at lower band)
		// Short: Stoch %K > 80 && Price > Keltner upper band (overbought at upper band)

		var stochTyped = (StochasticOscillatorValue)stochValue;
		if (stochTyped.K is not decimal stochK)
			return;

		var crossedBelow20 = _prevStochK >= 20m && stochK < 20m;
		var crossedAbove80 = _prevStochK <= 80m && stochK > 80m;
		_prevStochK = stochK;

		if (_cooldown > 0)
			_cooldown--;

		if (_cooldown == 0 && crossedBelow20 && price <= lowerBand * 1.001m && Position <= 0)
		{
			var volume = Volume + Math.Abs(Position);
			BuyMarket(volume);
			_cooldown = CooldownBars;
		}
		else if (_cooldown == 0 && crossedAbove80 && price >= upperBand * 0.999m && Position >= 0)
		{
			var volume = Volume + Math.Abs(Position);
			SellMarket(volume);
			_cooldown = CooldownBars;
		}
		// Exit conditions
		else if (Position > 0 && crossedAbove80)
		{
			SellMarket(Position);
			_cooldown = CooldownBars;
		}
		else if (Position < 0 && crossedBelow20)
		{
			BuyMarket(Math.Abs(Position));
			_cooldown = CooldownBars;
		}
	}
}