Honest Volatility Grid 戦略
複数のKeltner Channelレベルを使ってボラティリティグリッドを構築する戦略です。事前に定義されたバンドでロングおよびショートポジションをスケールインし、反対側のレベルまたは生のストップでエグジットします。
詳細
- エントリー条件: 価格が設定されたKeltnerチャネルのレベルに達する。
- ロング/ショート: 両方向。
- エグジット条件: 反対側のチャネルまたは生のストップ。
- ストップ: オプションの生のストップ。
- デフォルト値:
EmaPeriod= 200Multiplier= 1.0LEntry1Level= -2SEntry1Level= 2RawStopLevel= 20CandleType= TimeSpan.FromMinutes(5)
- フィルター:
- カテゴリ: グリッド
- 方向: 両方
- インジケーター: EMA, ATR
- ストップ: はい
- 複雑さ: 中級
- 時間軸: イントラデイ (5m)
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Honest Volatility Grid strategy.
/// Keltner levels are built as EMA + level * Multiplier * ATR, with the ATR over the same EmaPeriod. A long opens when the close
/// reaches the LEntry1Level band and a short when it reaches the SEntry1Level band; reaching the opposite entry band closes and
/// reverses the position. A raw stop closes a long below the -RawStopLevel band and a short above the +RawStopLevel band.
/// </summary>
public class HonestVolatilityGridStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<decimal> _multiplier;
private readonly StrategyParam<decimal> _lEntry1Level;
private readonly StrategyParam<decimal> _sEntry1Level;
private readonly StrategyParam<decimal> _rawStopLevel;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// EMA and ATR period of the Keltner channel.
/// </summary>
public int EmaPeriod
{
get => _emaPeriod.Value;
set => _emaPeriod.Value = value;
}
/// <summary>
/// ATR multiplier of one channel level.
/// </summary>
public decimal Multiplier
{
get => _multiplier.Value;
set => _multiplier.Value = value;
}
/// <summary>
/// Channel level of the long entry.
/// </summary>
public decimal LEntry1Level
{
get => _lEntry1Level.Value;
set => _lEntry1Level.Value = value;
}
/// <summary>
/// Channel level of the short entry.
/// </summary>
public decimal SEntry1Level
{
get => _sEntry1Level.Value;
set => _sEntry1Level.Value = value;
}
/// <summary>
/// Channel level of the raw stop (0 disables it).
/// </summary>
public decimal RawStopLevel
{
get => _rawStopLevel.Value;
set => _rawStopLevel.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public HonestVolatilityGridStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 200)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "EMA and ATR period of the Keltner channel", "Indicators");
_multiplier = Param(nameof(Multiplier), 1.0m)
.SetGreaterThanZero()
.SetDisplay("Multiplier", "ATR multiplier of one channel level", "Indicators");
_lEntry1Level = Param(nameof(LEntry1Level), -2m)
.SetDisplay("Long Entry Level", "Channel level of the long entry", "Grid");
_sEntry1Level = Param(nameof(SEntry1Level), 2m)
.SetDisplay("Short Entry Level", "Channel level of the short entry", "Grid");
_rawStopLevel = Param(nameof(RawStopLevel), 20m)
.SetNotNegative()
.SetDisplay("Raw Stop Level", "Channel level of the raw stop", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var atr = new AverageTrueRange { Length = EmaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal ema, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var step = atr * Multiplier;
if (step <= 0)
return;
var close = candle.ClosePrice;
var longEntry = ema + LEntry1Level * step;
var shortEntry = ema + SEntry1Level * step;
if (RawStopLevel > 0)
{
if (Position > 0 && close <= ema - RawStopLevel * step)
{
SellMarket(Position);
return;
}
if (Position < 0 && close >= ema + RawStopLevel * step)
{
BuyMarket(-Position);
return;
}
}
if (close <= longEntry && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (close >= shortEntry && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
}
}
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 honest_volatility_grid_strategy(Strategy):
"""
Honest Volatility Grid strategy.
Keltner levels are built as EMA + level * Multiplier * ATR, with the ATR over the same EmaPeriod. A long opens when the close
reaches the LEntry1Level band and a short when it reaches the SEntry1Level band; reaching the opposite entry band closes and
reverses the position. A raw stop closes a long below the -RawStopLevel band and a short above the +RawStopLevel band.
"""
def __init__(self):
super(honest_volatility_grid_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 200).SetGreaterThanZero().SetDisplay("EMA Period", "EMA and ATR period of the Keltner channel", "Indicators")
self._multiplier = self.Param("Multiplier", 1.0).SetGreaterThanZero().SetDisplay("Multiplier", "ATR multiplier of one channel level", "Indicators")
self._l_entry1_level = self.Param("LEntry1Level", -2.0).SetDisplay("Long Entry Level", "Channel level of the long entry", "Grid")
self._s_entry1_level = self.Param("SEntry1Level", 2.0).SetDisplay("Short Entry Level", "Channel level of the short entry", "Grid")
self._raw_stop_level = self.Param("RawStopLevel", 20.0).SetNotNegative().SetDisplay("Raw Stop Level", "Channel level of the raw stop", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(honest_volatility_grid_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self._ema_period.Value
atr = AverageTrueRange()
atr.Length = self._ema_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, atr, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def _process_candle(self, candle, ema_value, atr_value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
ema = float(ema_value)
step = float(atr_value) * float(self._multiplier.Value)
if step <= 0:
return
close = float(candle.ClosePrice)
long_entry = ema + float(self._l_entry1_level.Value) * step
short_entry = ema + float(self._s_entry1_level.Value) * step
raw_stop = float(self._raw_stop_level.Value)
if raw_stop > 0:
if self.Position > 0 and close <= ema - raw_stop * step:
self.SellMarket(self.Position)
return
if self.Position < 0 and close >= ema + raw_stop * step:
self.BuyMarket(-self.Position)
return
if close <= long_entry and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif close >= short_entry and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return honest_volatility_grid_strategy()