Стратегия Three Parabolic SAR
Стратегия Three Parabolic SAR использует три индикатора Parabolic SAR, рассчитанных на свечах 6 часов, 3 часов и 1 часа. Сделки открываются на часовом таймфрейме, когда два старших таймфрейма подтверждают направление, а SAR на 1‑часовых свечах меняет положение относительно цены.
Детали
- Условия входа:
- SAR на 6ч и 3ч свечах ниже цены для длинной позиции; выше цены для короткой.
- На 1ч свечах SAR пересекает цену: сверху вниз для входа в лонг, снизу вверх для входа в шорт.
- Длинные/короткие: Оба направления.
- Условия выхода: Позиция закрывается, когда SAR на 1ч свечах меняется против позиции или когда любой из старших таймфреймов разворачивается.
- Стопы: Нет.
- Значения по умолчанию:
Acceleration= 0.02MaxAcceleration= 0.2HigherTimeframe= TimeSpan.FromHours(6)MiddleTimeframe= TimeSpan.FromHours(3)TradingTimeframe= TimeSpan.FromHours(1)
- Фильтры:
- Категория: Trend
- Направление: Both
- Индикаторы: Parabolic SAR
- Стопы: Нет
- Сложность: Базовая
- Таймфрейм: Multi-timeframe
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// Parabolic SAR strategy using fast and slow SAR parameters.
/// Buys when price is above both SAR levels, sells when below both.
/// </summary>
public class ThreeParabolicSarStrategy : Strategy
{
private readonly StrategyParam<decimal> _fastAcceleration;
private readonly StrategyParam<decimal> _slowAcceleration;
private readonly StrategyParam<DataType> _candleType;
private bool _prevFastAbove;
private bool _prevSlowAbove;
private bool _hasPrev;
public decimal FastAcceleration { get => _fastAcceleration.Value; set => _fastAcceleration.Value = value; }
public decimal SlowAcceleration { get => _slowAcceleration.Value; set => _slowAcceleration.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ThreeParabolicSarStrategy()
{
_fastAcceleration = Param(nameof(FastAcceleration), 0.04m)
.SetDisplay("Fast Acceleration", "Fast SAR acceleration", "SAR");
_slowAcceleration = Param(nameof(SlowAcceleration), 0.01m)
.SetDisplay("Slow Acceleration", "Slow SAR acceleration", "SAR");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevFastAbove = false;
_prevSlowAbove = false;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastSar = new ParabolicSar { Acceleration = FastAcceleration, AccelerationMax = 0.2m };
var slowSar = new ParabolicSar { Acceleration = SlowAcceleration, AccelerationMax = 0.1m };
SubscribeCandles(CandleType).Bind(fastSar, slowSar, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastSar, decimal slowSar)
{
if (candle.State != CandleStates.Finished) return;
var fastAbove = candle.ClosePrice > fastSar;
var slowAbove = candle.ClosePrice > slowSar;
if (!_hasPrev)
{
_prevFastAbove = fastAbove;
_prevSlowAbove = slowAbove;
_hasPrev = true;
return;
}
// Buy when both SAR levels flip bullish
if (fastAbove && slowAbove && (!_prevFastAbove || !_prevSlowAbove) && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
// Sell when both SAR levels flip bearish
else if (!fastAbove && !slowAbove && (_prevFastAbove || _prevSlowAbove) && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
// Exit long if slow SAR turns bearish
else if (Position > 0 && !slowAbove)
{
SellMarket();
}
// Exit short if slow SAR turns bullish
else if (Position < 0 && slowAbove)
{
BuyMarket();
}
_prevFastAbove = fastAbove;
_prevSlowAbove = slowAbove;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ParabolicSar
from StockSharp.Algo.Strategies import Strategy
class three_parabolic_sar_strategy(Strategy):
def __init__(self):
super(three_parabolic_sar_strategy, self).__init__()
self._fast_acceleration = self.Param("FastAcceleration", 0.04) \
.SetDisplay("Fast Acceleration", "Fast SAR acceleration", "SAR")
self._slow_acceleration = self.Param("SlowAcceleration", 0.01) \
.SetDisplay("Slow Acceleration", "Slow SAR acceleration", "SAR")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_fast_above = False
self._prev_slow_above = False
self._has_prev = False
@property
def fast_acceleration(self):
return self._fast_acceleration.Value
@property
def slow_acceleration(self):
return self._slow_acceleration.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(three_parabolic_sar_strategy, self).OnReseted()
self._prev_fast_above = False
self._prev_slow_above = False
self._has_prev = False
def OnStarted2(self, time):
super(three_parabolic_sar_strategy, self).OnStarted2(time)
fast_sar = ParabolicSar()
fast_sar.Acceleration = self.fast_acceleration
fast_sar.AccelerationMax = 0.2
slow_sar = ParabolicSar()
slow_sar.Acceleration = self.slow_acceleration
slow_sar.AccelerationMax = 0.1
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_sar, slow_sar, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, fast_sar, slow_sar):
if candle.State != CandleStates.Finished:
return
fast_above = candle.ClosePrice > fast_sar
slow_above = candle.ClosePrice > slow_sar
if not self._has_prev:
self._prev_fast_above = fast_above
self._prev_slow_above = slow_above
self._has_prev = True
return
# Buy when both SAR levels flip bullish
if fast_above and slow_above and (not self._prev_fast_above or not self._prev_slow_above) and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Sell when both SAR levels flip bearish
elif not fast_above and not slow_above and (self._prev_fast_above or self._prev_slow_above) and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
# Exit long if slow SAR turns bearish
elif self.Position > 0 and not slow_above:
self.SellMarket()
# Exit short if slow SAR turns bullish
elif self.Position < 0 and slow_above:
self.BuyMarket()
self._prev_fast_above = fast_above
self._prev_slow_above = slow_above
def CreateClone(self):
return three_parabolic_sar_strategy()