在 GitHub 上查看
等量成交与区间柱
概述
等量成交与区间柱策略把 MetaTrader 4 脚本 equalvolumebars.mq4 移植到 StockSharp。原脚本用于生成离线图表:蜡烛在累计到固定笔数或价格走完指定点数时收盘。该策略在 StockSharp 中复刻同样的蜡烛构建流程——订阅实时成交,按需回放历史 M1 蜡烛,并在每根合成柱完成时输出详细日志。
蜡烛构建逻辑
- 双工作模式 –
EqualVolumeBars(等量成交)在累计成交笔数超过阈值时收线;RangeBars(区间柱)要求当日最高价与最低价的差值(按照合约最小价位计算)超过同一阈值。
- 逐笔驱动更新 – 每一笔成交都会刷新当前蜡烛的最高价、最低价、收盘价和成交笔数。当下一笔会使阈值被突破时,策略使用已有统计信息结算前一根蜡烛,并立即用当前成交开启新蜡烛。
- 可选的分钟级回放 – 启用
FromMinuteHistory 时,策略将已完成的 M1 蜡烛转换为“开盘 → 中间极值 → 收盘”的一组合成成交,从而模拟原始离线图的初始化过程,无需单独的 CSV Tick 文件。
- 时间戳单调递增 – 生成器确保时间戳严格递增,便于日志或后续组件消费数据时避免重复时间键。
参数
- Work Mode – 选择
EqualVolumeBars 或 RangeBars 运行模式。
- Ticks In Bar – 等量模式下每根蜡烛的成交笔数,或区间模式下的点数阈值(以最小价位为单位)。
- Use Minute History – 是否在实时数据到来前回放已完成的 M1 蜡烛。
- Minute Candle Type – 用于历史回放的蜡烛订阅类型(默认是一分钟周期)。
其他说明
- 策略优先从
Security.PriceStep 获取点值,若缺失则退回到 Security.MinPriceStep 或 0.0001,以复现 MetaTrader 中 _Point 常量的行为。
- C# 版本不再写入
.hst 文件或刷新窗口,而是把每根完成的蜡烛连同 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()