VWAP Breakout ATR Strategy
Enters long when price crosses above VWAP and short when it crosses below. Stop-loss and take-profit are based on ATR multiples.
Parameters
- AtrLength: ATR period.
- StopAtrMultiplier: ATR multiplier for stop-loss.
- TakeAtrMultiplier: ATR multiplier for take-profit.
- CandleType: Type of candles.
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// VWAP breakout strategy with StdDev-based stop-loss and take-profit.
/// Uses SMA as VWAP proxy and StdDev for ATR-like volatility stops.
/// Enters on price crossing above/below the moving average.
/// </summary>
public class VwapBreakoutAtrStrategy : Strategy
{
private readonly StrategyParam<int> _maLength;
private readonly StrategyParam<int> _stdLength;
private readonly StrategyParam<decimal> _stopMult;
private readonly StrategyParam<decimal> _takeMult;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevClose;
private decimal _prevMa;
private bool _hasPrev;
private decimal _entryPrice;
private decimal _stopPrice;
private decimal _takePrice;
public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }
public int StdLength { get => _stdLength.Value; set => _stdLength.Value = value; }
public decimal StopMult { get => _stopMult.Value; set => _stopMult.Value = value; }
public decimal TakeMult { get => _takeMult.Value; set => _takeMult.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public VwapBreakoutAtrStrategy()
{
_maLength = Param(nameof(MaLength), 20)
.SetGreaterThanZero()
.SetDisplay("MA Length", "Moving average period", "Parameters");
_stdLength = Param(nameof(StdLength), 14)
.SetGreaterThanZero()
.SetDisplay("StdDev Length", "Volatility period", "Parameters");
_stopMult = Param(nameof(StopMult), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Stop Mult", "StdDev multiplier for stop", "Parameters");
_takeMult = Param(nameof(TakeMult), 2m)
.SetGreaterThanZero()
.SetDisplay("Take Mult", "StdDev multiplier for TP", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_prevClose = 0;
_prevMa = 0;
_hasPrev = false;
_entryPrice = 0;
_stopPrice = 0;
_takePrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = MaLength };
var stdDev = new StandardDeviation { Length = StdLength };
_prevClose = 0;
_prevMa = 0;
_hasPrev = false;
_entryPrice = 0;
_stopPrice = 0;
_takePrice = 0;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(sma, stdDev, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal smaVal, decimal stdVal)
{
if (candle.State != CandleStates.Finished)
return;
// TP/SL management
if (Position > 0)
{
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _takePrice)
{
SellMarket();
_entryPrice = 0;
}
}
else if (Position < 0)
{
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _takePrice)
{
BuyMarket();
_entryPrice = 0;
}
}
if (_hasPrev && stdVal > 0)
{
var crossOver = _prevClose <= _prevMa && candle.ClosePrice > smaVal;
var crossUnder = _prevClose >= _prevMa && candle.ClosePrice < smaVal;
if (crossOver && Position <= 0)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice - stdVal * StopMult;
_takePrice = _entryPrice + stdVal * TakeMult;
}
else if (crossUnder && Position >= 0)
{
SellMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice + stdVal * StopMult;
_takePrice = _entryPrice - stdVal * TakeMult;
}
}
_prevClose = candle.ClosePrice;
_prevMa = smaVal;
_hasPrev = true;
}
}
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 SimpleMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class vwap_breakout_atr_strategy(Strategy):
def __init__(self):
super(vwap_breakout_atr_strategy, self).__init__()
self._ma_length = self.Param("MaLength", 20) \
.SetDisplay("MA Length", "Moving average period", "Parameters")
self._std_length = self.Param("StdLength", 14) \
.SetDisplay("StdDev Length", "Volatility period", "Parameters")
self._stop_mult = self.Param("StopMult", 1.5) \
.SetDisplay("Stop Mult", "StdDev multiplier for stop", "Parameters")
self._take_mult = self.Param("TakeMult", 2.0) \
.SetDisplay("Take Mult", "StdDev multiplier for TP", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_close = 0.0
self._prev_ma = 0.0
self._has_prev = False
self._entry_price = 0.0
self._stop_price = 0.0
self._take_price = 0.0
@property
def ma_length(self):
return self._ma_length.Value
@property
def std_length(self):
return self._std_length.Value
@property
def stop_mult(self):
return self._stop_mult.Value
@property
def take_mult(self):
return self._take_mult.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(vwap_breakout_atr_strategy, self).OnReseted()
self._prev_close = 0.0
self._prev_ma = 0.0
self._has_prev = False
self._entry_price = 0.0
self._stop_price = 0.0
self._take_price = 0.0
def OnStarted2(self, time):
super(vwap_breakout_atr_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = self.ma_length
std_dev = StandardDeviation()
std_dev.Length = self.std_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, std_dev, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawOwnTrades(area)
def on_process(self, candle, sma_val, std_val):
if candle.State != CandleStates.Finished:
return
# TP/SL management
if self.Position > 0:
if candle.LowPrice <= self._stop_price or candle.HighPrice >= self._take_price:
self.SellMarket()
self._entry_price = 0
elif self.Position < 0:
if candle.HighPrice >= self._stop_price or candle.LowPrice <= self._take_price:
self.BuyMarket()
self._entry_price = 0
if self._has_prev and std_val > 0:
cross_over = self._prev_close <= self._prev_ma and candle.ClosePrice > sma_val
cross_under = self._prev_close >= self._prev_ma and candle.ClosePrice < sma_val
if cross_over and self.Position <= 0:
self.BuyMarket()
self._entry_price = candle.ClosePrice
self._stop_price = self._entry_price - std_val * self.stop_mult
self._take_price = self._entry_price + std_val * self.take_mult
elif cross_under and self.Position >= 0:
self.SellMarket()
self._entry_price = candle.ClosePrice
self._stop_price = self._entry_price + std_val * self.stop_mult
self._take_price = self._entry_price - std_val * self.take_mult
self._prev_close = candle.ClosePrice
self._prev_ma = sma_val
self._has_prev = True
def CreateClone(self):
return vwap_breakout_atr_strategy()