Стратегия Internal Bar Strength IBS
Стратегия открывает длинную позицию, когда показатель внутренней силы бара (IBS) ниже нижнего порога, и закрывает её, когда IBS превышает верхний порог в заданном временном окне.
Детали
- Условия входа:
- IBS <
LowerThreshold. - Время между
StartTimeиEndTime.
- IBS <
- Long/Short: Только лонг.
- Условия выхода:
- IBS >=
UpperThreshold.
- IBS >=
- Стопы: Нет.
- Значения по умолчанию:
UpperThreshold= 0.8LowerThreshold= 0.2
- Фильтры:
- Категория: Mean reversion
- Направление: Long
- Индикаторы: None
- Стопы: No
- Сложность: Low
- Таймфрейм: Any
- Сезонность: No
- Нейросети: No
- Дивергенция: No
- Уровень риска: Low
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Internal bar strength mean reversion strategy.
/// </summary>
public class InternalBarStrengthIbsStrategy : Strategy
{
private readonly StrategyParam<decimal> _upperThreshold;
private readonly StrategyParam<decimal> _lowerThreshold;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<DateTimeOffset> _startTime;
private readonly StrategyParam<DateTimeOffset> _endTime;
/// <summary>
/// IBS value to exit position.
/// </summary>
public decimal UpperThreshold { get => _upperThreshold.Value; set => _upperThreshold.Value = value; }
/// <summary>
/// IBS value to enter long.
/// </summary>
public decimal LowerThreshold { get => _lowerThreshold.Value; set => _lowerThreshold.Value = value; }
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
/// <summary>
/// Start time for signals.
/// </summary>
public DateTimeOffset StartTime { get => _startTime.Value; set => _startTime.Value = value; }
/// <summary>
/// End time for signals.
/// </summary>
public DateTimeOffset EndTime { get => _endTime.Value; set => _endTime.Value = value; }
/// <summary>
/// Initializes a new instance of the <see cref="InternalBarStrengthIbsStrategy"/>.
/// </summary>
public InternalBarStrengthIbsStrategy()
{
_upperThreshold = Param(nameof(UpperThreshold), 0.8m)
.SetRange(0m, 1m)
.SetDisplay("Upper Threshold", "IBS value to exit position", "Parameters")
;
_lowerThreshold = Param(nameof(LowerThreshold), 0.2m)
.SetRange(0m, 1m)
.SetDisplay("Lower Threshold", "IBS value to enter long", "Parameters")
;
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_startTime = Param(nameof(StartTime), new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero))
.SetDisplay("Start Time", "Start time for strategy", "Time");
_endTime = Param(nameof(EndTime), new DateTimeOffset(2099, 1, 1, 0, 0, 0, TimeSpan.Zero))
.SetDisplay("End Time", "End time for strategy", "Time");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
StartProtection(null, null);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var time = candle.OpenTime;
var range = candle.HighPrice - candle.LowPrice;
if (range == 0)
return;
var ibs = (candle.ClosePrice - candle.LowPrice) / range;
var inWindow = time >= StartTime && time <= EndTime;
if (inWindow && ibs < LowerThreshold && Position <= 0)
BuyMarket();
if (Position > 0 && ibs >= UpperThreshold)
SellMarket();
}
}
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.Strategies import Strategy
class internal_bar_strength_ibs_strategy(Strategy):
def __init__(self):
super(internal_bar_strength_ibs_strategy, self).__init__()
self._upper_threshold = self.Param("UpperThreshold", 0.8) \
.SetDisplay("Upper Threshold", "IBS value to exit position", "Parameters")
self._lower_threshold = self.Param("LowerThreshold", 0.2) \
.SetDisplay("Lower Threshold", "IBS value to enter long", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(240))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(internal_bar_strength_ibs_strategy, self).OnStarted2(time)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def OnProcess(self, candle):
if candle.State != CandleStates.Finished:
return
high = float(candle.HighPrice)
low = float(candle.LowPrice)
close = float(candle.ClosePrice)
rng = high - low
if rng == 0:
return
ibs = (close - low) / rng
lower = float(self._lower_threshold.Value)
upper = float(self._upper_threshold.Value)
if ibs < lower and self.Position <= 0:
self.BuyMarket()
if self.Position > 0 and ibs >= upper:
self.SellMarket()
def CreateClone(self):
return internal_bar_strength_ibs_strategy()