Keltner RSI Divergence
Keltner RSI Divergence 策略基于 Keltner Channel and RSI Divergence。
测试表明年均收益约为 40%,该策略在加密市场表现最佳。
当 Keltner confirms divergence setups 在日内(5m)数据上得到确认时触发信号,适合积极交易者。
止损依赖于 ATR 倍数以及 EmaPeriod, AtrPeriod 等参数,可根据需要调整以平衡风险与收益。
详情
- 入场条件:参见指标条件实现.
- 多空方向:双向.
- 退出条件:反向信号或止损逻辑.
- 止损:是,基于指标计算.
- 默认值:
EmaPeriod = 20AtrPeriod = 14AtrMultiplier = 2.0mRsiPeriod = 14CandleType = TimeSpan.FromMinutes(5).TimeFrame()
- 过滤器:
- 分类: 趋势跟随
- 方向: 双向
- 指标: Keltner, Divergence
- 止损: 是
- 复杂度: 中等
- 时间框架: 日内 (5m)
- 季节性: 否
- 神经网络: 否
- 背离: 是
- 风险等级: 中等
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Mean-reversion strategy that trades Keltner band extremes only when RSI diverges from price.
/// </summary>
public class KeltnerWithRsiDivergenceStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private ExponentialMovingAverage _ema;
private AverageTrueRange _atr;
private RelativeStrengthIndex _rsi;
private decimal _prevRsi;
private decimal _prevPrice;
private bool _isInitialized;
private int _cooldown;
/// <summary>
/// EMA period.
/// </summary>
public int EmaPeriod
{
get => _emaPeriod.Value;
set => _emaPeriod.Value = value;
}
/// <summary>
/// ATR period.
/// </summary>
public int AtrPeriod
{
get => _atrPeriod.Value;
set => _atrPeriod.Value = value;
}
/// <summary>
/// ATR multiplier for Keltner bands.
/// </summary>
public decimal AtrMultiplier
{
get => _atrMultiplier.Value;
set => _atrMultiplier.Value = value;
}
/// <summary>
/// RSI period.
/// </summary>
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
/// <summary>
/// Bars to wait after each order.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Stop loss percentage.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public KeltnerWithRsiDivergenceStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 20)
.SetRange(2, 100)
.SetDisplay("EMA Period", "Period for EMA calculation", "Indicators");
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetRange(2, 100)
.SetDisplay("ATR Period", "Period for ATR calculation", "Indicators");
_atrMultiplier = Param(nameof(AtrMultiplier), 1.15m)
.SetRange(0.1m, 10m)
.SetDisplay("ATR Multiplier", "Multiplier for the Keltner band width", "Indicators");
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetRange(2, 100)
.SetDisplay("RSI Period", "Period for RSI calculation", "Indicators");
_cooldownBars = Param(nameof(CooldownBars), 72)
.SetRange(1, 500)
.SetDisplay("Cooldown Bars", "Bars to wait after each order", "Risk");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetRange(0.5m, 10m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
if (Security != null)
yield return (Security, CandleType);
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_ema = null;
_atr = null;
_rsi = null;
_prevRsi = 50m;
_prevPrice = 0m;
_isInitialized = false;
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
if (Security == null)
throw new InvalidOperationException("Security is not specified.");
_ema = new ExponentialMovingAverage { Length = EmaPeriod };
_atr = new AverageTrueRange { Length = AtrPeriod };
_rsi = new RelativeStrengthIndex { Length = RsiPeriod };
_isInitialized = false;
_cooldown = 0;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_ema, _atr, _rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _ema);
DrawIndicator(area, _rsi);
DrawOwnTrades(area);
}
StartProtection(new Unit(0, UnitTypes.Absolute), new Unit(StopLossPercent, UnitTypes.Percent), false);
}
private void ProcessCandle(ICandleMessage candle, decimal emaValue, decimal atrValue, decimal rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_ema.IsFormed || !_atr.IsFormed || !_rsi.IsFormed)
return;
if (ProcessState != ProcessStates.Started)
return;
if (!_isInitialized)
{
_prevPrice = candle.ClosePrice;
_prevRsi = rsiValue;
_isInitialized = true;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevPrice = candle.ClosePrice;
_prevRsi = rsiValue;
return;
}
var upperBand = emaValue + AtrMultiplier * atrValue;
var lowerBand = emaValue - AtrMultiplier * atrValue;
var bullishDivergence = (rsiValue >= _prevRsi && candle.ClosePrice < _prevPrice) || rsiValue <= 30m;
var bearishDivergence = (rsiValue <= _prevRsi && candle.ClosePrice > _prevPrice) || rsiValue >= 70m;
var price = candle.ClosePrice;
if (Position == 0)
{
if (price <= lowerBand + atrValue * 0.1m && bullishDivergence)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (price >= upperBand - atrValue * 0.1m && bearishDivergence)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position > 0)
{
if (price >= emaValue || rsiValue >= 50m)
{
SellMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
else if (Position < 0)
{
if (price <= emaValue || rsiValue <= 50m)
{
BuyMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
_prevPrice = price;
_prevRsi = rsiValue;
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import ExponentialMovingAverage, AverageTrueRange, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class keltner_rsi_divergence_strategy(Strategy):
"""
Mean-reversion strategy that trades Keltner band extremes only when RSI diverges from price.
"""
def __init__(self):
super(keltner_rsi_divergence_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 20) \
.SetRange(2, 100) \
.SetDisplay("EMA Period", "Period for EMA calculation", "Indicators")
self._atr_period = self.Param("AtrPeriod", 14) \
.SetRange(2, 100) \
.SetDisplay("ATR Period", "Period for ATR calculation", "Indicators")
self._atr_multiplier = self.Param("AtrMultiplier", 1.15) \
.SetRange(0.1, 10.0) \
.SetDisplay("ATR Multiplier", "Multiplier for the Keltner band width", "Indicators")
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetRange(2, 100) \
.SetDisplay("RSI Period", "Period for RSI calculation", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 72) \
.SetRange(1, 500) \
.SetDisplay("Cooldown Bars", "Bars to wait after each order", "Risk")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0) \
.SetRange(0.5, 10.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_rsi = 50.0
self._prev_price = 0.0
self._is_initialized = False
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(keltner_rsi_divergence_strategy, self).OnReseted()
self._prev_rsi = 50.0
self._prev_price = 0.0
self._is_initialized = False
self._cooldown = 0
def OnStarted2(self, time):
super(keltner_rsi_divergence_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = int(self._ema_period.Value)
atr = AverageTrueRange()
atr.Length = int(self._atr_period.Value)
rsi = RelativeStrengthIndex()
rsi.Length = int(self._rsi_period.Value)
self._is_initialized = False
self._cooldown = 0
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, atr, rsi, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
self.StartProtection(
Unit(0, UnitTypes.Absolute),
Unit(self._stop_loss_percent.Value, UnitTypes.Percent),
False
)
def _process_candle(self, candle, ema_val, atr_val, rsi_val):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
ema = float(ema_val)
atr = float(atr_val)
rsi = float(rsi_val)
price = float(candle.ClosePrice)
if not self._is_initialized:
self._prev_price = price
self._prev_rsi = rsi
self._is_initialized = True
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_price = price
self._prev_rsi = rsi
return
mult = float(self._atr_multiplier.Value)
upper_band = ema + mult * atr
lower_band = ema - mult * atr
bullish_divergence = (rsi >= self._prev_rsi and price < self._prev_price) or rsi <= 30.0
bearish_divergence = (rsi <= self._prev_rsi and price > self._prev_price) or rsi >= 70.0
cd = int(self._cooldown_bars.Value)
if self.Position == 0:
if price <= lower_band + atr * 0.1 and bullish_divergence:
self.BuyMarket()
self._cooldown = cd
elif price >= upper_band - atr * 0.1 and bearish_divergence:
self.SellMarket()
self._cooldown = cd
elif self.Position > 0:
if price >= ema or rsi >= 50.0:
self.SellMarket(Math.Abs(self.Position))
self._cooldown = cd
elif self.Position < 0:
if price <= ema or rsi <= 50.0:
self.BuyMarket(Math.Abs(self.Position))
self._cooldown = cd
self._prev_price = price
self._prev_rsi = rsi
def CreateClone(self):
return keltner_rsi_divergence_strategy()