Стратегия Three Down Three Up
Стратегия покупает после заданного числа подряд закрытий ниже и закрывает позицию после серии закрытий выше. Дополнительный фильтр EMA позволяет входить только когда цена выше средней.
Детали
- Условия входа: Цена закрывается ниже предыдущего бара N раз подряд. Дополнительно цена должна быть выше EMA.
- Условия выхода: Цена закрывается выше предыдущего бара M раз подряд.
- Длинные/короткие: Только длинные позиции.
- Стопы: Нет.
- Значения по умолчанию: Вход после 3 падений, выход после 3 ростов, период EMA = 200.
- Фильтры:
- Категория: Mean reversion
- Направление: Long
- Индикаторы: EMA (опционально)
- Стопы: Нет
- Сложность: Низкая
- Таймфрейм: Любой
- Сезонность: Нет
- Нейросети: Нет
- Дивергенции: Нет
- Уровень риска: Средний
namespace StockSharp.Samples.Strategies;
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// 3 Down, 3 Up Strategy.
/// Buys after N consecutive down closes (mean reversion).
/// Sells after N consecutive up closes.
/// Optional EMA trend filter.
/// </summary>
public class ThreeDownThreeUpStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _buyTrigger;
private readonly StrategyParam<int> _sellTrigger;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<int> _cooldownBars;
private ExponentialMovingAverage _ema;
private int _upCount;
private int _downCount;
private decimal _prevClose;
private bool _hasPrevClose;
private int _cooldownRemaining;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int BuyTrigger
{
get => _buyTrigger.Value;
set => _buyTrigger.Value = value;
}
public int SellTrigger
{
get => _sellTrigger.Value;
set => _sellTrigger.Value = value;
}
public int EmaLength
{
get => _emaLength.Value;
set => _emaLength.Value = value;
}
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
public ThreeDownThreeUpStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_buyTrigger = Param(nameof(BuyTrigger), 3)
.SetGreaterThanZero()
.SetDisplay("Buy Trigger", "Consecutive down closes for entry", "Trading");
_sellTrigger = Param(nameof(SellTrigger), 3)
.SetGreaterThanZero()
.SetDisplay("Sell Trigger", "Consecutive up closes for exit", "Trading");
_emaLength = Param(nameof(EmaLength), 50)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA trend filter period", "Indicators");
_cooldownBars = Param(nameof(CooldownBars), 12)
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_ema = null;
_upCount = 0;
_downCount = 0;
_prevClose = 0;
_hasPrevClose = false;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_ema = new ExponentialMovingAverage { Length = EmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_ema, OnProcess)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _ema);
DrawOwnTrades(area);
}
}
private void OnProcess(ICandleMessage candle, decimal emaVal)
{
if (candle.State != CandleStates.Finished)
return;
if (!_ema.IsFormed)
return;
// Track consecutive up/down closes
if (_hasPrevClose)
{
if (candle.ClosePrice > _prevClose)
{
_upCount++;
_downCount = 0;
}
else if (candle.ClosePrice < _prevClose)
{
_downCount++;
_upCount = 0;
}
else
{
_upCount = 0;
_downCount = 0;
}
}
_prevClose = candle.ClosePrice;
_hasPrevClose = true;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
return;
}
// Buy after consecutive down closes (mean reversion)
if (_downCount >= BuyTrigger && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_upCount = 0;
_cooldownRemaining = CooldownBars;
}
// Sell short after consecutive up closes
else if (_upCount >= SellTrigger && Position >= 0)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
SellMarket(Volume);
_downCount = 0;
_cooldownRemaining = CooldownBars;
}
// Exit long: price below EMA
else if (Position > 0 && candle.ClosePrice < emaVal && _upCount >= 2)
{
SellMarket(Math.Abs(Position));
_cooldownRemaining = CooldownBars;
}
// Exit short: price above EMA
else if (Position < 0 && candle.ClosePrice > emaVal && _downCount >= 2)
{
BuyMarket(Math.Abs(Position));
_cooldownRemaining = 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, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class three_down_three_up_strategy(Strategy):
"""3 Down, 3 Up Strategy."""
def __init__(self):
super(three_down_three_up_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._buy_trigger = self.Param("BuyTrigger", 3) \
.SetDisplay("Buy Trigger", "Consecutive down closes for entry", "Trading")
self._sell_trigger = self.Param("SellTrigger", 3) \
.SetDisplay("Sell Trigger", "Consecutive up closes for exit", "Trading")
self._ema_length = self.Param("EmaLength", 50) \
.SetDisplay("EMA Length", "EMA trend filter period", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 12) \
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk")
self._ema = None
self._up_count = 0
self._down_count = 0
self._prev_close = 0.0
self._has_prev_close = False
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(three_down_three_up_strategy, self).OnReseted()
self._ema = None
self._up_count = 0
self._down_count = 0
self._prev_close = 0.0
self._has_prev_close = False
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(three_down_three_up_strategy, self).OnStarted2(time)
self._ema = ExponentialMovingAverage()
self._ema.Length = int(self._ema_length.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._ema, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._ema)
self.DrawOwnTrades(area)
def _on_process(self, candle, ema_val):
if candle.State != CandleStates.Finished:
return
if not self._ema.IsFormed:
return
close = float(candle.ClosePrice)
if self._has_prev_close:
if close > self._prev_close:
self._up_count += 1
self._down_count = 0
elif close < self._prev_close:
self._down_count += 1
self._up_count = 0
else:
self._up_count = 0
self._down_count = 0
self._prev_close = close
self._has_prev_close = True
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
return
ema_v = float(ema_val)
buy_trig = int(self._buy_trigger.Value)
sell_trig = int(self._sell_trigger.Value)
cooldown = int(self._cooldown_bars.Value)
if self._down_count >= buy_trig and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._up_count = 0
self._cooldown_remaining = cooldown
elif self._up_count >= sell_trig and self.Position >= 0:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self.SellMarket(self.Volume)
self._down_count = 0
self._cooldown_remaining = cooldown
elif self.Position > 0 and close < ema_v and self._up_count >= 2:
self.SellMarket(Math.Abs(self.Position))
self._cooldown_remaining = cooldown
elif self.Position < 0 and close > ema_v and self._down_count >= 2:
self.BuyMarket(Math.Abs(self.Position))
self._cooldown_remaining = cooldown
def CreateClone(self):
return three_down_three_up_strategy()