在 GitHub 上查看
基础 RSI EA 模板策略
Basic RSI EA Template Strategy 为 MetaTrader 4 专家顾问 “Basic Rsi EA Template.mq4”(MQL/26750)的 StockSharp 版本。策略在指定的K线序列上监控相对强弱指数(RSI),当动量进入自定义的超买或超卖区域时执行交易。转换保留了原始机器人“单一持仓+固定止损止盈”的简洁风格,并采用 StockSharp 的高级订阅接口实现。
策略逻辑
指标
入场条件
- 做多:当 RSI 低于
OversoldLevel 且当前没有持仓时,以 OrderVolume 的固定数量市价买入。
- 做空:当 RSI 高于
OverboughtLevel 且当前没有持仓时,以 OrderVolume 的固定数量市价卖出。
策略使用净头寸模式,同一时间只允许一笔仓位。如果持有多单,则等待其平仓后才允许做空(反之亦然)。
出场条件
- 止损:
StopLossPips 根据品种最小跳动价转换为绝对价格距离;当价格不利运行达到该距离时,通过保护模块平仓。
- 止盈:
TakeProfitPips 以同样方式转换;当价格向有利方向移动达到目标距离时平仓获利。
没有额外的移动止损或信号反向平仓逻辑,策略完全依赖预设的保护距离或人工干预,与原始模板保持一致。
风险与仓位管理
OrderVolume 设置每次市价单的固定交易量(默认 0.01 手,与 MQL 示例一致)。
- 策略不加仓、不对冲。止损或止盈触发后,重新等待下一次 RSI 信号。
参数说明
CandleType:用于计算信号的 K 线类型(默认 1 分钟)。
RsiPeriod:RSI 计算窗口长度(默认 14)。
OverboughtLevel:RSI 超买阈值(默认 70)。
OversoldLevel:RSI 超卖阈值(默认 30)。
StopLossPips:止损距离(点),内部转换为绝对价格(默认 30 点)。
TakeProfitPips:止盈距离(点),内部转换为绝对价格(默认 20 点)。
OrderVolume:每笔市价单的固定数量(默认 0.01)。
实现细节
- 通过
SubscribeCandles(...).Bind(rsi, ProcessCandle) 获取指标数值,无需手动管理缓冲区。
CreateProtectionUnit 模拟原始 MQL 对点值的处理:报价保留 3 或 5 位小数的品种使用 10 倍乘数将点数映射为价格步长。
- 仅在 K 线收盘后评估信号,避免同一根 K 线上重复下单。
- 转换基于净头寸账户,与 MetaTrader 的对冲模式不同,因此反向交易会先平掉当前仓位。
- 代码中的注释与日志全部使用英文,便于国际化维护。
使用建议
- 根据交易周期调整
CandleType(例如切换到小时线进行波段交易)。
- 根据标的波动率调节
StopLossPips 与 TakeProfitPips,它们是风险控制的关键。
- 如需更复杂的资金管理,可在该模板基础上接入 StockSharp 的组合或风险管理模块。
namespace StockSharp.Samples.Strategies;
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
/// <summary>
/// Basic RSI template: buys when RSI is oversold, sells when RSI is overbought.
/// </summary>
public class BasicRsiEaTemplateStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _overboughtLevel;
private readonly StrategyParam<decimal> _oversoldLevel;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
public decimal OverboughtLevel
{
get => _overboughtLevel.Value;
set => _overboughtLevel.Value = value;
}
public decimal OversoldLevel
{
get => _oversoldLevel.Value;
set => _oversoldLevel.Value = value;
}
public BasicRsiEaTemplateStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI calculation period", "Indicators");
_overboughtLevel = Param(nameof(OverboughtLevel), 70m)
.SetDisplay("Overbought Level", "RSI overbought threshold", "Indicators");
_oversoldLevel = Param(nameof(OversoldLevel), 30m)
.SetDisplay("Oversold Level", "RSI oversold threshold", "Indicators");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
decimal? prevRsi = null;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, (candle, rsiValue) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (prevRsi.HasValue)
{
var crossBelowOversold = prevRsi.Value >= OversoldLevel && rsiValue < OversoldLevel;
var crossAboveOverbought = prevRsi.Value <= OverboughtLevel && rsiValue > OverboughtLevel;
if (crossBelowOversold && Position <= 0)
BuyMarket();
else if (crossAboveOverbought && Position >= 0)
SellMarket();
}
prevRsi = rsiValue;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, rsi);
DrawOwnTrades(area);
}
}
}
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 basic_rsi_ea_template_strategy(Strategy):
def __init__(self):
super(basic_rsi_ea_template_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI calculation period", "Indicators")
self._overbought_level = self.Param("OverboughtLevel", 70.0) \
.SetDisplay("Overbought Level", "RSI overbought threshold", "Indicators")
self._oversold_level = self.Param("OversoldLevel", 30.0) \
.SetDisplay("Oversold Level", "RSI oversold threshold", "Indicators")
self._rsi = None
self._prev_rsi = None
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def overbought_level(self):
return self._overbought_level.Value
@property
def oversold_level(self):
return self._oversold_level.Value
def OnReseted(self):
super(basic_rsi_ea_template_strategy, self).OnReseted()
self._rsi = None
self._prev_rsi = None
def OnStarted2(self, time):
super(basic_rsi_ea_template_strategy, self).OnStarted2(time)
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self.rsi_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(30)))
subscription.Bind(self._rsi, self._process_candle)
subscription.Start()
def _process_candle(self, candle, rsi_value):
if candle.State != CandleStates.Finished:
return
if not self._rsi.IsFormed:
return
rsi = float(rsi_value)
if self._prev_rsi is not None:
cross_below_oversold = self._prev_rsi >= self.oversold_level and rsi < self.oversold_level
cross_above_overbought = self._prev_rsi <= self.overbought_level and rsi > self.overbought_level
if cross_below_oversold and self.Position <= 0:
self.BuyMarket()
elif cross_above_overbought and self.Position >= 0:
self.SellMarket()
self._prev_rsi = rsi
def CreateClone(self):
return basic_rsi_ea_template_strategy()