Стратегия сочетает четыре осциллятора Stochastic на разных горизонтах и простой определитель пивотов ZigZag. Усреднённый Stochastic задаёт уровни перекупленности и перепроданности, а ZigZag подтверждает новые экстремумы. Покупка происходит, когда усреднённый Stochastic опускается ниже порога перепроданности и формируется новый минимум ZigZag. Продажа выполняется, когда осциллятор поднимается выше порога перекупленности и появляется новый максимум ZigZag. Противоположные позиции закрываются при обратном сигнале.
Подробности
Критерий входа: Усреднённый Stochastic в зоне перепроданности/перекупленности и соответствующий пивот ZigZag.
Длинные/Короткие: Обе стороны.
Критерий выхода: Противоположный сигнал.
Стопы: StartProtection 2%/2% (по умолчанию).
Значения по умолчанию:
ShortLength = 26
MidLength1 = 72
MidLength2 = 144
LongLength = 288
ZigZagDepth = 14
Oversold = 5
Overbought = 95
CandleType = TimeSpan.FromMinutes(5)
Фильтры:
Категория: Oscillator
Направление: Оба
Индикаторы: Stochastic, ZigZag
Стопы: Да
Сложность: Продвинутая
Таймфрейм: Внутридневной
Сезонность: Нет
Нейросети: Нет
Дивергенции: Нет
Уровень риска: Средний
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>
/// Averaged Stochastic with ZigZag-style pivot confirmation.
/// Uses RSI as simplified oscillator and highest/lowest for pivots.
/// </summary>
public class Aver4StochPostZigZagStrategy : Strategy
{
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _pivotLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevRsi;
private bool _hasPrev;
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int PivotLength { get => _pivotLength.Value; set => _pivotLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public Aver4StochPostZigZagStrategy()
{
_rsiLength = Param(nameof(RsiLength), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI period", "Indicators");
_pivotLength = Param(nameof(PivotLength), 20)
.SetGreaterThanZero()
.SetDisplay("Pivot Length", "Highest/Lowest period", "Indicators");
_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();
_prevRsi = 0;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var highest = new Highest { Length = PivotLength };
var lowest = new Lowest { Length = PivotLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, highest, lowest, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal rsi, decimal high, decimal low)
{
if (candle.State != CandleStates.Finished)
return;
if (!_hasPrev)
{
_prevRsi = rsi;
_hasPrev = true;
return;
}
var close = candle.ClosePrice;
// Near pivot low + RSI oversold -> buy
if (close <= low * 1.001m && rsi < 30 && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Near pivot high + RSI overbought -> sell
else if (close >= high * 0.999m && rsi > 70 && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
// Exit long on RSI overbought
else if (Position > 0 && rsi > 70)
{
SellMarket();
}
// Exit short on RSI oversold
else if (Position < 0 && rsi < 30)
{
BuyMarket();
}
_prevRsi = rsi;
}
}
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 RelativeStrengthIndex, Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class aver4_stoch_post_zig_zag_strategy(Strategy):
def __init__(self):
super(aver4_stoch_post_zig_zag_strategy, self).__init__()
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "RSI period", "Indicators")
self._pivot_length = self.Param("PivotLength", 20) \
.SetDisplay("Pivot Length", "Highest/Lowest period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_rsi = 0.0
self._has_prev = False
@property
def rsi_length(self):
return self._rsi_length.Value
@property
def pivot_length(self):
return self._pivot_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(aver4_stoch_post_zig_zag_strategy, self).OnReseted()
self._prev_rsi = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(aver4_stoch_post_zig_zag_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_length
highest = Highest()
highest.Length = self.pivot_length
lowest = Lowest()
lowest.Length = self.pivot_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, highest, lowest, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, rsi, high, low):
if candle.State != CandleStates.Finished:
return
if not self._has_prev:
self._prev_rsi = rsi
self._has_prev = True
return
close = candle.ClosePrice
# Near pivot low + RSI oversold -> buy
if close <= low * 1.001 and rsi < 30 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Near pivot high + RSI overbought -> sell
elif close >= high * 0.999 and rsi > 70 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
# Exit long on RSI overbought
elif self.Position > 0 and rsi > 70:
self.SellMarket()
# Exit short on RSI oversold
elif self.Position < 0 and rsi < 30:
self.BuyMarket()
self._prev_rsi = rsi
def CreateClone(self):
return aver4_stoch_post_zig_zag_strategy()