Стратегия Center of Gravity
Стратегия на основе индикатора Center of Gravity, который перемножает SMA и WMA и сглаживает результат. Длинная позиция открывается при пересечении центральной линии выше сглаженной средней, короткая позиция открывается при обратном пересечении. Позиции закрываются при смене сигнала на противоположный.
Детали
- Критерий входа: центральная линия пересекает свою сглаженную среднюю
- Длин/Шорт: обе стороны
- Критерий выхода: сигнал меняет сторону
- Стопы: нет
- Значения по умолчанию:
CandleType= H4Period= 10SmoothPeriod= 3
- Фильтры:
- Категория: Indicator
- Направление: обе
- Индикаторы: SMA, WMA
- Стопы: нет
- Сложность: базовая
- Таймфрейм: внутридневной
- Сезонность: нет
- Нейросети: нет
- Дивергенция: нет
- Уровень риска: средний
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>
/// Center of Gravity Strategy.
/// Uses SMA and WMA crossover.
/// Opens long when SMA crosses above WMA and short on the opposite cross.
/// </summary>
public class CenterOfGravityStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _period;
private decimal _prevSma;
private decimal _prevWma;
private bool _initialized;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int Period { get => _period.Value; set => _period.Value = value; }
public CenterOfGravityStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for calculation", "General");
_period = Param(nameof(Period), 10)
.SetDisplay("Period", "Center of Gravity averaging period", "Indicators");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevSma = 0m;
_prevWma = 0m;
_initialized = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = Period };
var wma = new WeightedMovingAverage { Length = Period };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(sma, wma, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawIndicator(area, wma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal smaValue, decimal wmaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_initialized)
{
_prevSma = smaValue;
_prevWma = wmaValue;
_initialized = true;
return;
}
var crossUp = _prevSma <= _prevWma && smaValue > wmaValue;
var crossDown = _prevSma >= _prevWma && smaValue < wmaValue;
if (crossUp && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
else if (crossDown && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_prevSma = smaValue;
_prevWma = wmaValue;
}
}
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 SimpleMovingAverage, WeightedMovingAverage
from StockSharp.Algo.Strategies import Strategy
class center_of_gravity_strategy(Strategy):
def __init__(self):
super(center_of_gravity_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for calculation", "General")
self._period = self.Param("Period", 10) \
.SetDisplay("Period", "Center of Gravity averaging period", "Indicators")
self._prev_sma = 0.0
self._prev_wma = 0.0
self._initialized = False
@property
def candle_type(self):
return self._candle_type.Value
@property
def period(self):
return self._period.Value
def OnReseted(self):
super(center_of_gravity_strategy, self).OnReseted()
self._prev_sma = 0.0
self._prev_wma = 0.0
self._initialized = False
def OnStarted2(self, time):
super(center_of_gravity_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = self.period
wma = WeightedMovingAverage()
wma.Length = self.period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, wma, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawIndicator(area, wma)
self.DrawOwnTrades(area)
def process_candle(self, candle, sma_value, wma_value):
if candle.State != CandleStates.Finished:
return
sma_value = float(sma_value)
wma_value = float(wma_value)
if not self._initialized:
self._prev_sma = sma_value
self._prev_wma = wma_value
self._initialized = True
return
cross_up = self._prev_sma <= self._prev_wma and sma_value > wma_value
cross_down = self._prev_sma >= self._prev_wma and sma_value < wma_value
if cross_up and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif cross_down and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_sma = sma_value
self._prev_wma = wma_value
def CreateClone(self):
return center_of_gravity_strategy()