Kalman PSaR [BackQuant] for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
N8ErQSl.png


Author Message:

The Kalman PSaR combines the well-known Parabolic SAR (PSaR) with the advanced smoothing capabilities of the Kalman Filter. This innovative tool aims to enhance the traditional PSaR by integrating Kalman filtering, which reduces noise and improves trend detection. The Kalman PSaR adapts dynamically to price movements, making it a highly effective indicator for spotting trend shifts while minimizing the impact of false signals caused by market volatility.

CODE:

CSS:
# // Indicator for TOS
#// © BackQuant
# indicator(title="Kalman PSaR [BackQuant]", shorttitle = "KPSaR [BackQuant]"
# Converted by Sam4Cok@Samer800    - 09/2024

input timeframe = AggregationPeriod.MIN;
input ProcessNoise     = 0.03; # "Process Noise"
input MeasurementNoise = 3.0;  # "Measurement Noise"
input MinStep = 0.02;          # "Min Step"
input MaxStep = 0.1;           # "Max Step"
input Acceleration = 0.02;     # "Acceleration"
input smoothing = yes;         # "Use Smoothing?"
input smoothingMaType = {Default "SMA", "HULL", "EMA", "WMA", "DEMA", "RMA", "LINREG", "TEMA"};# "Smoothing MA"
input SmoothingPeriod = 10;    # "Smoothing Period"
input colorBars = no;          # "Paint candles according to Trend?"
input showPsar  = yes;         # "Show PSaR on Chart?"

def na = Double.NaN;
def current = GetAggregationPeriod();
def tf = Max(current, timeframe);
#-- TV PSAR
script sar {
    input start = 0.02;
    input inc = 0.02;
    input max = 0.2;
    input h   = high;
    input l   = low;
    input hi = high;
    input lo = low;
    input cl = close;
    def na = Double.NaN;
    def bar = bar[1] + 1;
    def startTrend = cl > cl[1];
    def maxMin;
    def result;
    def acceleration ;
    def isBelow;
    def isFirstTrendBar;
    def sar;
    def maxMin2;
    def acceleration2;
    def isBelow1;
    def isFirstTrendBar1;
    def acceleration1;
    def maxMin1;
    def result11;
if bar == 1 {
    isFirstTrendBar1 = yes;
    acceleration1 = start;
        if startTrend {
            isBelow1 = yes;
            maxMin1  = h;
            result11  = l[1];
        } else {
            isBelow1 = no;
            maxMin1  = l;
            result11 = h[1];
        }
    } else {
    isBelow1 = isBelow[1];
    maxMin1 = CompoundValue(1, maxMin2[1], if startTrend then h else l);
    result11 = CompoundValue(1, sar[1], if startTrend then l[1] else h[1]);
    isFirstTrendBar1 = no;
    acceleration1 = acceleration2[1];
    }
    def result1  = CompoundValue(1, result11 + acceleration1 * (maxMin1 - result11), result11);
    if isBelow[1] {
        if result[1] > lo {
            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] < hi {
            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 hi > 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;
        }
script f_kalman {
    input src = close;
    input processNoise_kRoc = 0.03;
    input measurementNoise_kRoc = 3.0;
    def errorCovariance;
    def stateEstimate;
    def errorCovariance1 = CompoundValue(1, if !errorCovariance[1] then 1 else errorCovariance[1], 100);
    def stateEstimate1   = CompoundValue(1, if !stateEstimate[1] then src else stateEstimate[1], src);
    def predictedErrorCovariance =  errorCovariance1 + processNoise_kRoc;
    def kg = predictedErrorCovariance / (predictedErrorCovariance + measurementNoise_kRoc);
    stateEstimate = stateEstimate1 + kg * (src - stateEstimate1);
    errorCovariance = (1 - kg) * predictedErrorCovariance;
    plot out = stateEstimate;
}

def kalman_close = f_kalman(close(Period = tf), ProcessNoise, MeasurementNoise);
def kalman_high  = f_kalman(high(Period = tf) , ProcessNoise, MeasurementNoise);
def kalman_low   = f_kalman(low(Period = tf) , ProcessNoise, MeasurementNoise);

def psarKal = sar(MinStep, Acceleration, MaxStep, kalman_high, kalman_low,
                  high(Period = tf), low(Period = tf), close(Period = tf) );

def psar;
if smoothing {
Switch (smoothingMaType) {
Case "HULL" : psar = HullMovingAvg(psarKal, SmoothingPeriod);
Case "EMA" : psar = ExpAverage(psarKal, SmoothingPeriod);
Case "WMA" : psar = WMA(psarKal, SmoothingPeriod);
Case "DEMA" : psar = DEMA(psarKal, SmoothingPeriod);
Case "RMA" : psar = WildersAverage(psarKal, SmoothingPeriod);
Case "LINREG" : psar = Inertia(psarKal, SmoothingPeriod);
Case "TEMA" : psar = TEMA(psarKal, SmoothingPeriod);
Default : psar = Average(psarKal, SmoothingPeriod);}
 } else {
   psar = psarKal;
}
def psar_long  = close > psar;
def psar_short = close < psar;
def Trend = if psar_long then 1 else
            if psar_short then -1 else Trend[1];

#// Plotting
plot kalmanPSAR = if showPsar then psar else na; # "Kalman PSaR"
kalmanPSAR.SetLineWeight(2);
kalmanPSAR.AssignValueColor(if Trend>0 then Color.GREEN else
                            if Trend<0 then Color.RED else Color.GRAY);
#-- bar color

AssignPriceColor(if !colorBars then Color.CURRENT else
                 if Trend>0 then Color.GREEN else
                 if Trend<0 then Color.RED else Color.GRAY);


#-- 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
351 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