Indicator · Pine Script v4 · On the chart

Support and Resistance Levels v3

by techteam92· code credited to capissimo

This indicator identifies support and resistance turning points on the price chart using higher-order momentum analysis.

View on GitHub

GitHub stars1on the repository
Pine versionv4older, still runs
Lines of code177
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago20 Nov 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

177 lines of Pine Script v4 from scripts/121-Support-and-Resistance-Levels-(v3).pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

121-Support-and-Resistance-Levels-(v3).pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=4
study('Support and Resistance Levels (v.3)', '', true)

// Support and Resistance Levels augmented and reprocessed

// Description:

// This is an augmented version of my earlier script that can be found here:
// https://www.tradingview.com/script/cDivOtB4-Support-and-Resistance-Levels/

// This time it features zigzag and channel lines, signal generation and filtering
// and performance testing. Signal generation and filtering procedures are used only 
// for performance testing, not for the actual labelling. The labelling is governed 
// by zigzag logic.

//-------------------- Inputs

lookback  = input(6,      'Lag |2..n|',             minval=2)
filterDMI = input(false,  'Filter DMI?')
show_chan = input(true,   'Show Channal?')
ftype     = input('None', 'Filter Signals by',      options=['Volatility','Volume','Both','None'])
holding_p = input(20,     'Holding Period |1..n|',  minval=1)

//-------------------- System Variables

var int BUY      =  1
var int SELL     = -1
var int HOLD     =  0

//-------------------- Series 

var int   signal     = HOLD
var int   hp_counter = 0

//-------------------- Custom Functions

volumeBreak(thres) => hma(rsi(volume, 14), 10) > thres                     

volatilityBreak(volmin, volmax) => atr(volmin) > atr(volmax)

//-------------------- Logic

// 0) set up a bar life counter and a filter
float tbase   = (time - time[1]) / 1000
float tcurr   = (timenow - time_close[1]) / 1000
float barlife = tcurr / tbase

filter =   ftype=='Volatility' ? volatilityBreak(1, 10) 
         : ftype=='Volume'     ? volumeBreak(49) 
         : ftype=='Both'       ? volatilityBreak(1, 10) and volumeBreak(49)
         :                       true

// 1) get positive and negative directional movements.
[pdm, mdm, _] = dmi(14, lookback)    
 
// 2) the market data is smoothed.
dema = ema(ema(close, lookback), lookback)

// 3) the momentum of the market is calculated. 
mom1 = mom(dema, round(lookback/2))    // 1st momemtum of ma

// 4) the momentum of the momentum is calculated.
mom2 = mom(mom1, round(lookback/2))    // momemtum of momemtum of ma (2nd deviation)

// 5) determine criteria
crossmomover  = crossover(mom2, 0)
crossmomunder = crossunder(mom2, 0)

ll = lowest(low,   lookback)  // lowest low before now (this hour, today, etc.)
hh = highest(high, lookback)  // highest high before now

signal :=  crossmomover  and not filterDMI or (filterDMI and pdm>mdm) and filter ? BUY 
         : crossmomunder and not filterDMI or (filterDMI and pdm<mdm) and filter ? SELL 
         :                                                                         nz(signal[1])

changed = change(signal)
hp_counter := changed ? 0 : hp_counter + 1

startLongTrade  = changed and signal==BUY    
startShortTrade = changed and signal==SELL   
endLongTrade    = (changed and signal==SELL) or (signal==BUY  and hp_counter==holding_p and not changed) 
endShortTrade   = (changed and signal==BUY)  or (signal==SELL and hp_counter==holding_p and not changed)

//-------------------- Visualization

// If the second momentum crosses above zero, the first momentum will have 
// local low and the market will be in a state when the trend comes to an end.

if crossmomover       // possible low (2nd deviation is zero)
    if not filterDMI or (filterDMI and pdm>mdm)
        label.new(time-lookback, ll, xloc=xloc.bar_time, style=label.style_label_up, color=color.green, size=size.tiny)

// If the second momentum crosses below zero, the first momentum will have 
// local high and the market will be in a state when the trend comes to an end.

if crossmomunder      // possible high
    if not filterDMI or (filterDMI and pdm<mdm)
        label.new(time-lookback, hh, xloc=xloc.bar_time, style=label.style_label_down, color=color.red, size=size.tiny)

// Optionally, show channal
plot(show_chan and crossmomover  and (not filterDMI or pdm>mdm) ? ll : na, style=plot.style_stepline, color=color.green)        
plot(show_chan and crossmomunder and (not filterDMI or pdm<mdm) ? hh : na, style=plot.style_stepline, color=color.red)    

// Show zigzag
plot(crossmomover ? ll : crossmomunder ? hh : na, '', color.blue, 2, plot.style_stepline)

//==================== Doji

var string stop = '✖'

bool doji = (abs(open - close) <= (high - low) * input(0.15, "Doji Size", minval=0.01, step=.01))

plotchar((open-close)<0 ? doji : na, '', stop, location.abovebar, color.black) 
plotchar((open-close)>0 ? doji : na, '', stop, location.belowbar, color.black) 

//-------------------- Notification

if startLongTrade
    alert('Buy Alert', alert.freq_once_per_bar)  // alert.freq_once_per_bar_close
if startShortTrade
    alert('Sell Alert', alert.freq_once_per_bar)
    
