Calculate

What is it?

The Calculate method is one of the core functions used in a custom indicator. It’s responsible for calculating the logic of your indicator for each bar (candle) on the chart.

This function runs automatically on each price update (tick) and recalculates values for the given bar.


How It Works

  • index β€” This parameter tells you which bar you’re working with.

    • index = 0 β†’ the latest bar (rightmost on the chart).

    • index = 1 β†’ the previous bar, and so on.

  • The method runs once per tick (price change) and calculates the indicator value only for the specified bar.


Example Explained

public Calculate(index: number): void {
    // Skip if not enough bars to calculate moving average
    if (index + this.Period.value >= this.api.Bars()) {
        return
    }

    // Get the calculated value of the Moving Average
    const calculatedSMA = this.api.GetMA(
        index,
        0,                              // Shift (usually 0)
        this.Period.value,              // Period for MA
        this.MAtype.value,              // Type of MA (SMA, EMA, etc.)
        this.ApplyToPrice.value,        // Price type (Close, Open, etc.)
        this.SMA.getValue(index + 1)    // Previous value for smoothing (optional)
    )

    // Save the value to the SMA buffer
    this.SMA.setValue(index, calculatedSMA)

    // Save a shifted version to another buffer
    this.SSMA.setValue(index, calculatedSMA + this.VShift.value * this.api.Point())
}

What This Code Does

  1. Checks if there are enough bars to calculate the moving average. (We need Period number of candles; otherwise, we skip.)

  2. Calculates a Moving Average value using GetMA().

  3. Stores the result in the SMA buffer, which is used for drawing on the chart.

  4. Applies a vertical shift (VShift) and stores the result in a second buffer (SSMA).


In Short

  • This method is where you put your main logic.

  • It runs automatically for each bar.

  • You should use it to calculate and store indicator values.

  • Buffers like SMA and SSMA are how your indicator shows up visually on the chart.

this.SSMA.setValue(index, calculatedSMA + this.VShift.value * this.api.Point())

Last updated