Probe 策略
概述
Probe 策略在 StockSharp 高层框架中复刻了 MetaTrader 5 专家顾问 “Probe”。策略在可配置的时间框架上计算商品通道指数(CCI),当振荡指标突破对称通道时做出反应。出现突破信号后,策略会以设定的点距在当前价格附近挂出止损单,试图跟随突破后的动量,同时利用点距参数化的止损和跟踪止损来限制风险。
交易逻辑
- 在选定的
CandleType时间框架上生成蜡烛并计算 CCI。 - 保存上一根和当前 CCI 数值,以便识别指标突破上下通道边界的瞬间。
- 当 CCI 自下向上穿越
-CCI Channel时,在最近收盘价上方Indent (pips)点的位置放置买入止损单。 - 当 CCI 自上向下跌破
+CCI Channel时,在最近收盘价下方Indent (pips)点的位置放置卖出止损单。 - 任意时刻只允许一张挂单处于激活状态。若方向发生改变,原有挂单会被取消,在挂单激活期间新的信号会被忽略。
挂单管理
- 如果市场价格偏离挂单价格超过
1.5 * Indent (pips),止损单将被撤销,以避免在动能减弱时保留失效订单。 - 止损单成交后,策略会记录实际成交价作为入场价,并立即撤销所有方向相反的挂单。
风险管理
- 初始止损基于
Stop Loss (pips)参数计算,策略在内部监控该价格水平,一旦触发立即以市价平仓。 - 当浮动盈利超过
Trailing Stop (pips) + Trailing Step (pips)时启动跟踪止损。之后每当盈利再次增加指定的跟踪步长,止损价位都会按最小距离进行上移或下移。 - 所有以点表示的距离会根据交易品种的报价精度自动缩放,适配 3 位或 5 位小数的品种。
参数
| 参数 | 说明 |
|---|---|
CandleType |
用于生成蜡烛并计算 CCI 的主要时间框架。 |
CciLength |
CCI 指标的平均周期。 |
CciChannelLevel |
构成对称通道边界的绝对 CCI 阈值。 |
IndentPips |
在最近收盘价基础上偏移的点数,用于设置止损挂单价格。 |
StopLossPips |
初始保护性止损的点数。 |
TrailingStopPips |
启动跟踪止损所需的最小盈利点数。 |
TrailingStepPips |
每次调整跟踪止损之前需要增加的额外盈利点数。 |
说明
- 交易手数通过策略的
Volume属性设置。 - 策略按照净头寸模式运行,与原始 EA 的行为保持一致。
- 如果存在图表区域,策略会绘制蜡烛、CCI 指标以及实际成交。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Probe CCI breakout strategy converted from the original MetaTrader 5 expert advisor.
/// Listens for Commodity Channel Index threshold crossovers and enters with market orders.
/// </summary>
public class ProbeStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cciLength;
private readonly StrategyParam<decimal> _cciChannelLevel;
private readonly StrategyParam<decimal> _stopLossPips;
private readonly StrategyParam<decimal> _trailingStopPips;
private readonly StrategyParam<decimal> _trailingStepPips;
private decimal? _previousCci;
private decimal? _entryPrice;
private decimal? _stopPrice;
private decimal _pipSize;
public ProbeStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Primary timeframe used for indicator calculations", "General");
_cciLength = Param(nameof(CciLength), 60)
.SetGreaterThanZero()
.SetDisplay("CCI Length", "Averaging period of the Commodity Channel Index", "Indicators");
_cciChannelLevel = Param(nameof(CciChannelLevel), 120m)
.SetGreaterThanZero()
.SetDisplay("CCI Channel", "Absolute CCI level used as the channel boundary", "Indicators");
_stopLossPips = Param(nameof(StopLossPips), 50m)
.SetNotNegative()
.SetDisplay("Stop Loss (pips)", "Protective stop loss distance expressed in pips", "Risk");
_trailingStopPips = Param(nameof(TrailingStopPips), 5m)
.SetNotNegative()
.SetDisplay("Trailing Stop (pips)", "Minimum profit required before trailing activates", "Risk");
_trailingStepPips = Param(nameof(TrailingStepPips), 5m)
.SetNotNegative()
.SetDisplay("Trailing Step (pips)", "Additional profit required before the stop is moved again", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int CciLength
{
get => _cciLength.Value;
set => _cciLength.Value = value;
}
public decimal CciChannelLevel
{
get => _cciChannelLevel.Value;
set => _cciChannelLevel.Value = value;
}
public decimal StopLossPips
{
get => _stopLossPips.Value;
set => _stopLossPips.Value = value;
}
public decimal TrailingStopPips
{
get => _trailingStopPips.Value;
set => _trailingStopPips.Value = value;
}
public decimal TrailingStepPips
{
get => _trailingStepPips.Value;
set => _trailingStepPips.Value = value;
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_previousCci = null;
_entryPrice = null;
_stopPrice = null;
_pipSize = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_pipSize = CalculatePipSize();
_previousCci = null;
_entryPrice = null;
_stopPrice = null;
var cci = new CommodityChannelIndex { Length = CciLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(cci, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, cci);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal cciValue)
{
if (candle.State != CandleStates.Finished)
return;
if (_pipSize <= 0m)
_pipSize = CalculatePipSize();
// Manage existing position (stop loss / trailing)
var exited = ManagePosition(candle);
if (exited)
{
_previousCci = cciValue;
return;
}
// Check for CCI crossover signals
if (_previousCci.HasValue && Position == 0m)
{
var channel = CciChannelLevel;
var lower = -channel;
// CCI crosses up from below -channel -> buy signal
var crossUp = _previousCci.Value < lower && cciValue > lower;
// CCI crosses down from above +channel -> sell signal
var crossDown = _previousCci.Value > channel && cciValue < channel;
if (crossUp)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
var stopDistance = StopLossPips * _pipSize;
_stopPrice = stopDistance > 0m ? candle.ClosePrice - stopDistance : null;
}
else if (crossDown)
{
SellMarket();
_entryPrice = candle.ClosePrice;
var stopDistance = StopLossPips * _pipSize;
_stopPrice = stopDistance > 0m ? candle.ClosePrice + stopDistance : null;
}
}
_previousCci = cciValue;
}
private bool ManagePosition(ICandleMessage candle)
{
if (Position == 0m)
{
_entryPrice = null;
_stopPrice = null;
return false;
}
var trailingStop = TrailingStopPips * _pipSize;
var trailingStep = TrailingStepPips * _pipSize;
if (Position > 0m)
{
if (_entryPrice == null)
_entryPrice = candle.ClosePrice;
// Check stop loss
if (_stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
{
SellMarket();
ResetTradeState();
return true;
}
// Trailing stop logic
if (TrailingStopPips > 0m && trailingStop > 0m && _entryPrice.HasValue)
{
var profit = candle.ClosePrice - _entryPrice.Value;
var threshold = trailingStop + trailingStep;
if (profit > threshold)
{
var desiredStop = candle.ClosePrice - trailingStop;
if (!_stopPrice.HasValue || desiredStop > _stopPrice.Value)
_stopPrice = desiredStop;
}
}
}
else if (Position < 0m)
{
if (_entryPrice == null)
_entryPrice = candle.ClosePrice;
// Check stop loss
if (_stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
{
BuyMarket();
ResetTradeState();
return true;
}
// Trailing stop logic
if (TrailingStopPips > 0m && trailingStop > 0m && _entryPrice.HasValue)
{
var profit = _entryPrice.Value - candle.ClosePrice;
var threshold = trailingStop + trailingStep;
if (profit > threshold)
{
var desiredStop = candle.ClosePrice + trailingStop;
if (!_stopPrice.HasValue || desiredStop < _stopPrice.Value)
_stopPrice = desiredStop;
}
}
}
return false;
}
private void ResetTradeState()
{
_entryPrice = null;
_stopPrice = null;
}
private decimal CalculatePipSize()
{
var step = Security?.PriceStep ?? 0m;
if (step <= 0m)
return 0.01m;
return step;
}
}
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 CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
class probe_strategy(Strategy):
def __init__(self):
super(probe_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Primary timeframe used for indicator calculations", "General")
self._cci_length = self.Param("CciLength", 60) \
.SetDisplay("CCI Length", "Averaging period of the Commodity Channel Index", "Indicators")
self._cci_channel_level = self.Param("CciChannelLevel", 120.0) \
.SetDisplay("CCI Channel", "Absolute CCI level used as the channel boundary", "Indicators")
self._stop_loss_pips = self.Param("StopLossPips", 50.0) \
.SetDisplay("Stop Loss (pips)", "Protective stop loss distance expressed in pips", "Risk")
self._trailing_stop_pips = self.Param("TrailingStopPips", 5.0) \
.SetDisplay("Trailing Stop (pips)", "Minimum profit required before trailing activates", "Risk")
self._trailing_step_pips = self.Param("TrailingStepPips", 5.0) \
.SetDisplay("Trailing Step (pips)", "Additional profit required before the stop is moved again", "Risk")
self._previous_cci = None
self._entry_price = None
self._stop_price = None
self._pip_size = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@property
def CciLength(self):
return self._cci_length.Value
@property
def CciChannelLevel(self):
return self._cci_channel_level.Value
@property
def StopLossPips(self):
return self._stop_loss_pips.Value
@property
def TrailingStopPips(self):
return self._trailing_stop_pips.Value
@property
def TrailingStepPips(self):
return self._trailing_step_pips.Value
def OnReseted(self):
super(probe_strategy, self).OnReseted()
self._previous_cci = None
self._entry_price = None
self._stop_price = None
self._pip_size = 0.0
def OnStarted2(self, time):
super(probe_strategy, self).OnStarted2(time)
self._pip_size = self._calculate_pip_size()
self._previous_cci = None
self._entry_price = None
self._stop_price = None
cci = CommodityChannelIndex()
cci.Length = self.CciLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(cci, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, cci)
self.DrawOwnTrades(area)
def _on_process(self, candle, cci_value):
if candle.State != CandleStates.Finished:
return
cv = float(cci_value)
if self._pip_size <= 0.0:
self._pip_size = self._calculate_pip_size()
exited = self._manage_position(candle)
if exited:
self._previous_cci = cv
return
if self._previous_cci is not None and self.Position == 0:
channel = float(self.CciChannelLevel)
lower = -channel
cross_up = self._previous_cci < lower and cv > lower
cross_down = self._previous_cci > channel and cv < channel
if cross_up or cross_down:
if not self.IsFormedAndOnlineAndAllowTrading():
self._previous_cci = cv
return
if cross_up:
self.BuyMarket()
self._entry_price = float(candle.ClosePrice)
stop_dist = float(self.StopLossPips) * self._pip_size
self._stop_price = self._entry_price - stop_dist if stop_dist > 0.0 else None
elif cross_down:
self.SellMarket()
self._entry_price = float(candle.ClosePrice)
stop_dist = float(self.StopLossPips) * self._pip_size
self._stop_price = self._entry_price + stop_dist if stop_dist > 0.0 else None
self._previous_cci = cv
def _manage_position(self, candle):
if self.Position == 0:
self._entry_price = None
self._stop_price = None
return False
trailing_stop = float(self.TrailingStopPips) * self._pip_size
trailing_step = float(self.TrailingStepPips) * self._pip_size
if self.Position > 0:
if self._entry_price is None:
self._entry_price = float(candle.ClosePrice)
if self._stop_price is not None and float(candle.LowPrice) <= self._stop_price:
self.SellMarket()
self._reset_trade_state()
return True
if float(self.TrailingStopPips) > 0.0 and trailing_stop > 0.0 and self._entry_price is not None:
profit = float(candle.ClosePrice) - self._entry_price
threshold = trailing_stop + trailing_step
if profit > threshold:
desired_stop = float(candle.ClosePrice) - trailing_stop
if self._stop_price is None or desired_stop > self._stop_price:
self._stop_price = desired_stop
elif self.Position < 0:
if self._entry_price is None:
self._entry_price = float(candle.ClosePrice)
if self._stop_price is not None and float(candle.HighPrice) >= self._stop_price:
self.BuyMarket()
self._reset_trade_state()
return True
if float(self.TrailingStopPips) > 0.0 and trailing_stop > 0.0 and self._entry_price is not None:
profit = self._entry_price - float(candle.ClosePrice)
threshold = trailing_stop + trailing_step
if profit > threshold:
desired_stop = float(candle.ClosePrice) + trailing_stop
if self._stop_price is None or desired_stop < self._stop_price:
self._stop_price = desired_stop
return False
def _reset_trade_state(self):
self._entry_price = None
self._stop_price = None
def _calculate_pip_size(self):
sec = self.Security
step = float(sec.PriceStep) if sec is not None and sec.PriceStep is not None else 0.0
if step <= 0.0:
return 0.01
return step
def CreateClone(self):
return probe_strategy()