Super Woodies CCI 策略
该策略是原始 MQL5 Exp_SuperWoodiesCCI 专家的移植版本。它基于较高周期上的商品通道指数(CCI)方向进行交易。
逻辑
- 计算具有可配置周期的 CCI。
- 当 CCI 上穿零轴时:
- 可选择平掉空头头寸。
- 可选择开立多头头寸。
- 当 CCI 下穿零轴时:
- 可选择平掉多头头寸。
- 可选择开立空头头寸。
策略只处理已完成的K线,并在指定的 K 线类型上运行。
参数
- CciPeriod – CCI 的计算周期。
- CandleType – 要分析的 K 线时间框架。
- AllowLongEntry – 是否允许开多。
- AllowShortEntry – 是否允许开空。
- AllowLongExit – 当 CCI 为负时是否允许平多。
- AllowShortExit – 当 CCI 为正时是否允许平空。
说明
该策略使用 StockSharp 高级 API,通过 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()