Bollinger Winner Lite
Bollinger Winner Lite — упрощённая разворотная система, реагирующая на выход цены за пределы полос Боллинджера. Она отслеживает крупные свечи, закрывающиеся за пределами полосы, и ожидает быстрого возврата внутрь.
Параметр CandlePercent задаёт, насколько большая свеча нужна для сигнала.
Торговля ведётся только в лонг, если не активирован ShowShort, позволяющий
использовать зеркальные шорты.
Выход осуществляется при касании противоположной или средней полосы. Фиксированных стопов нет, стратегия полагается на возврат к среднему.
Подробности
- Данные: свечи цены.
- Условия входа:
- Лонг: закрытие ниже нижней полосы и размер свечи >
CandlePercent. - Шорт: закрытие выше верхней полосы и размер свечи >
CandlePercent(приShowShort).
- Лонг: закрытие ниже нижней полосы и размер свечи >
- Условия выхода: касание средней или противоположной полосы.
- Стопы: отсутствуют по умолчанию.
- Параметры по умолчанию:
BBLength= 20BBMultiplier= 2.0CandlePercent= 30ShowShort= false
- Фильтры:
- Категория: возврат к среднему
- Направление: только лонг по умолчанию
- Индикаторы: Bollinger Bands
- Сложность: простая
- Уровень риска: средний
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 Winner LITE Strategy.
/// Buys when candle body extends below lower BB, sells when above upper BB.
/// </summary>
public class BollingerWinnerLiteStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleTypeParam;
private readonly StrategyParam<int> _bbLength;
private readonly StrategyParam<decimal> _bbMultiplier;
private readonly StrategyParam<decimal> _candlePercent;
private readonly StrategyParam<bool> _showShort;
private readonly StrategyParam<int> _cooldownBars;
/// <summary>
/// Candle type for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleTypeParam.Value;
set => _candleTypeParam.Value = value;
}
/// <summary>
/// Bollinger Bands period.
/// </summary>
public int BBLength
{
get => _bbLength.Value;
set => _bbLength.Value = value;
}
/// <summary>
/// Bollinger Bands standard deviation multiplier.
/// </summary>
public decimal BBMultiplier
{
get => _bbMultiplier.Value;
set => _bbMultiplier.Value = value;
}
/// <summary>
/// Candle percentage below/above the BB.
/// </summary>
public decimal CandlePercent
{
get => _candlePercent.Value;
set => _candlePercent.Value = value;
}
/// <summary>
/// Enable short entries.
/// </summary>
public bool ShowShort
{
get => _showShort.Value;
set => _showShort.Value = value;
}
/// <summary>
/// Cooldown bars between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
private BollingerBands _bollinger;
private int _cooldownRemaining;
public BollingerWinnerLiteStrategy()
{
_candleTypeParam = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle type", "Candle type for strategy calculation.", "General");
_bbLength = Param(nameof(BBLength), 20)
.SetGreaterThanZero()
.SetDisplay("BB Period", "Bollinger Bands period", "Bollinger Bands");
_bbMultiplier = Param(nameof(BBMultiplier), 1.5m)
.SetDisplay("BB StdDev", "Bollinger Bands standard deviation multiplier", "Bollinger Bands");
_candlePercent = Param(nameof(CandlePercent), 30m)
.SetDisplay("Candle %", "Candle percentage below/above the BB", "Strategy");
_showShort = Param(nameof(ShowShort), true)
.SetDisplay("Short entries", "Enable short entries", "Strategy");
_cooldownBars = Param(nameof(CooldownBars), 10)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_bollinger = null;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_bollinger = new BollingerBands
{
Length = BBLength,
Width = BBMultiplier
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(_bollinger, OnProcess)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _bollinger);
DrawOwnTrades(area);
}
}
private void OnProcess(ICandleMessage candle, IIndicatorValue bollingerValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_bollinger.IsFormed)
return;
var bb = (BollingerBandsValue)bollingerValue;
if (bb.UpBand is not decimal upperBand ||
bb.LowBand is not decimal lowerBand)
return;
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
return;
}
var close = candle.ClosePrice;
var open = candle.OpenPrice;
var high = candle.HighPrice;
var low = candle.LowPrice;
// Buy: close below lower band (oversold)
var buy = close <= lowerBand;
// Sell: close above upper band (overbought)
var sell = close >= upperBand;
if (buy && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_cooldownRemaining = CooldownBars;
}
else if (sell)
{
if (Position > 0)
{
SellMarket(Math.Abs(Position));
_cooldownRemaining = CooldownBars;
}
else if (ShowShort && Position == 0)
{
SellMarket(Volume);
_cooldownRemaining = CooldownBars;
}
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import BollingerBands
from StockSharp.Algo.Strategies import Strategy
class bollinger_winner_lite_strategy(Strategy):
"""Bollinger Bands Winner LITE Strategy. Buys when candle body extends below lower BB, sells when above upper BB."""
def __init__(self):
super(bollinger_winner_lite_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle type", "Candle type for strategy calculation.", "General")
self._bb_length = self.Param("BBLength", 20) \
.SetDisplay("BB Period", "Bollinger Bands period", "Bollinger Bands")
self._bb_multiplier = self.Param("BBMultiplier", 1.5) \
.SetDisplay("BB StdDev", "Bollinger Bands standard deviation multiplier", "Bollinger Bands")
self._candle_percent = self.Param("CandlePercent", 30.0) \
.SetDisplay("Candle %", "Candle percentage below/above the BB", "Strategy")
self._show_short = self.Param("ShowShort", True) \
.SetDisplay("Short entries", "Enable short entries", "Strategy")
self._cooldown_bars = self.Param("CooldownBars", 10) \
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk")
self._bollinger = None
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(bollinger_winner_lite_strategy, self).OnReseted()
self._bollinger = None
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(bollinger_winner_lite_strategy, self).OnStarted2(time)
self._bollinger = BollingerBands()
self._bollinger.Length = int(self._bb_length.Value)
self._bollinger.Width = float(self._bb_multiplier.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(self._bollinger, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._bollinger)
self.DrawOwnTrades(area)
def _on_process(self, candle, bollinger_value):
if candle.State != CandleStates.Finished:
return
if not self._bollinger.IsFormed:
return
bb = bollinger_value
if bb.UpBand is None or bb.LowBand is None:
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
return
upper_band = float(bb.UpBand)
lower_band = float(bb.LowBand)
close = float(candle.ClosePrice)
cooldown = int(self._cooldown_bars.Value)
buy = close <= lower_band
sell = close >= upper_band
if buy and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._cooldown_remaining = cooldown
elif sell:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self._cooldown_remaining = cooldown
elif bool(self._show_short.Value) and self.Position == 0:
self.SellMarket(self.Volume)
self._cooldown_remaining = cooldown
def CreateClone(self):
return bollinger_winner_lite_strategy()