在 GitHub 上查看
iCCI iRSI 策略
概述
iCCI iRSI Strategy 源自 MetaTrader 5 智能交易程序 iCCI iRSI.mq5。原版策略结合 CCI 与 RSI 两个振荡指标,在两者同时进入超买或超卖区域时发出信号,并立即设置止损、止盈以及可选的移动止损。本次移植在 StockSharp 中复现了所有核心要素:以“点”(pip)为单位的参数、自动平掉反向仓位以及可选的信号反转模式。
交易逻辑
- 订阅指定的蜡烛周期,分别计算
CciPeriod 周期的 CommodityChannelIndex 与 RsiPeriod 周期的 RelativeStrengthIndex。
- 只在蜡烛收盘后评估信号,完全对应 MQL 脚本里对新棒的等待逻辑。
- 当 CCI 与 RSI 同时低于各自的下阈值(
CciLowerLevel、RsiLowerLevel)时开多或翻多;当两者同时高于上阈值(CciUpperLevel、RsiUpperLevel)时开空或翻空。将 ReverseSignals 设为 true 可反向解读信号。
- 下单前若存在反向持仓,会先市价平仓,确保净持仓方向与当前信号一致。
- 入场后在随后每根蜡烛的收盘价上检查止损与止盈。两个距离参数仍以“点”为单位,通过
PriceStep 转换为实际价格。若标的的 Decimals 为 3 或 5,则额外乘以 10,以匹配 MT5 中对 fractional pip 的处理方式。
TrailingStopPips 大于 0 时启用移动止损:仅当盈利幅度超过 TrailingStopPips + TrailingStepPips 时才会沿价格方向收紧止损,并遵循最小移动步长。
风险控制
- 止盈 / 止损:可选的点数距离,成交后立即转换成价格水平。若在蜡烛收盘时达到任一水平,则立即以市价出场。
- 移动止损:复刻原策略的逻辑——只有当盈利足够大并超过最小步长时,才会上调(或下调)止损。
- 下单量:
TradeVolume 参数取代原 EA 的“固定手数 / 百分比风险”开关。需要动态资金管理时,可结合优化器或其他风险模块。
- 仓位管理:新信号出现时强制平掉反向仓位,保持持仓干净,与原函数
ClosePositions 一致。
参数说明
- Candle Type:信号计算所使用的蜡烛类型(默认 1 小时)。
- CciPeriod:CCI 周期(默认 14)。
- CciUpperLevel / CciLowerLevel:CCI 超买 / 超卖阈值(默认 +80 / −80)。
- RsiPeriod:RSI 周期(默认 42)。
- RsiUpperLevel / RsiLowerLevel:RSI 触发阈值(默认 60 / 30)。
- ReverseSignals:是否反转信号方向(默认
false)。
- TradeVolume:市价单手数(默认 0.1,对应 MT5 输入)。
- StopLossPips / TakeProfitPips:止损 / 止盈距离(默认 0 与 140,设置为 0 即关闭)。
- TrailingStopPips / TrailingStepPips:移动止损距离与最小步长(默认 5 / 5;若距离为 0 则不启用移动止损)。
实现细节
- 使用 StockSharp 自带的
CommodityChannelIndex 与 RelativeStrengthIndex 指标,并通过 Bind 高级 API 直接接收十进制数值,省去了 MQL 中的缓冲拷贝。
- 订单管理在蜡烛收盘时执行,与原版
PrevBars 变量的保护逻辑一致,避免单根 K 线内的重复交易。
- Pip 转换逻辑遵循 MT5:在报价小数位为 3 或 5 的情况下,对
PriceStep 乘以 10,以获得标准点值。
- 保护性止损/止盈在策略内部以市价平仓模拟,因为在 StockSharp 的回测环境中无法直接修改经纪商订单。
- 策略会自动创建展示区,将价格、CCI、RSI 画在独立面板上,方便验证信号。
与原版 EA 的差异
- 未移植
MoneyFixedMargin 模块,仓位完全由 TradeVolume 控制。
- 无法访问 MT5 的
FreezeStopsLevels,移动止损仅按照价格距离与步长判断。
- 移除了原脚本中的日志与弹窗提示,需要时可接入 StockSharp 自带的日志系统。
- 止损与止盈的触发在蜡烛收盘时检查,而不是像 MT5 那样依赖撮合即时触发,这使得回测更加确定。
使用建议
- 建议先在 1 小时时间框架上运行,以保持与原策略一致;更低周期虽然信号更多,但噪声也更大。
- CCI 与 RSI 的上下阈值应同时调优,只有两者一致才会产生信号。
- 在外汇品种上运行时,请确认证券对象提供了正确的
PriceStep 与 Decimals,以免点值转换错误。
- 若偏好突破策略,可启用
ReverseSignals;保持默认值则按照经典反转逻辑运行。
- 如需账户级风控,可结合 StockSharp 的权益保护、回撤限制等模块,替代原 EA 的
m_money 组件。
以上内容为在 StockSharp 平台部署、调试以及扩展 iCCI iRSI 策略提供了完整说明。
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;
public class IcciIrsiStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private int _cooldown;
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }
public IcciIrsiStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
}
protected override void OnReseted()
{
base.OnReseted();
_fast = null; _slow = null;
_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fast = new ExponentialMovingAverage { Length = FastPeriod };
_slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.Bind(_fast, _slow, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished) return;
if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }
_prevFast = fastValue; _prevSlow = slowValue;
}
}
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
from StockSharp.Algo.Strategies import Strategy
class icci_irsi_strategy(Strategy):
def __init__(self):
super(icci_irsi_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 14) \
.SetDisplay("Fast Period", "Fast MA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow MA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.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
def OnReseted(self):
super(icci_irsi_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(icci_irsi_strategy, self).OnStarted2(time)
self._fast = ExponentialMovingAverage()
self._fast.Length = self.fast_period
self._slow = ExponentialMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 100
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return icci_irsi_strategy()