Стратегия Momentum Candle Sign
Стратегия торгует на пересечении двух значений индикатора Momentum: рассчитанного по ценам открытия свечей и по ценам закрытия. Когда momentum цены открытия опускается ниже momentum цены закрытия, возникает бычий сигнал и открывается длинная позиция. Обратное пересечение указывает на медвежье давление и инициирует короткую позицию.
По умолчанию стратегия работает на 12‑часовых свечах с периодом Momentum 12.
Детали
- Условия входа:
- Покупка: Momentum открытия пересекает снизу Momentum закрытия.
- Продажа: Momentum открытия пересекает сверху Momentum закрытия.
- Длинные/короткие: Оба направления.
- Условия выхода: Обратное пересечение.
- Стопы: Нет.
- Фильтры: Отсутствуют.
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy based on crossover between momentum calculated on candle open and close prices.
/// A long position is opened when open momentum crosses below close momentum, and a short position on the opposite cross.
/// </summary>
public class MomentumCandleSignStrategy : Strategy
{
private readonly StrategyParam<int> _momentumPeriod;
private readonly StrategyParam<DataType> _candleType;
private Momentum _openMomentum;
private Momentum _closeMomentum;
private decimal _prevOpenMomentum;
private decimal _prevCloseMomentum;
private bool _isFormed;
/// <summary>
/// Period of the momentum indicators.
/// </summary>
public int MomentumPeriod
{
get => _momentumPeriod.Value;
set => _momentumPeriod.Value = value;
}
/// <summary>
/// Type of candles to process.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="MomentumCandleSignStrategy"/>.
/// </summary>
public MomentumCandleSignStrategy()
{
_momentumPeriod = Param(nameof(MomentumPeriod), 12)
.SetDisplay("Momentum Period", "Indicator period", "General")
;
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Time frame of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_openMomentum = default;
_closeMomentum = default;
_prevOpenMomentum = 0;
_prevCloseMomentum = 0;
_isFormed = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_openMomentum = new Momentum { Length = MomentumPeriod };
_closeMomentum = new Momentum { Length = MomentumPeriod };
_isFormed = false;
Indicators.Add(_openMomentum);
Indicators.Add(_closeMomentum);
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ProcessCandle).Start();
StartProtection(null, null);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _openMomentum);
DrawIndicator(area, _closeMomentum);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var openMom = _openMomentum.Process(new DecimalIndicatorValue(_openMomentum, candle.OpenPrice, candle.OpenTime) { IsFinal = true }).ToDecimal();
var closeMom = _closeMomentum.Process(new DecimalIndicatorValue(_closeMomentum, candle.ClosePrice, candle.OpenTime) { IsFinal = true }).ToDecimal();
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (!_isFormed)
{
_prevOpenMomentum = openMom;
_prevCloseMomentum = closeMom;
_isFormed = true;
return;
}
var buySignal = _prevOpenMomentum >= _prevCloseMomentum && openMom < closeMom;
var sellSignal = _prevOpenMomentum <= _prevCloseMomentum && openMom > closeMom;
if (buySignal && Position <= 0)
BuyMarket();
else if (sellSignal && Position >= 0)
SellMarket();
_prevOpenMomentum = openMom;
_prevCloseMomentum = closeMom;
}
}
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 Momentum
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class momentum_candle_sign_strategy(Strategy):
def __init__(self):
super(momentum_candle_sign_strategy, self).__init__()
self._momentum_period = self.Param("MomentumPeriod", 12) \
.SetDisplay("Momentum Period", "Indicator period", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Time frame of candles", "General")
self._open_momentum = None
self._close_momentum = None
self._prev_open_momentum = 0.0
self._prev_close_momentum = 0.0
self._is_formed = False
@property
def momentum_period(self):
return self._momentum_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(momentum_candle_sign_strategy, self).OnReseted()
self._open_momentum = None
self._close_momentum = None
self._prev_open_momentum = 0.0
self._prev_close_momentum = 0.0
self._is_formed = False
def OnStarted2(self, time):
super(momentum_candle_sign_strategy, self).OnStarted2(time)
self._open_momentum = Momentum()
self._open_momentum.Length = self.momentum_period
self._close_momentum = Momentum()
self._close_momentum.Length = self.momentum_period
self._is_formed = False
self.Indicators.Add(self._open_momentum)
self.Indicators.Add(self._close_momentum)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._open_momentum)
self.DrawIndicator(area, self._close_momentum)
self.DrawOwnTrades(area)
def process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
open_mom = float(process_float(self._open_momentum, candle.OpenPrice, candle.OpenTime, True))
close_mom = float(process_float(self._close_momentum, candle.ClosePrice, candle.OpenTime, True))
if not self._is_formed:
self._prev_open_momentum = open_mom
self._prev_close_momentum = close_mom
self._is_formed = True
return
buy_signal = self._prev_open_momentum >= self._prev_close_momentum and open_mom < close_mom
sell_signal = self._prev_open_momentum <= self._prev_close_momentum and open_mom > close_mom
if buy_signal and self.Position <= 0:
self.BuyMarket()
elif sell_signal and self.Position >= 0:
self.SellMarket()
self._prev_open_momentum = open_mom
self._prev_close_momentum = close_mom
def CreateClone(self):
return momentum_candle_sign_strategy()