Стратегия MA Parabolic SAR
Стратегия MA Parabolic SAR стремится захватывать продолжительные тренды, используя скользящую среднюю для определения направления и Parabolic SAR для точки входа и размещения стопа. Когда оба индикатора совпадают, предполагается, что импульс достаточно сильный, чтобы его поддержать.
Тестирование показывает среднегодичную доходность около 76%. Стратегию лучше запускать на рынке Форекс.
Длинная позиция открывается, когда цена выше скользящей средней и точки SAR располагаются под графиком. Короткая позиция берётся, когда цена ниже средней, а точки SAR над ценой, указывая на нисходящее давление. Выход происходит при пересечении цены и SAR в обратную сторону, фиксируя прибыль или ограничивая убыток.
Такой подход подойдёт трейдерам, предпочитающим системное следование тренду с понятными механическими стопами. Parabolic SAR постоянно подстраивается к изменению волатильности, удерживая позицию в согласии с рыночными условиями, а скользящая средняя не позволяет торговать против общего тренда.
Детали
- Условия входа:
- Лонг: Цена > MA и цена > Parabolic SAR
- Шорт: Цена < MA и цена < Parabolic SAR
- Лонг/Шорт: обе стороны.
- Условия выхода:
- Лонг: Выход при падении цены ниже Parabolic SAR
- Шорт: Выход при росте цены выше Parabolic SAR
- Стопы: да, динамические по Parabolic SAR и при желании фиксированный стоп.
- Значения по умолчанию:
MaPeriod = 20
SarStep = 0.02
SarMaxStep = 0.2
CandleType = TimeSpan.FromMinutes(5)
StopLossPercent = 2
Для входа оба условия должны выполняться на закрытии свечи, неважно, что произошло последним — переворот SAR или пересечение MA. Необязательный фиксированный стоп — StopLossPercent от цены входа, он отслеживается и между свечами; 0 отключает его. Правила не задают цель по прибыли, поэтому нулевой TakeValue убран. Сигнал на вход против открытой позиции разворачивает её.
- Фильтры:
- Категория: Тренд
- Направление: Оба
- Индикаторы: MA, Parabolic SAR
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// MA Parabolic SAR strategy.
/// A close above both the MaPeriod simple moving average and the Parabolic SAR goes long and a close below both goes short, reversing
/// an opposite position. The SAR is the trailing stop: a long closes when price closes below it and a short when price closes above it,
/// and a percent stop limits the loss.
/// </summary>
public class MaParabolicSarStrategy : Strategy
{
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<decimal> _sarStep;
private readonly StrategyParam<decimal> _sarMaxStep;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// Period of the simple moving average.
/// </summary>
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Acceleration factor of the SAR.
/// </summary>
public decimal SarStep
{
get => _sarStep.Value;
set => _sarStep.Value = value;
}
/// <summary>
/// Maximum acceleration factor of the SAR.
/// </summary>
public decimal SarMaxStep
{
get => _sarMaxStep.Value;
set => _sarMaxStep.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public MaParabolicSarStrategy()
{
_maPeriod = Param(nameof(MaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Period of the simple moving average", "Indicators");
_sarStep = Param(nameof(SarStep), 0.02m)
.SetGreaterThanZero()
.SetDisplay("SAR Step", "Acceleration factor of the SAR", "Indicators");
_sarMaxStep = Param(nameof(SarMaxStep), 0.2m)
.SetGreaterThanZero()
.SetDisplay("SAR Max Step", "Maximum acceleration factor of the SAR", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).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 OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ma = new SimpleMovingAverage { Length = MaPeriod };
var sar = new ParabolicSar
{
Acceleration = SarStep,
AccelerationMax = SarMaxStep,
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(ma, sar, ProcessCandle)
.Start();
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
// The stop has to see prices between candles, not only at their close.
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ma);
DrawIndicator(area, sar);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before this callback, also between signal bars.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue maValue, IIndicatorValue sarValue)
{
if (candle.State != CandleStates.Finished)
return;
// The first SAR value is formed but empty.
if (!maValue.IsFormed || !sarValue.IsFormed || sarValue.IsEmpty)
return;
var ma = maValue.GetValue<decimal>();
var sar = sarValue.GetValue<decimal>();
var close = candle.ClosePrice;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (close > ma && close > sar && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (close < ma && close < sar && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
else if (Position > 0 && close < sar)
SellMarket(Position);
else if (Position < 0 && close > sar)
BuyMarket(-Position);
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import SimpleMovingAverage, ParabolicSar
from StockSharp.Algo.Strategies import Strategy
class ma_parabolic_sar_strategy(Strategy):
"""
MA Parabolic SAR strategy.
A close above both the MaPeriod simple moving average and the Parabolic SAR goes long and a close below both goes short, reversing
an opposite position. The SAR is the trailing stop: a long closes when price closes below it and a short when price closes above it,
and a percent stop limits the loss.
"""
def __init__(self):
super(ma_parabolic_sar_strategy, self).__init__()
self._ma_period = self.Param("MaPeriod", 20).SetGreaterThanZero().SetDisplay("MA Period", "Period of the simple moving average", "Indicators")
self._sar_step = self.Param("SarStep", 0.02).SetGreaterThanZero().SetDisplay("SAR Step", "Acceleration factor of the SAR", "Indicators")
self._sar_max_step = self.Param("SarMaxStep", 0.2).SetGreaterThanZero().SetDisplay("SAR Max Step", "Maximum acceleration factor of the SAR", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(ma_parabolic_sar_strategy, self).OnStarted2(time)
ma = SimpleMovingAverage()
ma.Length = self._ma_period.Value
sar = ParabolicSar()
sar.Acceleration = Decimal(self._sar_step.Value)
sar.AccelerationMax = Decimal(self._sar_max_step.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(ma, sar, self._process_candle).Start()
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
# The stop has to see prices between candles, not only at their close.
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ma)
self.DrawIndicator(area, sar)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _process_candle(self, candle, ma_value, sar_value):
if candle.State != CandleStates.Finished:
return
# The first SAR value is formed but empty.
if not ma_value.IsFormed or not sar_value.IsFormed or sar_value.IsEmpty:
return
ma = ma_value.GetValue[Decimal](None)
sar = sar_value.GetValue[Decimal](None)
close = candle.ClosePrice
if not self.IsFormedAndOnlineAndAllowTrading():
return
if close > ma and close > sar and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif close < ma and close < sar and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif self.Position > 0 and close < sar:
self.SellMarket(self.Position)
elif self.Position < 0 and close > sar:
self.BuyMarket(-self.Position)
def CreateClone(self):
return ma_parabolic_sar_strategy()