Стратегия Parabolic SAR CCI
Стратегия использует индикаторы Parabolic SAR и CCI для генерации сигналов. Длинная позиция открывается, когда цена выше SAR и CCI ниже -100, что указывает на восходящий тренд с перепроданностью. Короткая позиция возникает при цене ниже SAR и CCI выше 100 — нисходящий тренд с перекупленностью.
Тестирование показывает среднегодичную доходность около 49%. Стратегию лучше запускать на крипторынке.
Она подходит трейдерам, ищущим возможности в смешанном рынке.
Детали
- Условия входа:
- Лонг: Цена > SAR и CCI < -100 (восходящий тренд с перепроданностью)
- Шорт: Цена < SAR и CCI > 100 (нисходящий тренд с перекупленностью)
- Лонг/Шорт: обе стороны.
- Условия выхода:
- Лонг: Закрыть позицию при падении цены ниже SAR
- Шорт: Закрыть позицию при росте цены выше SAR
- Стопы: нет.
- Значения по умолчанию:
SarAccelerationFactor= 0.02mSarMaxAccelerationFactor= 0.2mCciPeriod= 20CandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Смешанная
- Направление: Оба
- Индикаторы: Parabolic SAR CCI
- Стопы: Нет
- Сложность: Средняя
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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 Parabolic SAR and CCI indicators
/// </summary>
public class ParabolicSarCciStrategy : Strategy
{
private readonly StrategyParam<decimal> _sarAccelerationFactor;
private readonly StrategyParam<decimal> _sarMaxAccelerationFactor;
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private int _cooldown;
private decimal _prevCci;
/// <summary>
/// Parabolic SAR acceleration factor
/// </summary>
public decimal SarAccelerationFactor
{
get => _sarAccelerationFactor.Value;
set => _sarAccelerationFactor.Value = value;
}
/// <summary>
/// Parabolic SAR maximum acceleration factor
/// </summary>
public decimal SarMaxAccelerationFactor
{
get => _sarMaxAccelerationFactor.Value;
set => _sarMaxAccelerationFactor.Value = value;
}
/// <summary>
/// CCI period
/// </summary>
public int CciPeriod
{
get => _cciPeriod.Value;
set => _cciPeriod.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 ParabolicSarCciStrategy()
{
_sarAccelerationFactor = Param(nameof(SarAccelerationFactor), 0.02m)
.SetRange(0.01m, 0.05m)
.SetDisplay("SAR AF", "Parabolic SAR acceleration factor", "Indicators")
;
_sarMaxAccelerationFactor = Param(nameof(SarMaxAccelerationFactor), 0.2m)
.SetRange(0.1m, 0.5m)
.SetDisplay("SAR Max AF", "Parabolic SAR maximum acceleration factor", "Indicators")
;
_cciPeriod = Param(nameof(CciPeriod), 20)
.SetRange(10, 50)
.SetDisplay("CCI Period", "Period for CCI indicator", "Indicators")
;
_cooldownBars = Param(nameof(CooldownBars), 50)
.SetRange(1, 200)
.SetDisplay("Cooldown Bars", "Bars between trades", "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();
_cooldown = 0;
_prevCci = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Initialize indicators
var parabolicSar = new ParabolicSar
{
Acceleration = SarAccelerationFactor,
AccelerationMax = SarMaxAccelerationFactor
};
var cci = new CommodityChannelIndex { Length = CciPeriod };
// Create subscription and bind indicators
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(parabolicSar, cci, ProcessCandle)
.Start();
// Setup chart visualization if available
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, parabolicSar);
DrawIndicator(area, cci);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal sarValue, decimal cciValue)
{
// Skip unfinished candles
if (candle.State != CandleStates.Finished)
return;
// Check if strategy is ready to trade
if (!IsFormedAndOnlineAndAllowTrading())
return;
var price = candle.ClosePrice;
var crossedUp = _prevCci <= 100m && cciValue > 100m;
var crossedDown = _prevCci >= -100m && cciValue < -100m;
_prevCci = cciValue;
if (_cooldown > 0)
_cooldown--;
// Trading logic:
// Long: Price > SAR && CCI < -100 (trend up with oversold conditions)
// Short: Price < SAR && CCI > 100 (trend down with overbought conditions)
if (_cooldown == 0 && price > sarValue && crossedUp && Position <= 0)
{
// Buy signal - trend up with oversold CCI
var volume = Volume + Math.Abs(Position);
BuyMarket(volume);
_cooldown = CooldownBars;
}
else if (_cooldown == 0 && price < sarValue && crossedDown && Position >= 0)
{
// Sell signal - trend down with overbought CCI
var volume = Volume + Math.Abs(Position);
SellMarket(volume);
_cooldown = CooldownBars;
}
// Exit conditions based on SAR breakout (dynamic stop-loss)
else if (Position > 0 && price < sarValue && cciValue < 0m)
{
// Exit long position when price drops below SAR
SellMarket(Position);
_cooldown = CooldownBars;
}
else if (Position < 0 && price > sarValue && cciValue > 0m)
{
// Exit short position when price rises above SAR
BuyMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ParabolicSar, CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
from datatype_extensions import *
class parabolic_sar_cci_strategy(Strategy):
"""Strategy based on Parabolic SAR and CCI indicators"""
def __init__(self):
super(parabolic_sar_cci_strategy, self).__init__()
self._sar_acceleration_factor = self.Param("SarAccelerationFactor", 0.02) \
.SetRange(0.01, 0.05) \
.SetDisplay("SAR AF", "Parabolic SAR acceleration factor", "Indicators")
self._sar_max_acceleration_factor = self.Param("SarMaxAccelerationFactor", 0.2) \
.SetRange(0.1, 0.5) \
.SetDisplay("SAR Max AF", "Parabolic SAR maximum acceleration factor", "Indicators")
self._cci_period = self.Param("CciPeriod", 20) \
.SetRange(10, 50) \
.SetDisplay("CCI Period", "Period for CCI indicator", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 50) \
.SetRange(1, 200) \
.SetDisplay("Cooldown Bars", "Bars between trades", "General")
self._candle_type = self.Param("CandleType", tf(15)) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._cooldown = 0
self._prev_cci = 0.0
@property
def CandleType(self):
return self._candle_type.Value
def OnReseted(self):
super(parabolic_sar_cci_strategy, self).OnReseted()
self._cooldown = 0
self._prev_cci = 0.0
def OnStarted2(self, time):
super(parabolic_sar_cci_strategy, self).OnStarted2(time)
self._cooldown = 0
self._prev_cci = 0.0
parabolic_sar = ParabolicSar()
parabolic_sar.Acceleration = self._sar_acceleration_factor.Value
parabolic_sar.AccelerationMax = self._sar_max_acceleration_factor.Value
cci = CommodityChannelIndex()
cci.Length = self._cci_period.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(parabolic_sar, cci, self.ProcessCandle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, parabolic_sar)
self.DrawIndicator(area, cci)
self.DrawOwnTrades(area)
def ProcessCandle(self, candle, sar_value, cci_value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
price = float(candle.ClosePrice)
sar = float(sar_value)
cci = float(cci_value)
crossed_up = self._prev_cci <= 100 and cci > 100
crossed_down = self._prev_cci >= -100 and cci < -100
self._prev_cci = cci
if self._cooldown > 0:
self._cooldown -= 1
cooldown_val = int(self._cooldown_bars.Value)
if self._cooldown == 0 and price > sar and crossed_up and self.Position <= 0:
volume = self.Volume + abs(self.Position)
self.BuyMarket(volume)
self._cooldown = cooldown_val
elif self._cooldown == 0 and price < sar and crossed_down and self.Position >= 0:
volume = self.Volume + abs(self.Position)
self.SellMarket(volume)
self._cooldown = cooldown_val
elif self.Position > 0 and price < sar and cci < 0:
self.SellMarket(self.Position)
self._cooldown = cooldown_val
elif self.Position < 0 and price > sar and cci > 0:
self.BuyMarket(abs(self.Position))
self._cooldown = cooldown_val
def CreateClone(self):
return parabolic_sar_cci_strategy()