Стратегия LSMA Fast And Simple Alternative Calculation
Стратегия использует быструю аппроксимацию скользящей средней наименьших квадратов (LSMA), вычисляемую как 3 × WMA − 2 × SMA. Длинная позиция открывается при пересечении цены выше LSMA, короткая — при пересечении ниже.
Детали
- Условия входа:
- Лонг: закрытие выше LSMA.
- Шорт: закрытие ниже LSMA.
- Лонг/Шорт: оба направления.
- Условия выхода: противоположный сигнал.
- Стопы: нет.
- Значения по умолчанию:
- Длина 25.
- Фильтры:
- Категория: тренд
- Направление: оба
- Индикаторы: WMA, SMA
- Стопы: нет
- Сложность: простая
- Таймфрейм: не задан
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>
/// LSMA Fast And Simple Alternative Calculation Strategy.
/// Buys when close price crosses above LSMA and sells when it crosses below.
/// </summary>
public class LsmaFastSimpleAlternativeCalculationStrategy : Strategy
{
private readonly StrategyParam<int> _length;
private readonly StrategyParam<DataType> _candleType;
private WeightedMovingAverage _wma;
private SimpleMovingAverage _sma;
private decimal _prevDiff;
private int _cooldown;
public LsmaFastSimpleAlternativeCalculationStrategy()
{
_length = Param(nameof(Length), 50)
.SetDisplay("LSMA Length", "Length for LSMA calculation", "LSMA");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
public int Length
{
get => _length.Value;
set => _length.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();
_prevDiff = default;
_cooldown = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_wma = new WeightedMovingAverage { Length = Length };
_sma = new SimpleMovingAverage { Length = Length };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_wma, _sma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal wmaValue, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_wma.IsFormed || !_sma.IsFormed)
return;
var lsma = 3m * wmaValue - 2m * smaValue;
var diff = candle.ClosePrice - lsma;
if (_cooldown > 0)
{
_cooldown--;
_prevDiff = diff;
return;
}
if (_prevDiff <= 0m && diff > 0m && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_cooldown = 10;
}
else if (_prevDiff >= 0m && diff < 0m && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
_cooldown = 10;
}
_prevDiff = diff;
}
}
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 WeightedMovingAverage, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class lsma_fast_simple_alternative_calculation_strategy(Strategy):
def __init__(self):
super(lsma_fast_simple_alternative_calculation_strategy, self).__init__()
self._length = self.Param("Length", 50) \
.SetDisplay("LSMA Length", "Length for LSMA calculation", "LSMA")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_diff = 0.0
self._cooldown = 0
@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(lsma_fast_simple_alternative_calculation_strategy, self).OnReseted()
self._prev_diff = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(lsma_fast_simple_alternative_calculation_strategy, self).OnStarted2(time)
self._prev_diff = 0.0
self._cooldown = 0
self._wma = WeightedMovingAverage()
self._wma.Length = self._length.Value
self._sma = SimpleMovingAverage()
self._sma.Length = self._length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._wma, self._sma, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def OnProcess(self, candle, wma_val, sma_val):
if candle.State != CandleStates.Finished:
return
if not self._wma.IsFormed or not self._sma.IsFormed:
return
wv = float(wma_val)
sv = float(sma_val)
close = float(candle.ClosePrice)
lsma = 3.0 * wv - 2.0 * sv
diff = close - lsma
if self._cooldown > 0:
self._cooldown -= 1
self._prev_diff = diff
return
if self._prev_diff <= 0.0 and diff > 0.0 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._cooldown = 10
elif self._prev_diff >= 0.0 and diff < 0.0 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._cooldown = 10
self._prev_diff = diff
def CreateClone(self):
return lsma_fast_simple_alternative_calculation_strategy()