Standardized PSAR Oscillator [AlgoAlpha] for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
FhEQbhe.png


Author Message:

"Standardized PSAR Oscillator" a powerful tool that combines the Parabolic Stop and Reverse (PSAR) with standardization techniques to offer more nuanced insights into market trends and potential reversals.

CODE:

CSS:
#// Indicator for TOS
#// © AlgoAlpha
#indicator(title="Standardized PSAR Oscillator [AlgoAlpha]", shorttitle="AlgoAlpha - 🪝 PSAR Oscillator"
# Converted by Sam4Cok@Samer800    - 09/2024
declare lower;

#// Inputs with tooltips and groups
input start = 0.02; #Hint Start: The initial value for the PSAR calculation.
input increment = 0.0005; #Hint Increment: The step value by which the PSAR accelerates.
input MaxValue = 0.2; #Hint MaxValue: The maximum value the PSAR can reach during its calculation.
input StandardizationLength = 21; #Hint StandardizationLength: Length used to calculate the EMA for standardization.
input wmaLength = 40; #Hint WMALength: Length of the Weighted Moving Average (WMA) applied to the standardized PSAR oscillator.
input wmaLagLength = 3; #Hint WMALagLength: Lag length for comparison of the WMA with its past values.
input DivergenceLeftLookback = 15; #Hint DivergenceLeftLookback: The larger this number, the less sensitive the divergence detection is. A smaller number will detect smaller and/or shorter term divergences.
input DivergenceRightLookback = 1; #Hint DivergenceRightLookback: This number is how many bars the indicator will wait for confirmation to plot the divergences. The higher the number, the longer the delay of the signal, but the lesser the number of false signals. Set this to 0 if you do not want any delay at all.
input showBullishDivergences = yes;
input showBearishDivergences = yes;

def na = Double.NaN;
def last = IsNaN(close);
def lbl = DivergenceLeftLookback;
def lbr = DivergenceRightLookback;
#-- Color
DefineGlobalColor("up", CreateColor(0, 255, 187));
DefineGlobalColor("dn", CreateColor(255, 17, 0));
#-- PSAR
Script sar {
    input start = 0.02;
    input inc = 0.0005;
    input max = 0.2;
    input h   = high;
    input l   = low;
    input c   = close;
    def na = Double.NaN;
    def bar = CompoundValue(1, bar[1] + 1, 1);
    def startTrend = c > c[1];
    def maxMin;
    def result;
    def acceleration ;
    def isBelow;
    def isFirstTrendBar;
    def sar;
    def maxMin2;
    def acceleration2;
    def isBelow1         = CompoundValue(1, isBelow[1], if startTrend then yes else no);
    def isFirstTrendBar1 = CompoundValue(1, no, yes);
    def acceleration1    = CompoundValue(1, acceleration2[1], start);
    def maxMin1  = CompoundValue(1, maxMin2[1], if startTrend then h else l);
    def result11 = CompoundValue(1, sar[1], if startTrend then l[1] else h[1]);
    def result1  = CompoundValue(1, result11 + acceleration1 * (maxMin1 - result11), result11);
    if isBelow1 {
        if result[1] > l {
            isFirstTrendBar = yes;
            isBelow = no;
            result = max(h, maxMin1);
            maxMin = l;
            acceleration = start;
            } else {
            maxMin = maxMin1;
            acceleration = acceleration1;
            isFirstTrendBar = isFirstTrendBar1;
            isBelow = isBelow1;
            result = result1;
            }
    } else {
        if result[1] < h {
            isFirstTrendBar = yes;
            isBelow = yes;
            result = min(l , maxMin1);
            maxMin = h;
            acceleration = start;
            } else {
            acceleration  = acceleration1;
            maxMin = maxMin1;
            isFirstTrendBar = isFirstTrendBar1;
            isBelow = isBelow1;
            result = result1;
        }}
    if !isFirstTrendBar {
        if isBelow {
            if h > maxMin {
                maxMin2 = h;
                acceleration2 = min(acceleration + inc, max);
             } else {
                maxMin2 = maxMin;
                acceleration2 = acceleration;
             }
        } else {
            if l < maxMin {
                maxMin2 = l;
                acceleration2 = min(acceleration + inc, max);
            } else {
                maxMin2 = maxMin;
                acceleration2 = acceleration;
            }}
    } else {
            maxMin2 = maxMin;
           acceleration2 = acceleration;
}
        sar = if isBelow then if bar > 1 then Min(result, l[2]) else Min(result, l[1]) else
                              if bar > 1 then max(result, h[2]) else max(result, h[1]);
        plot psar  = if !isNaN(close) then sar else Double.NaN;
        }
#/ PSAR Calculation
def out = sar(start, increment, MaxValue);
def PSARoscillator = close - out;
def ema = ExpAverage(high - low, StandardizationLength);
def stand_PSARoscillator = PSARoscillator / ema * 100;
def MA = WMA(stand_PSARoscillator, wmaLength);

def FINALcol = if stand_PSARoscillator > 0 then 1 else -1;
def modCol1 = (1 - AbsValue(stand_PSARoscillator) / 800) * 100;
def modCol = if (MA > MA[wmaLagLength] and stand_PSARoscillator > 0) or
                (MA < MA[wmaLagLength] and stand_PSARoscillator < 0) then FINALcol else 0;
def col = if isNaN(modCol1) then 0 else
          if (modCol1 + 100) > 200 then 255 else
          if (modCol1 + 100) < 0 then 0 else AbsValue(modCol1) * 2.55;

