feat: add new indicators (Decay, Edecay, MinusDi, MinusDm, PlusDi, PlusDm, Maxindex, Minindex, Sarext) and update pine scripts, core libs, validation tests, and python bindings

This commit is contained in:
Miha Kralj
2026-03-09 13:45:46 -07:00
parent 8e43d62cbb
commit 031f1b5fe6
491 changed files with 6156 additions and 5590 deletions
+1
View File
@@ -16,5 +16,6 @@ Reversal indicators identify potential turning points where price may change dir
| [PIVOTFIB](pivotfib/Pivotfib.md) | Fibonacci Pivot Points | Fibonacci-ratio based pivots; Golden Ratio (61.8%) at R2/S2. |
| [PIVOTWOOD](pivotwood/Pivotwood.md) | Woodie's Pivot Points | Weighted close pivots (2× close weight) for intraday trading. |
| [PSAR](psar/Psar.md) | Parabolic Stop And Reverse | Trailing stop that accelerates with trend; SAR dots mark entry/exit signals. |
| [SAREXT](sarext/Sarext.md) | Parabolic SAR Extended | PSAR with asymmetric long/short acceleration factors. Sign-encoded output. |
| [SWINGS](swings/Swings.md) | Swing High/Low Detection | Configurable-lookback pattern detector for swing highs/lows; dual SwingHigh/SwingLow. |
| [TTM_SCALPER](ttm_scalper/TtmScalper.md) | TTM Scalper Alert | 3-bar pivot high/low detection for scalping entries. John Carter. |
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Williams Fractals", "FRACTALS", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Pivot Points (Classic)", "PIVOT", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Pivot Points (Camarilla)", "PIVOTCAM", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Pivot Points (DeMark)", "PIVOTDEM", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Pivot Points (Extended)", "PIVOTEXT", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Pivot Points (Fibonacci)", "PIVOTFIB", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Pivot Points (Woodie)", "PIVOTWOOD", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Parabolic SAR", "PSAR", overlay=true)
+658
View File
@@ -0,0 +1,658 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// SAREXT: Parabolic SAR Extended (TA-Lib)
/// </summary>
/// <remarks>
/// Extended Parabolic Stop And Reverse with asymmetric acceleration factors.
/// Separate AF initialization, increment, and maximum for long vs short positions.
/// Sign-encoded output: positive = long (SAR below price), negative = short (SAR above price).
///
/// Calculation extends Wilder's PSAR:
/// <code>
/// Long: SAR = SAR + AF_long × (EP - SAR), output = +SAR
/// Short: SAR = SAR + AF_short × (EP - SAR), output = -SAR
///
/// Bar 0: Collect OHLC data
/// Bar 1: Determine direction from startValue or DM auto-detect
/// Bar 2+: Standard SAR state machine with asymmetric AF parameters
/// </code>
///
/// <b>Key characteristics:</b>
/// - O(1) per-bar state machine with long/short mode transitions
/// - Asymmetric acceleration factors for long and short positions
/// - startValue parameter forces initial direction (0 = auto-detect from DM)
/// - offsetOnReverse adds gap buffer on trend reversal
/// - Sign-encoded output matches TA-Lib SAREXT convention
/// - Default parameters: afInitLong/Short=0.02, afLong/Short=0.02, afMaxLong/Short=0.20
/// </remarks>
/// <seealso href="Sarext.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Sarext : ITValuePublisher
{
private const double DefaultStartValue = 0;
private const double DefaultOffsetOnReverse = 0;
private const double DefaultAfInitLong = 0.02;
private const double DefaultAfLong = 0.02;
private const double DefaultAfMaxLong = 0.20;
private const double DefaultAfInitShort = 0.02;
private const double DefaultAfShort = 0.02;
private const double DefaultAfMaxShort = 0.20;
private readonly double _startValue;
private readonly double _offsetOnReverse;
private readonly double _afInitLong;
private readonly double _afLong;
private readonly double _afMaxLong;
private readonly double _afInitShort;
private readonly double _afShort;
private readonly double _afMaxShort;
private int _samples;
private int _p_samples;
[StructLayout(LayoutKind.Auto)]
private record struct State(
bool IsLong,
double Sar,
double Ep,
double Af,
double Prev1High,
double Prev1Low,
double Prev2High,
double Prev2Low,
double LastValidOpen,
double LastValidHigh,
double LastValidLow,
double LastValidClose);
private State _s;
private State _ps;
private readonly TBarPublishedHandler _barHandler;
/// <summary>Display name for the indicator.</summary>
public string Name { get; }
/// <summary>Bars required for the indicator to warm up.</summary>
public int WarmupPeriod { get; }
/// <summary>Current SAR value (unsigned).</summary>
public double Sar => _s.Sar;
/// <summary>True when the SAREXT is in long (uptrend) mode.</summary>
public bool IsLong => _s.IsLong;
/// <summary>Primary output value (sign-encoded SAR: positive = long, negative = short).</summary>
public TValue Last { get; private set; }
/// <summary>True when enough bars have been processed for valid output.</summary>
public bool IsHot => _samples >= 2;
/// <inheritdoc />
public event TValuePublishedHandler? Pub;
/// <summary>
/// Creates a Parabolic SAR Extended indicator.
/// </summary>
/// <param name="startValue">Initial direction: positive = long, negative = short, 0 = auto-detect from DM.</param>
/// <param name="offsetOnReverse">Gap added to SAR on reversal (default 0).</param>
/// <param name="afInitLong">Initial acceleration factor for long positions (default 0.02).</param>
/// <param name="afLong">AF increment per new EP in long positions (default 0.02).</param>
/// <param name="afMaxLong">Maximum AF for long positions (default 0.20).</param>
/// <param name="afInitShort">Initial acceleration factor for short positions (default 0.02).</param>
/// <param name="afShort">AF increment per new EP in short positions (default 0.02).</param>
/// <param name="afMaxShort">Maximum AF for short positions (default 0.20).</param>
public Sarext(
double startValue = DefaultStartValue,
double offsetOnReverse = DefaultOffsetOnReverse,
double afInitLong = DefaultAfInitLong,
double afLong = DefaultAfLong,
double afMaxLong = DefaultAfMaxLong,
double afInitShort = DefaultAfInitShort,
double afShort = DefaultAfShort,
double afMaxShort = DefaultAfMaxShort)
{
if (afInitLong <= 0)
{
throw new ArgumentException("afInitLong must be > 0.", nameof(afInitLong));
}
if (afLong <= 0)
{
throw new ArgumentException("afLong must be > 0.", nameof(afLong));
}
if (afMaxLong <= afInitLong)
{
throw new ArgumentException("afMaxLong must be > afInitLong.", nameof(afMaxLong));
}
if (afInitShort <= 0)
{
throw new ArgumentException("afInitShort must be > 0.", nameof(afInitShort));
}
if (afShort <= 0)
{
throw new ArgumentException("afShort must be > 0.", nameof(afShort));
}
if (afMaxShort <= afInitShort)
{
throw new ArgumentException("afMaxShort must be > afInitShort.", nameof(afMaxShort));
}
if (offsetOnReverse < 0)
{
throw new ArgumentException("offsetOnReverse must be >= 0.", nameof(offsetOnReverse));
}
_startValue = startValue;
_offsetOnReverse = offsetOnReverse;
_afInitLong = afInitLong;
_afLong = afLong;
_afMaxLong = afMaxLong;
_afInitShort = afInitShort;
_afShort = afShort;
_afMaxShort = afMaxShort;
_samples = 0;
_p_samples = 0;
_s = new State(
IsLong: true,
Sar: double.NaN,
Ep: double.NaN,
Af: afInitLong,
Prev1High: double.NaN,
Prev1Low: double.NaN,
Prev2High: double.NaN,
Prev2Low: double.NaN,
LastValidOpen: double.NaN,
LastValidHigh: double.NaN,
LastValidLow: double.NaN,
LastValidClose: double.NaN);
_ps = _s;
Name = "Sarext";
WarmupPeriod = 2;
_barHandler = HandleBar;
}
/// <summary>
/// Creates a SAREXT indicator chained to a TBarSeries source.
/// </summary>
public Sarext(TBarSeries source,
double startValue = DefaultStartValue,
double offsetOnReverse = DefaultOffsetOnReverse,
double afInitLong = DefaultAfInitLong,
double afLong = DefaultAfLong,
double afMaxLong = DefaultAfMaxLong,
double afInitShort = DefaultAfInitShort,
double afShort = DefaultAfShort,
double afMaxShort = DefaultAfMaxShort)
: this(startValue, offsetOnReverse, afInitLong, afLong, afMaxLong, afInitShort, afShort, afMaxShort)
{
Prime(source);
source.Pub += _barHandler;
}
private void HandleBar(object? sender, in TBarEventArgs e) => Update(e.Value, e.IsNew);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void PubEvent(TValue value, bool isNew = true) =>
Pub?.Invoke(this, new TValueEventArgs { Value = value, IsNew = isNew });
/// <summary>
/// Updates the SAREXT with a new OHLC bar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TBar input, bool isNew = true)
{
if (isNew)
{
_ps = _s;
_p_samples = _samples;
_samples++;
}
else
{
_s = _ps;
_samples = _p_samples + 1;
}
var s = _s;
// Validate inputs — substitute last-valid on NaN/Infinity
double open = input.Open;
double high = input.High;
double low = input.Low;
double close = input.Close;
if (double.IsFinite(open)) { s.LastValidOpen = open; }
else { open = s.LastValidOpen; }
if (double.IsFinite(high)) { s.LastValidHigh = high; }
else { high = s.LastValidHigh; }
if (double.IsFinite(low)) { s.LastValidLow = low; }
else { low = s.LastValidLow; }
if (double.IsFinite(close)) { s.LastValidClose = close; }
else { close = s.LastValidClose; }
// If still no valid data, return NaN
if (double.IsNaN(open) || double.IsNaN(high) || double.IsNaN(low) || double.IsNaN(close))
{
_s = s;
Last = new TValue(input.Time, double.NaN);
PubEvent(Last, isNew);
return Last;
}
double sarResult;
if (_samples == 1)
{
// Bar 0: Collect first bar's OHLC, no output yet
s.Prev1High = high;
s.Prev1Low = low;
s.Prev2High = high;
s.Prev2Low = low;
s.LastValidOpen = open;
s.LastValidHigh = high;
s.LastValidLow = low;
s.LastValidClose = close;
// Tentative initialization — will be finalized on bar 1
s.Sar = high;
s.Ep = low;
s.Af = _afInitShort;
s.IsLong = false;
_s = s;
Last = new TValue(input.Time, double.NaN);
PubEvent(Last, isNew);
return Last;
}
else if (_samples == 2)
{
// Bar 1: Determine initial direction
double prevHigh = s.Prev1High;
double prevLow = s.Prev1Low;
if (_startValue > 0)
{
// Force long
s.IsLong = true;
s.Sar = Math.Min(prevLow, low);
s.Ep = Math.Max(prevHigh, high);
s.Af = _afInitLong;
}
else if (_startValue < 0)
{
// Force short
s.IsLong = false;
s.Sar = Math.Max(prevHigh, high);
s.Ep = Math.Min(prevLow, low);
s.Af = _afInitShort;
}
else
{
// Auto-detect from DM: compare plusDM vs minusDM
double plusDM = high - prevHigh;
double minusDM = prevLow - low;
if (plusDM > minusDM && plusDM > 0)
{
// Long
s.IsLong = true;
s.Sar = Math.Min(prevLow, low);
s.Ep = Math.Max(prevHigh, high);
s.Af = _afInitLong;
}
else
{
// Short (default when equal or minusDM dominates)
s.IsLong = false;
s.Sar = Math.Max(prevHigh, high);
s.Ep = Math.Min(prevLow, low);
s.Af = _afInitShort;
}
}
sarResult = s.Sar;
// Update prev-bar tracking
s.Prev2High = s.Prev1High;
s.Prev2Low = s.Prev1Low;
s.Prev1High = high;
s.Prev1Low = low;
_s = s;
double output = s.IsLong ? sarResult : -sarResult;
Last = new TValue(input.Time, output);
PubEvent(Last, isNew);
return Last;
}
// Bar 2+: Standard SAR state machine with asymmetric AF
// Compute new SAR using FMA: sar + af * (ep - sar)
double newSar = Math.FusedMultiplyAdd(s.Af, s.Ep - s.Sar, s.Sar);
if (s.IsLong)
{
// Long mode: SAR must be at or below prior two bars' lows
newSar = Math.Min(newSar, s.Prev1Low);
newSar = Math.Min(newSar, s.Prev2Low);
// Check for reversal: price crosses below SAR
if (low <= newSar)
{
// Reverse to short
s.IsLong = false;
newSar = s.Ep + _offsetOnReverse;
s.Ep = low;
s.Af = _afInitShort;
}
else
{
// Check for new extreme point (new high)
if (high > s.Ep)
{
s.Ep = high;
s.Af = Math.Min(s.Af + _afLong, _afMaxLong);
}
}
}
else
{
// Short mode: SAR must be at or above prior two bars' highs
newSar = Math.Max(newSar, s.Prev1High);
newSar = Math.Max(newSar, s.Prev2High);
// Check for reversal: price crosses above SAR
if (high >= newSar)
{
// Reverse to long
s.IsLong = true;
newSar = s.Ep - _offsetOnReverse;
s.Ep = high;
s.Af = _afInitLong;
}
else
{
// Check for new extreme point (new low)
if (low < s.Ep)
{
s.Ep = low;
s.Af = Math.Min(s.Af + _afShort, _afMaxShort);
}
}
}
s.Sar = newSar;
sarResult = newSar;
// Shift prior bar tracking
if (isNew)
{
s.Prev2High = s.Prev1High;
s.Prev2Low = s.Prev1Low;
s.Prev1High = high;
s.Prev1Low = low;
}
else
{
// Bar correction: update current bar's values
s.Prev1High = high;
s.Prev1Low = low;
}
_s = s;
double signedResult = s.IsLong ? sarResult : -sarResult;
Last = new TValue(input.Time, signedResult);
PubEvent(Last, isNew);
return Last;
}
/// <summary>
/// Updates the SAREXT with a TValue (uses value as OHLC proxy).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true) =>
Update(new TBar(input.Time, input.Value, input.Value, input.Value, input.Value, 0), isNew);
/// <summary>
/// Processes a full TBarSeries and returns sign-encoded SAREXT output.
/// </summary>
public TSeries Update(TBarSeries source)
{
if (source.Count == 0)
{
return new TSeries([], []);
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
Batch(source.OpenValues, source.HighValues, source.LowValues, source.CloseValues,
CollectionsMarshal.AsSpan(v), len,
_startValue, _offsetOnReverse,
_afInitLong, _afLong, _afMaxLong,
_afInitShort, _afShort, _afMaxShort);
source.Times.CopyTo(CollectionsMarshal.AsSpan(t));
// Prime internal state for continued streaming
Prime(source);
var lastTime = new DateTime(source.Times[^1], DateTimeKind.Utc);
Last = new TValue(lastTime, CollectionsMarshal.AsSpan(v)[^1]);
return new TSeries(t, v);
}
/// <summary>
/// Primes the indicator from a TBarSeries (replays all bars to set state).
/// </summary>
public void Prime(TBarSeries source)
{
Reset();
if (source.Count == 0)
{
return;
}
for (int i = 0; i < source.Count; i++)
{
Update(source[i], isNew: true);
}
}
/// <summary>
/// Primes the indicator from a span of doubles (uses each value as OHLC proxy).
/// </summary>
public void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
Reset();
if (source.Length == 0)
{
return;
}
long t = DateTime.UtcNow.Ticks;
long stepTicks = (step ?? TimeSpan.FromMinutes(1)).Ticks;
for (int i = 0; i < source.Length; i++)
{
double val = source[i];
Update(new TBar(t, val, val, val, val, 0), isNew: true);
t += stepTicks;
}
}
/// <summary>
/// Resets the indicator to its initial state.
/// </summary>
public void Reset()
{
_samples = 0;
_p_samples = 0;
_s = new State(
IsLong: true,
Sar: double.NaN,
Ep: double.NaN,
Af: _afInitLong,
Prev1High: double.NaN,
Prev1Low: double.NaN,
Prev2High: double.NaN,
Prev2Low: double.NaN,
LastValidOpen: double.NaN,
LastValidHigh: double.NaN,
LastValidLow: double.NaN,
LastValidClose: double.NaN);
_ps = _s;
Last = default;
}
/// <summary>
/// Span-based batch computation of SAREXT.
/// </summary>
/// <param name="open">Input open prices.</param>
/// <param name="high">Input high prices.</param>
/// <param name="low">Input low prices.</param>
/// <param name="close">Input close prices.</param>
/// <param name="output">Output span for sign-encoded SAR values.</param>
/// <param name="n">Number of bars to process.</param>
/// <param name="startValue">Initial direction: positive = long, negative = short, 0 = auto-detect.</param>
/// <param name="offsetOnReverse">Gap added to SAR on reversal.</param>
/// <param name="afInitLong">Initial AF for long positions.</param>
/// <param name="afLong">AF increment for long positions.</param>
/// <param name="afMaxLong">Maximum AF for long positions.</param>
/// <param name="afInitShort">Initial AF for short positions.</param>
/// <param name="afShort">AF increment for short positions.</param>
/// <param name="afMaxShort">Maximum AF for short positions.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(
ReadOnlySpan<double> open,
ReadOnlySpan<double> high,
ReadOnlySpan<double> low,
ReadOnlySpan<double> close,
Span<double> output,
int n,
double startValue = DefaultStartValue,
double offsetOnReverse = DefaultOffsetOnReverse,
double afInitLong = DefaultAfInitLong,
double afLong = DefaultAfLong,
double afMaxLong = DefaultAfMaxLong,
double afInitShort = DefaultAfInitShort,
double afShort = DefaultAfShort,
double afMaxShort = DefaultAfMaxShort)
{
if (afInitLong <= 0 || afInitLong >= afMaxLong)
{
throw new ArgumentException("afInitLong must be > 0 and < afMaxLong.", nameof(afInitLong));
}
if (afLong <= 0)
{
throw new ArgumentException("afLong must be > 0.", nameof(afLong));
}
if (afInitShort <= 0 || afInitShort >= afMaxShort)
{
throw new ArgumentException("afInitShort must be > 0 and < afMaxShort.", nameof(afInitShort));
}
if (afShort <= 0)
{
throw new ArgumentException("afShort must be > 0.", nameof(afShort));
}
if (high.Length != low.Length || high.Length != close.Length || high.Length != open.Length)
{
throw new ArgumentException("Input spans must have the same length.", nameof(high));
}
if (output.Length < n)
{
throw new ArgumentException("Output span must be at least n elements.", nameof(output));
}
if (n == 0)
{
return;
}
// State machine prevents SIMD — compute via streaming instance
var indicator = new Sarext(startValue, offsetOnReverse,
afInitLong, afLong, afMaxLong, afInitShort, afShort, afMaxShort);
long baseTime = DateTime.UtcNow.Ticks;
for (int i = 0; i < n; i++)
{
_ = indicator.Update(
new TBar(baseTime + i, open[i], high[i], low[i], close[i], 0),
isNew: true);
output[i] = indicator.Last.Value;
}
}
/// <summary>
/// Batch computation from a TBarSeries.
/// </summary>
public static TSeries Batch(
TBarSeries source,
double startValue = DefaultStartValue,
double offsetOnReverse = DefaultOffsetOnReverse,
double afInitLong = DefaultAfInitLong,
double afLong = DefaultAfLong,
double afMaxLong = DefaultAfMaxLong,
double afInitShort = DefaultAfInitShort,
double afShort = DefaultAfShort,
double afMaxShort = DefaultAfMaxShort)
{
if (source == null || source.Count == 0)
{
return new TSeries([], []);
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
Batch(source.OpenValues, source.HighValues, source.LowValues, source.CloseValues,
CollectionsMarshal.AsSpan(v), len,
startValue, offsetOnReverse,
afInitLong, afLong, afMaxLong,
afInitShort, afShort, afMaxShort);
source.Times.CopyTo(CollectionsMarshal.AsSpan(t));
return new TSeries(t, v);
}
/// <summary>
/// Calculates SAREXT and returns both the result series and the primed indicator.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static (TSeries Results, Sarext Indicator) Calculate(
TBarSeries source,
double startValue = DefaultStartValue,
double offsetOnReverse = DefaultOffsetOnReverse,
double afInitLong = DefaultAfInitLong,
double afLong = DefaultAfLong,
double afMaxLong = DefaultAfMaxLong,
double afInitShort = DefaultAfInitShort,
double afShort = DefaultAfShort,
double afMaxShort = DefaultAfMaxShort)
{
var indicator = new Sarext(startValue, offsetOnReverse,
afInitLong, afLong, afMaxLong, afInitShort, afShort, afMaxShort);
var results = indicator.Update(source);
return (results, indicator);
}
}
+177
View File
@@ -0,0 +1,177 @@
# SAREXT: Parabolic SAR Extended
| Property | Value |
| ---------------- | -------------------------------- |
| **Category** | Reversal |
| **Inputs** | OHLCV bar (TBar) |
| **Parameters** | `startValue` (0), `offsetOnReverse` (0), `afInitLong` (0.02), `afLong` (0.02), `afMaxLong` (0.20), `afInitShort` (0.02), `afShort` (0.02), `afMaxShort` (0.20) |
| **Outputs** | Single series (sign-encoded SAR) |
| **Output range** | ±price level (positive = long, negative = short) |
| **Warmup** | `2` bars |
### TL;DR
- Extended Parabolic SAR with **asymmetric acceleration factors** for long and short positions.
- Sign-encoded output: positive = long (SAR below price), negative = short (SAR above price).
- Matches TA-Lib `TA_SAREXT` specification with 8 parameters.
- Auto-detects initial direction from Directional Movement when `startValue == 0`.
- Requires `2` bars of warmup before first valid output (IsHot = true).
- Validated against TA-Lib reference implementation.
> "The trend is your friend — but which way it accelerates depends on whether you're long or short." — QuanTAlib
## Introduction
The Parabolic SAR Extended (SAREXT) is an enhanced version of Wilder's Parabolic Stop And Reverse that allows **separate acceleration factor configurations for long and short positions**. While standard PSAR uses the same AF start, increment, and maximum for both trend directions, SAREXT provides six independent AF parameters (three for long, three for short), plus a `startValue` to force initial direction and `offsetOnReverse` to add a gap buffer when the indicator reverses.
This design makes SAREXT suitable for markets where bullish and bearish trends have different characteristics — for example, equity markets where rallies tend to be gradual (lower AF) and selloffs tend to be sharp (higher AF).
## Historical Context
SAREXT originates from the TA-Lib open-source technical analysis library, where it appears as `TA_SAREXT`. It extends Wilder's original 1978 PSAR with asymmetric parameters, addressing a common criticism: that markets don't behave symmetrically in both directions. The TA-Lib implementation adds the `startValue` parameter for deterministic initialization (useful in backtesting) and `offsetOnReverse` for creating a buffer zone that reduces whipsaw on reversals.
## Architecture and Physics
### 1. State Machine
SAREXT operates as a two-state machine identical to PSAR: **Long** (uptrend) and **Short** (downtrend). Each state tracks:
- **SAR**: Current stop level
- **EP** (Extreme Point): Highest high in long mode, lowest low in short mode
- **AF** (Acceleration Factor): Uses direction-specific parameters
### 2. Initialization (Bars 01)
| Bar | Action |
|-----|--------|
| Bar 0 | Collect first OHLC data, no output |
| Bar 1 | Determine direction: `startValue > 0` → long, `startValue < 0` → short, `startValue == 0` → auto-detect from DM |
**Auto-detection**: Compares plusDM (High[1] - High[0]) vs minusDM (Low[0] - Low[1]). If plusDM > minusDM and plusDM > 0, start long; otherwise start short.
### 3. SAR Update Rule (Asymmetric)
**Long mode:**
$$\text{SAR}_{t} = \text{SAR}_{t-1} + \text{AF}_{\text{long}} \times (\text{EP} - \text{SAR}_{t-1})$$
**Short mode:**
$$\text{SAR}_{t} = \text{SAR}_{t-1} + \text{AF}_{\text{short}} \times (\text{EP} - \text{SAR}_{t-1})$$
Both computed using `Math.FusedMultiplyAdd` for numerical precision.
### 4. SAR Clamping
Identical to PSAR:
- Long: $\text{SAR}_{t} = \min(\text{SAR}_{t}, \text{Low}_{t-1}, \text{Low}_{t-2})$
- Short: $\text{SAR}_{t} = \max(\text{SAR}_{t}, \text{High}_{t-1}, \text{High}_{t-2})$
### 5. Reversal Detection with Offset
- **Long → Short**: When $\text{Low}_t \leq \text{SAR}_t$:
- $\text{SAR} = \text{EP} + \text{offsetOnReverse}$
- $\text{EP} = \text{Low}_t$, $\text{AF} = \text{afInitShort}$
- **Short → Long**: When $\text{High}_t \geq \text{SAR}_t$:
- $\text{SAR} = \text{EP} - \text{offsetOnReverse}$
- $\text{EP} = \text{High}_t$, $\text{AF} = \text{afInitLong}$
### 6. EP/AF Update (No Reversal)
- Long: if $\text{High}_t > \text{EP}$, then $\text{EP} = \text{High}$, $\text{AF} = \min(\text{AF} + \text{afLong}, \text{afMaxLong})$
- Short: if $\text{Low}_t < \text{EP}$, then $\text{EP} = \text{Low}$, $\text{AF} = \min(\text{AF} + \text{afShort}, \text{afMaxShort})$
### 7. Sign-Encoded Output
$$\text{output} = \begin{cases} +\text{SAR} & \text{if long (SAR below price)} \\ -\text{SAR} & \text{if short (SAR above price)} \end{cases}$$
## Mathematical Foundation
The SAR update is a first-order IIR filter with time-varying, direction-dependent coefficient:
$$y_t = y_{t-1} + \alpha_t^{(d)} (x^* - y_{t-1})$$
where $d \in \{\text{long}, \text{short}\}$ selects the parameter set. The asymmetric AF progression:
$$\text{AF}_t^{(\text{long})} = \min(\text{afInitLong} + n_{\text{long}} \times \text{afLong}, \text{afMaxLong})$$
$$\text{AF}_t^{(\text{short})} = \min(\text{afInitShort} + n_{\text{short}} \times \text{afShort}, \text{afMaxShort})$$
### Parameter Reference
| Parameter | Default | Effect |
|-----------|---------|--------|
| startValue | 0 | Initial direction: >0 long, <0 short, 0 auto-detect |
| offsetOnReverse | 0 | Gap added to SAR on reversal (reduces whipsaw) |
| afInitLong | 0.02 | Initial AF for long positions |
| afLong | 0.02 | AF increment per new high in long mode |
| afMaxLong | 0.20 | Maximum AF for long positions |
| afInitShort | 0.02 | Initial AF for short positions |
| afShort | 0.02 | AF increment per new low in short mode |
| afMaxShort | 0.20 | Maximum AF for short positions |
## Performance Profile
### Operation Count (Streaming Mode)
SAREXT is O(1) per bar — identical to PSAR with minor overhead for parameter selection.
| Operation | Count | Cost (cycles) | Subtotal |
| :--- | :---: | :---: | :---: |
| Direction check + param select | 1 | 3 cy | ~3 cy |
| EP (extreme point) update | 1 | 2 cy | ~2 cy |
| AF increment (conditional) | 1 | 2 cy | ~2 cy |
| SAR = SAR + AF*(EP - SAR) via FMA | 1 | 1 cy | ~1 cy |
| Reversal detection + offset | 1 | 4 cy | ~4 cy |
| Sign encoding + state update | 1 | 2 cy | ~2 cy |
| **Total** | **O(1)** | — | **~14 cy** |
| Operation | Complexity | Notes |
|-----------|-----------|-------|
| Update (streaming) | O(1) | State machine: constant work per bar |
| Batch (span) | O(n) | Sequential state machine (no SIMD possible) |
| Memory | O(1) | Fixed state: 12 doubles + 1 bool |
| Warmup | 2 bars | Bar 0 collects data, bar 1 determines direction |
### SIMD Analysis
SAREXT cannot be vectorized. The state machine has data-dependent branches (reversal detection, direction-specific AF selection) and sequential dependencies. The Batch API delegates to streaming for correctness.
### Quality Metrics (110 Scale)
| Metric | Score | Rationale |
|--------|-------|-----------|
| Trend detection | 7 | Same as PSAR; asymmetric AF can reduce false reversals |
| Responsiveness | 9 | Independent AF tuning per direction improves adaptability |
| False signals | 6 | offsetOnReverse helps reduce whipsaw vs standard PSAR |
| Flexibility | 10 | 8 parameters allow fine-grained control |
| TA-Lib compatibility | 10 | Matches TA_SAREXT specification |
## Validation
| Library | Match | Tolerance | Notes |
|---------|-------|-----------|-------|
| TA-Lib | ✅ | 1e-8 | `Functions.SarExt(highs, lows, ...)` with all 8 parameters |
| Self | ✅ | 1e-10 | Streaming == Batch == Span |
## Common Pitfalls
1. **Sign interpretation**: Output is sign-encoded. Use `Math.Abs(output)` for the raw SAR level. Check `output > 0` for long, `output < 0` for short.
2. **Bar 0 outputs NaN**: The first bar collects data only. Valid output starts at bar 1 (sample index 2).
3. **offsetOnReverse too large**: Large offsets create SAR values far from price, delaying re-entry. Start with 0 and increase incrementally.
4. **Asymmetric AF interaction**: Setting `afMaxShort` much higher than `afMaxLong` makes short-side SAR track price tightly while long-side SAR lags. This is intentional for bearish-bias strategies but may surprise.
5. **Auto-detect sensitivity**: When `startValue == 0`, the DM comparison on bars 01 determines initial direction. A single bar's DM can be noisy; use `startValue` for deterministic behavior in backtests.
6. **No SIMD path**: Sequential state machine with data-dependent branches prevents vectorization. Batch API is O(n) sequential.
## References
- TA-Lib. "TA_SAREXT — SAR Extended." Open-source technical analysis library.
- Wilder, J. W. Jr. (1978). *New Concepts in Technical Trading Systems*. Trend Research. ISBN 978-0894590276.
- Kaufman, P. J. (2013). *Trading Systems and Methods*, 5th ed. Wiley.
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Swing High/Low Detection", "SWINGS", overlay=true)
+1 -1
View File
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("TTM Scalper Alert", "TTM_SCALPER", overlay=true)