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()