VWAP 回归
该策略在价格偏离成交量加权平均价(VWAP)较远时逆势交易,待价格回归后离场。由于VWAP代表典型成交水平,极端偏离往往吸引价格回到其附近,常与日内趋势过滤结合提高胜率。
测试表明年均收益约为 127%,该策略在股票市场表现最佳。
详情
- 入场条件: 基于 RSI、VWAP 的信号
- 多空方向: 双向
- 退出条件: 反向信号或止损
- 止损: 是
- 默认值:
DeviationPercent= 2.0mStopLossPercent= 2.0mCandleType= TimeSpan.FromMinutes(5)
- 过滤器:
- 类型: 均值回归
- 方向: 双向
- 指标: RSI, VWAP
- 止损: 是
- 复杂度: 基础
- 时间框架: 日内 (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>
/// VWAP Reversion strategy that trades on deviations from Volume Weighted Average Price.
/// Opens positions when price deviates from VWAP and exits when price returns.
/// </summary>
public class VwapReversionStrategy : Strategy
{
private readonly StrategyParam<decimal> _deviationPercent;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cooldownBars;
private int _cooldown;
/// <summary>
/// Deviation percentage from VWAP required for entry.
/// </summary>
public decimal DeviationPercent
{
get => _deviationPercent.Value;
set => _deviationPercent.Value = value;
}
/// <summary>
/// Type of candles used for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Cooldown bars between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Initialize the VWAP Reversion strategy.
/// </summary>
public VwapReversionStrategy()
{
_deviationPercent = Param(nameof(DeviationPercent), 0.5m)
.SetDisplay("Deviation %", "Deviation from VWAP for entry", "Entry")
.SetOptimize(0.2m, 2.0m, 0.2m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_cooldownBars = Param(nameof(CooldownBars), 500)
.SetRange(1, 1000)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_cooldown = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_cooldown = 0;
var vwap = new VolumeWeightedMovingAverage();
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(vwap, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, vwap);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal vwapValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (vwapValue <= 0)
return;
if (_cooldown > 0)
{
_cooldown--;
return;
}
var deviationRatio = (candle.ClosePrice - vwapValue) / vwapValue;
var threshold = DeviationPercent / 100m;
if (Position == 0)
{
if (deviationRatio < -threshold)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (deviationRatio > threshold)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position > 0)
{
if (candle.ClosePrice >= vwapValue)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position < 0)
{
if (candle.ClosePrice <= vwapValue)
{
BuyMarket();
_cooldown = CooldownBars;
}
}
}
}
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 VolumeWeightedMovingAverage
from StockSharp.Algo.Strategies import Strategy
class vwap_reversion_strategy(Strategy):
"""
VWAP Reversion strategy.
Trades on deviations from VWAP, exits when price returns.
"""
def __init__(self):
super(vwap_reversion_strategy, self).__init__()
self._deviation_percent = self.Param("DeviationPercent", 0.5).SetDisplay("Deviation %", "Deviation from VWAP for entry", "Entry")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._cooldown_bars = self.Param("CooldownBars", 500).SetDisplay("Cooldown Bars", "Bars to wait between trades", "General")
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(vwap_reversion_strategy, self).OnReseted()
self._cooldown = 0
def OnStarted2(self, time):
super(vwap_reversion_strategy, self).OnStarted2(time)
self._cooldown = 0
vwap = VolumeWeightedMovingAverage()
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(vwap, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, vwap)
self.DrawOwnTrades(area)
def _process_candle(self, candle, vwap_val):
if candle.State != CandleStates.Finished:
return
vv = float(vwap_val)
if vv <= 0:
return
if self._cooldown > 0:
self._cooldown -= 1
return
close = float(candle.ClosePrice)
ratio = (close - vv) / vv
threshold = float(self._deviation_percent.Value) / 100.0
cd = self._cooldown_bars.Value
if self.Position == 0:
if ratio < -threshold:
self.BuyMarket()
self._cooldown = cd
elif ratio > threshold:
self.SellMarket()
self._cooldown = cd
elif self.Position > 0:
if close >= vv:
self.SellMarket()
self._cooldown = cd
elif self.Position < 0:
if close <= vv:
self.BuyMarket()
self._cooldown = cd
def CreateClone(self):
return vwap_reversion_strategy()