Zigzag Candles
Простая стратегия, реагирующая на пивоты ZigZag. Длинная позиция открывается при формировании нового минимума, короткая — при новом максимуме.
Детали
- Условия входа: Пивоты ZigZag.
- Длинные/короткие: Обе стороны.
- Условия выхода: Противоположный пивот.
- Стопы: Нет.
- Значения по умолчанию:
ZigzagLength= 5CandleType= TimeSpan.FromMinutes(1)
- Фильтры:
- Категория: Тренд
- Направление: Обе
- Индикаторы: Highest, Lowest
- Стопы: Нет
- Сложность: Базовая
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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 trading on ZigZag pivots.
/// </summary>
public class ZigzagCandlesStrategy : Strategy
{
private readonly StrategyParam<int> _zigzagLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _lastZigzag;
private decimal _lastZigzagHigh;
private decimal _lastZigzagLow;
private int _direction;
private bool _signalFired;
public int ZigzagLength
{
get => _zigzagLength.Value;
set => _zigzagLength.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public ZigzagCandlesStrategy()
{
_zigzagLength = Param(nameof(ZigzagLength), 5)
.SetDisplay("ZigZag Length", "Lookback for pivot search", "ZigZag");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_lastZigzag = 0m;
_lastZigzagHigh = 0m;
_lastZigzagLow = 0m;
_direction = 0;
_signalFired = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_lastZigzag = 0m;
_lastZigzagHigh = 0m;
_lastZigzagLow = 0m;
_direction = 0;
_signalFired = false;
var highest = new Highest { Length = ZigzagLength };
var lowest = new Lowest { Length = ZigzagLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(highest, lowest, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal highest, decimal lowest)
{
if (candle.State != CandleStates.Finished)
return;
var prevDirection = _direction;
if (candle.HighPrice >= highest && _direction != 1)
{
_lastZigzag = candle.HighPrice;
_lastZigzagHigh = candle.HighPrice;
_direction = 1;
_signalFired = false;
}
else if (candle.LowPrice <= lowest && _direction != -1)
{
_lastZigzag = candle.LowPrice;
_lastZigzagLow = candle.LowPrice;
_direction = -1;
_signalFired = false;
}
if (_signalFired)
return;
if (_direction == -1 && prevDirection != -1 && Position <= 0)
{
BuyMarket();
_signalFired = true;
}
else if (_direction == 1 && prevDirection != 1 && Position >= 0)
{
SellMarket();
_signalFired = true;
}
}
}
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 Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class zigzag_candles_strategy(Strategy):
def __init__(self):
super(zigzag_candles_strategy, self).__init__()
self._zigzag_length = self.Param("ZigzagLength", 5) \
.SetDisplay("ZigZag Length", "Lookback for pivot search", "ZigZag")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._last_zigzag = 0.0
self._last_zigzag_high = 0.0
self._last_zigzag_low = 0.0
self._direction = 0
self._signal_fired = False
@property
def zigzag_length(self):
return self._zigzag_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(zigzag_candles_strategy, self).OnReseted()
self._last_zigzag = 0.0
self._last_zigzag_high = 0.0
self._last_zigzag_low = 0.0
self._direction = 0
self._signal_fired = False
def OnStarted2(self, time):
super(zigzag_candles_strategy, self).OnStarted2(time)
highest = Highest()
highest.Length = self.zigzag_length
lowest = Lowest()
lowest.Length = self.zigzag_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(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, highest, lowest):
if candle.State != CandleStates.Finished:
return
prev_direction = self._direction
if candle.HighPrice >= highest and self._direction != 1:
self._last_zigzag = candle.HighPrice
self._last_zigzag_high = candle.HighPrice
self._direction = 1
self._signal_fired = False
elif candle.LowPrice <= lowest and self._direction != -1:
self._last_zigzag = candle.LowPrice
self._last_zigzag_low = candle.LowPrice
self._direction = -1
self._signal_fired = False
if self._signal_fired:
return
if self._direction == -1 and prev_direction != -1 and self.Position <= 0:
self.BuyMarket()
self._signal_fired = True
elif self._direction == 1 and prev_direction != 1 and self.Position >= 0:
self.SellMarket()
self._signal_fired = True
def CreateClone(self):
return zigzag_candles_strategy()