#// Hidden Levels
def maxLevelPlot = if last then na else 800;
def minLevelPlot = if last then na else -800;
def upperMidLevelPlot = if last then na else 600;
def lowerMidLevelPlot = if last then na else -600;

# fills
AddCloud(lowerMidLevelPlot, minLevelPlot, Color.DARK_GREEN);
AddCloud(maxLevelPlot, upperMidLevelPlot, Color.DARK_RED);

#// Plots
def crossUp = (stand_PSARoscillator Crosses Above -600);
def crossDn = (stand_PSARoscillator Crosses Below 600);

plot sigDn = if crossDn then 750 else na; #, "Bearish Reversal", "▼",
plot sigUp = if CrossUp then -750 else na; # "Bullish Reversal", "▲",
plot maLine = MA;
plot ParabolicSAR = stand_PSARoscillator; # "ParabolicSAR"
sigDn.SetDefaultColor(Color.MAGENTA);
sigUp.SetDefaultColor(Color.CYAN);
sigDn.SetPaintingStrategy(PaintingStrategy.SQUARES);
sigUp.SetPaintingStrategy(PaintingStrategy.SQUARES);
maLine.SetLineWeight(2);
ParabolicSAR.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
ParabolicSAR.AssignValueColor(if modCol > 0 then GlobalColor("up") else
                              if modCol < 0 then GlobalColor("dn") else
                              if modCol1 > 0 then CreateColor(255-col,255-col,255-col) else CreateColor(col, col, col));
maLine.AssignValueColor(if MA > MA[wmaLagLength] then Color.CYAN else Color.MAGENTA);

#-- Div

Script Pivot {
    input series    = close;
    input leftBars  = 10;
    input rightBars = 10;
    input isHigh = yes;
    def na = Double.NaN;
    def HH = series == Highest(series, leftBars + 1);
    def LL = series == Lowest(series, leftBars + 1);
    def pivotRange = (leftBars + rightBars + 1);
    def leftEdgeValue = if series[pivotRange] ==0 then na else series[pivotRange];
    def pvtCond = !isNaN(series) and leftBars > 0 and rightBars > 0 and !isNaN(leftEdgeValue);
    def barIndexH = if pvtCond then
                    fold i = 1 to rightBars + 1 with p=1 while p do
                    series > GetValue(series, - i) else na;
    def barIndexL = if pvtCond then
                    fold j = 1 to rightBars + 1 with q=1 while q do
                    series < GetValue(series, - j) else na;
    def PivotPoint;
if isHigh {
    PivotPoint = if HH and barIndexH then series else na;
    } else {
    PivotPoint = if LL and barIndexL then series else na;
    }
    plot pvt = PivotPoint;
}
Script _inRange {
input cond = no;
    def bars = if cond == yes then 0 else bars[1] + 1;
    def inRange = -80 <= bars and bars <= 80;
    plot out = inRange;
}
def bar = bar[1] + 1;
def pl = pivot(stand_PSARoscillator[lbR], lbL, lbR, no);
def ph = pivot(stand_PSARoscillator[lbR], lbL, lbR, yes);
def plFound = if isNaN(pl) then no else yes;
def phFound = if isNaN(ph) then no else yes;
def PvtL = if plFound then pl else PvtL[1];
def PvtH = if phFound then ph else PvtH[1];
def plLo = if plFound then low[lbr] else plLo[1];
def phHi = if phFound then high[lbr] else phHi[1];
def plBar = if plFound then bar[1] else plBar[1];
def phBar = if phFound then bar[1] else phBar[1];
def pvtL1 = if PvtL!=PvtL[1] then PvtL[1] else PvtL1[1];
def pvtH1 = if PvtH!=PvtH[1] then PvtH[1] else PvtH1[1];
def plLo1 = if plLo!=plLo[1] then plLo[1] else plLo1[1];
def phHi1 = if phHi!=phHi[1] then phHi[1] else phHi1[1];
#// Regular Bullish
def oscHL = stand_PSARoscillator[lbR] > pvtL1 and _inRange(plFound[1]);
def priceLL = low[lbR] < plLo1;
def bullCond = showBullishDivergences and priceLL and oscHL and plFound;
#// Regular Bearish
def oscLH = stand_PSARoscillator[lbR] < pvtH1 and _inRange(phFound[1]);
def priceHH = high[lbR] > phHi1;
def bearCond = showBearishDivergences and priceHH and oscLH and phFound;
#//
def bullBar = if bullCond[-lbR] then bar else na;
def lastPl  = if !isNaN(bullBar) then plBar else na;
def bearBar = if bearCond[-lbR] then bar else na;
def lastPh  = if !isNaN(bearBar) then phBar else na;

plot bulishLine = if bar == highestAll(bullBar) then stand_PSARoscillator else
                  if bar == highestAll(lastPl)  then stand_PSARoscillator else na;
plot bearishLine = if bar == highestAll(bearBar) then stand_PSARoscillator else
                   if bar == highestAll(lastPh)  then stand_PSARoscillator else na;
bulishLine.EnableApproximation();
bulishLine.SetDefaultColor(Color.GREEN);
bearishLine.EnableApproximation();
bearishLine.SetDefaultColor(Color.RED);

AddChartBubble(bullCond[-lbR], stand_PSARoscillator, "D", Color.GREEN, no);
AddChartBubble(bearCond[-lbR], stand_PSARoscillator, "D", Color.RED);


#-- END of CODE
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
320 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top