GitHub で見る
等しい音量と範囲のバー
概要
Equal Volume & Range Bars は、MetaTrader 4 スクリプト equalvolumebars.mq4 を StockSharp に移植します。元のスクリプトは、固定数のティックの後、または価格が構成可能なポイント範囲を通過した後にローソク足が閉じるオフライン チャートを生成しました。この戦略は、StockSharp 環境内で同じローソク足構築ロジックを再現します。ライブティックをリッスンし、オプションで過去の M1 ローソク足をプリロードし、合成バーが完了するたびに詳細なログ エントリを出力します。
キャンドル構築ロジック
- デュアル動作モード –
EqualVolumeBars は、累積ティック量が設定されたしきい値を超えるとバーを閉じますが、RangeBars は、ローソク足の高値と安値の範囲 (証券価格ステップで測定) が同じ数値しきい値を超える必要があります。
- ティック主導の更新 – 取引を更新するたびに、現在のローソク足の高値、安値、終値、およびティックの出来高が更新されます。しきい値を超えると、この戦略は既存の統計を使用して前のローソク足を確定し、現在のティックを最初のエントリとして新しいバーを即座に開始します。
- 分履歴シード (オプション) –
FromMinuteHistory が有効な場合、戦略は終了した M1 ローソク足を一連の合成ティック (始値 → 中間の極値 → 終値) として再生します。これは、外部 CSV ティック ファイルを必要とせずに、オフライン チャートの初期化ステップに近似します。
- 単調なタイムスタンプ – ビルダーは、ログ コンシューマまたはダウンストリーム モジュールが重複するタイム キーに遭遇することなくデータをロードできるように、タイムスタンプを厳密に増加させるように強制します。
パラメーター
- 作業モード –
EqualVolumeBars と RangeBars のキャンドル構造を選択します。
- バーのティック数 – ローソク足あたりのティック数 (等量モード)、または価格ステップで測定されたポイント範囲 (レンジ モード)。
- 分履歴を使用 – ライブティックが到着する前に、完成した M1 ローソクの合成再生を有効にします。
- 分キャンドル タイプ – 履歴シード ステップに使用されるキャンドル サブスクリプション (デフォルトは 1 分の時間枠)。
追加の注意事項
- この戦略は、
Security.PriceStep からポイント サイズを推測し (メタデータが利用できない場合は Security.MinPriceStep または 0.0001 にフォールバックします)、MetaTrader で使用される _Point 定数をミラーリングします。
.hst ファイルを作成してチャート ウィンドウを更新する代わりに、C# ポートは完成したすべてのローソク足を完全な OHLCV データとともにログに記録するため、別のコンポーネントにフィードしたり、MT4 オフライン チャート ビルダーと結果を比較したりすることが簡単になります。
- 注文は決して送信されません。このクラスは、元のスクリプトと同様にデータ変換のみに焦点を当てています。
- C# バージョンのみが提供されます。 Python のバージョンとフォルダーは、変換要件に従って意図的に省略されています。
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>
/// Equal Volume Range Bars strategy - ATR-based volatility breakout.
/// Buys when close breaks above EMA + ATR band.
/// Sells when close breaks below EMA - ATR band.
/// </summary>
public class EqualVolumeRangeBarsStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<DataType> _candleType;
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public int AtrPeriod { get => _atrPeriod.Value; set => _atrPeriod.Value = value; }
public decimal AtrMultiplier { get => _atrMultiplier.Value; set => _atrMultiplier.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public EqualVolumeRangeBarsStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 20)
.SetDisplay("EMA Period", "EMA lookback", "Indicators");
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetDisplay("ATR Period", "ATR lookback", "Indicators");
_atrMultiplier = Param(nameof(AtrMultiplier), 2m)
.SetDisplay("ATR Multiplier", "ATR band multiplier", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
protected override void OnReseted() { base.OnReseted(); }
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, atr, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal ema, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
var upper = ema + atr * AtrMultiplier;
var lower = ema - atr * AtrMultiplier;
if (close > upper && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
else if (close < lower && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
}
}
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, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class equal_volume_range_bars_strategy(Strategy):
def __init__(self):
super(equal_volume_range_bars_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 20).SetDisplay("EMA Period", "EMA lookback", "Indicators")
self._atr_period = self.Param("AtrPeriod", 14).SetDisplay("ATR Period", "ATR lookback", "Indicators")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0).SetDisplay("ATR Multiplier", "ATR band multiplier", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Candle timeframe", "General")
@property
def ema_period(self): return self._ema_period.Value
@property
def atr_period(self): return self._atr_period.Value
@property
def atr_multiplier(self): return self._atr_multiplier.Value
@property
def candle_type(self): return self._candle_type.Value
def OnReseted(self): super(equal_volume_range_bars_strategy, self).OnReseted()
def OnStarted2(self, time):
super(equal_volume_range_bars_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage(); ema.Length = self.ema_period
atr = AverageTrueRange(); atr.Length = self.atr_period
sub = self.SubscribeCandles(self.candle_type)
sub.Bind(ema, atr, self.process_candle).Start()
def process_candle(self, candle, ema, atr):
if candle.State != CandleStates.Finished: return
close = float(candle.ClosePrice); e = float(ema); a = float(atr)
upper = e + a * self.atr_multiplier; lower = e - a * self.atr_multiplier
if close > upper and self.Position <= 0:
if self.Position < 0: self.BuyMarket()
self.BuyMarket()
elif close < lower and self.Position >= 0:
if self.Position > 0: self.SellMarket()
self.SellMarket()
def CreateClone(self): return equal_volume_range_bars_strategy()