A Estratégia Exp i-KlPrice Vol Direto é uma adaptação StockSharp do consultor especialista MetaTrader 5
Exp_i-KlPrice_Vol_Direct. O sistema original multiplica um oscilador KlPrice personalizado pelo volume, suaviza-o com várias
etapas de média móvel e reage a mudanças na inclinação da linha resultante. O port mantém a cadeia de processamento de
múltiplos estágios, expõe os mesmos parâmetros configuráveis e executa operações através da API de alto nível do StockSharp
em candles completadas.
Ideias-chave preservadas da versão MQL5:
Suavização de dois estágios de preço e intervalo – os dados de preço são filtrados por uma média móvel configurável, o
intervalo máximo-mínimo é suavizado separadamente.
Ponderação de volume – a saída do oscilador é multiplicada pelo fluxo de volume selecionado antes de um filtro Jurik
final.
Mapa de cor direcional – a estratégia monitora o sinal da inclinação do oscilador suavizado.
Atraso de sinal – SignalBar permite ao usuário exigir candles fechadas adicionais antes de agir.
Pipeline de Processamento
Seleção de Preço Aplicado – escolher entre as mesmas doze fórmulas de preço aplicado do indicador MQL.
Suavização Primária – aplicar PriceMethod sobre PriceLength barras com PricePhase opcional.
Suavização de Intervalo – repetir o mesmo procedimento para o intervalo da candle (High - Low) usando RangeMethod,
RangeLength e RangePhase.
Construção do Oscilador – calcular (Price - (PriceMA - RangeMA)) / (2 * RangeMA) * 100 - 50, idêntico à fórmula MQL,
e multiplicar pelo fluxo de volume selecionado (VolumeSource).
Filtro Jurik Final – o oscilador ponderado por volume e o fluxo de volume bruto são ambos passados por médias móveis
Jurik com período ResultLength.
Detecção de Cor – comparar o valor mais recente do oscilador suavizado com o anterior. Valores crescentes colorem a
barra de altista (0), decrescentes de baixista (1), iguais herdam a cor anterior.
Lógica de Trading
Lado Comprado
Entrada: quando a cor na barra de sinal (SignalBar) é altista (0) e a cor imediatamente anterior é baixista (1),
abrir posição comprada se AllowLongEntries = true e a posição líquida atual não é positiva.
Saída: se a cor da barra de sinal é altista e AllowShortExits = true, fechar quaisquer posições vendidas abertas.
Lado Vendido
Entrada: quando a cor da barra de sinal se torna baixista (1) após ser altista (0), abrir posição vendida se
AllowShortEntries = true e a posição líquida atual não é negativa.
Saída: se a cor da barra de sinal é baixista e AllowLongExits = true, fechar a exposição comprada existente.
Referência de Parâmetros
Parâmetro
Descrição
Padrão
CandleType
Período das candles analisadas.
H4
VolumeSource
Fluxo de volume para ponderação (Tick ou Real).
Tick
PriceMethod / PriceLength / PricePhase
Algoritmo de suavização primário, período e fase Jurik para o preço aplicado.
Sma, 100, 15
RangeMethod / RangeLength / RangePhase
Algoritmo de suavização, período e fase para o intervalo da candle.
Jjma, 20, 100
ResultLength
Período Jurik para o oscilador ponderado por volume e o fluxo de volume.
20
PriceMode
Fórmula de preço aplicado (Close, Open, Median, Demark, TrendFollow0/1, etc.).
Close
HighLevel2, HighLevel1, LowLevel1, LowLevel2
Multiplicadores de nível para diagnóstico visual; não alteram sinais.
0, 0, 0, 0
SignalBar
Número de candles completamente fechadas a pular antes de avaliar a mudança de cor.
1
AllowLongEntries / AllowShortEntries
Indicadores de permissão para abrir operações compradas/vendidas.
true
AllowLongExits / AllowShortExits
Indicadores de permissão para fechar posições existentes em cor oposta.
true
StopLossPoints / TakeProfitPoints
Offsets de proteção em pontos de preço passados ao StartProtection.
1000, 2000
Gestão de Risco
Níveis de stop-loss e take-profit são traduzidos em offsets UnitTypes.Point e gerenciados pelo StartProtection. Definir
qualquer valor como 0 para desabilitar a proteção respectiva.
O tamanho de posição é completamente controlado por Strategy.Volume.
Cores são avaliadas apenas quando a estratégia está formada, online e o trading é permitido.
Limitações e Diferenças vs. MQL5
Aproximações de suavização mais exóticas podem se desviar ligeiramente da saída do MT5.
Candles do StockSharp expõem apenas o volume total.
Modos de gestão de dinheiro do EA original não estão portados.
Ordens são enviadas imediatamente após o fechamento da candle de sinal.
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Exp i-KlPrice Vol Direct strategy using EMA crossover with volume-weighted confirmation.
/// Buys when fast EMA crosses above slow EMA. Sells on reverse crossover.
/// </summary>
public class ExpIKlPriceVolDirectStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private int _cooldown;
/// <summary>
/// Fast EMA period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow EMA period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Stop-loss distance in price steps.
/// </summary>
public int StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Take-profit distance in price steps.
/// </summary>
public int TakeProfitPoints
{
get => _takeProfitPoints.Value;
set => _takeProfitPoints.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpIKlPriceVolDirectStrategy"/> class.
/// </summary>
public ExpIKlPriceVolDirectStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("Fast Period", "Fast EMA period", "Indicator");
_slowPeriod = Param(nameof(SlowPeriod), 200)
.SetGreaterThanZero()
.SetDisplay("Slow Period", "Slow EMA period", "Indicator");
_stopLossPoints = Param(nameof(StopLossPoints), 200)
.SetNotNegative()
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 400)
.SetNotNegative()
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_fast = null;
_slow = null;
_prevFast = 0;
_prevSlow = 0;
_entryPrice = 0;
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fast = new ExponentialMovingAverage { Length = FastPeriod };
_slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.Bind(_fast, _slow, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fast.IsFormed || !_slow.IsFormed)
{
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
// Check SL/TP
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step)
{
SellMarket();
_entryPrice = 0;
_cooldown = 60;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step)
{
SellMarket();
_entryPrice = 0;
_cooldown = 60;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step)
{
BuyMarket();
_entryPrice = 0;
_cooldown = 60;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step)
{
BuyMarket();
_entryPrice = 0;
_cooldown = 60;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
}
// EMA crossover
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_entryPrice = close;
_cooldown = 60;
}
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
_entryPrice = close;
_cooldown = 60;
}
_prevFast = fastValue;
_prevSlow = slowValue;
}
}
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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class exp_i_kl_price_vol_direct_strategy(Strategy):
def __init__(self):
super(exp_i_kl_price_vol_direct_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 50) \
.SetDisplay("Fast Period", "Fast EMA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 200) \
.SetDisplay("Slow Period", "Slow EMA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
def OnReseted(self):
super(exp_i_kl_price_vol_direct_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(exp_i_kl_price_vol_direct_strategy, self).OnStarted2(time)
self._fast = ExponentialMovingAverage()
self._fast.Length = self.fast_period
self._slow = ExponentialMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
# Check SL/TP
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 60
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 60
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 60
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 60
self._prev_fast = fast_val
self._prev_slow = slow_val
return
# EMA crossover
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 60
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 60
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return exp_i_kl_price_vol_direct_strategy()