Skip to content

Top 5 Trading Indicators with Pine Script Codes

Find the most commonly used trading indicators and get the pine script code for each of those indicators.

Here is the list of 5 indicators that are often used and sourced to create more complex indicators;

Moving Averages (MA)

Moving averages are a commonly used technical analysis tool that can help traders smooth out the noise on a price chart and better identify trends. They work by taking the average price of a security over a certain period, such as the past 10 days or 50 days. By looking at the direction of the moving average, traders can get a general idea of whether the price is moving up, down, or staying relatively stable. Moving averages can also act as support or resistance levels, meaning the price may struggle to break above or below the moving average line.

//@version=5
indicator(title="Moving Average", shorttitle="MA", overlay=true, timeframe="", timeframe_gaps=true)
len = input.int(9, minval=1, title="Length")
src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.sma(src, len)
plot(out, color=color.blue, title="MA", offset=offset)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")

smoothingLine = ma(out, smoothingLength, typeMA)
plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)
Moving Averages (MA) Code for Pine Script

Moving Average Convergence Divergence (MACD)

The moving average convergence divergence (MACD) is a technical indicator that calculates the difference between an instrument's 26-day and 12-day exponential moving averages (EMA). It uses closing prices over the specified periods to calculate the EMAs and then plots a nine-period EMA of the MACD itself, called the signal line. The MACD is considered the "faster" line because it moves faster than the signal line, which is regarded as the "slower" line. The MACD can help identify trend changes and generate buy and sell signals.

//@version=5
indicator(title="Moving Average Convergence Divergence", shorttitle="MACD", timeframe="", timeframe_gaps=true)
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type",  defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Line  ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line  ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above   Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(macd, title="MACD", color=col_macd)
plot(signal, title="Signal", color=col_signal)
Moving Average Convergence Divergence (MACD) Code for Pine Script

Bollinger Bands

Bollinger Bands are another famous technical analysis tool traders use to identify trend lines and potential buying or selling points. They are plotted two standard deviations from the simple moving average price of a security and are designed to help traders know when to enter or exit a position. Bollinger Bands work by signaling changes in volatility and are particularly useful for identifying overbought or oversold conditions in relatively stable ranges of a security, such as currency pairs. They were created by John Bollinger and are a widely used tool among traders.

//@version=5
indicator(shorttitle="BB", title="Bollinger Bands", overlay=true, timeframe="", timeframe_gaps=true)
length = input.int(20, minval=1)
src = input(close, title="Source")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
Bollinger Bands Code for Pine Script

On-balance Volume (OBV)

The on-balance volume (OBV) is a technical trading momentum indicator that uses volume flow to predict changes in the price of a security. It is based on the idea that mutual funds and pension funds, or "the smart money," tend to lead the market and can influence the price of an issue even if retail investors are selling it. As large investors begin to buy into a problem, the volume may increase even as the price remains relatively stable. Eventually, this volume will drive the price upward, at which point large investors may begin to sell while smaller investors may start to buy. OBV can identify trend changes and generate buy and sell signals.

//@version=3
study("On Balance Volume", shorttitle="OBV", precision=0)

showSignal = input(title="Show Signal ?", type=bool, defval=true)
signalType = input(title="Signal Smoothing Type", defval="SMA", options=["EMA", "SMA"])
signalLength = input(title="Signal Smoothing Length", type=integer, defval=21)
highlightCrossovers = input(title="Highlight Crossovers ?", type=bool, defval=false)
applyFilling = input(title="Apply Ribbon Filling ?", type=bool, defval=true)
src = input(title="Source", type=source, defval=close)

obv = cum(sign(change(src)) * volume)
signal = signalType == "EMA" ? ema(obv, signalLength) : sma(obv, signalLength)

trendColor = obv > signal ? #0ebb23 : red

obvColor = applyFilling ? trendColor : #0094ff
signalColor = applyFilling ? trendColor : #ff6a00

obvPlot = plot(obv, title="OBV", linewidth=2, color=obvColor, transp=0)
signalPlot = plot(showSignal ? signal : na, title="Signal", color=signalColor, transp=0)

transparent = color(white, 100)

fillColor = applyFilling ? trendColor : transparent
fill(obvPlot, signalPlot, color=fillColor, transp=70)

plotshape(crossover(obv, signal) and highlightCrossovers ? obv : na, title="Crossover", location=location.absolute, style=shape.circle, size=size.tiny, color=green, transp=0)
plotshape(crossunder(obv, signal) and highlightCrossovers ? obv : na, title="Crossunder", location=location.absolute, style=shape.circle, size=size.tiny, color=red, transp=0)
On-balance Volume (OBV) Code for Pine Script

Relative Strength Index (RSI)

The relative strength index (RSI) is another momentum indicator that traders use to evaluate the strength of a security's price movement. It measures the speed and magnitude of recent price changes to identify overvalued or undervalued conditions. The RSI is displayed as an oscillator on a scale of zero to 100, and traditionally, a reading above 70 indicates an overbought situation, while a reading below 30 indicates an oversold condition. The RSI can help predict trend reversals or corrective pullbacks in price and signal when to buy or sell a security.

//@version=5
indicator(title="Relative Strength Index", shorttitle="RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "Bollinger Bands" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")

up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA = ma(rsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"

plot(rsi, "RSI", color=#7E57C2)
plot(rsiMA, "RSI-based MA", color=color.yellow)
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill")
Relative Strength Index (RSI) Code for Pine Script

Comments

Latest