alertcondition(startLongTrade,  'Buy Alert',  'Go Long!')
alertcondition(startShortTrade, 'Sell Alert', 'Go Short!')

//-------------------- Backtest

show_info = input(true,  'Performance')
lot_size  = input(0.01,  'Lot Size', options=[0.01,0.1,0.2,0.3,0.5,1,2,3,5,10,20,30,50,100,1000]) 
ubase     = input(false, 'Use Base Price?')

float bidask = ubase ? (open+high+low)/3 : open

var float start_long_trade  = ohlc4  
var float long_trades       = 0.
var float start_short_trade = ohlc4  
var float short_trades      = 0.
var int   wins              = 0
var int   trade_count       = 0

if startLongTrade 
    start_long_trade := bidask 
if endLongTrade
    ldiff         = (bidask - start_long_trade)
    wins         := ldiff > 0 ? 1 : 0
    long_trades  := ldiff * lot_size   
    trade_count  := 1
if startShortTrade 
    start_short_trade := bidask
if endShortTrade
    sdiff         = (start_short_trade - bidask)
    wins         := sdiff > 0 ? 1 : 0
    short_trades := sdiff * lot_size 
    trade_count  := 1
    
cumreturn   = cum(long_trades) + cum(short_trades)  //-- cumulative return 
totaltrades = cum(trade_count)
totalwins   = cum(wins)  
totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins

//------------------- Information

var label lbl = na

info =  'CR='          + tostring(cumreturn,             '#.#') 
      + '\nTrades: '   + tostring(totaltrades,           '#')
      + '\nWin/Loss: ' + tostring(totalwins/totallosses, '#.##') 
      + '\nWinrate: '  + tostring(totalwins/totaltrades, '#.#%')       
      + '\nBar Time: ' + tostring(barlife,               '#.#%')

if show_info and barstate.islast  
    lbl := label.new(bar_index, ohlc4, info, xloc.bar_index, yloc.price, 
                     color.new(color.blue, 100), label.style_label_left, color.black, size.small, text.align_left)
    label.delete(lbl[1])

Overview

Support and Resistance Levels v3 calculates a double-smoothed exponential moving average, derives its first momentum, and detects zero-crossings of its second momentum to pinpoint potential local highs and lows over a specified lookback period. Users can filter signals with directional movement (DMI), volatility breakouts based on ATR, and volume breakouts using HMA-smoothed RSI. It also supports channel visualization and internal performance tracking across a configurable holding period.

Details

Published by

techteam92 on GitHub

Code credit

capissimo, as written in the script's header

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Support & resistance, Oscillators & momentum, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Lag |2..n|int6lookback
Filter DMI?boolfalsefilterDMI
Show Channal?booltrueshow_chan
Filter Signals bystringNoneftype
Holding Period |1..n|int20holding_p
Doji Sizefloat0.15Doji Size
Performancebooltrueshow_info
Lot Sizefloat0.01lot_size
Use Base Price?boolfalseubase
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

114 stars

This indicator calculates key support and resistance levels by analyzing the first and second momentum derivatives of a Double Exponential Moving Average (DEMA). When the second derivative (momentum of momentum) crosses zero, it identifies local turning points

Indicator v4 Support & resistanceOscillators & momentum
Updated 1 year ago · None stated GitHub repository of Support and Resistance Levels

Moon Dev Lunar Sniper

by moondevonyt
92 stars

Moon Dev Lunar Sniper is a multi-indicator overlay that scores confluence across fast and slow EMAs, RSI, MACD, DMI, and BB width to fire signals only when score meets the minimum threshold. It plots buy and sell signals on the price chart, highlights cosmic b

Indicator v6 TrendOscillators & momentum Repaints
Updated 8 weeks ago · Custom licence GitHub repository of Moon Dev Lunar Sniper
14 stars

Self-Aware Trend System calculates volatility-adaptive ATR trailing bands using a Trend Quality Index engine that evaluates market efficiency, momentum persistence, and structural pivots. It plots adaptive trend bands and character-flip trend signals directly

Indicator v6 TrendVolatility & bands
Updated 2 weeks ago · MIT GitHub repository of Self-Aware Trend System [WillyAlgoTrader]

SPY 0DTE Scalper - 15min

by chris-c-thomas
14 stars

This intraday overlay establishes directional bias and high-conviction swing setups for SPY on the 15-minute timeframe. It computes a weighted confluence score combining an EMA ribbon, a 50 EMA anchor, session VWAP bands, RSI divergence, ADX, TTM Squeeze, cand

Indicator v6 TrendOscillators & momentum
Updated 6 months ago · MIT GitHub repository of SPY 0DTE Scalper - 15min

Market Trend

by azamiftikhar1000
12 stars

Market Trend is an overlay indicator that identifies market direction and key price levels. It calculates a Relative Strength Index with Bollinger Bands to construct a 20-step color gradient reflecting momentum shifts. The script incorporates exponential movin

Indicator v4 TrendOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Market Trend

BTE Acc AO SMIO

by f-cksociety
11 stars

This script provides an indicator-based backtesting engine framework that simulates trade entries, exits, and filtering directly on the price chart. It evaluates selected entry rules and multi-layered filters, including moving average trends, volume increases,

Indicator v5 TrendOscillators & momentum
Updated 4 years ago · MPL-2.0 GitHub repository of BTE Acc AO SMIO

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers