How To Calculate Parabolic SAR (Stop and Reverse) using TypeScript?

Member

by emelie , in category: SEO Tools , a month ago

How To Calculate Parabolic SAR (Stop and Reverse) using TypeScript?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by larry_orn , a month ago

@emelie 

In TypeScript, you can calculate the Parabolic SAR by following the formula and steps below:


Formula:

  1. Start with an initial value for the SAR
  2. Calculate the SAR for each period using the following formula: SAR = Previous SAR + AF * (Previous EP - Previous SAR) where EP is the extreme price for the previous period and AF is the acceleration factor
  3. Update the acceleration factor and the extreme price for each period based on certain conditions


Here is a TypeScript code snippet to calculate the Parabolic SAR:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function calculateSAR(data: number[], initialSAR: number, initialAF: number, maxAF: number): number[] {
    const sarValues: number[] = [];
    let EP = 0;
    let SAR = initialSAR;
    let AF = initialAF;

    for (let i = 1; i < data.length; i++) {
        if (SAR > data[i - 1]) {
            EP = Math.max(EP, data[i]);
            if (AF < maxAF) {
                AF += initialAF;
            }
        } else {
            EP = Math.min(EP, data[i]);
            if (AF < maxAF) {
                AF += initialAF;
            }
        }

        const newSAR = SAR + AF * (EP - SAR);

        // Check if SAR should reverse
        if (data[i] > data[i - 1]) {
            if (newSAR > data[i]) {
                newSAR = EP;
                AF = initialAF;
            }
        } else {
            if (newSAR < data[i]) {
                newSAR = EP;
                AF = initialAF;
            }
        }

        sarValues.push(newSAR);
        SAR = newSAR;
    }

    return sarValues;
}

// Example usage
const data = [10, 15, 20, 25, 20, 15, 10];
const initialSAR = 10;
const initialAF = 0.02;
const maxAF = 0.2;

const sarValues = calculateSAR(data, initialSAR, initialAF, maxAF);
console.log(sarValues);


You can adjust the initialSAR, initialAF, and maxAF values based on your requirements. This code snippet calculates the Parabolic SAR values for the given data array using the provided initial values and prints them to the console.