GitHub で見る
Exp i-KlPrice Vol ダイレクト戦略
概要
Exp i-KlPrice Vol ダイレクト戦略はMetaTrader 5エキスパートアドバイザーExp_i-KlPrice_Vol_DirectのStockSharp適応版です。
元のシステムはカスタムKlPriceオシレーターをボリュームで乗算し、複数の移動平均ステージで平滑化し、結果の線の傾きの変化に反応
します。ポートはマルチステージ処理チェーンを維持し、同じ設定可能なパラメーターを公開し、完成した足でStockSharpの高レベルAPI
を通じて取引を実行します。
MQL5バージョンから保持された主要なアイデア:
- 価格と値幅の2段階平滑化 – 価格データは設定可能な移動平均でフィルタリングされ、高-低値幅は別々に平滑化されます。
- ボリューム重み付け – オシレーター出力は最終Jurikフィルターの前に選択されたボリュームストリームで乗算されます。
- 方向カラーマップ – 戦略は平滑化されたオシレーター傾きの符号を監視します。
- シグナル遅延 –
SignalBarでユーザーが行動前に追加の閉じた足を必要とできます。
処理パイプライン
- 適用価格の選択 – MQLインジケーターと同じ12種類の適用価格フォーミュラから選択。
- 一次平滑化 – オプションの
PricePhase付きでPriceLengthバーにPriceMethodを適用。
- 値幅平滑化 –
RangeMethod、RangeLength、RangePhaseを使用して足の値幅(High - Low)に同じ手順を繰り返す。
- オシレーター構築 –
(Price - (PriceMA - RangeMA)) / (2 * RangeMA) * 100 - 50をMQLフォーミュラと同一に計算し、
選択されたボリュームストリーム(VolumeSource)で乗算。
- 最終Jurikフィルター – ボリューム加重オシレーターと生ボリュームストリームの両方を期間
ResultLengthのJurik移動平均
を通じて渡す。
- カラー検出 – 最新の平滑化されたオシレーター値を前の値と比較。上昇値は足を強気(
0)、下落値は弱気(1)、
等しい値は前のカラーを継承。
取引ロジック
ロングサイド
- エントリー:シグナルバー(
SignalBar)のカラーが強気(0)で、直前のカラーが弱気(1)のとき、
AllowLongEntries = trueかつ現在のネットポジションが正でなければロングポジションを開く。
- 決済:シグナルバーのカラーが強気で
AllowShortExits = trueの場合、オープンなショートポジションを閉じる。
ショートサイド
- エントリー:シグナルバーのカラーが強気(
0)の後に弱気(1)になったとき、AllowShortEntries = trueかつ現在の
ネットポジションが負でなければショートポジションを開く。
- 決済:シグナルバーのカラーが弱気で
AllowLongExits = trueの場合、既存のロングポジションを閉じる。
パラメーター参照
| パラメーター |
説明 |
デフォルト |
CandleType |
分析される足の時間軸。 |
H4 |
VolumeSource |
重み付けに使用するボリュームストリーム(TickまたはReal)。 |
Tick |
PriceMethod / PriceLength / PricePhase |
適用価格の一次平滑化アルゴリズム、期間、Jurik位相。 |
Sma, 100, 15 |
RangeMethod / RangeLength / RangePhase |
足値幅の平滑化アルゴリズム、期間、位相。 |
Jjma, 20, 100 |
ResultLength |
ボリューム加重オシレーターとボリュームストリームのJurik期間。 |
20 |
PriceMode |
適用価格フォーミュラ(Close、Open、Median、Demark、TrendFollow0/1など)。 |
Close |
HighLevel2, HighLevel1, LowLevel1, LowLevel2 |
視覚診断用のレベル乗数;シグナルは変更しない。 |
0, 0, 0, 0 |
SignalBar |
カラー変化を評価する前にスキップする完全に閉じた足数。 |
1 |
AllowLongEntries / AllowShortEntries |
ロング/ショート取引を開くための許可フラグ。 |
true |
AllowLongExits / AllowShortExits |
反対カラーで既存ポジションを閉じるための許可フラグ。 |
true |
StopLossPoints / TakeProfitPoints |
StartProtectionに渡される価格ポイント単位の保護オフセット。 |
1000, 2000 |
リスク管理
- ストップロスとテイクプロフィットレベルは
UnitTypes.Pointオフセットに変換され、StartProtectionで管理されます。
それぞれの保護を無効にするにはいずれかの値を0に設定。
- ポジションサイズは
Strategy.Volumeで完全に制御されます。
- カラーは戦略が形成され、オンラインで、取引が許可されている場合にのみ評価されます。
制限とMQL5との違い
- よりエキゾチックな平滑化近似はMT5出力とわずかに異なる場合があります。
- StockSharp足は総ボリュームのみを公開します。
- 元のEAのマネー管理モードはポートされていません。
- 注文はシグナル足のクローズ直後に送られます。
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()