Momentum Percentage 戦略
価格モメンタムの変化率に基づく戦略
テストでは年平均リターンが約97%であることが示されています。暗号資産市場で最もよく機能します。
Momentum Percentageは価格の変化率を追跡します。モメンタムが正または負のレベルを超えると取引が始まり、反対のシグナルまたはボラティリティストップで退場します。
設定されたルックバック期間にわたるリターンを測定することで、システムはさまざまな市場に適応します。ボラティリティストップは、大きな不利な動きが素早く退場することを保証します。
詳細
- エントリー条件: MA、Momentumに基づくシグナル。
- ロング/ショート: 両方向。
- エグジット条件: 逆シグナルまたはストップ。
- ストップ: はい。
- デフォルト値:
MomentumPeriod= 10ThresholdPercent= 5mStopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- フィルター:
- カテゴリ: トレンド
- 方向: 両方
- インジケーター: MA、Momentum
- ストップ: はい
- 複雑さ: 基本
- 時間軸: イントラデイ (5m)
- 季節性: いいえ
- Neural Networks: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Strategy based on price momentum percentage change.
/// Uses percentage RateOfChange with an SMA trend filter and actual-fill percent protection.
/// Trades signed percentage threshold crossings, completely reversing on a counter signal.
/// </summary>
public class MomentumPercentageStrategy : Strategy
{
private readonly StrategyParam<int> _momentumPeriod;
private readonly StrategyParam<int> _smaPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _thresholdPercent;
private readonly StrategyParam<decimal> _stopLossPercent;
private decimal _prevMom;
private bool _hasPrevValues;
private Order _pendingOrder;
/// <summary>
/// Momentum period.
/// </summary>
public int MomentumPeriod
{
get => _momentumPeriod.Value;
set => _momentumPeriod.Value = value;
}
/// <summary>
/// SMA period.
/// </summary>
public int SmaPeriod
{
get => _smaPeriod.Value;
set => _smaPeriod.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public decimal ThresholdPercent { get => _thresholdPercent.Value; set => _thresholdPercent.Value = value; }
public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
/// <summary>
/// Initializes a new instance of the <see cref="MomentumPercentageStrategy"/>.
/// </summary>
public MomentumPercentageStrategy()
{
_momentumPeriod = Param(nameof(MomentumPeriod), 10)
.SetDisplay("Momentum Period", "Period for momentum calculation", "Indicators")
.SetOptimize(8, 20, 4);
_smaPeriod = Param(nameof(SmaPeriod), 20)
.SetDisplay("SMA Period", "Period for SMA trend filter", "Indicators")
.SetOptimize(15, 30, 5);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_thresholdPercent = Param(nameof(ThresholdPercent), 5m).SetGreaterThanZero()
.SetDisplay("Threshold (%)", "Symmetric percentage return breakout level.", "Signal");
_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();
_prevMom = default;
_hasPrevValues = default;
_pendingOrder = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var momentum = new RateOfChange { Length = MomentumPeriod };
var sma = new SimpleMovingAverage { Length = SmaPeriod };
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(momentum, sma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, momentum);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before the callback, including between bars.
}
private void ProcessCandle(ICandleMessage candle, decimal momValue, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (smaValue == 0)
return;
if (!_hasPrevValues)
{
_hasPrevValues = true;
_prevMom = momValue;
return;
}
if (_pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed))
{
_prevMom = momValue;
return;
}
var price = candle.ClosePrice;
// Cross the configured positive percent return with an SMA confirmation.
if (_prevMom <= ThresholdPercent && momValue > ThresholdPercent && price > smaValue && Position <= 0)
{
var volume = Volume + Math.Abs(Position);
BuyMarket(volume);
}
// A confirmed opposite threshold reverses the complete position, not just its default volume.
else if (_prevMom >= -ThresholdPercent && momValue < -ThresholdPercent && price < smaValue && Position >= 0)
{
var volume = Volume + Math.Abs(Position);
SellMarket(volume);
}
_prevMom = momValue;
}
}
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 RateOfChange, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class momentum_percentage_strategy(Strategy):
"""
Signed percentage momentum crossings with SMA confirmation and actual-fill percent protection.
"""
def __init__(self):
super(momentum_percentage_strategy, self).__init__()
self._momentum_period = self.Param("MomentumPeriod", 10).SetDisplay("Momentum Period", "Momentum period", "Indicators")
self._sma_period = self.Param("SmaPeriod", 20).SetDisplay("SMA Period", "SMA trend filter period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Timeframe", "General")
self._threshold_percent = self.Param("ThresholdPercent", 5.0).SetGreaterThanZero() \
.SetDisplay("Threshold (%)", "Symmetric percentage return breakout level.", "Signal")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative() \
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection")
self._prev_mom = 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(momentum_percentage_strategy, self).OnReseted()
self._prev_mom = Decimal.Zero
self._has_prev = False
self._pending_order = None
def OnStarted2(self, time):
super(momentum_percentage_strategy, self).OnStarted2(time)
mom = RateOfChange()
mom.Length = self._momentum_period.Value
sma = SimpleMovingAverage()
sma.Length = self._sma_period.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(mom, sma, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, mom)
self.DrawIndicator(area, sma)
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, mom, sma):
if candle.State != CandleStates.Finished or not self.IsFormedAndOnlineAndAllowTrading():
return
if sma == 0:
return
if not self._has_prev:
self._has_prev = True
self._prev_mom = mom
return
if self._pending_order is not None and self._pending_order.State not in (OrderStates.Done, OrderStates.Failed):
self._prev_mom = mom
return
price = candle.ClosePrice
threshold = Decimal(self._threshold_percent.Value)
if self._prev_mom <= threshold and mom > threshold and price > sma and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif self._prev_mom >= -threshold and mom < -threshold and price < sma and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
self._prev_mom = mom
def CreateClone(self):
return momentum_percentage_strategy()