Long Term Profitable Swing 策略
当快速 EMA 上穿慢速 EMA 且 RSI 高于设定阈值时,本策略开多。价格触及基于 ATR 的止损或止盈水平时退出。
细节
- 入场条件:
- 多头:快速 EMA 上穿慢速 EMA 且 RSI > 阈值。
- 多空方向:仅多头。
- 出场条件:
- 价格到达 ATR 止损或 ATR 止盈。
- 止损:使用 ATR 倍数设置止损与止盈。
- 默认参数:
FastEmaLength= 16SlowEmaLength= 30RsiLength= 9AtrLength= 21RsiThreshold= 50AtrStopMult= 8AtrTpMult= 11
- 过滤器:
- 类别:趋势跟随
- 方向:多头
- 指标:EMA、RSI、ATR
- 止损:是
- 复杂度:低
- 周期:任意
- 季节性:无
- 神经网络:无
- 背离:无
- 风险等级:中等
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>
/// Long Term Profitable Swing strategy based on EMA crossover with RSI filter and ATR exits.
/// </summary>
public class LongTermProfitableSwingAbbasStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastEmaLength;
private readonly StrategyParam<int> _slowEmaLength;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _rsiThreshold;
private readonly StrategyParam<decimal> _atrStopMult;
private readonly StrategyParam<decimal> _atrTpMult;
private ExponentialMovingAverage _fastEma;
private ExponentialMovingAverage _slowEma;
private RelativeStrengthIndex _rsi;
private AverageTrueRange _atr;
private decimal _prevFast;
private decimal _prevSlow;
/// <summary>
/// Candle type for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Fast EMA length.
/// </summary>
public int FastEmaLength
{
get => _fastEmaLength.Value;
set => _fastEmaLength.Value = value;
}
/// <summary>
/// Slow EMA length.
/// </summary>
public int SlowEmaLength
{
get => _slowEmaLength.Value;
set => _slowEmaLength.Value = value;
}
/// <summary>
/// RSI calculation length.
/// </summary>
public int RsiLength
{
get => _rsiLength.Value;
set => _rsiLength.Value = value;
}
/// <summary>
/// ATR calculation length.
/// </summary>
public int AtrLength
{
get => _atrLength.Value;
set => _atrLength.Value = value;
}
/// <summary>
/// RSI bullish threshold.
/// </summary>
public decimal RsiThreshold
{
get => _rsiThreshold.Value;
set => _rsiThreshold.Value = value;
}
/// <summary>
/// ATR stop loss multiplier.
/// </summary>
public decimal AtrStopMult
{
get => _atrStopMult.Value;
set => _atrStopMult.Value = value;
}
/// <summary>
/// ATR take profit multiplier.
/// </summary>
public decimal AtrTpMult
{
get => _atrTpMult.Value;
set => _atrTpMult.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public LongTermProfitableSwingAbbasStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_fastEmaLength = Param(nameof(FastEmaLength), 16)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA length", "Indicators")
.SetOptimize(5, 50, 1);
_slowEmaLength = Param(nameof(SlowEmaLength), 25)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA length", "Indicators")
.SetOptimize(20, 100, 5);
_rsiLength = Param(nameof(RsiLength), 9)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI calculation length", "Indicators")
.SetOptimize(5, 30, 1);
_atrLength = Param(nameof(AtrLength), 21)
.SetGreaterThanZero()
.SetDisplay("ATR Length", "ATR calculation length", "Indicators")
.SetOptimize(5, 40, 1);
_rsiThreshold = Param(nameof(RsiThreshold), 50m)
.SetRange(0m, 100m)
.SetDisplay("RSI Threshold", "RSI bullish threshold", "Indicators")
.SetOptimize(40m, 60m, 1m);
_atrStopMult = Param(nameof(AtrStopMult), 15m)
.SetRange(0.1m, 30m)
.SetDisplay("ATR Stop Mult", "ATR stop loss multiplier", "Risk")
.SetOptimize(1m, 15m, 0.5m);
_atrTpMult = Param(nameof(AtrTpMult), 20m)
.SetRange(0.1m, 30m)
.SetDisplay("ATR TP Mult", "ATR take profit multiplier", "Risk")
.SetOptimize(1m, 20m, 0.5m);
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_fastEma = null;
_slowEma = null;
_rsi = null;
_atr = null;
_prevFast = 0;
_prevSlow = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevFast = 0;
_prevSlow = 0;
_fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
_slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };
_rsi = new RelativeStrengthIndex { Length = RsiLength };
_atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_fastEma, _slowEma, _rsi, _atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _fastEma);
DrawIndicator(area, _slowEma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal rsi, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fastEma.IsFormed || !_slowEma.IsFormed || !_rsi.IsFormed || !_atr.IsFormed)
return;
if (_prevFast == 0 || _prevSlow == 0)
{
_prevFast = fast;
_prevSlow = slow;
return;
}
var crossUp = _prevFast <= _prevSlow && fast > slow;
var crossDown = _prevFast >= _prevSlow && fast < slow;
_prevFast = fast;
_prevSlow = slow;
if (crossUp && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
}
else if (crossDown && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
}
}
}
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, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class long_term_profitable_swing_abbas_strategy(Strategy):
def __init__(self):
super(long_term_profitable_swing_abbas_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._fast_ema_length = self.Param("FastEmaLength", 16) \
.SetGreaterThanZero() \
.SetDisplay("Fast EMA", "Fast EMA length", "Indicators")
self._slow_ema_length = self.Param("SlowEmaLength", 25) \
.SetGreaterThanZero() \
.SetDisplay("Slow EMA", "Slow EMA length", "Indicators")
self._rsi_length = self.Param("RsiLength", 9) \
.SetGreaterThanZero() \
.SetDisplay("RSI Length", "RSI calculation length", "Indicators")
self._atr_length = self.Param("AtrLength", 21) \
.SetGreaterThanZero() \
.SetDisplay("ATR Length", "ATR calculation length", "Indicators")
self._rsi_threshold = self.Param("RsiThreshold", 50.0) \
.SetDisplay("RSI Threshold", "RSI bullish threshold", "Indicators")
self._atr_stop_mult = self.Param("AtrStopMult", 15.0) \
.SetDisplay("ATR Stop Mult", "ATR stop loss multiplier", "Risk")
self._atr_tp_mult = self.Param("AtrTpMult", 20.0) \
.SetDisplay("ATR TP Mult", "ATR take profit multiplier", "Risk")
self._prev_fast = 0.0
self._prev_slow = 0.0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(long_term_profitable_swing_abbas_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
def OnStarted2(self, time):
super(long_term_profitable_swing_abbas_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self._fast_ema_length.Value
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self._slow_ema_length.Value
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self._rsi_length.Value
self._atr = AverageTrueRange()
self._atr.Length = self._atr_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_ema, self._slow_ema, self._rsi, self._atr, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._fast_ema)
self.DrawIndicator(area, self._slow_ema)
self.DrawOwnTrades(area)
def OnProcess(self, candle, fast, slow, rsi, atr):
if candle.State != CandleStates.Finished:
return
if not self._fast_ema.IsFormed or not self._slow_ema.IsFormed or not self._rsi.IsFormed or not self._atr.IsFormed:
return
fv = float(fast)
sv = float(slow)
if self._prev_fast == 0.0 or self._prev_slow == 0.0:
self._prev_fast = fv
self._prev_slow = sv
return
cross_up = self._prev_fast <= self._prev_slow and fv > sv
cross_down = self._prev_fast >= self._prev_slow and fv < sv
self._prev_fast = fv
self._prev_slow = sv
if cross_up and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif cross_down and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return long_term_profitable_swing_abbas_strategy()