Candle Strategy — это точный порт классического эксперта MT5 «Candle.mq5». Стратегия анализирует цвет каждого завершённого бара на выбранном таймфрейме и синхронизирует позицию с последним закрытием. Бычья свеча приводит к открытию длинной позиции, медвежья — короткой, а плоская свеча оставляет позицию без изменений. Управление рисками реализовано через тейк-профит и трейлинг-стоп в пунктах, которые конвертируются в абсолютные цены с учётом шага цены инструмента.
Обработка происходит только после формирования свечи, чтобы исключить шум внутри бара. Перед началом торговли стратегия проверяет, что в истории имеется минимум MinBars * 2 завершённых свечей, а между торговыми операциями выдерживается настраиваемая пауза. Это позволяет реализовать логику оригинального MetaTrader-советника средствами высокоуровневого API StockSharp без прямой работы с буферами цен.
Торговая логика
Подготовка
Используются только свечи типа CandleType; дополнительные источники данных не требуются.
До появления не менее 2 * MinBars завершённых свечей сделки не совершаются.
Торговля разрешена только при готовности стратегии (IsFormedAndOnlineAndAllowTrading).
Между любыми двумя операциями выдерживается интервал TradeCooldown (по умолчанию 10 секунд).
Правила входа и реверса
Отсутствует позиция:
Открыть длинную позицию (BuyMarket), если свеча закрылась выше открытия.
Открыть короткую позицию (SellMarket), если свеча закрылась ниже открытия.
Уже есть позиция:
При длинной позиции и появлении медвежьей свечи продать объём |Position| + Volume, тем самым закрыв лонг и сразу перевернувшись в шорт размером Volume.
При короткой позиции и появлении бычьей свечи купить объём |Position| + Volume, закрыв шорт и тут же открыв лонг размером Volume.
Нейтральная свеча:
Если закрытие равно открытию, вручную ничего не делается; выход возможен только по защитным ордерам.
Управление рисками и выходы
Метод StartProtection устанавливает тейк-профит и трейлинг-стоп, заданные в пунктах. Значение пункта вычисляется как (PriceStep * 10), что повторяет «digits adjust» из оригинального эксперта для инструментов с 3 или 5 знаками после запятой.
Трейлинг-стоп активен, только если TrailingStopPips больше нуля, и автоматически следует за ценой при движении в прибыль.
Тейк-профит закрывает позицию при достижении заданной дистанции. После исполнения любой защиты противоположный ордер отменяется.
Ручные реверсы по цвету свечи закрывают предыдущую позицию и сразу открывают новую в противоположную сторону.
Параметры
CandleType — таймфрейм свечей для анализа (по умолчанию 15 минут).
TakeProfitPips — расстояние до тейк-профита в пунктах (по умолчанию 50).
TrailingStopPips — расстояние трейлинг-стопа в пунктах (по умолчанию 30).
MinBars — минимальное количество баров, необходимое до первой сделки (по умолчанию 26, что означает ожидание 52 завершённых свечей).
TradeCooldown — пауза после каждой торговой операции (по умолчанию 10 секунд).
Задайте свойство Volume стратегии равным требуемому объёму сделки. При реверсе стратегия автоматически отправляет достаточный объём, чтобы закрыть текущую позицию и открыть новую.
Особенности реализации
Обрабатываются только завершённые свечи (CandleStates.Finished), что соответствует работе MQL-советника через функции CopyOpen/CopyClose.
Используется высокоуровневый API StockSharp: подписка через SubscribeCandles, обработка в Bind, исполнение приказов через BuyMarket и SellMarket.
Управление защитными ордерами полностью доверено StartProtection, поэтому нет необходимости самостоятельно отслеживать стопы и тейки.
Расчёт пункта (PriceStep * 10) воспроизводит корректировку для трёх- и пятизначных котировок.
Поскольку входы завязаны на цвет последней свечи, стратегия часто находится в рынке, попеременно сменяя направление при каждом изменении цвета.
Параметры дистанций в пунктах, паузу и таймфрейм следует адаптировать под выбранный инструмент. Значения по умолчанию соответствуют оригинальному эксперту MT5, но могут быть оптимизированы средствами StockSharp.
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Candle color reversal strategy with pip-based protection and trade cooldown.
/// </summary>
public class CandleStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _takeProfitPips;
private readonly StrategyParam<decimal> _trailingStopPips;
private readonly StrategyParam<int> _minBars;
private readonly StrategyParam<TimeSpan> _tradeCooldown;
private decimal _pipSize;
private int _finishedCandles;
private DateTimeOffset _nextAllowedTime;
/// <summary>
/// Initializes a new instance of the <see cref="CandleStrategy"/>.
/// </summary>
public CandleStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe used for candle evaluation", "General");
_takeProfitPips = Param(nameof(TakeProfitPips), 50m)
.SetDisplay("Take Profit (pips)", "Distance to take profit in pips", "Risk")
.SetGreaterThanZero();
_trailingStopPips = Param(nameof(TrailingStopPips), 30m)
.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk")
.SetGreaterThanZero();
_minBars = Param(nameof(MinBars), 26)
.SetDisplay("Minimum Bars", "History length required before trading", "General")
.SetGreaterThanZero();
_tradeCooldown = Param(nameof(TradeCooldown), TimeSpan.FromSeconds(10))
.SetDisplay("Trade Cooldown", "Waiting time after each trade", "Risk");
}
/// <summary>
/// Candle type and timeframe used by the strategy.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Take profit distance expressed in pips.
/// </summary>
public decimal TakeProfitPips
{
get => _takeProfitPips.Value;
set => _takeProfitPips.Value = value;
}
/// <summary>
/// Trailing stop distance expressed in pips.
/// </summary>
public decimal TrailingStopPips
{
get => _trailingStopPips.Value;
set => _trailingStopPips.Value = value;
}
/// <summary>
/// Minimum number of bars required on the chart.
/// </summary>
public int MinBars
{
get => _minBars.Value;
set => _minBars.Value = value;
}
/// <summary>
/// Cooldown between consecutive trading operations.
/// </summary>
public TimeSpan TradeCooldown
{
get => _tradeCooldown.Value;
set => _tradeCooldown.Value = value;
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_pipSize = 0m;
_finishedCandles = 0;
_nextAllowedTime = DateTimeOffset.MinValue;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_pipSize = (Security?.PriceStep ?? 1m) * 10m;
Unit takeProfit = TakeProfitPips > 0m && _pipSize > 0m
? new Unit(TakeProfitPips * _pipSize, UnitTypes.Absolute)
: null;
Unit trailingStop = TrailingStopPips > 0m && _pipSize > 0m
? new Unit(TrailingStopPips * _pipSize, UnitTypes.Absolute)
: null;
// Enable automatic protective orders and trailing stop handling.
if (trailingStop != null || takeProfit != null)
StartProtection(takeProfit, trailingStop);
// Subscribe to candle data for the configured timeframe.
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
// Draw candles and executions on the chart if visualization is available.
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
// Skip unfinished candles to work only with final prices.
if (candle.State != CandleStates.Finished)
return;
_finishedCandles++;
// Wait until the chart has enough historical data.
if (_finishedCandles < MinBars * 2)
return;
var time = candle.CloseTime;
// Enforce cooldown between trading operations.
if (time < _nextAllowedTime)
return;
var isBullish = candle.ClosePrice > candle.OpenPrice;
var isBearish = candle.ClosePrice < candle.OpenPrice;
var tradeExecuted = false;
if (Position > 0 && isBearish)
{
// Reverse from long to short when a bearish candle appears.
var volume = Math.Abs(Position) + Volume;
if (volume > 0m)
{
SellMarket();
tradeExecuted = true;
}
}
else if (Position < 0 && isBullish)
{
// Reverse from short to long when a bullish candle appears.
var volume = Math.Abs(Position) + Volume;
if (volume > 0m)
{
BuyMarket();
tradeExecuted = true;
}
}
else if (Position == 0)
{
if (isBullish)
{
// Enter long on bullish close.
if (Volume > 0m)
{
BuyMarket();
tradeExecuted = true;
}
}
else if (isBearish)
{
// Enter short on bearish close.
if (Volume > 0m)
{
SellMarket();
tradeExecuted = true;
}
}
}
if (tradeExecuted)
{
_nextAllowedTime = time + TradeCooldown;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math, DateTimeOffset
from StockSharp.Messages import DataType, CandleStates, UnitTypes, Unit
from StockSharp.Algo.Strategies import Strategy
class candle_strategy(Strategy):
"""
Candle color reversal strategy with pip-based protection and trade cooldown.
"""
def __init__(self):
super(candle_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe used for candle evaluation", "General")
self._take_profit_pips = self.Param("TakeProfitPips", 50.0) \
.SetDisplay("Take Profit (pips)", "Distance to take profit in pips", "Risk")
self._trailing_stop_pips = self.Param("TrailingStopPips", 30.0) \
.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk")
self._min_bars = self.Param("MinBars", 26) \
.SetDisplay("Minimum Bars", "History length required before trading", "General")
self._trade_cooldown = self.Param("TradeCooldown", TimeSpan.FromSeconds(10)) \
.SetDisplay("Trade Cooldown", "Waiting time after each trade", "Risk")
self._pip_size = 0.0
self._finished_candles = 0
self._next_allowed_time = DateTimeOffset.MinValue
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
@property
def take_profit_pips(self):
return self._take_profit_pips.Value
@take_profit_pips.setter
def take_profit_pips(self, value):
self._take_profit_pips.Value = value
@property
def trailing_stop_pips(self):
return self._trailing_stop_pips.Value
@trailing_stop_pips.setter
def trailing_stop_pips(self, value):
self._trailing_stop_pips.Value = value
@property
def min_bars(self):
return self._min_bars.Value
@min_bars.setter
def min_bars(self, value):
self._min_bars.Value = value
@property
def trade_cooldown(self):
return self._trade_cooldown.Value
@trade_cooldown.setter
def trade_cooldown(self, value):
self._trade_cooldown.Value = value
def OnReseted(self):
super(candle_strategy, self).OnReseted()
self._pip_size = 0.0
self._finished_candles = 0
self._next_allowed_time = DateTimeOffset.MinValue
def OnStarted2(self, time):
super(candle_strategy, self).OnStarted2(time)
self._pip_size = (self.Security.PriceStep if self.Security.PriceStep is not None else 1.0) * 10.0
tp = None
trailing = None
if self.take_profit_pips > 0 and self._pip_size > 0:
tp = Unit(self.take_profit_pips * self._pip_size, UnitTypes.Absolute)
if self.trailing_stop_pips > 0 and self._pip_size > 0:
trailing = Unit(self.trailing_stop_pips * self._pip_size, UnitTypes.Absolute)
if trailing is not None or tp is not None:
self.StartProtection(tp, trailing)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle):
if candle.State != CandleStates.Finished:
return
self._finished_candles += 1
if self._finished_candles < self.min_bars * 2:
return
close_time = candle.CloseTime
if self._next_allowed_time != DateTimeOffset.MinValue:
try:
if close_time < self._next_allowed_time:
return
except:
if DateTimeOffset(close_time) < self._next_allowed_time:
return
is_bullish = candle.ClosePrice > candle.OpenPrice
is_bearish = candle.ClosePrice < candle.OpenPrice
trade_executed = False
if self.Position > 0 and is_bearish:
self.SellMarket()
trade_executed = True
elif self.Position < 0 and is_bullish:
self.BuyMarket()
trade_executed = True
elif self.Position == 0:
if is_bullish:
self.BuyMarket()
trade_executed = True
elif is_bearish:
self.SellMarket()
trade_executed = True
if trade_executed:
self._next_allowed_time = close_time + self.trade_cooldown
def CreateClone(self):
return candle_strategy()