Стратегия Super Woodies CCI
Данная стратегия является конвертацией оригинального советника MQL5 Exp_SuperWoodiesCCI. Торговля ведётся на основе направления индикатора Commodity Channel Index (CCI), рассчитанного на старшем таймфрейме.
Логика
- Вычисляется CCI с настраиваемым периодом.
- Когда CCI пересекает ноль снизу вверх:
- По желанию закрываются короткие позиции.
- По желанию открывается длинная позиция.
- Когда CCI пересекает ноль сверху вниз:
- По желанию закрываются длинные позиции.
- По желанию открывается короткая позиция.
Обрабатываются только завершённые свечи, стратегия работает с указанным типом свечей.
Параметры
- CciPeriod – период расчёта CCI.
- CandleType – таймфрейм свечей для анализа.
- AllowLongEntry – разрешение на открытие длинных позиций.
- AllowShortEntry – разрешение на открытие коротких позиций.
- AllowLongExit – разрешение на закрытие длинных позиций при отрицательном CCI.
- AllowShortExit – разрешение на закрытие коротких позиций при положительном CCI.
Примечания
Стратегия использует высокоуровневый API StockSharp: подписка на свечи через SubscribeCandles и привязка индикатора. Для управления позициями применяются методы BuyMarket и SellMarket.
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>
/// Super Woodies CCI strategy.
/// Opens long when CCI crosses above zero and short when crosses below.
/// </summary>
public class SuperWoodiesCciStrategy : Strategy
{
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<bool> _allowLongEntry;
private readonly StrategyParam<bool> _allowShortEntry;
private readonly StrategyParam<bool> _allowLongExit;
private readonly StrategyParam<bool> _allowShortExit;
private CommodityChannelIndex _cci = null!;
private bool _hasPrev;
private bool _wasPositive;
/// <summary>
/// CCI calculation period.
/// </summary>
public int CciPeriod
{
get => _cciPeriod.Value;
set => _cciPeriod.Value = value;
}
/// <summary>
/// Candle type used by the strategy.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Allow opening long positions.
/// </summary>
public bool AllowLongEntry
{
get => _allowLongEntry.Value;
set => _allowLongEntry.Value = value;
}
/// <summary>
/// Allow opening short positions.
/// </summary>
public bool AllowShortEntry
{
get => _allowShortEntry.Value;
set => _allowShortEntry.Value = value;
}
/// <summary>
/// Allow closing long positions when CCI goes below zero.
/// </summary>
public bool AllowLongExit
{
get => _allowLongExit.Value;
set => _allowLongExit.Value = value;
}
/// <summary>
/// Allow closing short positions when CCI goes above zero.
/// </summary>
public bool AllowShortExit
{
get => _allowShortExit.Value;
set => _allowShortExit.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="SuperWoodiesCciStrategy"/>.
/// </summary>
public SuperWoodiesCciStrategy()
{
_cciPeriod = Param(nameof(CciPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("CCI Period", "CCI lookback length", "General")
.SetOptimize(20, 100, 10);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_allowLongEntry = Param(nameof(AllowLongEntry), true)
.SetDisplay("Allow Long Entry", "Enable opening long positions", "Trading");
_allowShortEntry = Param(nameof(AllowShortEntry), true)
.SetDisplay("Allow Short Entry", "Enable opening short positions", "Trading");
_allowLongExit = Param(nameof(AllowLongExit), true)
.SetDisplay("Allow Long Exit", "Enable closing long positions", "Trading");
_allowShortExit = Param(nameof(AllowShortExit), true)
.SetDisplay("Allow Short Exit", "Enable closing short positions", "Trading");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_hasPrev = false;
_wasPositive = false;
_cci = null!;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_cci = new CommodityChannelIndex { Length = CciPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_cci, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _cci);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal cciValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_cci.IsFormed || !IsFormedAndOnlineAndAllowTrading())
return;
var isPositive = cciValue > 0m;
if (_hasPrev && isPositive != _wasPositive)
{
if (isPositive)
{
if (AllowLongEntry && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
}
else
{
if (AllowShortEntry && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
}
}
else
{
if (isPositive)
{
if (AllowShortExit && Position < 0)
BuyMarket();
}
else
{
if (AllowLongExit && Position > 0)
SellMarket();
}
}
_wasPositive = isPositive;
_hasPrev = 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 CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
class super_woodies_cci_strategy(Strategy):
def __init__(self):
super(super_woodies_cci_strategy, self).__init__()
self._cci_period = self.Param("CciPeriod", 50) \
.SetDisplay("CCI Period", "CCI lookback length", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._allow_long_entry = self.Param("AllowLongEntry", True) \
.SetDisplay("Allow Long Entry", "Enable opening long positions", "Trading")
self._allow_short_entry = self.Param("AllowShortEntry", True) \
.SetDisplay("Allow Short Entry", "Enable opening short positions", "Trading")
self._allow_long_exit = self.Param("AllowLongExit", True) \
.SetDisplay("Allow Long Exit", "Enable closing long positions", "Trading")
self._allow_short_exit = self.Param("AllowShortExit", True) \
.SetDisplay("Allow Short Exit", "Enable closing short positions", "Trading")
self._cci = None
self._has_prev = False
self._was_positive = False
@property
def cci_period(self):
return self._cci_period.Value
@property
def candle_type(self):
return self._candle_type.Value
@property
def allow_long_entry(self):
return self._allow_long_entry.Value
@property
def allow_short_entry(self):
return self._allow_short_entry.Value
@property
def allow_long_exit(self):
return self._allow_long_exit.Value
@property
def allow_short_exit(self):
return self._allow_short_exit.Value
def OnReseted(self):
super(super_woodies_cci_strategy, self).OnReseted()
self._has_prev = False
self._was_positive = False
self._cci = None
def OnStarted2(self, time):
super(super_woodies_cci_strategy, self).OnStarted2(time)
self._cci = CommodityChannelIndex()
self._cci.Length = self.cci_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._cci, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._cci)
self.DrawOwnTrades(area)
def process_candle(self, candle, cci_value):
if candle.State != CandleStates.Finished:
return
if not self._cci.IsFormed or not self.IsFormedAndOnlineAndAllowTrading():
return
is_positive = float(cci_value) > 0.0
if self._has_prev and is_positive != self._was_positive:
if is_positive:
if self.allow_long_entry and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
else:
if self.allow_short_entry and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
else:
if is_positive:
if self.allow_short_exit and self.Position < 0:
self.BuyMarket()
else:
if self.allow_long_exit and self.Position > 0:
self.SellMarket()
self._was_positive = is_positive
self._has_prev = True
def CreateClone(self):
return super_woodies_cci_strategy()