Auf GitHub ansehen

SAR Trailing System Strategy

Strategy that enters random long or short positions at fixed time intervals and manages exits using the Parabolic SAR indicator. The Parabolic SAR value acts as a trailing stop: the position closes when price crosses the SAR level.

Details

  • Entry Criteria:
    • Every TimerInterval, if there is no open position and UseRandomEntry is enabled, a random long or short trade is opened.
  • Long/Short: Both
  • Exit Criteria: Price crossing the Parabolic SAR.
  • Stops: Initial stop-loss in ticks with Parabolic SAR trailing exit.
  • Default Values:
    • TimerInterval = 300 seconds
    • StopLossTicks = 10
    • AccelerationStep = 0.02
    • AccelerationMax = 0.2
    • UseRandomEntry = true
    • CandleType = TimeSpan.FromMinutes(1).TimeFrame()
  • Filters:
    • Category: Trend-following
    • Direction: Both
    • Indicators: Parabolic SAR
    • Stops: Yes
    • Complexity: Beginner
    • Timeframe: Short-term
    • Seasonality: No
    • Neural Networks: No
    • Divergence: No
    • Risk Level: Medium
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>
/// Strategy that uses Parabolic SAR for trend-following entries and exits.
/// Buy when price crosses above SAR, sell when below.
/// </summary>
public class SarTrailingSystemStrategy : Strategy
{
	private readonly StrategyParam<decimal> _accelerationStep;
	private readonly StrategyParam<decimal> _accelerationMax;
	private readonly StrategyParam<DataType> _candleType;

	public decimal AccelerationStep { get => _accelerationStep.Value; set => _accelerationStep.Value = value; }
	public decimal AccelerationMax { get => _accelerationMax.Value; set => _accelerationMax.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public SarTrailingSystemStrategy()
	{
		_accelerationStep = Param(nameof(AccelerationStep), 0.02m)
			.SetGreaterThanZero()
			.SetDisplay("SAR Step", "Parabolic SAR acceleration step", "Indicators");

		_accelerationMax = Param(nameof(AccelerationMax), 0.2m)
			.SetGreaterThanZero()
			.SetDisplay("SAR Max", "Parabolic SAR maximum acceleration", "Indicators");

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

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

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var sar = new ParabolicSar
		{
			Acceleration = AccelerationStep,
			AccelerationStep = AccelerationStep,
			AccelerationMax = AccelerationMax
		};

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

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

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		// Price above SAR = uptrend, buy
		if (candle.ClosePrice > sarValue && Position <= 0)
			BuyMarket();
		// Price below SAR = downtrend, sell
		else if (candle.ClosePrice < sarValue && Position >= 0)
			SellMarket();
	}
}