Bollinger Bands & Fibonacci-Strategie
Diese Strategie handelt Bollinger Band-Ausbrüche, gefiltert durch Fibonacci-Levels. Eine Long-Position öffnet sich, wenn der Preis über das obere Band kreuzt und das Kerzentief über einem Fibonacci-basierten Support liegt. Eine Short-Position öffnet sich, wenn der Preis unter das untere Band fällt und das Kerzenhoch unter einem Fibonacci-basierten Widerstand liegt.
Details
- Einstiegskriterien:
- Long: Close kreuzt über das obere Band und Tief > Fibonacci-Tief.
- Short: Close kreuzt unter das untere Band und Hoch < Fibonacci-Hoch.
- Long/Short: Beide Seiten.
- Ausstiegskriterien:
- Long: Close kreuzt unter das mittlere Band.
- Short: Close kreuzt über das mittlere Band.
- Stops: Keine.
- Standardwerte:
BollingerLength= 20BollingerMultiplier= 2FibonacciLength= 50FibonacciLevel0= 0FibonacciLevel100= 1
- Filter:
- Kategorie: Bandausbruch
- Richtung: Beide
- Indikatoren: Bollinger Bands, Highest, Lowest
- Stops: Keine
- Komplexität: Niedrig
- Zeitrahmen: 1H
- Saisonalität: Nein
- Neuronale Netze: Nein
- Divergenz: Nein
- Risikolevel: Mittel
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 and Fibonacci strategy.
/// The Fibonacci levels lie at FibonacciLevel0 and FibonacciLevel100 of the range between the lowest low and the highest high of
/// the last FibonacciLength candles. A close crossing above the upper Bollinger band with the low above the Fibonacci low goes long,
/// a close crossing below the lower band with the high below the Fibonacci high goes short, reversing an opposite position.
/// A long closes when the close crosses below the middle band and a short when it crosses above it.
/// </summary>
public class BollingerBandsFibonacciStrategy : Strategy
{
private readonly StrategyParam<int> _bollingerLength;
private readonly StrategyParam<decimal> _bollingerMultiplier;
private readonly StrategyParam<int> _fibonacciLength;
private readonly StrategyParam<decimal> _fibonacciLevel0;
private readonly StrategyParam<decimal> _fibonacciLevel100;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevClose;
private decimal? _prevUpper;
private decimal? _prevLower;
private decimal? _prevMiddle;
/// <summary>
/// Bollinger period.
/// </summary>
public int BollingerLength
{
get => _bollingerLength.Value;
set => _bollingerLength.Value = value;
}
/// <summary>
/// Bollinger standard deviation multiplier.
/// </summary>
public decimal BollingerMultiplier
{
get => _bollingerMultiplier.Value;
set => _bollingerMultiplier.Value = value;
}
/// <summary>
/// Candles of the Fibonacci range.
/// </summary>
public int FibonacciLength
{
get => _fibonacciLength.Value;
set => _fibonacciLength.Value = value;
}
/// <summary>
/// Fraction of the range that gives the Fibonacci low.
/// </summary>
public decimal FibonacciLevel0
{
get => _fibonacciLevel0.Value;
set => _fibonacciLevel0.Value = value;
}
/// <summary>
/// Fraction of the range that gives the Fibonacci high.
/// </summary>
public decimal FibonacciLevel100
{
get => _fibonacciLevel100.Value;
set => _fibonacciLevel100.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public BollingerBandsFibonacciStrategy()
{
_bollingerLength = Param(nameof(BollingerLength), 20)
.SetGreaterThanZero()
.SetDisplay("Bollinger Length", "Bollinger period", "Bollinger");
_bollingerMultiplier = Param(nameof(BollingerMultiplier), 2m)
.SetGreaterThanZero()
.SetDisplay("Bollinger Multiplier", "Bollinger standard deviation multiplier", "Bollinger");
_fibonacciLength = Param(nameof(FibonacciLength), 50)
.SetGreaterThanZero()
.SetDisplay("Fibonacci Length", "Candles of the Fibonacci range", "Fibonacci");
_fibonacciLevel0 = Param(nameof(FibonacciLevel0), 0m)
.SetDisplay("Fibonacci Level 0", "Fraction of the range that gives the Fibonacci low", "Fibonacci");
_fibonacciLevel100 = Param(nameof(FibonacciLevel100), 1m)
.SetDisplay("Fibonacci Level 100", "Fraction of the range that gives the Fibonacci high", "Fibonacci");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
ResetState();
}
private void ResetState()
{
_prevClose = null;
_prevUpper = null;
_prevLower = null;
_prevMiddle = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
ResetState();
var bollinger = new BollingerBands { Length = BollingerLength, Width = BollingerMultiplier };
var highest = new Highest { Length = FibonacciLength };
var lowest = new Lowest { Length = FibonacciLength };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(bollinger, highest, lowest, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, bollinger);
DrawIndicator(area, highest);
DrawIndicator(area, lowest);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue bollingerValue, IIndicatorValue highestValue, IIndicatorValue lowestValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!bollingerValue.IsFormed || !highestValue.IsFormed || !lowestValue.IsFormed)
return;
var bands = (BollingerBandsValue)bollingerValue;
if (bands.UpBand is not decimal upper || bands.LowBand is not decimal lower || bands.MovingAverage is not decimal middle)
return;
var close = candle.ClosePrice;
var prevClose = _prevClose;
var prevUpper = _prevUpper;
var prevLower = _prevLower;
var prevMiddle = _prevMiddle;
_prevClose = close;
_prevUpper = upper;
_prevLower = lower;
_prevMiddle = middle;
if (prevClose is not decimal pc || prevUpper is not decimal pu || prevLower is not decimal pl || prevMiddle is not decimal pm)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var highest = highestValue.GetValue<decimal>();
var lowest = lowestValue.GetValue<decimal>();
var range = highest - lowest;
var fibLow = lowest + range * FibonacciLevel0;
var fibHigh = lowest + range * FibonacciLevel100;
var crossAboveUpper = pc <= pu && close > upper;
var crossBelowLower = pc >= pl && close < lower;
if (crossAboveUpper && candle.LowPrice > fibLow && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (crossBelowLower && candle.HighPrice < fibHigh && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
else if (Position > 0 && pc >= pm && close < middle)
SellMarket(Position);
else if (Position < 0 && pc <= pm && close > middle)
BuyMarket(-Position);
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import BollingerBands, Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class bollinger_bands_fibonacci_strategy(Strategy):
"""
Bollinger Bands and Fibonacci strategy.
The Fibonacci levels lie at FibonacciLevel0 and FibonacciLevel100 of the range between the lowest low and the highest high of
the last FibonacciLength candles. A close crossing above the upper Bollinger band with the low above the Fibonacci low goes long,
a close crossing below the lower band with the high below the Fibonacci high goes short, reversing an opposite position.
A long closes when the close crosses below the middle band and a short when it crosses above it.
"""
def __init__(self):
super(bollinger_bands_fibonacci_strategy, self).__init__()
self._bollinger_length = self.Param("BollingerLength", 20).SetGreaterThanZero().SetDisplay("Bollinger Length", "Bollinger period", "Bollinger")
self._bollinger_multiplier = self.Param("BollingerMultiplier", 2.0).SetGreaterThanZero().SetDisplay("Bollinger Multiplier", "Bollinger standard deviation multiplier", "Bollinger")
self._fibonacci_length = self.Param("FibonacciLength", 50).SetGreaterThanZero().SetDisplay("Fibonacci Length", "Candles of the Fibonacci range", "Fibonacci")
self._fibonacci_level0 = self.Param("FibonacciLevel0", 0.0).SetDisplay("Fibonacci Level 0", "Fraction of the range that gives the Fibonacci low", "Fibonacci")
self._fibonacci_level100 = self.Param("FibonacciLevel100", 1.0).SetDisplay("Fibonacci Level 100", "Fraction of the range that gives the Fibonacci high", "Fibonacci")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_close = None
self._prev_upper = None
self._prev_lower = None
self._prev_middle = None
def OnReseted(self):
super(bollinger_bands_fibonacci_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(bollinger_bands_fibonacci_strategy, self).OnStarted2(time)
self._reset_state()
bollinger = BollingerBands()
bollinger.Length = self._bollinger_length.Value
bollinger.Width = Decimal(self._bollinger_multiplier.Value)
highest = Highest()
highest.Length = self._fibonacci_length.Value
lowest = Lowest()
lowest.Length = self._fibonacci_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(bollinger, highest, lowest, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, bollinger)
self.DrawIndicator(area, highest)
self.DrawIndicator(area, lowest)
self.DrawOwnTrades(area)
def _process_candle(self, candle, bollinger_value, highest_value, lowest_value):
if candle.State != CandleStates.Finished:
return
if not bollinger_value.IsFormed or not highest_value.IsFormed or not lowest_value.IsFormed:
return
upper = bollinger_value.UpBand
lower = bollinger_value.LowBand
middle = bollinger_value.MovingAverage
if upper is None or lower is None or middle is None:
return
close = candle.ClosePrice
pc = self._prev_close
pu = self._prev_upper
pl = self._prev_lower
pm = self._prev_middle
self._prev_close = close
self._prev_upper = upper
self._prev_lower = lower
self._prev_middle = middle
if pc is None or pu is None or pl is None or pm is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
highest = highest_value.GetValue[Decimal](None)
lowest = lowest_value.GetValue[Decimal](None)
price_range = highest - lowest
fib_low = lowest + price_range * Decimal(self._fibonacci_level0.Value)
fib_high = lowest + price_range * Decimal(self._fibonacci_level100.Value)
cross_above_upper = pc <= pu and close > upper
cross_below_lower = pc >= pl and close < lower
if cross_above_upper and candle.LowPrice > fib_low and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif cross_below_lower and candle.HighPrice < fib_high and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif self.Position > 0 and pc >= pm and close < middle:
self.SellMarket(self.Position)
elif self.Position < 0 and pc <= pm and close > middle:
self.BuyMarket(-self.Position)
def CreateClone(self):
return bollinger_bands_fibonacci_strategy()