Robust EA 模板策略
该策略根据 MQL 的 Robust EA 模板实现,使用 CCI 和 RSI 指标生成交易信号,并应用固定的止盈与止损。
逻辑
- 当 CCI 位于 -200..-150 或 -100..-50 且 RSI 在 0 到 25 之间时买入。
- 当 CCI 位于 50 到 150 且 RSI 在 80 到 100 之间时卖出。
- 止损和止盈以点数表示,并转换为价格。
参数
Candle Type– 蜡烛图类型。CCI Period– CCI 指标周期。RSI Period– RSI 指标周期。Take Profit (pips)– 止盈距离。Stop Loss (pips)– 止损距离。Volume– 交易量。
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>
/// Strategy using CCI and RSI indicators to generate trading signals.
/// </summary>
public class RobustEaTemplateStrategy : Strategy
{
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<DataType> _candleType;
public int CciPeriod
{
get => _cciPeriod.Value;
set => _cciPeriod.Value = value;
}
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
public decimal TakeProfitPct
{
get => _takeProfitPct.Value;
set => _takeProfitPct.Value = value;
}
public decimal StopLossPct
{
get => _stopLossPct.Value;
set => _stopLossPct.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public RobustEaTemplateStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(8).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_cciPeriod = Param(nameof(CciPeriod), 14)
.SetDisplay("CCI Period", "Commodity Channel Index period", "Indicators");
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetDisplay("RSI Period", "Relative Strength Index period", "Indicators");
_takeProfitPct = Param(nameof(TakeProfitPct), 3m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk");
_stopLossPct = Param(nameof(StopLossPct), 2m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var cci = new CommodityChannelIndex { Length = CciPeriod };
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.BindEx(cci, rsi, (candle, cciVal, rsiVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!cciVal.IsFormed || !rsiVal.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var cciValue = cciVal.ToDecimal();
var rsiValue = rsiVal.ToDecimal();
// Wider signal conditions
var longSignal = cciValue < -50m && rsiValue < 40m;
var shortSignal = cciValue > 50m && rsiValue > 60m;
if (longSignal && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (shortSignal && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
}).Start();
StartProtection(
takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent),
stopLoss: new Unit(StopLossPct, UnitTypes.Percent),
useMarketOrders: true);
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import CommodityChannelIndex, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class robust_ea_template_strategy(Strategy):
def __init__(self):
super(robust_ea_template_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(8))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._cci_period = self.Param("CciPeriod", 14) \
.SetDisplay("CCI Period", "Commodity Channel Index period", "Indicators")
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "Relative Strength Index period", "Indicators")
self._take_profit_pct = self.Param("TakeProfitPct", 3.0) \
.SetDisplay("Take Profit %", "Take profit percentage", "Risk")
self._stop_loss_pct = self.Param("StopLossPct", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
@property
def candle_type(self):
return self._candle_type.Value
@property
def cci_period(self):
return self._cci_period.Value
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def take_profit_pct(self):
return self._take_profit_pct.Value
@property
def stop_loss_pct(self):
return self._stop_loss_pct.Value
def OnStarted2(self, time):
super(robust_ea_template_strategy, self).OnStarted2(time)
cci = CommodityChannelIndex()
cci.Length = self.cci_period
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(cci, rsi, self.on_candle).Start()
self.StartProtection(
takeProfit=Unit(self.take_profit_pct, UnitTypes.Percent),
stopLoss=Unit(self.stop_loss_pct, UnitTypes.Percent),
useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
def on_candle(self, candle, cci_val, rsi_val):
if candle.State != CandleStates.Finished:
return
if not cci_val.IsFormed or not rsi_val.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
cci_value = float(cci_val)
rsi_value = float(rsi_val)
long_signal = cci_value < -50.0 and rsi_value < 40.0
short_signal = cci_value > 50.0 and rsi_value > 60.0
if long_signal and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif short_signal and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
def CreateClone(self):
return robust_ea_template_strategy()