RSI Automated Strategy
利用相对强弱指数(RSI)在极度超卖和超买状态下进行交易的动量策略。 当RSI跌破超卖水平时开多仓,当RSI升破超买水平时开空仓。 当RSI回到中间阈值或触发止损、止盈或追踪止损时平仓。
细节
- 入场条件:RSI跌破
Oversold做多或升破Overbought做空。 - 多空方向:双向。
- 出场条件:RSI触及
ExitLevel、止损、止盈或追踪止损。 - 止损:是,固定止损、止盈以及可选的追踪止损。
- 默认值:
RsiPeriod= 14Overbought= 75Oversold= 25ExitLevel= 50StopLossPoints= 50TakeProfitPoints= 150TrailingStopPoints= 25CandleType= TimeSpan.FromMinutes(1)
- 筛选:
- 分类:振荡指标
- 方向:双向
- 指标:RSI
- 止损:是
- 复杂度:基础
- 时间框架:日内 (1m)
- 季节性:否
- 神经网络:否
- 背离:否
- 风险等级:中等
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>
/// RSI based trading strategy with fixed stop loss, take profit and trailing stop.
/// Opens long when RSI falls below oversold level and short when RSI rises above overbought level.
/// Positions close when RSI returns to a mid level or when stops are reached.
/// </summary>
public class RsiAutomatedStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _overbought;
private readonly StrategyParam<decimal> _oversold;
private readonly StrategyParam<decimal> _exitLevel;
private readonly StrategyParam<decimal> _stopLossPoints;
private readonly StrategyParam<decimal> _takeProfitPoints;
private readonly StrategyParam<decimal> _trailingStopPoints;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
private decimal _stopPrice;
private decimal _takeProfitPrice;
/// <summary>
/// RSI calculation period.
/// </summary>
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
/// <summary>
/// RSI level to open short positions.
/// </summary>
public decimal Overbought { get => _overbought.Value; set => _overbought.Value = value; }
/// <summary>
/// RSI level to open long positions.
/// </summary>
public decimal Oversold { get => _oversold.Value; set => _oversold.Value = value; }
/// <summary>
/// RSI level that closes any existing position.
/// </summary>
public decimal ExitLevel { get => _exitLevel.Value; set => _exitLevel.Value = value; }
/// <summary>
/// Initial stop loss distance in price points.
/// </summary>
public decimal StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
/// <summary>
/// Take profit distance in price points.
/// </summary>
public decimal TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }
/// <summary>
/// Trailing stop distance in price points.
/// </summary>
public decimal TrailingStopPoints { get => _trailingStopPoints.Value; set => _trailingStopPoints.Value = value; }
/// <summary>
/// Type of candles used for calculations.
/// </summary>
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public RsiAutomatedStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI calculation length", "RSI")
.SetOptimize(5, 30, 5);
_overbought = Param(nameof(Overbought), 75m)
.SetDisplay("Overbought", "RSI value to open short", "RSI");
_oversold = Param(nameof(Oversold), 25m)
.SetDisplay("Oversold", "RSI value to open long", "RSI");
_exitLevel = Param(nameof(ExitLevel), 50m)
.SetDisplay("Exit Level", "RSI level to close position", "RSI");
_stopLossPoints = Param(nameof(StopLossPoints), 50m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss", "Initial stop loss in points", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 150m)
.SetGreaterThanZero()
.SetDisplay("Take Profit", "Take profit distance in points", "Risk");
_trailingStopPoints = Param(nameof(TrailingStopPoints), 25m)
.SetNotNegative()
.SetDisplay("Trailing", "Trailing stop distance in points", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).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();
_entryPrice = 0m;
_stopPrice = 0m;
_takeProfitPrice = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex
{
Length = RsiPeriod
};
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, rsi);
DrawOwnTrades(area);
}
}
private void ResetState()
{
_entryPrice = 0m;
_stopPrice = 0m;
_takeProfitPrice = 0m;
}
private void ProcessCandle(ICandleMessage candle, decimal rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (Position == 0)
{
if (rsiValue < Oversold)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice - StopLossPoints;
_takeProfitPrice = _entryPrice + TakeProfitPoints;
}
else if (rsiValue > Overbought)
{
SellMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice + StopLossPoints;
_takeProfitPrice = _entryPrice - TakeProfitPoints;
}
return;
}
if (Position > 0)
{
if (rsiValue > ExitLevel)
{
SellMarket();
ResetState();
return;
}
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _takeProfitPrice)
{
SellMarket();
ResetState();
return;
}
if (TrailingStopPoints > 0 && candle.ClosePrice - _entryPrice > TrailingStopPoints)
{
var newStop = candle.ClosePrice - TrailingStopPoints;
if (newStop > _stopPrice)
_stopPrice = newStop;
}
}
else
{
if (rsiValue < ExitLevel)
{
BuyMarket();
ResetState();
return;
}
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _takeProfitPrice)
{
BuyMarket();
ResetState();
return;
}
if (TrailingStopPoints > 0 && _entryPrice - candle.ClosePrice > TrailingStopPoints)
{
var newStop = candle.ClosePrice + TrailingStopPoints;
if (_stopPrice == 0m || newStop < _stopPrice)
_stopPrice = newStop;
}
}
}
}
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 RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class rsi_automated_strategy(Strategy):
def __init__(self):
super(rsi_automated_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI calculation length", "RSI")
self._overbought = self.Param("Overbought", 75.0) \
.SetDisplay("Overbought", "RSI value to open short", "RSI")
self._oversold = self.Param("Oversold", 25.0) \
.SetDisplay("Oversold", "RSI value to open long", "RSI")
self._exit_level = self.Param("ExitLevel", 50.0) \
.SetDisplay("Exit Level", "RSI level to close position", "RSI")
self._stop_loss_points = self.Param("StopLossPoints", 50.0) \
.SetDisplay("Stop Loss", "Initial stop loss in points", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 150.0) \
.SetDisplay("Take Profit", "Take profit distance in points", "Risk")
self._trailing_stop_points = self.Param("TrailingStopPoints", 25.0) \
.SetDisplay("Trailing", "Trailing stop distance in points", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._entry_price = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def overbought(self):
return self._overbought.Value
@property
def oversold(self):
return self._oversold.Value
@property
def exit_level(self):
return self._exit_level.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
@property
def trailing_stop_points(self):
return self._trailing_stop_points.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(rsi_automated_strategy, self).OnReseted()
self._entry_price = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
def OnStarted2(self, time):
super(rsi_automated_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
def _reset_state(self):
self._entry_price = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
def process_candle(self, candle, rsi_value):
if candle.State != CandleStates.Finished:
return
rsi_val = float(rsi_value)
close = float(candle.ClosePrice)
sl = float(self.stop_loss_points)
tp = float(self.take_profit_points)
trail = float(self.trailing_stop_points)
if self.Position == 0:
if rsi_val < float(self.oversold):
self.BuyMarket()
self._entry_price = close
self._stop_price = close - sl
self._take_profit_price = close + tp
elif rsi_val > float(self.overbought):
self.SellMarket()
self._entry_price = close
self._stop_price = close + sl
self._take_profit_price = close - tp
return
if self.Position > 0:
if rsi_val > float(self.exit_level):
self.SellMarket()
self._reset_state()
return
low = float(candle.LowPrice)
high = float(candle.HighPrice)
if low <= self._stop_price or high >= self._take_profit_price:
self.SellMarket()
self._reset_state()
return
if trail > 0.0 and close - self._entry_price > trail:
new_stop = close - trail
if new_stop > self._stop_price:
self._stop_price = new_stop
else:
if rsi_val < float(self.exit_level):
self.BuyMarket()
self._reset_state()
return
high = float(candle.HighPrice)
low = float(candle.LowPrice)
if high >= self._stop_price or low <= self._take_profit_price:
self.BuyMarket()
self._reset_state()
return
if trail > 0.0 and self._entry_price - close > trail:
new_stop = close + trail
if self._stop_price == 0.0 or new_stop < self._stop_price:
self._stop_price = new_stop
def CreateClone(self):
return rsi_automated_strategy()