IU 4 Bar UP Strategy
IU 4 Bar UP Strategy — лонговая стратегия, которая покупает после четырёх подряд бычьих свечей, если цена находится выше индикатора SuperTrend.
Подробности
- Данные: ценовые свечи.
- Условия входа:
- Лонг: четыре подряд бычьи свечи и закрытие выше SuperTrend.
- Условия выхода: закрытие ниже SuperTrend.
- Стопы: отсутствуют.
- Параметры по умолчанию:
SupertrendLength= 14SupertrendMultiplier= 1
- Фильтры:
- Категория: трендовая
- Направление: лонг
- Индикаторы: SuperTrend
- Сложность: низкая
- Уровень риска: средний
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>
/// Long-only strategy that buys after four consecutive bullish candles when the price is above the SuperTrend.
/// </summary>
public class Iu4BarUpStrategy : Strategy
{
private readonly StrategyParam<int> _supertrendLength;
private readonly StrategyParam<decimal> _supertrendMultiplier;
private readonly StrategyParam<DataType> _candleType;
private bool _prevBull1;
private bool _prevBull2;
private bool _prevBull3;
public Iu4BarUpStrategy()
{
_supertrendLength = Param(nameof(SupertrendLength), 14)
.SetDisplay("SuperTrend ATR Period", "ATR period for SuperTrend", "General")
;
_supertrendMultiplier = Param(nameof(SupertrendMultiplier), 1m)
.SetDisplay("SuperTrend ATR Factor", "ATR factor for SuperTrend", "General")
;
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public int SupertrendLength
{
get => _supertrendLength.Value;
set => _supertrendLength.Value = value;
}
public decimal SupertrendMultiplier
{
get => _supertrendMultiplier.Value;
set => _supertrendMultiplier.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevBull1 = false;
_prevBull2 = false;
_prevBull3 = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var supertrend = new SuperTrend
{
Length = SupertrendLength,
Multiplier = SupertrendMultiplier
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(supertrend, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, supertrend);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue stValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!stValue.IsFinal)
return;
if (stValue.IsEmpty) return;
var st = stValue.ToDecimal();
var bullish = candle.ClosePrice > candle.OpenPrice;
var fourBull = bullish && _prevBull1 && _prevBull2 && _prevBull3;
if (Position <= 0 && fourBull && candle.ClosePrice > st)
BuyMarket();
if (Position > 0 && candle.ClosePrice < st)
SellMarket();
_prevBull3 = _prevBull2;
_prevBull2 = _prevBull1;
_prevBull1 = bullish;
}
}
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 SuperTrend
from StockSharp.Algo.Strategies import Strategy
class iu_4_bar_up_strategy(Strategy):
def __init__(self):
super(iu_4_bar_up_strategy, self).__init__()
self._supertrend_length = self.Param("SupertrendLength", 14) \
.SetDisplay("SuperTrend ATR Period", "ATR period for SuperTrend", "General")
self._supertrend_multiplier = self.Param("SupertrendMultiplier", 1.0) \
.SetDisplay("SuperTrend ATR Factor", "ATR factor for SuperTrend", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(240))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_bull1 = False
self._prev_bull2 = False
self._prev_bull3 = False
@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(iu_4_bar_up_strategy, self).OnReseted()
self._prev_bull1 = False
self._prev_bull2 = False
self._prev_bull3 = False
def OnStarted2(self, time):
super(iu_4_bar_up_strategy, self).OnStarted2(time)
st = SuperTrend()
st.Length = self._supertrend_length.Value
st.Multiplier = self._supertrend_multiplier.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(st, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, st)
self.DrawOwnTrades(area)
def OnProcess(self, candle, st_val):
if candle.State != CandleStates.Finished:
return
if st_val.IsEmpty:
return
st_v = float(st_val)
close = float(candle.ClosePrice)
open_p = float(candle.OpenPrice)
bullish = close > open_p
four_bull = bullish and self._prev_bull1 and self._prev_bull2 and self._prev_bull3
if self.Position <= 0 and four_bull and close > st_v:
self.BuyMarket()
if self.Position > 0 and close < st_v:
self.SellMarket()
self._prev_bull3 = self._prev_bull2
self._prev_bull2 = self._prev_bull1
self._prev_bull1 = bullish
def CreateClone(self):
return iu_4_bar_up_strategy()