P-Square Nth Percentile Strategy
Estimates the selected percentile of the source series using the P-Square algorithm. Opens a long position when the value exceeds the upper percentile and a short position when the value falls below the lower percentile.
Parameters
Percentile– percentile to estimate.UseReturns– process returns instead of prices.CandleType– candle data type.
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy using SMA and StandardDeviation as percentile approximation.
/// </summary>
public class PSquareNthPercentileStrategy : Strategy
{
private readonly StrategyParam<int> _length;
private readonly StrategyParam<decimal> _nSigma;
private readonly StrategyParam<DataType> _candleType;
public int Length { get => _length.Value; set => _length.Value = value; }
public decimal NSigma { get => _nSigma.Value; set => _nSigma.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public PSquareNthPercentileStrategy()
{
_length = Param(nameof(Length), 50).SetGreaterThanZero();
_nSigma = Param(nameof(NSigma), 1.5m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = Length };
var stdDev = new StandardDeviation { Length = Length };
var lastSignal = DateTimeOffset.MinValue;
var cooldown = TimeSpan.FromMinutes(360);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, stdDev, (candle, avg, std) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!sma.IsFormed || !stdDev.IsFormed)
return;
if (std <= 0 || candle.OpenTime - lastSignal < cooldown)
return;
var upper = avg + NSigma * std;
var lower = avg - NSigma * std;
if (candle.ClosePrice > upper && Position <= 0)
{
BuyMarket();
lastSignal = candle.OpenTime;
}
else if (candle.ClosePrice < lower && Position >= 0)
{
SellMarket();
lastSignal = candle.OpenTime;
}
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
}
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, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class p_square_nth_percentile_strategy(Strategy):
def __init__(self):
super(p_square_nth_percentile_strategy, self).__init__()
self._length = self.Param("Length", 50) \
.SetGreaterThanZero()
self._n_sigma = self.Param("NSigma", 1.5)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._last_signal_ticks = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(p_square_nth_percentile_strategy, self).OnReseted()
self._last_signal_ticks = 0
def OnStarted2(self, time):
super(p_square_nth_percentile_strategy, self).OnStarted2(time)
self._last_signal_ticks = 0
self._sma = SimpleMovingAverage()
self._sma.Length = self._length.Value
self._std = StandardDeviation()
self._std.Length = self._length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._sma, self._std, self.OnProcess).Start()
def OnProcess(self, candle, avg, std):
if candle.State != CandleStates.Finished:
return
if not self._sma.IsFormed or not self._std.IsFormed:
return
av = float(avg)
sd = float(std)
close = float(candle.ClosePrice)
if sd <= 0:
return
cooldown_ticks = TimeSpan.FromMinutes(360).Ticks
current_ticks = candle.OpenTime.Ticks
if current_ticks - self._last_signal_ticks < cooldown_ticks:
return
ns = float(self._n_sigma.Value)
upper = av + ns * sd
lower = av - ns * sd
if close > upper and self.Position <= 0:
self.BuyMarket()
self._last_signal_ticks = current_ticks
elif close < lower and self.Position >= 0:
self.SellMarket()
self._last_signal_ticks = current_ticks
def CreateClone(self):
return p_square_nth_percentile_strategy()