Godbot 策略
该策略利用布林带和移动平均线来识别反转以及趋势强度。
逻辑
- 使用主时间框(默认 30 分钟)。
- 在该时间框上计算布林带和 EMA。
- 另外在更高时间框(默认 1 天)上计算 DEMA 以判定总体趋势。
- 当价格回落到上轨下方时平掉多头仓位。
- 当价格回升到下轨上方时平掉空头仓位。
- 当价格上破下轨且 DEMA 与 EMA 均向上时开多。
- 当价格下破上轨且 DEMA 与 EMA 均向下时开空。
参数
- Bollinger Period – 布林带周期。
- Bollinger Deviation – 布林带偏差倍数。
- EMA Period – 趋势过滤用的 EMA 周期。
- DEMA Period – 高时间框 DEMA 周期。
- Candle Type – 计算布林带和 EMA 的时间框。
- DEMA Candle Type – 计算 DEMA 的更高时间框。
说明
- 同一时间仅持有一个仓位。
- 策略使用市价单进出场。
- 在交易开始前需要累积足够的 DEMA 数据。
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 based on Bollinger Bands and EMA trend confirmation.
/// Buys when price crosses below lower band with uptrend, sells when above upper band with downtrend.
/// </summary>
public class GodbotStrategy : Strategy
{
private readonly StrategyParam<int> _bollingerPeriod;
private readonly StrategyParam<decimal> _bollingerDeviation;
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevEma;
private bool _hasPrevEma;
public int BollingerPeriod { get => _bollingerPeriod.Value; set => _bollingerPeriod.Value = value; }
public decimal BollingerDeviation { get => _bollingerDeviation.Value; set => _bollingerDeviation.Value = value; }
public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public GodbotStrategy()
{
_bollingerPeriod = Param(nameof(BollingerPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("BB Period", "Bollinger Bands period", "Indicators");
_bollingerDeviation = Param(nameof(BollingerDeviation), 2m)
.SetGreaterThanZero()
.SetDisplay("BB Deviation", "Bollinger Bands deviation", "Indicators");
_maPeriod = Param(nameof(MaPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "EMA period for trend", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle type", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevEma = 0;
_hasPrevEma = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var bb = new BollingerBands
{
Length = BollingerPeriod,
Width = BollingerDeviation
};
var ema = new ExponentialMovingAverage { Length = MaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, ProcessEma);
subscription
.BindEx(bb, ProcessBB)
.Start();
}
private void ProcessEma(ICandleMessage candle, decimal emaVal)
{
if (candle.State != CandleStates.Finished)
return;
_prevEma = emaVal;
_hasPrevEma = true;
}
private void ProcessBB(ICandleMessage candle, IIndicatorValue bbValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_hasPrevEma)
return;
var bb = (BollingerBandsValue)bbValue;
if (bb.UpBand is not decimal upper || bb.LowBand is not decimal lower || bb.MovingAverage is not decimal middle)
return;
var close = candle.ClosePrice;
// Buy: price below lower band
if (close < lower && Position <= 0)
BuyMarket();
// Sell: price above upper band
else if (close > upper && 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 StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import BollingerBands, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class godbot_strategy(Strategy):
def __init__(self):
super(godbot_strategy, self).__init__()
self._bollinger_period = self.Param("BollingerPeriod", 20) \
.SetDisplay("BB Period", "Bollinger Bands period", "Indicators")
self._bollinger_deviation = self.Param("BollingerDeviation", 2.0) \
.SetDisplay("BB Deviation", "Bollinger Bands deviation", "Indicators")
self._ma_period = self.Param("MaPeriod", 50) \
.SetDisplay("EMA Period", "EMA period for trend", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle type", "General")
self._prev_ema = 0.0
self._has_prev_ema = False
@property
def bollinger_period(self):
return self._bollinger_period.Value
@property
def bollinger_deviation(self):
return self._bollinger_deviation.Value
@property
def ma_period(self):
return self._ma_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(godbot_strategy, self).OnReseted()
self._prev_ema = 0.0
self._has_prev_ema = False
def OnStarted2(self, time):
super(godbot_strategy, self).OnStarted2(time)
bb = BollingerBands()
bb.Length = self.bollinger_period
bb.Width = self.bollinger_deviation
ema = ExponentialMovingAverage()
ema.Length = self.ma_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, self.on_ema)
subscription.BindEx(bb, self.on_bb).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, bb)
self.DrawOwnTrades(area)
def on_ema(self, candle, ema_val):
if candle.State != CandleStates.Finished:
return
self._prev_ema = float(ema_val)
self._has_prev_ema = True
def on_bb(self, candle, bb_value):
if candle.State != CandleStates.Finished:
return
if not self._has_prev_ema:
return
if bb_value.UpBand is None or bb_value.LowBand is None or bb_value.MovingAverage is None:
return
upper = float(bb_value.UpBand)
lower = float(bb_value.LowBand)
close = float(candle.ClosePrice)
if close < lower and self.Position <= 0:
self.BuyMarket()
elif close > upper and self.Position >= 0:
self.SellMarket()
def CreateClone(self):
return godbot_strategy()