Стратегия e-TurboFx — импульсное истощение
Обзор
e-TurboFx — это порт оригинального советника MetaTrader 4, анализирующего серию последних завершённых свечей. Идея заключается в поиске направленных «пробегов», где тела свечей с каждой новой свечой становятся всё больше. Растущие медвежьи свечи указывают на истощение продавцов и возможный разворот вверх, тогда как увеличивающиеся бычьи свечи сигнализируют о перегрете покупок и возможности для короткой позиции. Реализация на StockSharp работает в событийной модели: подписывается на свечи нужного таймфрейма, отслеживает их закрытие и автоматически добавляет защитные приказы по желанию пользователя.
Торговая логика
- Подписка на выбранный тип свечей (
CandleType) и обработка только завершённых свечей.
- Ведение двух независимых счётчиков — для медвежьих и для бычьих свечей.
- Для каждой свечи вычисляется абсолютный размер тела (
|Close - Open|).
- При появлении свечи противоположного направления сбрасывается противоположный счётчик.
- Внутри каждого счётчика допускаются только строго растущие тела: каждая новая свеча должна быть больше предыдущей, иначе последовательность перезапускается с 1.
- Когда длина последовательности достигает
DepthAnalysis, открывается рыночная сделка в противоположную сторону (покупка после серии медвежьих свечей, продажа после серии бычьих).
- При наличии открытой позиции генерация новых сигналов приостанавливается до её закрытия. В
OnStarted вызывается StartProtection, чтобы при необходимости выставлять стоп-лосс и тейк-профит в шагах цены.
Такой алгоритм полностью повторяет MQL4-вариант, где советник проверял N последних свечей на предмет совпадения направления и увеличения тела у каждой более новой свечи.
Особенности реализации
- Используется высокоуровневый API:
SubscribeCandles + Bind, никаких прямых запросов к индикаторам или коллекциям.
- Внутреннее состояние хранится в примитивных полях (
_bearishSequence, _bullishSequence, _previousBearishBody, _previousBullishBody), что упрощает перенос и соответствует правилам репозитория.
StartProtection вызывается единожды при старте, что позволяет быстро задать защитные дистанции в шагах цены. Ноль отключает соответствующий приказ — как и в оригинальной версии.
- В исходном коде добавлены подробные комментарии на английском языке, поясняющие логику сбросов и условий входа.
- При запуске в Designer дополнительно строится область графика со свечами и сделками для наглядности.
Параметры
| Параметр |
Описание |
Значение по умолчанию |
DepthAnalysis |
Количество подряд завершённых свечей в одном направлении с растущими телами, необходимое для входа. |
3 |
TakeProfitSteps |
Дистанция тейк-профита в шагах цены (тик). Значение 0 отключает тейк. |
120 |
StopLossSteps |
Дистанция стоп-лосса в шагах цены (тик). Значение 0 отключает стоп. |
70 |
TradeVolume |
Объём рыночных заявок. При изменении автоматически обновляет Strategy.Volume. |
0.1 |
CandleType |
Тип свечей (таймфрейм), по которым ведётся анализ. |
1 час |
Все числовые параметры снабжены метаданными для оптимизации, поэтому стратегию легко подбирать в оптимизаторе StockSharp.
Рекомендации
- Выбор таймфрейма напрямую влияет на частоту сигналов: чем он меньше, тем больше сделок, но тем выше требования к точности защитных приказов.
- Для корректной работы защитных шагов убедитесь, что у инструмента задан
PriceStep.
- Перед боевым использованием протестируйте стратегию в Designer, чтобы убедиться в корректности пересчёта стопов и целей.
- Стратегия поддерживает только одну открытую позицию. После закрытия сделки счётчики сбрасываются и паттерн строится заново, как и в оригинале.
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>
/// Momentum reversal strategy that tracks consecutive candles with expanding bodies.
/// </summary>
public class ETurboFxMomentumStrategy : Strategy
{
private readonly StrategyParam<int> _depthAnalysis;
private readonly StrategyParam<decimal> _takeProfitSteps;
private readonly StrategyParam<decimal> _stopLossSteps;
private readonly StrategyParam<decimal> _tradeVolume;
private readonly StrategyParam<DataType> _candleType;
private int _bearishSequence;
private int _bullishSequence;
private decimal _previousBearishBody;
private decimal _previousBullishBody;
/// <summary>
/// Number of recent candles analysed for momentum confirmation.
/// </summary>
public int DepthAnalysis
{
get => _depthAnalysis.Value;
set => _depthAnalysis.Value = value;
}
/// <summary>
/// Take profit distance measured in price steps (ticks).
/// A value of zero disables the take profit order.
/// </summary>
public decimal TakeProfitSteps
{
get => _takeProfitSteps.Value;
set => _takeProfitSteps.Value = value;
}
/// <summary>
/// Stop loss distance measured in price steps (ticks).
/// A value of zero disables the protective stop.
/// </summary>
public decimal StopLossSteps
{
get => _stopLossSteps.Value;
set => _stopLossSteps.Value = value;
}
/// <summary>
/// Volume used when sending market orders.
/// </summary>
public decimal TradeVolume
{
get => _tradeVolume.Value;
set
{
_tradeVolume.Value = value;
Volume = value;
}
}
/// <summary>
/// Candle type analysed by the strategy.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="ETurboFxMomentumStrategy" /> class.
/// </summary>
public ETurboFxMomentumStrategy()
{
_depthAnalysis = Param(nameof(DepthAnalysis), 3)
.SetGreaterThanZero()
.SetDisplay("Depth Analysis", "Number of finished candles used for pattern detection", "Trading Rules")
.SetOptimize(2, 6, 1);
_takeProfitSteps = Param(nameof(TakeProfitSteps), 120m)
.SetNotNegative()
.SetDisplay("Take Profit (steps)", "Take profit distance in price steps (ticks)", "Risk Management")
.SetOptimize(60m, 180m, 20m);
_stopLossSteps = Param(nameof(StopLossSteps), 70m)
.SetNotNegative()
.SetDisplay("Stop Loss (steps)", "Stop loss distance in price steps (ticks)", "Risk Management")
.SetOptimize(40m, 120m, 10m);
_tradeVolume = Param(nameof(TradeVolume), 0.1m)
.SetGreaterThanZero()
.SetDisplay("Trade Volume", "Order volume used for entries", "Trading Rules")
.SetOptimize(0.1m, 0.5m, 0.1m);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Timeframe of the candles analysed by the strategy", "Market Data");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
ResetState();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
ResetState();
Volume = TradeVolume;
var takeProfitUnit = CreateStepUnit(TakeProfitSteps);
var stopLossUnit = CreateStepUnit(StopLossSteps);
if (takeProfitUnit != null || stopLossUnit != null)
{
// Configure protective orders once the strategy starts.
StartProtection(
takeProfit: takeProfitUnit,
stopLoss: stopLossUnit,
isStopTrailing: false,
useMarketOrders: true);
}
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private Unit CreateStepUnit(decimal steps)
{
if (steps <= 0)
return null;
// Convert the user-friendly tick distance into a StockSharp Unit instance.
return new Unit(steps, UnitTypes.Absolute);
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
// indicators formed check removed
if (Position != 0)
{
// Do not look for new signals while a position is active.
ResetState();
return;
}
var bodySize = Math.Abs(candle.ClosePrice - candle.OpenPrice);
// The original expert compared absolute bodies of the latest N closed candles.
// Measuring the body here reproduces that behaviour candle by candle.
if (candle.ClosePrice < candle.OpenPrice)
{
HandleBearishCandle(bodySize);
}
else if (candle.ClosePrice > candle.OpenPrice)
{
HandleBullishCandle(bodySize);
}
else
{
// Neutral candle breaks both sequences.
ResetState();
}
}
private void HandleBearishCandle(decimal bodySize)
{
// Bearish candles reset the bullish path and allow the downside streak to continue.
ResetBullishSequence();
if (bodySize <= 0)
{
ResetBearishSequence();
return;
}
if (_bearishSequence == 0 || bodySize > _previousBearishBody)
{
// Body is larger than the previous bearish candle, extend the sequence.
_bearishSequence++;
}
else
{
// Sequence restarts because body did not expand.
_bearishSequence = 1;
}
_previousBearishBody = bodySize;
if (_bearishSequence >= DepthAnalysis)
{
// Expanding bearish bodies suggest exhaustion that can trigger a long entry.
BuyMarket();
ResetBearishSequence();
}
}
private void HandleBullishCandle(decimal bodySize)
{
// Bullish candles reset the bearish path and allow the upside streak to continue.
ResetBearishSequence();
if (bodySize <= 0)
{
ResetBullishSequence();
return;
}
if (_bullishSequence == 0 || bodySize > _previousBullishBody)
{
// Body is larger than the previous bullish candle, extend the sequence.
_bullishSequence++;
}
else
{
// Sequence restarts because body did not expand.
_bullishSequence = 1;
}
_previousBullishBody = bodySize;
if (_bullishSequence >= DepthAnalysis)
{
// Expanding bullish bodies suggest potential reversal to the downside.
SellMarket();
ResetBullishSequence();
}
}
private void ResetBearishSequence()
{
_bearishSequence = 0;
_previousBearishBody = 0m;
}
private void ResetBullishSequence()
{
_bullishSequence = 0;
_previousBullishBody = 0m;
}
private void ResetState()
{
ResetBearishSequence();
ResetBullishSequence();
}
}
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
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Strategies import Strategy
class e_turbo_fx_momentum_strategy(Strategy):
"""Momentum reversal strategy that tracks consecutive candles with expanding bodies.
Uses StartProtection for SL/TP."""
def __init__(self):
super(e_turbo_fx_momentum_strategy, self).__init__()
self._depth_analysis = self.Param("DepthAnalysis", 3) \
.SetGreaterThanZero() \
.SetDisplay("Depth Analysis", "Number of finished candles used for pattern detection", "Trading Rules")
self._take_profit_steps = self.Param("TakeProfitSteps", 120.0) \
.SetDisplay("Take Profit (steps)", "Take profit distance in price steps (ticks)", "Risk Management")
self._stop_loss_steps = self.Param("StopLossSteps", 70.0) \
.SetDisplay("Stop Loss (steps)", "Stop loss distance in price steps (ticks)", "Risk Management")
self._trade_volume = self.Param("TradeVolume", 0.1) \
.SetGreaterThanZero() \
.SetDisplay("Trade Volume", "Order volume used for entries", "Trading Rules")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Timeframe of the candles analysed by the strategy", "Market Data")
self._bearish_sequence = 0
self._bullish_sequence = 0
self._previous_bearish_body = 0.0
self._previous_bullish_body = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def DepthAnalysis(self):
return self._depth_analysis.Value
@property
def TakeProfitSteps(self):
return self._take_profit_steps.Value
@property
def StopLossSteps(self):
return self._stop_loss_steps.Value
@property
def TradeVolume(self):
return self._trade_volume.Value
def OnReseted(self):
super(e_turbo_fx_momentum_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(e_turbo_fx_momentum_strategy, self).OnStarted2(time)
self._reset_state()
self.Volume = float(self.TradeVolume)
tp_steps = float(self.TakeProfitSteps)
sl_steps = float(self.StopLossSteps)
tp_unit = Unit(tp_steps, UnitTypes.Absolute) if tp_steps > 0 else None
sl_unit = Unit(sl_steps, UnitTypes.Absolute) if sl_steps > 0 else None
if tp_unit is not None or sl_unit is not None:
self.StartProtection(tp_unit, sl_unit)
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._process_candle).Start()
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
if self.Position != 0:
self._reset_state()
return
body_size = abs(float(candle.ClosePrice) - float(candle.OpenPrice))
if float(candle.ClosePrice) < float(candle.OpenPrice):
self._handle_bearish_candle(body_size)
elif float(candle.ClosePrice) > float(candle.OpenPrice):
self._handle_bullish_candle(body_size)
else:
self._reset_state()
def _handle_bearish_candle(self, body_size):
self._reset_bullish_sequence()
if body_size <= 0:
self._reset_bearish_sequence()
return
if self._bearish_sequence == 0 or body_size > self._previous_bearish_body:
self._bearish_sequence += 1
else:
self._bearish_sequence = 1
self._previous_bearish_body = body_size
if self._bearish_sequence >= self.DepthAnalysis:
self.BuyMarket()
self._reset_bearish_sequence()
def _handle_bullish_candle(self, body_size):
self._reset_bearish_sequence()
if body_size <= 0:
self._reset_bullish_sequence()
return
if self._bullish_sequence == 0 or body_size > self._previous_bullish_body:
self._bullish_sequence += 1
else:
self._bullish_sequence = 1
self._previous_bullish_body = body_size
if self._bullish_sequence >= self.DepthAnalysis:
self.SellMarket()
self._reset_bullish_sequence()
def _reset_bearish_sequence(self):
self._bearish_sequence = 0
self._previous_bearish_body = 0.0
def _reset_bullish_sequence(self):
self._bullish_sequence = 0
self._previous_bullish_body = 0.0
def _reset_state(self):
self._reset_bearish_sequence()
self._reset_bullish_sequence()
def CreateClone(self):
return e_turbo_fx_momentum_strategy()