Color XXDPO Strategy
Стратегия использует дважды сглаженный осциллятор DPO для поиска разворотов наклона.
Подробности
- Условия входа: Наклон индикатора вверх и текущий рост значения открывает лонг; наклон вниз и падение значения открывает шорт.
- Направление: Лонг и шорт.
- Условия выхода: Противоположное изменение наклона.
- Стопы: Нет.
- Параметры по умолчанию: Длина первой MA 21, длина второй MA 5, таймфрейм свечей 6 часов.
- Фильтры: Нет.
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>
/// Strategy based on a double smoothed Detrended Price Oscillator.
/// </summary>
public class ColorXXDPOStrategy : Strategy
{
private readonly StrategyParam<int> _firstLength;
private readonly StrategyParam<int> _secondLength;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _signalCooldownBars;
private readonly SimpleMovingAverage _ma1 = new();
private readonly SimpleMovingAverage _ma2 = new();
private static readonly object _sync = new();
private decimal _prev1;
private decimal _prev2;
private bool _isInitialized;
private int _cooldownRemaining;
public ColorXXDPOStrategy()
{
_firstLength = Param(nameof(FirstLength), 21)
.SetDisplay("First MA Length", "Length for the first smoothing stage.", "Indicators");
_secondLength = Param(nameof(SecondLength), 5)
.SetDisplay("Second MA Length", "Length for the second smoothing stage.", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Candle type for strategy calculation.", "General");
_signalCooldownBars = Param(nameof(SignalCooldownBars), 3)
.SetNotNegative()
.SetDisplay("Signal Cooldown Bars", "Closed candles to wait before a new direction change.", "General");
_ma1.Length = FirstLength;
_ma2.Length = SecondLength;
}
public int FirstLength
{
get => _firstLength.Value;
set => _firstLength.Value = value;
}
public int SecondLength
{
get => _secondLength.Value;
set => _secondLength.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int SignalCooldownBars
{
get => _signalCooldownBars.Value;
set => _signalCooldownBars.Value = value;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_ma1.Reset();
_ma2.Reset();
_ma1.Length = FirstLength;
_ma2.Length = SecondLength;
_prev1 = 0m;
_prev2 = 0m;
_isInitialized = false;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_ma1.Length = FirstLength;
_ma2.Length = SecondLength;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
lock (_sync)
{
if (candle.State != CandleStates.Finished)
return;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
var ma1Result = _ma1.Process(candle.ClosePrice, candle.OpenTime, true);
if (!_ma1.IsFormed || ma1Result.IsEmpty)
return;
var ma1 = ma1Result.ToDecimal();
var dpo = candle.ClosePrice - ma1;
var xxdpoResult = _ma2.Process(dpo, candle.OpenTime, true);
if (!_ma2.IsFormed || xxdpoResult.IsEmpty)
return;
var xxdpo = xxdpoResult.ToDecimal();
if (!_isInitialized)
{
_prev2 = xxdpo;
_prev1 = xxdpo;
_isInitialized = true;
return;
}
var turnedUp = _prev2 >= _prev1 && xxdpo > _prev1;
var turnedDown = _prev2 <= _prev1 && xxdpo < _prev1;
if (_cooldownRemaining == 0 && turnedUp && Position <= 0)
{
BuyMarket(Volume + (Position < 0 ? -Position : 0m));
_cooldownRemaining = SignalCooldownBars;
}
else if (_cooldownRemaining == 0 && turnedDown && Position >= 0)
{
SellMarket(Volume + (Position > 0 ? Position : 0m));
_cooldownRemaining = SignalCooldownBars;
}
_prev2 = _prev1;
_prev1 = xxdpo;
}
}
}
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
from indicator_extensions import *
class color_xxdpo_strategy(Strategy):
def __init__(self):
super(color_xxdpo_strategy, self).__init__()
self._first_length = self.Param("FirstLength", 21) \
.SetDisplay("First MA Length", "Length for the first smoothing stage.", "Indicators")
self._second_length = self.Param("SecondLength", 5) \
.SetDisplay("Second MA Length", "Length for the second smoothing stage.", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candle type for strategy calculation.", "General")
self._signal_cooldown_bars = self.Param("SignalCooldownBars", 3) \
.SetDisplay("Signal Cooldown Bars", "Closed candles to wait before a new direction change.", "General")
self._ma1 = None
self._ma2 = None
self._prev1 = 0.0
self._prev2 = 0.0
self._is_initialized = False
self._cooldown_remaining = 0
@property
def FirstLength(self):
return self._first_length.Value
@FirstLength.setter
def FirstLength(self, value):
self._first_length.Value = value
@property
def SecondLength(self):
return self._second_length.Value
@SecondLength.setter
def SecondLength(self, value):
self._second_length.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def SignalCooldownBars(self):
return self._signal_cooldown_bars.Value
@SignalCooldownBars.setter
def SignalCooldownBars(self, value):
self._signal_cooldown_bars.Value = value
def OnStarted2(self, time):
super(color_xxdpo_strategy, self).OnStarted2(time)
self._ma1 = SimpleMovingAverage()
self._ma1.Length = self.FirstLength
self._ma2 = SimpleMovingAverage()
self._ma2.Length = self.SecondLength
self._is_initialized = False
self._cooldown_remaining = 0
self.SubscribeCandles(self.CandleType) \
.Bind(self.ProcessCandle) \
.Start()
def ProcessCandle(self, candle):
if candle.State != CandleStates.Finished:
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
close = float(candle.ClosePrice)
t = candle.OpenTime
ma1_result = process_float(self._ma1, close, t, True)
if not self._ma1.IsFormed or ma1_result.IsEmpty:
return
ma1_val = float(ma1_result)
dpo = close - ma1_val
xxdpo_result = process_float(self._ma2, dpo, t, True)
if not self._ma2.IsFormed or xxdpo_result.IsEmpty:
return
xxdpo = float(xxdpo_result)
if not self._is_initialized:
self._prev2 = xxdpo
self._prev1 = xxdpo
self._is_initialized = True
return
turned_up = self._prev2 >= self._prev1 and xxdpo > self._prev1
turned_down = self._prev2 <= self._prev1 and xxdpo < self._prev1
if self._cooldown_remaining == 0 and turned_up and self.Position <= 0:
volume = self.Volume + (-self.Position if self.Position < 0 else 0)
self.BuyMarket(volume)
self._cooldown_remaining = self.SignalCooldownBars
elif self._cooldown_remaining == 0 and turned_down and self.Position >= 0:
volume = self.Volume + (self.Position if self.Position > 0 else 0)
self.SellMarket(volume)
self._cooldown_remaining = self.SignalCooldownBars
self._prev2 = self._prev1
self._prev1 = xxdpo
def OnReseted(self):
super(color_xxdpo_strategy, self).OnReseted()
self._ma1 = None
self._ma2 = None
self._prev1 = 0.0
self._prev2 = 0.0
self._is_initialized = False
self._cooldown_remaining = 0
def CreateClone(self):
return color_xxdpo_strategy()