Стратегия Lego V3
Эта стратегия является портом советника MQL4 «Lego_v3».
Она объединяет несколько классических индикаторов для определения входов и выходов:
- Скользящие средние – быстрая и медленная SMA показывают направление тренда.
- Стохастик – значения %K и %D определяют зоны перекупленности и перепроданности.
- Awesome Oscillator – подтверждает импульс в направлении тренда.
- Average True Range – задаёт расстояния до стоп-лосса и тейк-профита.
Длинная позиция открывается, когда быстрая SMA выше медленной, %K ниже уровня покупки и AO положителен.
Короткая позиция открывается при обратных условиях. ATR используется один раз в начале для запуска управления защитными ордерами.
Параметры
FastMaPeriod– период быстрой SMA.SlowMaPeriod– период медленной SMA.StochK– период %K стохастика.StochD– период %D стохастика.StochBuy– порог покупки для %K.StochSell– порог продажи для %K.AtrPeriod– период ATR.AtrMultiplier– множитель ATR для стопов.CandleType– тип используемых свечей.
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>
/// Lego V3 strategy using MA crossover with ATR-based stops.
/// </summary>
public class LegoV3Strategy : Strategy
{
private readonly StrategyParam<int> _fastMa;
private readonly StrategyParam<int> _slowMa;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private bool _hasPrev;
public int FastMa { get => _fastMa.Value; set => _fastMa.Value = value; }
public int SlowMa { get => _slowMa.Value; set => _slowMa.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public LegoV3Strategy()
{
_fastMa = Param(nameof(FastMa), 8)
.SetGreaterThanZero()
.SetDisplay("Fast MA", "Fast EMA period", "Indicators");
_slowMa = Param(nameof(SlowMa), 21)
.SetGreaterThanZero()
.SetDisplay("Slow MA", "Slow EMA period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0;
_prevSlow = 0;
_entryPrice = 0;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fast = new ExponentialMovingAverage { Length = FastMa };
var slow = new ExponentialMovingAverage { Length = SlowMa };
var atr = new StandardDeviation { Length = 14 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fast, slow, atr, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
if (atr <= 0) return;
if (!_hasPrev)
{
_prevFast = fast;
_prevSlow = slow;
_hasPrev = true;
return;
}
var close = candle.ClosePrice;
// ATR stop check
if (Position > 0 && _entryPrice > 0 && close < _entryPrice - 2 * atr)
{
SellMarket();
_entryPrice = 0;
}
else if (Position < 0 && _entryPrice > 0 && close > _entryPrice + 2 * atr)
{
BuyMarket();
_entryPrice = 0;
}
// MA crossover
if (_prevFast <= _prevSlow && fast > slow && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
_entryPrice = close;
}
else if (_prevFast >= _prevSlow && fast < slow && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
_entryPrice = close;
}
_prevFast = fast;
_prevSlow = slow;
}
}
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 ExponentialMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class lego_v3_strategy(Strategy):
def __init__(self):
super(lego_v3_strategy, self).__init__()
self._fast_ma = self.Param("FastMa", 8) \
.SetDisplay("Fast MA", "Fast EMA period", "Indicators")
self._slow_ma = self.Param("SlowMa", 21) \
.SetDisplay("Slow MA", "Slow EMA period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._has_prev = False
@property
def fast_ma(self):
return self._fast_ma.Value
@property
def slow_ma(self):
return self._slow_ma.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(lego_v3_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(lego_v3_strategy, self).OnStarted2(time)
fast = ExponentialMovingAverage()
fast.Length = self.fast_ma
slow = ExponentialMovingAverage()
slow.Length = self.slow_ma
atr = StandardDeviation()
atr.Length = 14
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast, slow, atr, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow, atr):
if candle.State != CandleStates.Finished:
return
if atr <= 0:
return
if not self._has_prev:
self._prev_fast = fast
self._prev_slow = slow
self._has_prev = True
return
close = candle.ClosePrice
# ATR stop check
if self.Position > 0 and self._entry_price > 0 and close < self._entry_price - 2 * atr:
self.SellMarket()
self._entry_price = 0
elif self.Position < 0 and self._entry_price > 0 and close > self._entry_price + 2 * atr:
self.BuyMarket()
self._entry_price = 0
# MA crossover
if self._prev_fast <= self._prev_slow and fast > slow and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
elif self._prev_fast >= self._prev_slow and fast < slow and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._prev_fast = fast
self._prev_slow = slow
def CreateClone(self):
return lego_v3_strategy()