Early Top Prorate V1 策略
本文档说明 MetaTrader 专家顾问 earlyTopProrate_V1 在 StockSharp 平台上的移植版本。该策略关注日内价格相对于每日开盘价的偏离,并通过三个分级止盈逐步减仓。移植使用 StockSharp 高级 API,保留了原策略的仓位管理与资金管理思想。
核心流程
- 日内背景:根据收到的K线重建当日开盘价、最高价和最低价,通过比较
high - open 与 open - low 判断多空方向。
- 交易时段:仅在
StartHour(含)到 EndHour(不含)之间允许开仓。默认设置覆盖欧洲早盘。
- 开仓条件:
- 若多头方向占优且最新收盘价高于日开盘价,则开多单。
- 若空头方向占优且最新收盘价低于日开盘价,则开空单。
- 任意时刻只允许持有一张净仓(默认
MaxPositions = 1)。
- 资金管理:开仓手数由
MoneyManagementType 选择的模式计算,并根据交易所最小/最大手数及步长进行调整。
- 仓位管理:建仓后按照下节所述规则进行止损、移动保护和分级止盈。逻辑与原EA一致,但通过高级API发送市价单实现。
- 收盘平仓:到达
ClosingHour 时,如仍有持仓,则立即市价平仓。
仓位管理细节
原始 EA 通过修改止损/止盈实现保护。本移植版本在每根收盘K线执行以下检查:
- 回本保护(
BreakEvenTrigger):若价格对持仓不利移动指定点数,则等待价格回到开仓价并在该价位离场。
- 紧急止损(
StopLoss0):当浮亏超过阈值时立即平仓。
- 移动到开仓价(
StopLoss1):获利达到该距离后,将保护价移至开仓价。
- 移动到盈利区(
StopLoss2):利润继续扩大到该阈值后,保护价进一步移动到开仓价之外,偏移量等于 StopLoss2 - StopLoss1,对应原代码中的 setSL2-35 计算。
- 分批止盈(
TakeProfit1/2/3 和 Ratio1/2/3):三个目标价分别关闭当前持仓的一部分,比例基于剩余仓位,因此目标越靠后,剩余仓位越小。第三个目标会清空全部仓位。
所有距离类参数均以“点”(points)表示。参数 PointMultiplier 用于将 PriceStep 乘以倍率,以复刻原脚本中 value * 10 * Point 的计算方式(默认倍率为 10)。
资金管理模式
MoneyManagementType 决定下列四种仓位计算方式之一:
| 模式 |
说明 |
0 或 1 |
固定手数,等于 BaseVolume(与原EA一致)。 |
2 |
平方根模型:0.1 * sqrt(balance / 1000) * MoneyManagementFactor,余额使用当前投资组合价值。 |
3 |
权益风险模型:equity / price / 1000 * MoneyManagementRiskPercent / 100,模拟 MetaTrader 的 AccountEquity/Close[0] 公式。 |
最终结果会按交易所手数步长及限制进行归一化。
参数概览
| 参数 |
含义 |
CandleType |
用于决策的K线类型(默认 5 分钟)。 |
StartHour / EndHour |
允许开仓的小时区间(0–23)。 |
ClosingHour |
收盘强制平仓的小时。 |
TimeZoneShift |
保留的时区偏移,仅用于说明。 |
BaseVolume |
资金管理前的基础手数。 |
MaxPositions |
最大同时持仓数量。 |
TakeProfit1/2/3 |
三个止盈目标的点数距离。 |
BreakEvenTrigger |
触发回本保护的亏损点数。 |
StopLoss0/1/2 |
控制紧急止损与移动保护的点数阈值。 |
Ratio1/2/3 |
各止盈目标关闭的仓位百分比。 |
MoneyManagementType |
资金管理模式(0–3)。 |
MoneyManagementFactor |
平方根模型的乘数。 |
MoneyManagementRiskPercent |
权益风险模型使用的百分比。 |
PointMultiplier |
将点数转换为实际价格偏移时乘以的倍率。 |
使用建议
- 根据品种流动性选择合适的K线周期,默认的 5 分钟在响应速度和噪音之间取得平衡。
- 若经纪商对“点”的定义不同,请调整
PointMultiplier 以匹配真实跳动单位。
- 本实现依赖收盘K线计算移动止损,因此与原始基于tick的执行相比,可能存在细微差异,回测时请注意验证。
TimeZoneShift 仅用于记录。实际交易时间请通过 StartHour、EndHour 和 ClosingHour 配置。
上手步骤
- 将策略添加到 StockSharp 项目中,或在 Designer/Runner 环境运行。
- 配置目标品种的K线类型 (
CandleType) 以及交易时间。
- 根据波动率调节点数阈值和分批比例。
- 选择资金管理模式,并设定相关参数(如
BaseVolume、MoneyManagementFactor、MoneyManagementRiskPercent)。
- 先在模拟或历史数据环境验证策略行为,确认符合预期后再连接真实资金。
using System;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Early Top Prorate V1: EMA crossover with RSI filter and ATR stops.
/// </summary>
public class EarlyTopProrateV1Strategy : 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 decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
public EarlyTopProrateV1Strategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe.", "General");
_fastEmaLength = Param(nameof(FastEmaLength), 10)
.SetDisplay("Fast EMA Length", "Fast EMA period.", "Indicators");
_slowEmaLength = Param(nameof(SlowEmaLength), 25)
.SetDisplay("Slow EMA Length", "Slow EMA period.", "Indicators");
_rsiLength = Param(nameof(RsiLength), 14)
.SetDisplay("RSI Length", "RSI period.", "Indicators");
_atrLength = Param(nameof(AtrLength), 14)
.SetDisplay("ATR Length", "ATR period.", "Indicators");
}
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int FastEmaLength { get => _fastEmaLength.Value; set => _fastEmaLength.Value = value; }
public int SlowEmaLength { get => _slowEmaLength.Value; set => _slowEmaLength.Value = value; }
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0; _prevSlow = 0; _entryPrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevFast = 0; _prevSlow = 0; _entryPrice = 0;
var fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
var slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var 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 fastVal, decimal slowVal, decimal rsiVal, decimal atrVal)
{
if (candle.State != CandleStates.Finished) return;
if (_prevFast == 0 || _prevSlow == 0 || atrVal <= 0) { _prevFast = fastVal; _prevSlow = slowVal; return; }
var close = candle.ClosePrice;
if (Position > 0)
{
if ((fastVal < slowVal && _prevFast >= _prevSlow) || close <= _entryPrice - atrVal * 1.5m) { SellMarket(); _entryPrice = 0; }
}
else if (Position < 0)
{
if ((fastVal > slowVal && _prevFast <= _prevSlow) || close >= _entryPrice + atrVal * 1.5m) { BuyMarket(); _entryPrice = 0; }
}
if (Position == 0)
{
if (fastVal > slowVal && _prevFast <= _prevSlow && rsiVal > 55) { _entryPrice = close; BuyMarket(); }
else if (fastVal < slowVal && _prevFast >= _prevSlow && rsiVal < 45) { _entryPrice = close; SellMarket(); }
}
_prevFast = fastVal; _prevSlow = slowVal;
}
}
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.Strategies import Strategy
from StockSharp.Algo.Indicators import ExponentialMovingAverage, RelativeStrengthIndex, AverageTrueRange
class early_top_prorate_v1_strategy(Strategy):
def __init__(self):
super(early_top_prorate_v1_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe.", "General")
self._fast_ema_length = self.Param("FastEmaLength", 10) \
.SetDisplay("Fast EMA Length", "Fast EMA period.", "Indicators")
self._slow_ema_length = self.Param("SlowEmaLength", 25) \
.SetDisplay("Slow EMA Length", "Slow EMA period.", "Indicators")
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "RSI period.", "Indicators")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period.", "Indicators")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@property
def FastEmaLength(self):
return self._fast_ema_length.Value
@property
def SlowEmaLength(self):
return self._slow_ema_length.Value
@property
def RsiLength(self):
return self._rsi_length.Value
@property
def AtrLength(self):
return self._atr_length.Value
def OnStarted2(self, time):
super(early_top_prorate_v1_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self.FastEmaLength
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self.SlowEmaLength
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self.RsiLength
self._atr = AverageTrueRange()
self._atr.Length = self.AtrLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._fast_ema, self._slow_ema, self._rsi, self._atr, self.ProcessCandle).Start()
def ProcessCandle(self, candle, fast_val, slow_val, rsi_val, atr_val):
if candle.State != CandleStates.Finished:
return
fv = float(fast_val)
sv = float(slow_val)
rv = float(rsi_val)
av = float(atr_val)
if self._prev_fast == 0 or self._prev_slow == 0 or av <= 0:
self._prev_fast = fv
self._prev_slow = sv
return
close = float(candle.ClosePrice)
if self.Position > 0:
if (fv < sv and self._prev_fast >= self._prev_slow) or close <= self._entry_price - av * 1.5:
self.SellMarket()
self._entry_price = 0.0
elif self.Position < 0:
if (fv > sv and self._prev_fast <= self._prev_slow) or close >= self._entry_price + av * 1.5:
self.BuyMarket()
self._entry_price = 0.0
if self.Position == 0:
if fv > sv and self._prev_fast <= self._prev_slow and rv > 55:
self._entry_price = close
self.BuyMarket()
elif fv < sv and self._prev_fast >= self._prev_slow and rv < 45:
self._entry_price = close
self.SellMarket()
self._prev_fast = fv
self._prev_slow = sv
def OnReseted(self):
super(early_top_prorate_v1_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
def CreateClone(self):
return early_top_prorate_v1_strategy()