EMA RSI Trailing Stop 策略
该策略在短期 EMA 穿越中期 EMA 且位于长期 EMA 之上或之下时开仓。通过 RSI 水平和平移止损结合固定百分比止损退出。若交易在盈利,可在指定 K 线数量后平仓。
详情
- 入场条件:EMA A 与 EMA B 金叉/死叉并由 EMA C 确认趋势,且 K 线方向一致。
- 多空方向:双向。
- 出场条件:RSI 阈值、移动止损或时间退出。
- 止损:固定百分比止损,当价格向有利方向移动
TrailOffset后转为移动止损。 - 默认参数:
EmaALength= 10EmaBLength= 20EmaCLength= 100RsiLength= 14ExitLongRsi= 70ExitShortRsi= 30TrailPoints= 50TrailOffset= 10FixStopLossPercent= 5CloseAfterXBars= trueXBars= 24ShowLong= trueShowShort= falseCandleType= TimeSpan.FromMinutes(1)
- 过滤器:
- 类别:趋势
- 方向:双向
- 指标:EMA, RSI
- 止损:移动
- 复杂度:中等
- 时间框架:日内
- 季节性:无
- 神经网络:无
- 背离:无
- 风险等级:中等
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>
/// EMA RSI trail stop strategy.
/// EMA A crossing above EMA B with the close above EMA C on a bullish candle goes long, the mirrored conditions go short.
/// RSI above ExitLongRsi closes a long and RSI below ExitShortRsi closes a short. A fixed percent stop protects the position
/// and turns into a trailing stop TrailPoints price steps behind the best price once price has moved TrailOffset steps in favour.
/// Optionally a profitable position is closed after XBars candles.
/// </summary>
public class EmaRsiTrailStopStrategy : Strategy
{
private readonly StrategyParam<int> _emaALength;
private readonly StrategyParam<int> _emaBLength;
private readonly StrategyParam<int> _emaCLength;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<decimal> _exitLongRsi;
private readonly StrategyParam<decimal> _exitShortRsi;
private readonly StrategyParam<decimal> _trailPoints;
private readonly StrategyParam<decimal> _trailOffset;
private readonly StrategyParam<decimal> _fixStopLossPercent;
private readonly StrategyParam<bool> _closeAfterXBars;
private readonly StrategyParam<int> _xBars;
private readonly StrategyParam<bool> _showLong;
private readonly StrategyParam<bool> _showShort;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevA;
private decimal? _prevB;
private decimal _entryPrice;
private decimal _bestPrice;
private decimal? _stopPrice;
private int _barsInPosition;
/// <summary>
/// Fast EMA length.
/// </summary>
public int EmaALength
{
get => _emaALength.Value;
set => _emaALength.Value = value;
}
/// <summary>
/// Medium EMA length.
/// </summary>
public int EmaBLength
{
get => _emaBLength.Value;
set => _emaBLength.Value = value;
}
/// <summary>
/// Trend EMA length.
/// </summary>
public int EmaCLength
{
get => _emaCLength.Value;
set => _emaCLength.Value = value;
}
/// <summary>
/// RSI length.
/// </summary>
public int RsiLength
{
get => _rsiLength.Value;
set => _rsiLength.Value = value;
}
/// <summary>
/// RSI level that closes a long.
/// </summary>
public decimal ExitLongRsi
{
get => _exitLongRsi.Value;
set => _exitLongRsi.Value = value;
}
/// <summary>
/// RSI level that closes a short.
/// </summary>
public decimal ExitShortRsi
{
get => _exitShortRsi.Value;
set => _exitShortRsi.Value = value;
}
/// <summary>
/// Trailing distance in price steps.
/// </summary>
public decimal TrailPoints
{
get => _trailPoints.Value;
set => _trailPoints.Value = value;
}
/// <summary>
/// Favourable move in price steps that activates the trailing stop.
/// </summary>
public decimal TrailOffset
{
get => _trailOffset.Value;
set => _trailOffset.Value = value;
}
/// <summary>
/// Fixed stop loss percentage from entry price.
/// </summary>
public decimal FixStopLossPercent
{
get => _fixStopLossPercent.Value;
set => _fixStopLossPercent.Value = value;
}
/// <summary>
/// Close a profitable position after XBars candles.
/// </summary>
public bool CloseAfterXBars
{
get => _closeAfterXBars.Value;
set => _closeAfterXBars.Value = value;
}
/// <summary>
/// Candles after which a profitable position is closed.
/// </summary>
public int XBars
{
get => _xBars.Value;
set => _xBars.Value = value;
}
/// <summary>
/// Allow long trades.
/// </summary>
public bool ShowLong
{
get => _showLong.Value;
set => _showLong.Value = value;
}
/// <summary>
/// Allow short trades.
/// </summary>
public bool ShowShort
{
get => _showShort.Value;
set => _showShort.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public EmaRsiTrailStopStrategy()
{
_emaALength = Param(nameof(EmaALength), 10)
.SetGreaterThanZero()
.SetDisplay("EMA A", "Fast EMA length", "Indicators");
_emaBLength = Param(nameof(EmaBLength), 20)
.SetGreaterThanZero()
.SetDisplay("EMA B", "Medium EMA length", "Indicators");
_emaCLength = Param(nameof(EmaCLength), 100)
.SetGreaterThanZero()
.SetDisplay("EMA C", "Trend EMA length", "Indicators");
_rsiLength = Param(nameof(RsiLength), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI length", "Indicators");
_exitLongRsi = Param(nameof(ExitLongRsi), 70m)
.SetDisplay("Exit Long RSI", "RSI level that closes a long", "Exits");
_exitShortRsi = Param(nameof(ExitShortRsi), 30m)
.SetDisplay("Exit Short RSI", "RSI level that closes a short", "Exits");
_trailPoints = Param(nameof(TrailPoints), 50m)
.SetNotNegative()
.SetDisplay("Trail Points", "Trailing distance in price steps", "Risk");
_trailOffset = Param(nameof(TrailOffset), 10m)
.SetNotNegative()
.SetDisplay("Trail Offset", "Favourable move in price steps that activates trailing", "Risk");
_fixStopLossPercent = Param(nameof(FixStopLossPercent), 5m)
.SetNotNegative()
.SetDisplay("Fixed Stop %", "Fixed stop loss percentage from entry price", "Risk");
_closeAfterXBars = Param(nameof(CloseAfterXBars), true)
.SetDisplay("Close After X Bars", "Close a profitable position after XBars candles", "Exits");
_xBars = Param(nameof(XBars), 24)
.SetGreaterThanZero()
.SetDisplay("X Bars", "Candles after which a profitable position is closed", "Exits");
_showLong = Param(nameof(ShowLong), true)
.SetDisplay("Long Trades", "Allow long trades", "General");
_showShort = Param(nameof(ShowShort), false)
.SetDisplay("Short Trades", "Allow short trades", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(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()
{
_prevA = null;
_prevB = null;
_entryPrice = 0m;
_bestPrice = 0m;
_stopPrice = null;
_barsInPosition = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
ResetState();
var emaA = new ExponentialMovingAverage { Length = EmaALength };
var emaB = new ExponentialMovingAverage { Length = EmaBLength };
var emaC = new ExponentialMovingAverage { Length = EmaCLength };
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(emaA, emaB, emaC, rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, emaA);
DrawIndicator(area, emaB);
DrawIndicator(area, emaC);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal a, decimal b, decimal c, decimal rsi)
{
if (candle.State != CandleStates.Finished)
return;
var prevA = _prevA;
var prevB = _prevB;
_prevA = a;
_prevB = b;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (Position != 0 && ManagePosition(candle, rsi))
return;
if (prevA is not decimal pa || prevB is not decimal pb)
return;
var crossUp = pa <= pb && a > b;
var crossDown = pa >= pb && a < b;
if (ShowLong && crossUp && candle.ClosePrice > c && candle.ClosePrice > candle.OpenPrice && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
OpenPosition(candle.ClosePrice, true);
}
else if (ShowShort && crossDown && candle.ClosePrice < c && candle.ClosePrice < candle.OpenPrice && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
OpenPosition(candle.ClosePrice, false);
}
}
private void OpenPosition(decimal price, bool isLong)
{
_entryPrice = price;
_bestPrice = price;
_barsInPosition = 0;
_stopPrice = FixStopLossPercent > 0m
? (isLong ? price * (1m - FixStopLossPercent / 100m) : price * (1m + FixStopLossPercent / 100m))
: null;
}
private bool ManagePosition(ICandleMessage candle, decimal rsi)
{
var step = Security?.PriceStep ?? 1m;
_barsInPosition++;
if (Position > 0)
{
if (_stopPrice is decimal stop && candle.LowPrice <= stop)
{
SellMarket(Position);
return true;
}
if (rsi > ExitLongRsi || (CloseAfterXBars && _barsInPosition >= XBars && candle.ClosePrice > _entryPrice))
{
SellMarket(Position);
return true;
}
_bestPrice = Math.Max(_bestPrice, candle.HighPrice);
if (_bestPrice - _entryPrice >= TrailOffset * step)
{
var trail = _bestPrice - TrailPoints * step;
_stopPrice = _stopPrice is decimal current ? Math.Max(current, trail) : trail;
}
}
else
{
if (_stopPrice is decimal stop && candle.HighPrice >= stop)
{
BuyMarket(-Position);
return true;
}
if (rsi < ExitShortRsi || (CloseAfterXBars && _barsInPosition >= XBars && candle.ClosePrice < _entryPrice))
{
BuyMarket(-Position);
return true;
}
_bestPrice = Math.Min(_bestPrice, candle.LowPrice);
if (_entryPrice - _bestPrice >= TrailOffset * step)
{
var trail = _bestPrice + TrailPoints * step;
_stopPrice = _stopPrice is decimal current ? Math.Min(current, trail) : trail;
}
}
return false;
}
}
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 ExponentialMovingAverage, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class ema_rsi_trail_stop_strategy(Strategy):
"""
EMA RSI trail stop strategy.
EMA A crossing above EMA B with the close above EMA C on a bullish candle goes long, the mirrored conditions go short.
RSI above ExitLongRsi closes a long and RSI below ExitShortRsi closes a short. A fixed percent stop protects the position
and turns into a trailing stop TrailPoints price steps behind the best price once price has moved TrailOffset steps in favour.
Optionally a profitable position is closed after XBars candles.
"""
def __init__(self):
super(ema_rsi_trail_stop_strategy, self).__init__()
self._ema_a_length = self.Param("EmaALength", 10).SetGreaterThanZero().SetDisplay("EMA A", "Fast EMA length", "Indicators")
self._ema_b_length = self.Param("EmaBLength", 20).SetGreaterThanZero().SetDisplay("EMA B", "Medium EMA length", "Indicators")
self._ema_c_length = self.Param("EmaCLength", 100).SetGreaterThanZero().SetDisplay("EMA C", "Trend EMA length", "Indicators")
self._rsi_length = self.Param("RsiLength", 14).SetGreaterThanZero().SetDisplay("RSI Length", "RSI length", "Indicators")
self._exit_long_rsi = self.Param("ExitLongRsi", 70.0).SetDisplay("Exit Long RSI", "RSI level that closes a long", "Exits")
self._exit_short_rsi = self.Param("ExitShortRsi", 30.0).SetDisplay("Exit Short RSI", "RSI level that closes a short", "Exits")
self._trail_points = self.Param("TrailPoints", 50.0).SetNotNegative().SetDisplay("Trail Points", "Trailing distance in price steps", "Risk")
self._trail_offset = self.Param("TrailOffset", 10.0).SetNotNegative().SetDisplay("Trail Offset", "Favourable move in price steps that activates trailing", "Risk")
self._fix_stop_loss_percent = self.Param("FixStopLossPercent", 5.0).SetNotNegative().SetDisplay("Fixed Stop %", "Fixed stop loss percentage from entry price", "Risk")
self._close_after_x_bars = self.Param("CloseAfterXBars", True).SetDisplay("Close After X Bars", "Close a profitable position after XBars candles", "Exits")
self._x_bars = self.Param("XBars", 24).SetGreaterThanZero().SetDisplay("X Bars", "Candles after which a profitable position is closed", "Exits")
self._show_long = self.Param("ShowLong", True).SetDisplay("Long Trades", "Allow long trades", "General")
self._show_short = self.Param("ShowShort", False).SetDisplay("Short Trades", "Allow short trades", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(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_a = None
self._prev_b = None
self._entry_price = 0.0
self._best_price = 0.0
self._stop_price = None
self._bars_in_position = 0
def OnReseted(self):
super(ema_rsi_trail_stop_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(ema_rsi_trail_stop_strategy, self).OnStarted2(time)
self._reset_state()
ema_a = ExponentialMovingAverage()
ema_a.Length = self._ema_a_length.Value
ema_b = ExponentialMovingAverage()
ema_b.Length = self._ema_b_length.Value
ema_c = ExponentialMovingAverage()
ema_c.Length = self._ema_c_length.Value
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema_a, ema_b, ema_c, rsi, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema_a)
self.DrawIndicator(area, ema_b)
self.DrawIndicator(area, ema_c)
self.DrawOwnTrades(area)
def _process_candle(self, candle, a_value, b_value, c_value, rsi_value):
if candle.State != CandleStates.Finished:
return
a = float(a_value)
b = float(b_value)
c = float(c_value)
rsi = float(rsi_value)
prev_a = self._prev_a
prev_b = self._prev_b
self._prev_a = a
self._prev_b = b
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self.Position != 0 and self._manage_position(candle, rsi):
return
if prev_a is None or prev_b is None:
return
cross_up = prev_a <= prev_b and a > b
cross_down = prev_a >= prev_b and a < b
close = float(candle.ClosePrice)
open_price = float(candle.OpenPrice)
if self._show_long.Value and cross_up and close > c and close > open_price and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
self._open_position(close, True)
elif self._show_short.Value and cross_down and close < c and close < open_price and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
self._open_position(close, False)
def _open_position(self, price, is_long):
self._entry_price = price
self._best_price = price
self._bars_in_position = 0
percent = float(self._fix_stop_loss_percent.Value)
if percent > 0:
self._stop_price = price * (1.0 - percent / 100.0) if is_long else price * (1.0 + percent / 100.0)
else:
self._stop_price = None
def _manage_position(self, candle, rsi):
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
self._bars_in_position += 1
close = float(candle.ClosePrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
trail_points = float(self._trail_points.Value) * step
trail_offset = float(self._trail_offset.Value) * step
time_exit = self._close_after_x_bars.Value and self._bars_in_position >= self._x_bars.Value
if self.Position > 0:
if self._stop_price is not None and low <= self._stop_price:
self.SellMarket(self.Position)
return True
if rsi > float(self._exit_long_rsi.Value) or (time_exit and close > self._entry_price):
self.SellMarket(self.Position)
return True
self._best_price = max(self._best_price, high)
if self._best_price - self._entry_price >= trail_offset:
trail = self._best_price - trail_points
self._stop_price = trail if self._stop_price is None else max(self._stop_price, trail)
else:
if self._stop_price is not None and high >= self._stop_price:
self.BuyMarket(-self.Position)
return True
if rsi < float(self._exit_short_rsi.Value) or (time_exit and close < self._entry_price):
self.BuyMarket(-self.Position)
return True
self._best_price = min(self._best_price, low)
if self._entry_price - self._best_price >= trail_offset:
trail = self._best_price + trail_points
self._stop_price = trail if self._stop_price is None else min(self._stop_price, trail)
return False
def CreateClone(self):
return ema_rsi_trail_stop_strategy()