CCI Failure Swing Strategy
The CCI Failure Swing is based on the Commodity Channel Index forming a lower high above +100 or a higher low below -100. This inability to make a new extreme often signals the end of the prior trend.
Testing indicates an average annual return of about 73%. It performs best in the crypto market.
The strategy goes long when CCI holds above -100 and turns up, or short when it fails near +100 and turns down.
A percent stop keeps risk small and trades exit if the CCI crosses back through the previous swing level.
Details
- Entry Criteria: indicator signal
- Long/Short: Both
- Exit Criteria: stop-loss or opposite signal
- Stops: Yes, percent based
- Default Values:
CandleType= 15 minuteStopLoss= 2%
- Filters:
- Category: Reversal
- Direction: Both
- Indicators: CCI
- Stops: Yes
- Complexity: Intermediate
- Timeframe: Intraday
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: Medium
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>
/// Strategy that trades based on CCI Failure Swing pattern.
/// A failure swing occurs when CCI reverses direction without crossing through centerline.
/// Uses cooldown to control trade frequency.
/// </summary>
public class CciFailureSwingStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<decimal> _oversoldLevel;
private readonly StrategyParam<decimal> _overboughtLevel;
private readonly StrategyParam<int> _cooldownBars;
private CommodityChannelIndex _cci;
private decimal _prevCci;
private decimal _prevPrevCci;
private int _cooldown;
/// <summary>
/// Candle type and timeframe.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// CCI period.
/// </summary>
public int CciPeriod
{
get => _cciPeriod.Value;
set => _cciPeriod.Value = value;
}
/// <summary>
/// Oversold level.
/// </summary>
public decimal OversoldLevel
{
get => _oversoldLevel.Value;
set => _oversoldLevel.Value = value;
}
/// <summary>
/// Overbought level.
/// </summary>
public decimal OverboughtLevel
{
get => _overboughtLevel.Value;
set => _overboughtLevel.Value = value;
}
/// <summary>
/// Cooldown bars between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public CciFailureSwingStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
_cciPeriod = Param(nameof(CciPeriod), 20)
.SetDisplay("CCI Period", "Period for CCI", "CCI Settings")
.SetRange(5, 50);
_oversoldLevel = Param(nameof(OversoldLevel), -50m)
.SetDisplay("Oversold Level", "CCI oversold threshold", "CCI Settings")
.SetRange(-200m, -20m);
_overboughtLevel = Param(nameof(OverboughtLevel), 50m)
.SetDisplay("Overbought Level", "CCI overbought threshold", "CCI Settings")
.SetRange(20m, 200m);
_cooldownBars = Param(nameof(CooldownBars), 350)
.SetDisplay("Cooldown Bars", "Bars between trades", "General")
.SetRange(10, 2000);
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_cci = default;
_prevCci = 0;
_prevPrevCci = 0;
_cooldown = 0;
}
/// <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 (!IsFormedAndOnlineAndAllowTrading())
return;
// Need at least 2 previous CCI values
if (_prevCci == 0 || _prevPrevCci == 0)
{
_prevPrevCci = _prevCci;
_prevCci = cciValue;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevPrevCci = _prevCci;
_prevCci = cciValue;
return;
}
// Bullish Failure Swing: CCI was oversold, rose, pulled back but stayed above prior low
var isBullish = _prevPrevCci < OversoldLevel &&
_prevCci > _prevPrevCci &&
cciValue < _prevCci &&
cciValue > _prevPrevCci;
// Bearish Failure Swing: CCI was overbought, fell, bounced but stayed below prior high
var isBearish = _prevPrevCci > OverboughtLevel &&
_prevCci < _prevPrevCci &&
cciValue > _prevCci &&
cciValue < _prevPrevCci;
if (Position == 0)
{
if (isBullish)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (isBearish)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position > 0)
{
// Exit long when CCI crosses above overbought
if (cciValue > OverboughtLevel)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position < 0)
{
// Exit short when CCI crosses below oversold
if (cciValue < OversoldLevel)
{
BuyMarket();
_cooldown = CooldownBars;
}
}
_prevPrevCci = _prevCci;
_prevCci = cciValue;
}
}
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 cci_failure_swing_strategy(Strategy):
"""
Strategy that trades based on CCI Failure Swing pattern.
A failure swing occurs when CCI reverses direction without crossing through centerline.
Uses cooldown to control trade frequency.
"""
def __init__(self):
super(cci_failure_swing_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Candle timeframe", "General")
self._cci_period = self.Param("CciPeriod", 20).SetDisplay("CCI Period", "Period for CCI", "CCI Settings")
self._oversold_level = self.Param("OversoldLevel", -50.0).SetDisplay("Oversold Level", "CCI oversold threshold", "CCI Settings")
self._overbought_level = self.Param("OverboughtLevel", 50.0).SetDisplay("Overbought Level", "CCI overbought threshold", "CCI Settings")
self._cooldown_bars = self.Param("CooldownBars", 350).SetDisplay("Cooldown Bars", "Bars between trades", "General")
self._prev_cci = 0.0
self._prev_prev_cci = 0.0
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(cci_failure_swing_strategy, self).OnReseted()
self._prev_cci = 0.0
self._prev_prev_cci = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(cci_failure_swing_strategy, self).OnStarted2(time)
self._prev_cci = 0.0
self._prev_prev_cci = 0.0
self._cooldown = 0
cci = CommodityChannelIndex()
cci.Length = self._cci_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(cci, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, cci)
self.DrawOwnTrades(area)
def _process_candle(self, candle, cci_val):
if candle.State != CandleStates.Finished:
return
cv = float(cci_val)
# Need at least 2 previous CCI values
if self._prev_cci == 0 or self._prev_prev_cci == 0:
self._prev_prev_cci = self._prev_cci
self._prev_cci = cv
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_prev_cci = self._prev_cci
self._prev_cci = cv
return
cd = self._cooldown_bars.Value
oversold = self._oversold_level.Value
overbought = self._overbought_level.Value
# Bullish Failure Swing: CCI was oversold, rose, pulled back but stayed above prior low
is_bullish = (
self._prev_prev_cci < oversold and
self._prev_cci > self._prev_prev_cci and
cv < self._prev_cci and
cv > self._prev_prev_cci
)
# Bearish Failure Swing: CCI was overbought, fell, bounced but stayed below prior high
is_bearish = (
self._prev_prev_cci > overbought and
self._prev_cci < self._prev_prev_cci and
cv > self._prev_cci and
cv < self._prev_prev_cci
)
if self.Position == 0:
if is_bullish:
self.BuyMarket()
self._cooldown = cd
elif is_bearish:
self.SellMarket()
self._cooldown = cd
elif self.Position > 0:
# Exit long when CCI crosses above overbought
if cv > overbought:
self.SellMarket()
self._cooldown = cd
elif self.Position < 0:
# Exit short when CCI crosses below oversold
if cv < oversold:
self.BuyMarket()
self._cooldown = cd
self._prev_prev_cci = self._prev_cci
self._prev_cci = cv
def CreateClone(self):
return cci_failure_swing_strategy()