Стратегия OBV Traffic Lights
Стратегия использует OBV на основе свечей Heikin Ashi и три EMA, окрашенные как светофор. Лонг открывается, когда OBV и быстрая EMA выше медленной EMA; шорт — когда OBV и быстрая EMA ниже медленной. Позиция закрывается при исчезновении условий.
- Условия входа: OBV > медленной EMA и быстрая EMA > медленной EMA; OBV < медленной EMA и быстрая EMA < медленной EMA.
- Условия выхода: противоположный сигнал или потеря согласования.
- Индикаторы: OBV, EMA, Highest/Lowest
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
public class ObvTrafficLightsStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevClose;
private decimal _obv;
private decimal _prevFast;
private decimal _prevSlow;
private int _count;
private DateTimeOffset _lastSignal = DateTimeOffset.MinValue;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ObvTrafficLightsStrategy()
{
_fastLength = Param(nameof(FastLength), 5).SetGreaterThanZero();
_slowLength = Param(nameof(SlowLength), 14).SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevClose = 0;
_obv = 0;
_prevFast = 0;
_prevSlow = 0;
_count = 0;
_lastSignal = DateTimeOffset.MinValue;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevClose = 0;
_obv = 0;
_prevFast = 0;
_prevSlow = 0;
_count = 0;
// Use a dummy indicator to ensure IsFormed checks work through Bind
var sma = new SimpleMovingAverage { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
_count++;
// OBV calculation
if (_prevClose != 0)
{
if (candle.ClosePrice > _prevClose)
_obv += candle.TotalVolume;
else if (candle.ClosePrice < _prevClose)
_obv -= candle.TotalVolume;
}
_prevClose = candle.ClosePrice;
// EMA of OBV
var fastMult = 2.0m / (FastLength + 1);
var slowMult = 2.0m / (SlowLength + 1);
if (_count <= 2)
{
_prevFast = _obv;
_prevSlow = _obv;
return;
}
var fastValue = _obv * fastMult + _prevFast * (1 - fastMult);
var slowValue = _obv * slowMult + _prevSlow * (1 - slowMult);
_prevFast = fastValue;
_prevSlow = slowValue;
if (_count < SlowLength + 5)
return;
var goLong = _obv > slowValue && fastValue > slowValue;
var goShort = _obv < slowValue && fastValue < slowValue;
var cooldown = TimeSpan.FromMinutes(600);
if (candle.OpenTime - _lastSignal < cooldown)
return;
if (goLong && Position <= 0)
{
BuyMarket();
_lastSignal = candle.OpenTime;
}
else if (goShort && Position >= 0)
{
SellMarket();
_lastSignal = candle.OpenTime;
}
}
}
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
from StockSharp.Algo.Strategies import Strategy
class obv_traffic_lights_strategy(Strategy):
def __init__(self):
super(obv_traffic_lights_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 5) \
.SetGreaterThanZero()
self._slow_length = self.Param("SlowLength", 14) \
.SetGreaterThanZero()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._prev_close = 0.0
self._obv = 0.0
self._prev_fast = 0.0
self._prev_slow = 0.0
self._count = 0
self._last_signal_ticks = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(obv_traffic_lights_strategy, self).OnReseted()
self._prev_close = 0.0
self._obv = 0.0
self._prev_fast = 0.0
self._prev_slow = 0.0
self._count = 0
self._last_signal_ticks = 0
def OnStarted2(self, time):
super(obv_traffic_lights_strategy, self).OnStarted2(time)
self._prev_close = 0.0
self._obv = 0.0
self._prev_fast = 0.0
self._prev_slow = 0.0
self._count = 0
self._last_signal_ticks = 0
self._sma = SimpleMovingAverage()
self._sma.Length = self._slow_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._sma, self.OnProcess).Start()
def OnProcess(self, candle, sma_val):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
vol = float(candle.TotalVolume)
self._count += 1
if self._prev_close != 0.0:
if close > self._prev_close:
self._obv += vol
elif close < self._prev_close:
self._obv -= vol
self._prev_close = close
fl = self._fast_length.Value
sl = self._slow_length.Value
fast_mult = 2.0 / (fl + 1)
slow_mult = 2.0 / (sl + 1)
if self._count <= 2:
self._prev_fast = self._obv
self._prev_slow = self._obv
return
fast_value = self._obv * fast_mult + self._prev_fast * (1 - fast_mult)
slow_value = self._obv * slow_mult + self._prev_slow * (1 - slow_mult)
self._prev_fast = fast_value
self._prev_slow = slow_value
if self._count < sl + 5:
return
go_long = self._obv > slow_value and fast_value > slow_value
go_short = self._obv < slow_value and fast_value < slow_value
cooldown_ticks = TimeSpan.FromMinutes(600).Ticks
current_ticks = candle.OpenTime.Ticks
if current_ticks - self._last_signal_ticks < cooldown_ticks:
return
if go_long and self.Position <= 0:
self.BuyMarket()
self._last_signal_ticks = current_ticks
elif go_short and self.Position >= 0:
self.SellMarket()
self._last_signal_ticks = current_ticks
def CreateClone(self):
return obv_traffic_lights_strategy()