Главная
/
Примеры стратегий
Открыть на GitHub
Стратегия MTF RSI SAR
Стратегия объединяет значения индикатора RSI на четырёх таймфреймах, Parabolic SAR и полосы Боллинджера. Сигналы формируются на 5‑минутных свечах, а старшие периоды служат фильтрами тренда.
Концепция
RSI‑фильтр – RSI на 5, 15, 30 и 60 мин. должны быть выше 50 для лонга или ниже 50 для шорта, что согласует сделку с преобладающим трендом.
Фильтр Parabolic SAR – значения SAR на 5, 15 и 30 мин. должны находиться ниже текущей свечи для покупок и выше для продаж, подтверждая направление движения цены.
Триггер полос Боллинджера – закрытие 5‑минутной свечи выше верхней полосы запускает покупку, ниже нижней полосы – продажу. Полосы Боллинджера задают моменты перекупленности/перепроданности.
Вход и выход – позиция открывается, когда все активированные фильтры указывают в одну сторону. Противоположный сигнал закрывает позицию.
Любой из трёх фильтров можно отключить параметрами, оставив только нужные комбинации.
Параметры
UseRsi – включить фильтр RSI (по умолчанию: true)
UseBollinger – включить триггер полос Боллинджера (по умолчанию: true)
UseSar – включить фильтр Parabolic SAR (по умолчанию: true)
RsiPeriod – период RSI (по умолчанию: 14)
BollingerPeriod – период полос Боллинджера (по умолчанию: 20)
BollingerWidth – ширина полос Боллинджера, множитель стандартного отклонения (по умолчанию: 2)
SarStep – шаг Parabolic SAR (по умолчанию: 0.02)
SarMax – максимальное ускорение Parabolic SAR (по умолчанию: 0.2)
CandleType – базовый таймфрейм свечей, по умолчанию 5 минут
Правила торговли
Лонг : все включённые фильтры дают сигнал на покупку.
Шорт : все включённые фильтры дают сигнал на продажу.
Выход : противоположный сигнал закрывает текущую позицию.
Примечания
Стратегия подписывает 5, 15, 30 и 60‑минутные свечи одного инструмента.
Пример демонстрирует работу многотаймфреймовой фильтрации на высокоуровневом API StockSharp.
Фиксированные стоп‑лоссы и тейк‑профиты не предусмотрены; при необходимости добавьте управление рисками отдельно.
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>
/// RSI and Parabolic SAR strategy.
/// Buys when RSI below oversold and SAR below price; sells on opposite.
/// </summary>
public class MtfRsiSarStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _rsiOversold;
private readonly StrategyParam<decimal> _rsiOverbought;
private readonly StrategyParam<DataType> _candleType;
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
public decimal RsiOversold { get => _rsiOversold.Value; set => _rsiOversold.Value = value; }
public decimal RsiOverbought { get => _rsiOverbought.Value; set => _rsiOverbought.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public MtfRsiSarStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI period", "Indicators");
_rsiOversold = Param(nameof(RsiOversold), 35m)
.SetDisplay("RSI Oversold", "RSI oversold level", "Indicators");
_rsiOverbought = Param(nameof(RsiOverbought), 65m)
.SetDisplay("RSI Overbought", "RSI overbought level", "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 OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var sar = new ParabolicSar();
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, sar, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal rsi, decimal sar)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
// Buy: RSI oversold + SAR below price
if (rsi < RsiOversold && sar < close)
{
if (Position < 0)
BuyMarket();
if (Position <= 0)
BuyMarket();
}
// Sell: RSI overbought + SAR above price
else if (rsi > RsiOverbought && sar > close)
{
if (Position > 0)
SellMarket();
if (Position >= 0)
SellMarket();
}
// Exit long when RSI overbought
else if (Position > 0 && rsi > RsiOverbought)
{
SellMarket();
}
// Exit short when RSI oversold
else if (Position < 0 && rsi < RsiOversold)
{
BuyMarket();
}
}
}
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 ParabolicSar, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class mtf_rsi_sar_strategy(Strategy):
def __init__(self):
super(mtf_rsi_sar_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI period", "Indicators")
self._rsi_oversold = self.Param("RsiOversold", 35.0) \
.SetDisplay("RSI Oversold", "RSI oversold level", "Indicators")
self._rsi_overbought = self.Param("RsiOverbought", 65.0) \
.SetDisplay("RSI Overbought", "RSI overbought level", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def rsi_oversold(self):
return self._rsi_oversold.Value
@property
def rsi_overbought(self):
return self._rsi_overbought.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(mtf_rsi_sar_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
sar = ParabolicSar()
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, sar, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, rsi, sar):
if candle.State != CandleStates.Finished:
return
close = candle.ClosePrice
# Buy: RSI oversold + SAR below price
if rsi < self.rsi_oversold and sar < close:
if self.Position < 0:
self.BuyMarket()
if self.Position <= 0:
self.BuyMarket()
# Sell: RSI overbought + SAR above price
elif rsi > self.rsi_overbought and sar > close:
if self.Position > 0:
self.SellMarket()
if self.Position >= 0:
self.SellMarket()
# Exit long when RSI overbought
elif self.Position > 0 and rsi > self.rsi_overbought:
self.SellMarket()
# Exit short when RSI oversold
elif self.Position < 0 and rsi < self.rsi_oversold:
self.BuyMarket()
def CreateClone(self):
return mtf_rsi_sar_strategy()