首页
/
策略示例
在 GitHub 上查看
EA Stochastic 策略
这是 MetaTrader「EA Stochastic」专家顾问的 StockSharp 高级 API 版本。策略订阅单一的 K 线序列,读取随机指标数值,
并且始终只保持一笔仓位。当随机指标的主线在多根 K 线中持续位于同一侧阈值时触发开仓。止损、止盈与跟踪止损按点
数实现,尽量还原原始 MQL 逻辑。
策略概览
指标 :经典随机指标(可设置 %K、%D 周期及最终平滑)
方向 :多、空双向
持仓 :任意时刻最多一笔仓位(如果已有平仓指令在途,则忽略新的信号)
委托类型 :使用固定手数的市价单
数据源 :单一用户自选的蜡烛序列(默认 15 分钟)
入场逻辑
每根收盘蜡烛都会保存最新的随机指标主线值。
当缓存数量达到 ComparedBar 时,将当前值与 ComparedBar - 1 根之前的值进行比较。
做多 :当前值和对比值都低于 UpperLevel,对应原 EA 只有在随机指标持续低于上限时才买入。
做空 :当前值和对比值都高于 LowerLevel,对应原 EA 在随机指标持续高于下限时卖出。
若已有仓位或已经发出平仓指令,则忽略新的入场信号。
出场与风控
止损 :可选的点数距离,按入场价计算。多单使用蜡烛最低价,空单使用最高价判断触发。
止盈 :可选的固定点数目标,利用最高价/最低价模拟 MetaTrader 中的止盈委托行为。
跟踪止损 :当浮盈大于 (TrailingStopPips + TrailingStepPips) 点时启动,新的止损价位距离最新极值
TrailingStopPips 点,同时必须超过 TrailingStepPips 的增量,完全复刻原 EA 的条件。
平仓方式 :通过 SellMarket / BuyMarket 市价单实现。利用标志位避免在仓位尚未确认平掉时重复发送
指令。
参数说明
StopLossPips(默认 50 ):初始止损距离,0 表示禁用。
TakeProfitPips(默认 150 ):止盈距离,0 表示禁用。
TrailingStopPips(默认 15 ):跟踪止损距离,启用跟踪时必须大于 0。
TrailingStepPips(默认 5 ):每次移动跟踪止损所需的最小盈利增量,若为 0 则禁止开启跟踪。
Volume(默认 1 ):多空两侧共用的市价单手数。
KPeriod(默认 5 ):%K 计算周期。
DPeriod(默认 3 ):%D 平滑周期。
Slowing(默认 3 ):%K 最终平滑周期。
UpperLevel(默认 80 ):验证做多信号的阈值。
LowerLevel(默认 20 ):验证做空信号的阈值。
ComparedBar(默认 3 ):比较用的蜡烛数量(至少为 1)。
CandleType(默认 15 分钟蜡烛 ):策略订阅的蜡烛类型。
实现细节
点值由 Security.PriceStep 推算,若步长小于 0.001,会乘以 10 以模拟 MetaTrader 中对 3/5 位小数的处理。
在启动阶段验证跟踪止损参数,避免出现 TrailingStop > 0 且 TrailingStep = 0 的配置错误。
StockSharp 的随机指标采用默认的高/低价范围与简单平滑方式,与 EA 的设置对应。
原版 EA 支持按风险百分比计算手数。本移植版本保留固定 Volume,需要时可自行扩展。
策略会在图表上绘制蜡烛、指标与成交,方便调试与回测分析。
使用建议
适用于日内到波段级别的周期,请根据品种调整 CandleType 与随机指标参数。
调整 UpperLevel、LowerLevel 与 ComparedBar 以适配震荡或趋势行情。
实盘时建议结合券商端风控,因为策略通过蜡烛收盘后发送市价单来离场。
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>
/// EA Stochastic strategy (simplified). Uses RSI as oscillator proxy.
/// </summary>
public class EaStochasticStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<decimal> _upperLevel;
private readonly StrategyParam<decimal> _lowerLevel;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int RsiLength
{
get => _rsiLength.Value;
set => _rsiLength.Value = value;
}
public decimal UpperLevel
{
get => _upperLevel.Value;
set => _upperLevel.Value = value;
}
public decimal LowerLevel
{
get => _lowerLevel.Value;
set => _lowerLevel.Value = value;
}
public EaStochasticStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
_rsiLength = Param(nameof(RsiLength), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI period", "Indicators");
_upperLevel = Param(nameof(UpperLevel), 70m)
.SetDisplay("Upper Level", "Overbought level", "Levels");
_lowerLevel = Param(nameof(LowerLevel), 30m)
.SetDisplay("Lower Level", "Oversold level", "Levels");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiLength };
decimal prevRsi = 50;
bool hasPrev = false;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, (ICandleMessage candle, decimal rsiValue) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!hasPrev)
{
prevRsi = rsiValue;
hasPrev = true;
return;
}
if (!IsFormedAndOnlineAndAllowTrading())
{
prevRsi = rsiValue;
return;
}
// Cross up from oversold
if (prevRsi < LowerLevel && rsiValue >= LowerLevel && Position <= 0)
{
BuyMarket();
}
// Cross down from overbought
else if (prevRsi > UpperLevel && rsiValue <= UpperLevel && Position >= 0)
{
SellMarket();
}
prevRsi = rsiValue;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
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 ea_stochastic_strategy(Strategy):
def __init__(self):
super(ea_stochastic_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Candles", "General")
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "RSI period", "Indicators")
self._upper_level = self.Param("UpperLevel", 70.0) \
.SetDisplay("Upper Level", "Overbought level", "Levels")
self._lower_level = self.Param("LowerLevel", 30.0) \
.SetDisplay("Lower Level", "Oversold level", "Levels")
self._prev_rsi = 50.0
self._has_prev = False
@property
def CandleType(self):
return self._candle_type.Value
@property
def RsiLength(self):
return self._rsi_length.Value
@property
def UpperLevel(self):
return self._upper_level.Value
@property
def LowerLevel(self):
return self._lower_level.Value
def OnReseted(self):
super(ea_stochastic_strategy, self).OnReseted()
self._prev_rsi = 50.0
self._has_prev = False
def OnStarted2(self, time):
super(ea_stochastic_strategy, self).OnStarted2(time)
self._prev_rsi = 50.0
self._has_prev = False
rsi = RelativeStrengthIndex()
rsi.Length = self.RsiLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(rsi, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def _on_process(self, candle, rsi_value):
if candle.State != CandleStates.Finished:
return
rv = float(rsi_value)
if not self._has_prev:
self._prev_rsi = rv
self._has_prev = True
return
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_rsi = rv
return
ll = float(self.LowerLevel)
ul = float(self.UpperLevel)
if self._prev_rsi < ll and rv >= ll and self.Position <= 0:
self.BuyMarket()
elif self._prev_rsi > ul and rv <= ul and self.Position >= 0:
self.SellMarket()
self._prev_rsi = rv
def CreateClone(self):
return ea_stochastic_strategy()