VWAP Breakout 戦略
VWAP Breakoutは価格が出来高加重平均価格(VWAP)を反対側からクロスするタイミングを探します。VWAPを上抜けると強気の圧力、VWAPを下抜けると弱気のセンチメントを示します。
テストでは年平均リターン約181%を示しています。暗号資産市場での運用に最も適しています。
戦略はVWAPの反対側での終値を待ってその方向にトレードします。価格がVWAPを逆方向に再クロスした時点で決済します。
VWAPは平均取引価格を表すため、ブレイクアウト後はモメンタム相場につながることが多いです。
詳細
- エントリー条件: 価格がVWAPの反対側で引ける。
- ロング/ショート: 両方向。
- エグジット条件: 価格がVWAPを再クロスまたはストップ。
- ストップ: あり。
- デフォルト値:
CandleType= TimeSpan.FromMinutes(5)
- フィルター:
- カテゴリ: ブレイクアウト
- 方向: 両方
- インジケーター: VWAP
- ストップ: はい
- 複雑さ: 基本
- 時間軸: イントラデイ
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Trades actual same-UTC-session Close crossings of cumulative candle VWAP.
/// The opposite crossing reverses the position; actual-fill percent protection flattens it.
/// </summary>
public class VWAPBreakoutStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private VolumeWeightedAveragePrice _vwap;
private DateTime? _sessionDate;
private decimal? _previousClose;
private decimal _previousVwap;
private Order _pendingOrder;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
public VWAPBreakoutStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_stopLossPercent = Param(nameof(StopLossPercent), 2m).SetNotNegative()
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection");
OrderRegistering += order => _pendingOrder = order;
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType), (Security, DataType.Level1)];
protected override void OnReseted()
{
base.OnReseted();
ClearSignalState();
_vwap = null;
}
private void ClearSignalState()
{
_sessionDate = null;
_previousClose = null;
_previousVwap = 0m;
_pendingOrder = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
ClearSignalState();
_vwap = new VolumeWeightedAveragePrice();
Indicators.Add(_vwap);
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _vwap);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// Native protection runs before this callback, including between finished candles.
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var date = candle.OpenTime.ToUniversalTime().Date;
if (_sessionDate != date)
{
_sessionDate = date;
// Reset BEFORE this day's first final bar; a reset jump is not a price crossing.
_vwap.Reset();
_previousClose = null;
}
var value = _vwap.Process(candle);
if (value.IsEmpty || !_vwap.IsFormed)
return;
var vwap = value.GetValue<decimal>();
var upwardCross = _previousClose is decimal up && up <= _previousVwap && candle.ClosePrice > vwap;
var downwardCross = _previousClose is decimal down && down >= _previousVwap && candle.ClosePrice < vwap;
// Seed the first valid session value and advance history even while orders are pending.
_previousClose = candle.ClosePrice;
_previousVwap = vwap;
if (!IsFormedAndOnlineAndAllowTrading() ||
_pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed))
return;
if (upwardCross && Position <= 0m) BuyMarket(this.ReversalVolume());
else if (downwardCross && Position >= 0m) SellMarket(this.ReversalVolume());
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, OrderStates, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import VolumeWeightedAveragePrice, CandleIndicatorValue
from StockSharp.Algo.Strategies import Strategy, StrategyHelper
class vwap_breakout_strategy(Strategy):
"""
Trades actual same-UTC-session Close crossings of cumulative candle VWAP.
The opposite crossing reverses the position; actual-fill percent protection flattens it.
"""
def __init__(self):
super(vwap_breakout_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection")
self._vwap = None
self._session_date = None
self._previous_close = None
self._previous_vwap = Decimal.Zero
self._pending_order = None
self.OrderRegistering += self._track_pending
@property
def candle_type(self):
return self._candle_type.Value
def GetWorkingSecurities(self):
return [(self.Security, self.candle_type), (self.Security, DataType.Level1)]
def _track_pending(self, order):
self._pending_order = order
def _clear_signal_state(self):
self._session_date = None
self._previous_close = None
self._previous_vwap = Decimal.Zero
self._pending_order = None
def OnReseted(self):
super(vwap_breakout_strategy, self).OnReseted()
self._clear_signal_state()
self._vwap = None
def OnStarted2(self, time):
super(vwap_breakout_strategy, self).OnStarted2(time)
self._clear_signal_state()
self._vwap = VolumeWeightedAveragePrice()
self.Indicators.Add(self._vwap)
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._vwap)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# Native protection runs before this callback, including between finished candles.
pass
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
date = candle.OpenTime.ToUniversalTime().Date
if self._session_date != date:
self._session_date = date
# Reset BEFORE this day's first final bar; a reset jump is not a price crossing.
self._vwap.Reset()
self._previous_close = None
value = self._vwap.Process(CandleIndicatorValue(self._vwap, candle))
if value.IsEmpty or not self._vwap.IsFormed:
return
vwap = value.GetValue[Decimal](None)
upward_cross = self._previous_close is not None and self._previous_close <= self._previous_vwap and candle.ClosePrice > vwap
downward_cross = self._previous_close is not None and self._previous_close >= self._previous_vwap and candle.ClosePrice < vwap
# Seed the first valid session value and advance history during pending orders.
self._previous_close = candle.ClosePrice
self._previous_vwap = vwap
if not self.IsFormedAndOnlineAndAllowTrading() or (self._pending_order is not None and self._pending_order.State not in (OrderStates.Done, OrderStates.Failed)):
return
if upward_cross and self.Position <= 0:
self.BuyMarket(StrategyHelper.ReversalVolume(self))
elif downward_cross and self.Position >= 0:
self.SellMarket(StrategyHelper.ReversalVolume(self))
def CreateClone(self):
return vwap_breakout_strategy()