Ver en GitHub

Bezier Standard Deviation Strategy

This strategy trades turning points in volatility using a standard deviation indicator. It interprets local minima and maxima of the indicator as potential reversals in price action. When the standard deviation forms a trough, the system expects volatility to expand upward and enters a long position. When a peak appears, it sells short anticipating volatility contraction.

The approach is designed for both long and short trading on a four-hour timeframe by default. It does not apply stop-loss orders, focusing instead on signal-based exits.

Details

  • Entry Criteria:
    • Long: Standard deviation value at the previous bar is lower than its neighbors (local minimum).
    • Short: Standard deviation value at the previous bar is higher than its neighbors (local maximum).
  • Long/Short: Both.
  • Exit Criteria:
    • Opposite signal triggers a reversal.
  • Stops: No.
  • Default Values:
    • StdDev Period = 9.
    • Candle Type = 4-hour candles.
  • Filters:
    • Category: Mean reversion
    • Direction: Both
    • Indicators: Standard deviation
    • Stops: No
    • Complexity: Simple
    • Timeframe: Medium-term
    • 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 standard deviation turning points.
/// Opens long at local minima and short at local maxima of the indicator.
/// </summary>
public class BezierStDevStrategy : Strategy
{
	private readonly StrategyParam<int> _stdDevPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevValue1;
	private decimal _prevValue2;

	/// <summary>
	/// Standard deviation calculation period.
	/// </summary>
	public int StdDevPeriod
	{
		get => _stdDevPeriod.Value;
		set => _stdDevPeriod.Value = value;
	}

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

	/// <summary>
	/// Initializes a new instance of the strategy.
	/// </summary>
	public BezierStDevStrategy()
	{
		_stdDevPeriod = Param(nameof(StdDevPeriod), 9)
			.SetGreaterThanZero()
			.SetDisplay("StdDev Period", "Period for standard deviation calculation", "General")
			
			.SetOptimize(5, 20, 1);

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

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

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

		_prevValue1 = 0m;
		_prevValue2 = 0m;
	}

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

		var stdDev = new StandardDeviation { Length = StdDevPeriod };

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

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

	private void ProcessCandle(ICandleMessage candle, decimal stdDevValue)
	{
		// We only work with finished candles.
		if (candle.State != CandleStates.Finished)
			return;

		// Ensure the strategy is ready for trading.
		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		// Check for local minima and maxima at the previous value.
		if (_prevValue2 != 0m)
		{
			var isLocalMin = _prevValue1 < _prevValue2 && _prevValue1 < stdDevValue;
			var isLocalMax = _prevValue1 > _prevValue2 && _prevValue1 > stdDevValue;

			if (isLocalMin)
			{
				if (Position <= 0)
					BuyMarket();
			}
			else if (isLocalMax)
			{
				if (Position >= 0)
					SellMarket();
			}
		}

		// Shift stored values for next calculation.
		_prevValue2 = _prevValue1;
		_prevValue1 = stdDevValue;
	}
}