Color BB Candles 策略
该策略利用布林带将蜡烛划分为多头、空头和中性区域。收盘价突破上轨时开多,收盘价跌破下轨时开空,当价格回到两条带之间时平掉所有持仓。
细节
- 入场条件:
- 多头:收盘价从下方突破上轨。
- 空头:收盘价从上方跌破下轨。
- 出场条件:价格回到上下轨之间。
- 指标:布林带。
- 默认参数:
BollingerPeriod= 100BollingerDeviation= 1.0CandleType= 4小时周期
- 方向:做多和做空。
- 止损:无。
- 复杂度:中等。
- 时间框架:中期。
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>
/// Bollinger Bands candle color strategy.
/// </summary>
public class ColorBbCandlesStrategy : Strategy
{
private enum BandStates
{
Neutral,
Above,
Below
}
private readonly StrategyParam<int> _bollingerPeriod;
private readonly StrategyParam<decimal> _bollingerDeviation;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _breakoutPercent;
private readonly StrategyParam<int> _cooldownBars;
private BandStates _previousState = BandStates.Neutral;
private int _cooldownRemaining;
public int BollingerPeriod
{
get => _bollingerPeriod.Value;
set => _bollingerPeriod.Value = value;
}
public decimal BollingerDeviation
{
get => _bollingerDeviation.Value;
set => _bollingerDeviation.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public decimal BreakoutPercent
{
get => _breakoutPercent.Value;
set => _breakoutPercent.Value = value;
}
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
public ColorBbCandlesStrategy()
{
_bollingerPeriod = Param(nameof(BollingerPeriod), 100)
.SetGreaterThanZero()
.SetDisplay("Bollinger Period", "Length of Bollinger Bands", "General")
.SetOptimize(50, 200, 25);
_bollingerDeviation = Param(nameof(BollingerDeviation), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Bollinger Deviation", "Width of Bollinger Bands", "General")
.SetOptimize(0.5m, 3m, 0.5m);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_breakoutPercent = Param(nameof(BreakoutPercent), 0.0005m)
.SetDisplay("Breakout %", "Minimum breakout beyond the Bollinger band", "Filters");
_cooldownBars = Param(nameof(CooldownBars), 3)
.SetDisplay("Cooldown Bars", "Completed candles to wait after a position change", "Trading");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_previousState = BandStates.Neutral;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var bollinger = new BollingerBands
{
Length = BollingerPeriod,
Width = BollingerDeviation
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(bollinger, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, bollinger);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue bbValue)
{
if (candle.State != CandleStates.Finished || !bbValue.IsFinal)
return;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
var bb = (BollingerBandsValue)bbValue;
if (bb.UpBand is not decimal upperBand || bb.LowBand is not decimal lowerBand)
return;
var state = BandStates.Neutral;
if (candle.ClosePrice > upperBand * (1m + BreakoutPercent))
state = BandStates.Above;
else if (candle.ClosePrice < lowerBand * (1m - BreakoutPercent))
state = BandStates.Below;
if (_cooldownRemaining == 0)
{
if (state == BandStates.Above && _previousState != BandStates.Above)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_cooldownRemaining = CooldownBars;
}
else if (state == BandStates.Below && _previousState != BandStates.Below)
{
if (Position > 0)
SellMarket();
SellMarket();
_cooldownRemaining = CooldownBars;
}
else if (state == BandStates.Neutral && _previousState != BandStates.Neutral)
{
if (Position > 0)
SellMarket();
else if (Position < 0)
BuyMarket();
_cooldownRemaining = CooldownBars;
}
}
_previousState = state;
}
}
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 BollingerBands
from StockSharp.Algo.Strategies import Strategy
class color_bb_candles_strategy(Strategy):
NEUTRAL = 0
ABOVE = 1
BELOW = 2
def __init__(self):
super(color_bb_candles_strategy, self).__init__()
self._bollinger_period = self.Param("BollingerPeriod", 100) \
.SetDisplay("Bollinger Period", "Length of Bollinger Bands", "General")
self._bollinger_deviation = self.Param("BollingerDeviation", 1.5) \
.SetDisplay("Bollinger Deviation", "Width of Bollinger Bands", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._breakout_percent = self.Param("BreakoutPercent", 0.0005) \
.SetDisplay("Breakout %", "Minimum breakout beyond the Bollinger band", "Filters")
self._cooldown_bars = self.Param("CooldownBars", 3) \
.SetDisplay("Cooldown Bars", "Completed candles to wait after a position change", "Trading")
self._previous_state = self.NEUTRAL
self._cooldown_remaining = 0
@property
def bollinger_period(self):
return self._bollinger_period.Value
@property
def bollinger_deviation(self):
return self._bollinger_deviation.Value
@property
def candle_type(self):
return self._candle_type.Value
@property
def breakout_percent(self):
return self._breakout_percent.Value
@property
def cooldown_bars(self):
return self._cooldown_bars.Value
def OnReseted(self):
super(color_bb_candles_strategy, self).OnReseted()
self._previous_state = self.NEUTRAL
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(color_bb_candles_strategy, self).OnStarted2(time)
bollinger = BollingerBands()
bollinger.Length = self.bollinger_period
bollinger.Width = float(self.bollinger_deviation)
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(bollinger, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, bollinger)
self.DrawOwnTrades(area)
def process_candle(self, candle, bb_value):
if candle.State != CandleStates.Finished or not bb_value.IsFinal:
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
upper_band = bb_value.UpBand
lower_band = bb_value.LowBand
if upper_band is None or lower_band is None:
return
upper_band = float(upper_band)
lower_band = float(lower_band)
close = float(candle.ClosePrice)
bp = float(self.breakout_percent)
state = self.NEUTRAL
if close > upper_band * (1.0 + bp):
state = self.ABOVE
elif close < lower_band * (1.0 - bp):
state = self.BELOW
if self._cooldown_remaining == 0:
if state == self.ABOVE and self._previous_state != self.ABOVE:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._cooldown_remaining = self.cooldown_bars
elif state == self.BELOW and self._previous_state != self.BELOW:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._cooldown_remaining = self.cooldown_bars
elif state == self.NEUTRAL and self._previous_state != self.NEUTRAL:
if self.Position > 0:
self.SellMarket()
elif self.Position < 0:
self.BuyMarket()
self._cooldown_remaining = self.cooldown_bars
self._previous_state = state
def CreateClone(self):
return color_bb_candles_strategy()