Zig Zag Aroon Strategy
Стратегия сочетает простое определение пивотов ZigZag с индикатором Aroon. Покупка выполняется, когда Aroon Up пересекает Aroon Down сверху и последний пивот является максимумом. Продажа открывается при обратном пересечении и последнем минимуме.
Детали
- Условия входа: Пересечение Aroon при соответствующем пивоте ZigZag.
- Длинные/короткие: Обе стороны.
- Условия выхода: Противоположный сигнал.
- Стопы: Нет.
- Значения по умолчанию:
ZigZagDepth= 5AroonLength= 14CandleType= TimeSpan.FromMinutes(1)
- Фильтры:
- Категория: Тренд
- Направление: Обе
- Индикаторы: Aroon, ZigZag
- Стопы: Нет
- Сложность: Базовая
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// ZigZag + Aroon strategy.
/// Uses manual ZigZag pivot detection and Aroon crossover for entry signals.
/// </summary>
public class ZigZagAroonStrategy : Strategy
{
private readonly StrategyParam<int> _zigZagDepth;
private readonly StrategyParam<int> _aroonLength;
private readonly StrategyParam<DataType> _candleType;
private readonly List<decimal> _highs = new();
private readonly List<decimal> _lows = new();
private decimal _lastZigzagHigh;
private decimal _lastZigzagLow;
private int _direction;
private decimal _prevAroonUp;
private decimal _prevAroonDown;
public int ZigZagDepth { get => _zigZagDepth.Value; set => _zigZagDepth.Value = value; }
public int AroonLength { get => _aroonLength.Value; set => _aroonLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ZigZagAroonStrategy()
{
_zigZagDepth = Param(nameof(ZigZagDepth), 5)
.SetGreaterThanZero()
.SetDisplay("ZigZag Depth", "Pivot search depth", "ZigZag");
_aroonLength = Param(nameof(AroonLength), 14)
.SetGreaterThanZero()
.SetDisplay("Aroon Period", "Aroon indicator period", "Aroon");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_highs.Clear();
_lows.Clear();
_lastZigzagHigh = 0;
_lastZigzagLow = 0;
_direction = 0;
_prevAroonUp = 0;
_prevAroonDown = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = 10 };
_highs.Clear();
_lows.Clear();
_lastZigzagHigh = 0;
_lastZigzagLow = 0;
_direction = 0;
_prevAroonUp = 0;
_prevAroonDown = 0;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(sma, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal _dummy)
{
if (candle.State != CandleStates.Finished)
return;
_highs.Add(candle.HighPrice);
_lows.Add(candle.LowPrice);
var maxLen = Math.Max(ZigZagDepth, AroonLength) + 2;
if (_highs.Count > maxLen * 2)
{
_highs.RemoveAt(0);
_lows.RemoveAt(0);
}
if (_highs.Count < ZigZagDepth)
return;
// Manual highest/lowest over ZigZagDepth
var recentHighs = _highs.Skip(_highs.Count - ZigZagDepth);
var recentLows = _lows.Skip(_lows.Count - ZigZagDepth);
var highest = recentHighs.Max();
var lowest = recentLows.Min();
// ZigZag direction
if (candle.HighPrice >= highest && _direction != 1)
{
_lastZigzagHigh = candle.HighPrice;
_direction = 1;
}
else if (candle.LowPrice <= lowest && _direction != -1)
{
_lastZigzagLow = candle.LowPrice;
_direction = -1;
}
if (_highs.Count < AroonLength + 1)
return;
// Manual Aroon calculation
var count = AroonLength + 1;
if (_highs.Count < count || _lows.Count < count)
return;
var aroonHighs = _highs.GetRange(_highs.Count - count, count);
var aroonLows = _lows.GetRange(_lows.Count - count, count);
var highestIdx = 0;
var lowestIdx = 0;
for (int i = 1; i < count; i++)
{
if (aroonHighs[i] >= aroonHighs[highestIdx]) highestIdx = i;
if (aroonLows[i] <= aroonLows[lowestIdx]) lowestIdx = i;
}
var aroonUp = 100m * highestIdx / AroonLength;
var aroonDown = 100m * lowestIdx / AroonLength;
// Aroon crossover
var crossUp = _prevAroonUp <= _prevAroonDown && aroonUp > aroonDown;
var crossDown = _prevAroonDown <= _prevAroonUp && aroonDown > aroonUp;
if (crossUp && _direction == 1 && Position <= 0)
BuyMarket();
else if (crossDown && _direction == -1 && Position >= 0)
SellMarket();
_prevAroonUp = aroonUp;
_prevAroonDown = aroonDown;
}
}
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 SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class zig_zag_aroon_strategy(Strategy):
def __init__(self):
super(zig_zag_aroon_strategy, self).__init__()
self._zig_zag_depth = self.Param("ZigZagDepth", 5) \
.SetDisplay("ZigZag Depth", "Pivot search depth", "ZigZag")
self._aroon_length = self.Param("AroonLength", 14) \
.SetDisplay("Aroon Period", "Aroon indicator period", "Aroon")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._highs = []
self._lows = []
self._last_zigzag_high = 0.0
self._last_zigzag_low = 0.0
self._direction = 0
self._prev_aroon_up = 0.0
self._prev_aroon_down = 0.0
@property
def zig_zag_depth(self):
return self._zig_zag_depth.Value
@property
def aroon_length(self):
return self._aroon_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(zig_zag_aroon_strategy, self).OnReseted()
self._highs = []
self._lows = []
self._last_zigzag_high = 0.0
self._last_zigzag_low = 0.0
self._direction = 0
self._prev_aroon_up = 0.0
self._prev_aroon_down = 0.0
def OnStarted2(self, time):
super(zig_zag_aroon_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = 10
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, _dummy):
if candle.State != CandleStates.Finished:
return
self._highs.append(candle.HighPrice)
self._lows.append(candle.LowPrice)
max_len = max(int(self.zig_zag_depth), int(self.aroon_length)) + 2
if len(self._highs) > max_len * 2:
self._highs.pop(0)
self._lows.pop(0)
if len(self._highs) < int(self.zig_zag_depth):
return
# Manual highest/lowest over ZigZagDepth
depth = int(self.zig_zag_depth)
recent_highs = self._highs[-depth:]
recent_lows = self._lows[-depth:]
highest = max(recent_highs)
lowest = min(recent_lows)
# ZigZag direction
if candle.HighPrice >= highest and self._direction != 1:
self._last_zigzag_high = candle.HighPrice
self._direction = 1
elif candle.LowPrice <= lowest and self._direction != -1:
self._last_zigzag_low = candle.LowPrice
self._direction = -1
al = int(self.aroon_length)
if len(self._highs) < al + 1:
return
# Manual Aroon calculation
count = al + 1
if len(self._highs) < count or len(self._lows) < count:
return
aroon_highs = self._highs[-count:]
aroon_lows = self._lows[-count:]
highest_idx = 0
lowest_idx = 0
for i in range(1, count):
if aroon_highs[i] >= aroon_highs[highest_idx]:
highest_idx = i
if aroon_lows[i] <= aroon_lows[lowest_idx]:
lowest_idx = i
aroon_up = 100.0 * highest_idx / al
aroon_down = 100.0 * lowest_idx / al
# Aroon crossover
cross_up = self._prev_aroon_up <= self._prev_aroon_down and aroon_up > aroon_down
cross_down = self._prev_aroon_down <= self._prev_aroon_up and aroon_down > aroon_up
if cross_up and self._direction == 1 and self.Position <= 0:
self.BuyMarket()
elif cross_down and self._direction == -1 and self.Position >= 0:
self.SellMarket()
self._prev_aroon_up = aroon_up
self._prev_aroon_down = aroon_down
def CreateClone(self):
return zig_zag_aroon_strategy()