Стратегия VininI Trend
Описание
Стратегия является конверсией советника Exp_VininI_Trend с MQL5 на StockSharp. Для имитации осциллятора VininI Trend используется индикатор Commodity Channel Index. Длинная позиция открывается при пробитии верхнего уровня или развороте вверх, короткая — при падении ниже нижнего уровня или развороте вниз. Работа ведётся только по завершённым свечам.
Параметры
- CCI Period – период индикатора CCI.
- Upper Level – уровень, при пересечении которого открывается покупка.
- Lower Level – уровень, при пересечении которого открывается продажа.
- Entry Modes –
Breakdownреагирует на пересечение уровней,Twistреагирует на смену направления. - Candle Type – таймфрейм свечей для расчёта.
Оригинал
Конвертирована из стратегии MQL5 по пути MQL/1365/exp_vinini_trend.mq5.
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>
/// Strategy based on the VininI Trend concept using the CCI indicator.
/// Buys when CCI breaks above upper level, sells when CCI breaks below lower level.
/// </summary>
public class VininITrendStrategy : Strategy
{
private readonly StrategyParam<int> _period;
private readonly StrategyParam<int> _upLevel;
private readonly StrategyParam<int> _downLevel;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prev1;
private decimal? _prev2;
public int Period { get => _period.Value; set => _period.Value = value; }
public int UpLevel { get => _upLevel.Value; set => _upLevel.Value = value; }
public int DownLevel { get => _downLevel.Value; set => _downLevel.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public VininITrendStrategy()
{
_period = Param(nameof(Period), 20)
.SetGreaterThanZero()
.SetDisplay("CCI Period", "Period for the CCI indicator", "Parameters");
_upLevel = Param(nameof(UpLevel), 10)
.SetDisplay("Upper Level", "Upper threshold to trigger buy", "Parameters");
_downLevel = Param(nameof(DownLevel), -10)
.SetDisplay("Lower Level", "Lower threshold to trigger sell", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prev1 = default;
_prev2 = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prev1 = _prev2 = null;
var cci = new CommodityChannelIndex { Length = Period };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(cci, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, cci);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue cciValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!cciValue.IsFormed)
return;
var cci = cciValue.ToDecimal();
var buySignal = false;
var sellSignal = false;
if (_prev1 is not null)
{
// Breakdown mode: CCI crosses level
if (_prev1 <= UpLevel && cci > UpLevel)
buySignal = true;
if (_prev1 >= DownLevel && cci < DownLevel)
sellSignal = true;
}
if (buySignal && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (sellSignal && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prev2 = _prev1;
_prev1 = cci;
}
}
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 CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
class vinin_i_trend_strategy(Strategy):
"""CCI crossing upper/lower levels for trend entry."""
def __init__(self):
super(vinin_i_trend_strategy, self).__init__()
self._period = self.Param("Period", 20).SetGreaterThanZero().SetDisplay("CCI Period", "CCI indicator period", "Parameters")
self._up_level = self.Param("UpLevel", 10).SetDisplay("Upper Level", "Upper threshold for buy", "Parameters")
self._down_level = self.Param("DownLevel", -10).SetDisplay("Lower Level", "Lower threshold for sell", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))).SetDisplay("Candle Type", "Timeframe", "General")
@property
def CandleType(self): return self._candle_type.Value
@CandleType.setter
def CandleType(self, value): self._candle_type.Value = value
def OnReseted(self):
super(vinin_i_trend_strategy, self).OnReseted()
self._prev_cci = None
def OnStarted2(self, time):
super(vinin_i_trend_strategy, self).OnStarted2(time)
self._prev_cci = None
cci = CommodityChannelIndex()
cci.Length = self._period.Value
sub = self.SubscribeCandles(self.CandleType)
sub.BindEx(cci, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, sub)
self.DrawIndicator(area, cci)
self.DrawOwnTrades(area)
def OnProcess(self, candle, cci_ind_val):
if candle.State != CandleStates.Finished:
return
if not cci_ind_val.IsFormed:
return
cci_val = float(cci_ind_val)
up = self._up_level.Value
down = self._down_level.Value
if self._prev_cci is not None:
buy_signal = self._prev_cci <= up and cci_val > up
sell_signal = self._prev_cci >= down and cci_val < down
if buy_signal and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif sell_signal and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_cci = cci_val
def CreateClone(self):
return vinin_i_trend_strategy()