Color Bulls Gap Strategy
Strategy that recreates the ColorBullsGap indicator by comparing smoothed gaps between the high price and averages of open and close. Enters long when a bullish color two bars ago turns neutral or bearish on the last bar, closing any short positions. Enters short when a bearish color two bars ago turns neutral or bullish on the last bar, closing any long positions.
Details
- Entry Criteria:
- Long:
PrevColor == 0 && LastColor > 0 - Short:
PrevColor == 2 && LastColor < 2
- Long:
- Long/Short: Both
- Exit Criteria: Opposite signal
- Stops: No
- Default Values:
Length1= 12Length2= 5CandleType= TimeSpan.FromHours(8).TimeFrame()
- Filters:
- Category: Indicator
- Direction: Both
- Indicators: SMA
- Stops: No
- Complexity: Intermediate
- Timeframe: Intraday
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy based on a simplified ColorBullsGap indicator.
/// Enters long when a bullish color turns neutral or bearish.
/// Enters short when a bearish color turns neutral or bullish.
/// </summary>
public class ColorBullsGapStrategy : Strategy
{
private readonly StrategyParam<int> _length1;
private readonly StrategyParam<int> _length2;
private readonly StrategyParam<DataType> _candleType;
private ExponentialMovingAverage _smaClose;
private ExponentialMovingAverage _smaOpen;
private ExponentialMovingAverage _smaBullsC;
private ExponentialMovingAverage _smaBullsO;
private readonly Queue<int> _colorHistory = new();
private decimal _prevXbullsC;
private bool _isFirst = true;
public int Length1 { get => _length1.Value; set => _length1.Value = value; }
public int Length2 { get => _length2.Value; set => _length2.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ColorBullsGapStrategy()
{
_length1 = Param(nameof(Length1), 12)
.SetGreaterThanZero()
.SetDisplay("First Length", "Length for initial smoothing", "Indicator");
_length2 = Param(nameof(Length2), 5)
.SetGreaterThanZero()
.SetDisplay("Second Length", "Length for secondary smoothing", "Indicator");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for indicator", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_smaClose = default;
_smaOpen = default;
_smaBullsC = default;
_smaBullsO = default;
_prevXbullsC = default;
_isFirst = true;
_colorHistory.Clear();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_smaClose = new ExponentialMovingAverage { Length = Length1 };
_smaOpen = new ExponentialMovingAverage { Length = Length1 };
_smaBullsC = new ExponentialMovingAverage { Length = Length2 };
_smaBullsO = new ExponentialMovingAverage { Length = Length2 };
_isFirst = true;
_colorHistory.Clear();
Indicators.Add(_smaClose);
Indicators.Add(_smaOpen);
Indicators.Add(_smaBullsC);
Indicators.Add(_smaBullsO);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var t = candle.OpenTime;
var smaClose = _smaClose.Process(candle.ClosePrice, t, true).GetValue<decimal>();
var smaOpen = _smaOpen.Process(candle.OpenPrice, t, true).GetValue<decimal>();
var bullsC = candle.HighPrice - smaClose;
var bullsO = candle.HighPrice - smaOpen;
var xbullsC = _smaBullsC.Process(bullsC, t, true).GetValue<decimal>();
var xbullsO = _smaBullsO.Process(bullsO, t, true).GetValue<decimal>();
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_isFirst)
{
_prevXbullsC = xbullsC;
_isFirst = false;
return;
}
var diff = xbullsO - _prevXbullsC;
var color = diff > 0 ? 0 : diff < 0 ? 2 : 1;
_prevXbullsC = xbullsC;
_colorHistory.Enqueue(color);
if (_colorHistory.Count > 2)
_colorHistory.Dequeue();
if (_colorHistory.Count < 2)
return;
var prevColor = _colorHistory.ElementAt(0);
var lastColor = _colorHistory.ElementAt(1);
if (prevColor == 0)
{
if (lastColor > 0)
BuyMarket();
else if (Position < 0)
BuyMarket();
}
else if (prevColor == 2)
{
if (lastColor < 2)
SellMarket();
else if (Position > 0)
SellMarket();
}
}
}
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 System.Collections.Generic import Queue
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class color_bulls_gap_strategy(Strategy):
def __init__(self):
super(color_bulls_gap_strategy, self).__init__()
self._length1 = self.Param("Length1", 12) \
.SetDisplay("First Length", "Length for initial smoothing", "Indicator")
self._length2 = self.Param("Length2", 5) \
.SetDisplay("Second Length", "Length for secondary smoothing", "Indicator")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for indicator", "General")
self._sma_close = None
self._sma_open = None
self._sma_bulls_c = None
self._sma_bulls_o = None
self._prev_xbulls_c = 0.0
self._is_first = True
self._color_history = []
@property
def length1(self):
return self._length1.Value
@property
def length2(self):
return self._length2.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(color_bulls_gap_strategy, self).OnReseted()
self._sma_close = None
self._sma_open = None
self._sma_bulls_c = None
self._sma_bulls_o = None
self._prev_xbulls_c = 0.0
self._is_first = True
self._color_history = []
def OnStarted2(self, time):
super(color_bulls_gap_strategy, self).OnStarted2(time)
self._sma_close = ExponentialMovingAverage()
self._sma_close.Length = self.length1
self._sma_open = ExponentialMovingAverage()
self._sma_open.Length = self.length1
self._sma_bulls_c = ExponentialMovingAverage()
self._sma_bulls_c.Length = self.length2
self._sma_bulls_o = ExponentialMovingAverage()
self._sma_bulls_o.Length = self.length2
self._is_first = True
self._color_history = []
self.Indicators.Add(self._sma_close)
self.Indicators.Add(self._sma_open)
self.Indicators.Add(self._sma_bulls_c)
self.Indicators.Add(self._sma_bulls_o)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
t = candle.OpenTime
sma_close_val = float(process_float(self._sma_close, candle.ClosePrice, t, True))
sma_open_val = float(process_float(self._sma_open, candle.OpenPrice, t, True))
bulls_c = float(candle.HighPrice) - sma_close_val
bulls_o = float(candle.HighPrice) - sma_open_val
xbulls_c = float(process_float(self._sma_bulls_c, bulls_c, t, True))
xbulls_o = float(process_float(self._sma_bulls_o, bulls_o, t, True))
if self._is_first:
self._prev_xbulls_c = xbulls_c
self._is_first = False
return
diff = xbulls_o - self._prev_xbulls_c
if diff > 0:
color = 0
elif diff < 0:
color = 2
else:
color = 1
self._prev_xbulls_c = xbulls_c
self._color_history.append(color)
if len(self._color_history) > 2:
self._color_history.pop(0)
if len(self._color_history) < 2:
return
prev_color = self._color_history[0]
last_color = self._color_history[1]
if prev_color == 0:
if last_color > 0:
self.BuyMarket()
elif self.Position < 0:
self.BuyMarket()
elif prev_color == 2:
if last_color < 2:
self.SellMarket()
elif self.Position > 0:
self.SellMarket()
def CreateClone(self):
return color_bulls_gap_strategy()