RSI Laguerre 戦略
Laguerre RSIに基づく戦略
テストでは年平均リターン約109%が示されています。暗号通貨市場で最もパフォーマンスが高くなります。
Laguerre RSIは標準RSIを平滑化してノイズを減らします。この戦略は、Laguerreの値が売られすぎゾーンから上にクロスしたときに買い、買われすぎゾーンから下にクロスしたときに売り、中間レベルに戻ったときにエグジットします。
Laguerreフィルタリングは、通常のRSIシグナルを悩ませる荒れた相場環境を避けるのに役立ちます。この手法は、マイナーな変動を無視しながらイントラデイチャートでの値動みを捉えるのに人気があります。
詳細
- エントリー条件: RSIに基づくシグナル。
- ロング/ショート: 両方。
- エグジット条件: 逆シグナルまたはストップ。
- ストップ: はい。
- デフォルト値:
Gamma= 0.7mStopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- フィルター:
- カテゴリ: トレンド
- 方向: 両方
- インジケーター: RSI
- ストップ: はい
- 複雑さ: 基本
- 時間軸: イントラデイ (5m)
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Native four-stage Laguerre RSI crossings with midpoint exits and actual-fill percent protection.
/// </summary>
public class LaguerreRsiStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _gamma;
private readonly StrategyParam<decimal> _stopLossPercent;
private decimal _prevRsi;
private bool _hasPrevValues;
private Order _pendingOrder;
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public decimal Gamma { get => _gamma.Value; set => _gamma.Value = value; }
public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
/// <summary>
/// Initializes a new instance of the <see cref="LaguerreRsiStrategy"/>.
/// </summary>
public LaguerreRsiStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_gamma = Param(nameof(Gamma), 0.7m).SetRange(0.000001m, 0.999999m)
.SetDisplay("Gamma", "Four-stage Laguerre smoothing coefficient.", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 2m).SetNotNegative()
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection");
OrderRegistering += order => _pendingOrder = order;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType), (Security, DataType.Level1)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevRsi = default;
_hasPrevValues = default;
_pendingOrder = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new LaguerreRSI { Gamma = Gamma };
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, rsi);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// Native protection runs before the callback, including between finished candles.
}
private void ProcessCandle(ICandleMessage candle, decimal rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (!_hasPrevValues)
{
_hasPrevValues = true;
_prevRsi = rsiValue;
return;
}
if (_pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed))
{
_prevRsi = rsiValue;
return;
}
// RSI crosses up from oversold (30) - buy
if (_prevRsi < 30 && rsiValue >= 30 && Position <= 0)
{
var volume = Volume + Math.Abs(Position);
BuyMarket(volume);
}
// RSI crosses down from overbought (70) - sell
else if (_prevRsi > 70 && rsiValue <= 70 && Position >= 0)
{
var volume = Volume + Math.Abs(Position);
SellMarket(volume);
}
else if (Position > 0m && rsiValue >= 50m)
SellMarket(Position);
else if (Position < 0m && rsiValue <= 50m)
BuyMarket(Math.Abs(Position));
_prevRsi = rsiValue;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, OrderStates, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import LaguerreRSI
from StockSharp.Algo.Strategies import Strategy
class laguerre_rsi_strategy(Strategy):
"""
Native four-stage Laguerre RSI with midpoint exits and actual-fill percent protection.
"""
def __init__(self):
super(laguerre_rsi_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Timeframe", "General")
self._gamma = self.Param("Gamma", 0.7).SetRange(0.000001, 0.999999) \
.SetDisplay("Gamma", "Four-stage Laguerre smoothing coefficient.", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative() \
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection")
self._prev_rsi = Decimal.Zero
self._has_prev = False
self._pending_order = None
self.OrderRegistering += self._track_pending
def GetWorkingSecurities(self):
return [(self.Security, self.candle_type), (self.Security, DataType.Level1)]
def _track_pending(self, order):
self._pending_order = order
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(laguerre_rsi_strategy, self).OnReseted()
self._prev_rsi = Decimal.Zero
self._has_prev = False
self._pending_order = None
def OnStarted2(self, time):
super(laguerre_rsi_strategy, self).OnStarted2(time)
rsi = LaguerreRSI()
rsi.Gamma = Decimal(self._gamma.Value)
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# Native protection runs before this callback, including between signal bars.
pass
def _process_candle(self, candle, rsi_val):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
rsi = rsi_val
if not self._has_prev:
self._has_prev = True
self._prev_rsi = rsi
return
if self._pending_order is not None and self._pending_order.State not in (OrderStates.Done, OrderStates.Failed):
self._prev_rsi = rsi
return
if self._prev_rsi < 30 and rsi >= 30 and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif self._prev_rsi > 70 and rsi <= 70 and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
elif self.Position > 0 and rsi >= 50:
self.SellMarket(self.Position)
elif self.Position < 0 and rsi <= 50:
self.BuyMarket(Math.Abs(self.Position))
self._prev_rsi = rsi
def CreateClone(self):
return laguerre_rsi_strategy()