Posts

Showing posts with the label RSI

How to Use the RSI Indicator in Pine Script v6: Overbought, Oversold, and Signal Logic

Image
The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and magnitude of recent price changes on a normalized 0–100 scale. In this article, we examine the mathematical foundation of RSI, how Pine Script v6 computes it internally, and how to build a verified, production-ready RSI indicator with overbought/oversold signal logic from scratch. 1. What Is RSI? The Mathematical Definition RSI was introduced by J. Welles Wilder Jr. in 1978. It is defined as: $$RSI = 100 - \frac{100}{1 + RS}$$ where RS (Relative Strength) is the ratio of the average gain to the average loss over a lookback period $n$: $$RS = \frac{\text{Average Gain}_n}{\text{Average Loss}_n}$$ Wilder used a Wilder Smoothing (RMA) — also called Exponential Moving Average with $\alpha = \frac{1}{n}$ — to compute the rolling averages. The recurrence relation is: $$\text{AvgGain}_t = \frac{\text{Gain}_t + (n-1) \cdot \text{AvgGain}_{t-1}}{n}$$ The ...

Pine Script 'if' Statements: A Complete Guide to Conditional Logic for Buy Signals and Color Changes

Image
Conditional logic is the backbone of any algorithmic trading script — without it, indicators and strategies cannot respond dynamically to market conditions. In Pine Script v6, the if statement provides a structured, deterministic mechanism to evaluate boolean expressions and execute specific branches of code, enabling everything from simple color changes to complex multi-condition buy/sell signal generation. 1. The Anatomy of an if Statement in Pine Script At its core, an if statement evaluates a boolean condition and executes a block of code only when that condition resolves to true . The general syntax follows this structure: //@version=6 // Basic if-else structure (conceptual) // if condition // // executed when condition is true // else // // executed when condition is false Pine Script uses indentation-based block scoping . Any statements belonging to an if branch must be consistently indented relative to the if key...