Стратегия представляет собой конвертацию MQL5 советника Exp_Arrows_Curves.
Она строит динамический ценовой канал по недавним максимумам и минимумам и
реагирует на пробои. В зависимости от настроек и направления тренда стратегия
может открывать или закрывать позиции.
Логика стратегии
Рассчитываются максимум и минимум за заданный период.
Диапазон расширяется на процент для формирования внешних линий канала.
Дополнительный процент создаёт внутренние линии остановки.
Пробой верхней линии — покупка, пробой нижней — продажа.
Пересечение внутренней линии в противоположную сторону закрывает позицию.
Параметры
SspPeriod – период расчёта максимумов и минимумов.
Channel – процент расширения основного канала.
StopChannel – дополнительный процент для внутренних линий.
CandleType – таймфрейм свечей.
BuyPosOpen / SellPosOpen – разрешение открывать длинные/короткие позиции.
BuyPosClose / SellPosClose – разрешение закрывать длинные/короткие позиции.
Индикаторы
Highest
Lowest
Примечания
Стратегия работает только на завершённых свечах. Управление стопами не
реализовано; выход осуществляется по сигналам канала.
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>
/// Channel breakout strategy using Highest/Lowest midpoint crossing.
/// </summary>
public class ArrowsCurvesStrategy : Strategy
{
private readonly StrategyParam<int> _period;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevHigh;
private decimal _prevLow;
private bool _hasPrev;
public int Period { get => _period.Value; set => _period.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ArrowsCurvesStrategy()
{
_period = Param(nameof(Period), 20)
.SetGreaterThanZero()
.SetDisplay("Period", "Channel period", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle type", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevHigh = 0;
_prevLow = 0;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var highest = new Highest { Length = Period };
var lowest = new Lowest { Length = Period };
SubscribeCandles(CandleType)
.Bind(highest, lowest, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal high, decimal low)
{
if (candle.State != CandleStates.Finished) return;
if (!_hasPrev)
{
_prevHigh = high;
_prevLow = low;
_hasPrev = true;
return;
}
var close = candle.ClosePrice;
if (close > _prevHigh && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (close < _prevLow && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prevHigh = high;
_prevLow = low;
}
}
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 arrows_curves_strategy(Strategy):
def __init__(self):
super(arrows_curves_strategy, self).__init__()
self._period = self.Param("Period", 20) .SetDisplay("Period", "Channel lookback period", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) .SetDisplay("Candle Type", "Candle type", "General")
self._prev_high = 0.0
self._prev_low = 0.0
self._has_prev = False
@property
def period(self):
return self._period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(arrows_curves_strategy, self).OnReseted()
self._prev_high = 0.0
self._prev_low = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(arrows_curves_strategy, self).OnStarted2(time)
highest = Highest()
highest.Length = self.period
lowest = Lowest()
lowest.Length = self.period
self.SubscribeCandles(self.candle_type).Bind(highest, lowest, self.process_candle).Start()
def process_candle(self, candle, high, low):
if candle.State != CandleStates.Finished:
return
hv = float(high)
lv = float(low)
if not self._has_prev:
self._prev_high = hv
self._prev_low = lv
self._has_prev = True
return
close = float(candle.ClosePrice)
if close > self._prev_high and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif close < self._prev_low and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_high = hv
self._prev_low = lv
def CreateClone(self):
return arrows_curves_strategy()