Indicator · Pine Script v4 · On the chart

ADX Strategy (original)

by capissimo

ADX Strategy (original) is an overlay indicator that identifies trend-following trade signals using the Average Directional Index (ADX) combined with a Simple Moving Average filter.

View on GitHub

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code154
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 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

154 lines of Pine Script v4 from scripts/116-ADX-Strategy-(original).pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

116-ADX-Strategy-(original).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("ADX Strategy (original)", '', true)

// ADX Strategy

// Description:

//     Generates a long entry signal when the Average Directional Index (ADX)
//     value is greater than the trendlevel and the close is greater than the filter
//     value, and/or generates a short entry signal when the ADX value is greater than 
//     the trendlevel and the close is less than the filter value.

//     The Average Directional Index evaluates the strength of a current trend. 
//     The ADX is an oscillator that fluctuates between 0 and 100. Values below 20 
//     indicate a weak trend, values above 40 indicate a strong trend. The direction 
//     of the trend is not measured by this indicator.

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

ptype      = input('Close','Dataset',               options=['Open','High','Low','Close','HL2','OC2','OHL3','HLC3','OHLC4'])
reso       = input('',     'Resolution',            input.resolution)

lag        = input(20,     'ADX Lag |1..n|',        minval=1)
trendlevel = input(20,     'Trend Level |1..n|',    minval=1)
filterlag  = input(38,     'Filter Lag |1..n|',     minval=1)

ftype      = input('None', 'Filter Signals by',     options=['Volatility','Volume','Both','None'])
holding_p  = input(1,      '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) =>  
    rsivol   = rsi(volume, 14)  
    osc      = hma(rsivol, 10)  
    osc > thres                     

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

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

tbase   = (time - time[1]) / 1000
tcurr   = (timenow - time_close[1]) / 1000
barlife = tcurr / tbase

filter =   ftype=='Volatility' ? volatilityBreak(1, 10) 
         : ftype=='Volume'     ? volumeBreak(49) 
         : ftype=='Both'       ? volatilityBreak(1, 10) and volumeBreak(49)
         :                       true
         
dset   =   ptype=='Open'  ? open 
         : ptype=='High'  ? high 
         : ptype=='Low'   ? low 
         : ptype=='Close' ? close 
         : ptype=='OC2'   ? (open+close)/2 
         : ptype=='HL2'   ? hl2 
         : ptype=='OHL3'  ? (open+high+low)/3 
         : ptype=='HLC3'  ? hlc3 
         :                  ohlc4

dataset = security('', reso, dset)

[_, _, adx] = dmi(lag, lag)
filterval   = sma(dataset, filterlag)

signal := adx>trendlevel and dataset>filterval and filter ? BUY : adx>trendlevel and dataset<filterval 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

plotshape(startLongTrade  ? low  : na, 'Buy',  shape.labelup,   location.belowbar, color.blue, 30, size=size.small)
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, color.red,  30, size=size.small)
plot(startLongTrade  ? low  : startShortTrade ? high : na, '', color.blue, 2, plot.style_stepline)

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

if changed and signal==BUY 
    alert('Buy Alert', alert.freq_once_per_bar)  // alert.freq_once_per_bar_close
if changed and signal==SELL 
    alert('Sell Alert', alert.freq_once_per_bar)
    
alertcondition(startLongTrade,  'Buy Alert',  'Go Long!')
alertcondition(startShortTrade, 'Sell Alert', 'Go Short!')

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

show_info = input(false, '===Information===')
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]) 

bidask = open //-- (open+high+low)/3 is less optimistic

var float start_long_trade  = bidask  
var float long_trades       = 0.
var float start_short_trade = bidask  
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 =  ptype
      + '\nCR='        + 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

A long signal is generated when the ADX rises above a user-defined trend level while price remains above the filter line. A short signal triggers when ADX exceeds the trend level while price stays below the filter. The script includes optional volume and ATR volatility condition filters, plots signal shapes directly on the chart, and manages exits through a custom holding period parameter.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Trend, Oscillators & momentum, Moving averages, Volatility & bands

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
DatasetstringCloseptype
Resolutiontimeframereso
ADX Lag |1..n|int20lag
Trend Level |1..n|int20trendlevel
Filter Lag |1..n|int38filterlag
Filter Signals bystringNoneftype
Holding Period |1..n|int1holding_p
===Information===boolfalseshow_info
Lot Sizefloat0.01lot_size
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

56 stars

Double Screened Decision is a multi-timeframe trend and momentum indicator overlaid directly on the price chart. It dynamically selects a higher timeframe based on the active chart resolution to evaluate higher-timeframe MACD, Bollinger Bands, RSI, and Stochas

Indicator v5 TrendMoving averages Repaints
Updated 4 months ago · None stated GitHub repository of Double Screened Decision
24 stars

This indicator plots Bollinger Bands on the price chart alongside a baseline moving average to identify trend-aligned swing setups. It calculates trend bias by comparing the Bollinger Bands basis to a customizable moving average, such as a 200 EMA. Trade signa

Indicator v5 Volatility & bandsOscillators & momentum
Updated 4 years ago · MPL-2.0 GitHub repository of Bollinger Band Swing

Index Intraday Analyst

by chris-c-thomas
14 stars

Index Intraday Analyst overlays CBOE cash indices such as SPX, NDX, RUT, and DJX. It plots a multi-EMA ribbon, a session-anchored TWAP with standard-deviation bands, and session levels such as prior-day high, low, and close, the opening range, and the high and

Indicator v6 TrendOscillators & momentum
Updated 6 months ago · MIT GitHub repository of Index Intraday Analyst

RePaNoCHa V4

by wocclyl
9 stars

RePaNoCHa V4 is an overlay alert indicator that plots a Tillson T3 moving average on the price chart and colors it by whether the line is rising or falling. It combines that slope with a range filter, ADX, parabolic SAR, RSI, and MACD to mark long and short si

Indicator v4 TrendOscillators & momentum
Updated 7 years ago · MIT GitHub repository of RePaNoCHa V4

Kijun-Sen + SSL + WAE

by krosenfeld7
5 stars

Combines the Kijun-Sen baseline, SSL channel crossovers, and Waddah Attar Explosion momentum calculations to generate directional trade signals. The indicator plots the Kijun-Sen and SSL lines directly on the price chart. When price aligns relative to the Kiju

Indicator v4 TrendOscillators & momentum
Updated 3 years ago · Apache-2.0 GitHub repository of Kijun-Sen + SSL + WAE

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