Genie Stoch RSI 策略
该策略结合相对强弱指数(RSI)和随机指标(Stochastic Oscillator)。 当市场进入超买或超卖区域时,策略等待 Stochastic 主线与信号线的交叉来确认可能的反转。 同时使用移动止损和固定止盈进行风险控制。
逻辑
- 订阅所选时间框架的K线。
- 计算具有可配置周期的 RSI。
- 计算具有可配置 %K、%D 及减缓参数的 Stochastic。
- 做多条件:
- RSI 低于超卖水平;
- %K 低于 Stochastic 的超卖水平;
- 上一根 %K 低于上一根 %D 且当前 %K 向上穿越当前 %D。
- 做空条件:
- RSI 高于超买水平;
- %K 高于 Stochastic 的超买水平;
- 上一根 %K 高于上一根 %D 且当前 %K 向下穿越当前 %D。
- 持仓量来自策略的
Volume属性,如出现反向信号则反手。 StartProtection使用价格点数设置的止盈和移动止损。
参数
| 名称 | 说明 |
|---|---|
RsiPeriod |
RSI 计算周期。 |
KPeriod |
Stochastic %K 周期。 |
DPeriod |
Stochastic %D 周期。 |
Slowing |
Stochastic 减缓值。 |
RsiOverbought |
RSI 超买水平。 |
RsiOversold |
RSI 超卖水平。 |
StochOverbought |
Stochastic 超买水平。 |
StochOversold |
Stochastic 超卖水平。 |
TakeProfit |
止盈距离(价格点)。 |
TrailingStop |
移动止损距离(价格点)。 |
CandleType |
分析用的K线类型与时间框架。 |
注意
策略仅处理已完成的K线,直到所有指标形成后才产生信号。 该示例仅供学习使用,实际交易前需要充分测试。
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy that trades based on RSI and Stochastic oscillator cross signals.
/// </summary>
public class GenieStochRsiStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _rsiOverbought;
private readonly StrategyParam<decimal> _rsiOversold;
private readonly StrategyParam<decimal> _stochOverbought;
private readonly StrategyParam<decimal> _stochOversold;
private readonly StrategyParam<decimal> _takeProfit;
private readonly StrategyParam<decimal> _trailingStop;
private readonly StrategyParam<DataType> _candleType;
private RelativeStrengthIndex _rsi = null!;
private StochasticOscillator _stochastic = null!;
private decimal _prevK;
private decimal _prevD;
private bool _initialized;
/// <summary>RSI calculation period.</summary>
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
/// <summary>RSI overbought level.</summary>
public decimal RsiOverbought { get => _rsiOverbought.Value; set => _rsiOverbought.Value = value; }
/// <summary>RSI oversold level.</summary>
public decimal RsiOversold { get => _rsiOversold.Value; set => _rsiOversold.Value = value; }
/// <summary>Stochastic overbought level.</summary>
public decimal StochOverbought { get => _stochOverbought.Value; set => _stochOverbought.Value = value; }
/// <summary>Stochastic oversold level.</summary>
public decimal StochOversold { get => _stochOversold.Value; set => _stochOversold.Value = value; }
/// <summary>Take profit in price points.</summary>
public decimal TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
/// <summary>Trailing stop in price points.</summary>
public decimal TrailingStop { get => _trailingStop.Value; set => _trailingStop.Value = value; }
/// <summary>Candle type to process.</summary>
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
/// <summary>
/// Initializes a new instance of <see cref="GenieStochRsiStrategy"/>.
/// </summary>
public GenieStochRsiStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI calculation length", "Parameters");
_rsiOverbought = Param(nameof(RsiOverbought), 70m)
.SetDisplay("RSI Overbought", "RSI overbought level", "Signals");
_rsiOversold = Param(nameof(RsiOversold), 30m)
.SetDisplay("RSI Oversold", "RSI oversold level", "Signals");
_stochOverbought = Param(nameof(StochOverbought), 80m)
.SetDisplay("Stoch Overbought", "Stochastic overbought level", "Signals");
_stochOversold = Param(nameof(StochOversold), 20m)
.SetDisplay("Stoch Oversold", "Stochastic oversold level", "Signals");
_takeProfit = Param(nameof(TakeProfit), 500m)
.SetDisplay("Take Profit", "Take profit in price points", "Risk");
_trailingStop = Param(nameof(TrailingStop), 200m)
.SetDisplay("Trailing Stop", "Trailing stop in price points", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevK = default;
_prevD = default;
_initialized = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_rsi = new RelativeStrengthIndex { Length = RsiPeriod };
_stochastic = new StochasticOscillator();
var subscription = SubscribeCandles(CandleType);
subscription.BindEx(_stochastic, ProcessCandle).Start();
StartProtection(
new Unit(TakeProfit, UnitTypes.Absolute),
new Unit(TrailingStop, UnitTypes.Absolute),
isStopTrailing: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _rsi);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue stochValue)
{
if (candle.State != CandleStates.Finished)
return;
// Process RSI manually
var rsiResult = _rsi.Process(candle.ClosePrice, candle.OpenTime, true);
if (!_rsi.IsFormed || !_stochastic.IsFormed)
return;
var rsiValue = rsiResult.ToDecimal();
var stochTyped = (StochasticOscillatorValue)stochValue;
if (stochTyped.K is not decimal kValue || stochTyped.D is not decimal dValue)
return;
if (!_initialized)
{
_prevK = kValue;
_prevD = dValue;
_initialized = true;
return;
}
// Sell when RSI overbought + stochastic K crosses below D in overbought zone
var sellSignal = rsiValue > RsiOverbought &&
kValue > StochOverbought &&
_prevK > _prevD &&
kValue < dValue;
// Buy when RSI oversold + stochastic K crosses above D in oversold zone
var buySignal = rsiValue < RsiOversold &&
kValue < StochOversold &&
_prevK < _prevD &&
kValue > dValue;
if (sellSignal && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
else if (buySignal && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
_prevK = kValue;
_prevD = dValue;
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import RelativeStrengthIndex, StochasticOscillator
from StockSharp.Algo.Strategies import Strategy
class genie_stoch_rsi_strategy(Strategy):
def __init__(self):
super(genie_stoch_rsi_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetGreaterThanZero() \
.SetDisplay("RSI Period", "RSI calculation length", "Parameters")
self._rsi_overbought = self.Param("RsiOverbought", 70.0) \
.SetDisplay("RSI Overbought", "RSI overbought level", "Signals")
self._rsi_oversold = self.Param("RsiOversold", 30.0) \
.SetDisplay("RSI Oversold", "RSI oversold level", "Signals")
self._stoch_overbought = self.Param("StochOverbought", 80.0) \
.SetDisplay("Stoch Overbought", "Stochastic overbought level", "Signals")
self._stoch_oversold = self.Param("StochOversold", 20.0) \
.SetDisplay("Stoch Oversold", "Stochastic oversold level", "Signals")
self._take_profit_param = self.Param("TakeProfit", 500.0) \
.SetDisplay("Take Profit", "Take profit in price points", "Risk")
self._trailing_stop = self.Param("TrailingStop", 200.0) \
.SetDisplay("Trailing Stop", "Trailing stop in price points", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_k = 0.0
self._prev_d = 0.0
self._initialized = False
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def rsi_overbought(self):
return self._rsi_overbought.Value
@property
def rsi_oversold(self):
return self._rsi_oversold.Value
@property
def stoch_overbought(self):
return self._stoch_overbought.Value
@property
def stoch_oversold(self):
return self._stoch_oversold.Value
@property
def take_profit(self):
return self._take_profit_param.Value
@property
def trailing_stop(self):
return self._trailing_stop.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(genie_stoch_rsi_strategy, self).OnReseted()
self._prev_k = 0.0
self._prev_d = 0.0
self._initialized = False
def OnStarted2(self, time):
super(genie_stoch_rsi_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
stochastic = StochasticOscillator()
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(stochastic, rsi, self.process_candle).Start()
self.StartProtection(
Unit(float(self.take_profit), UnitTypes.Absolute),
Unit(float(self.trailing_stop), UnitTypes.Absolute),
isStopTrailing=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
def process_candle(self, candle, stoch_value, rsi_value):
if candle.State != CandleStates.Finished:
return
if not stoch_value.IsFinal or not rsi_value.IsFinal:
return
rsi_val = float(rsi_value)
k_val = stoch_value.K
d_val = stoch_value.D
if k_val is None or d_val is None:
return
k = float(k_val)
d = float(d_val)
if not self._initialized:
self._prev_k = k
self._prev_d = d
self._initialized = True
return
# Sell when RSI overbought + stochastic K crosses below D in overbought zone
sell_signal = (rsi_val > float(self.rsi_overbought) and
k > float(self.stoch_overbought) and
self._prev_k > self._prev_d and
k < d)
# Buy when RSI oversold + stochastic K crosses above D in oversold zone
buy_signal = (rsi_val < float(self.rsi_oversold) and
k < float(self.stoch_oversold) and
self._prev_k < self._prev_d and
k > d)
if sell_signal and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
elif buy_signal and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._prev_k = k
self._prev_d = d
def CreateClone(self):
return genie_stoch_rsi_strategy()