Strategy · Pine Script v5 · On the chart

ADX/DMI Strategy

by benso87

This strategy calculates ADX and plus and minus directional movement and adds a Bollinger Band Width Percentile filter.

View on GitHub

GitHub stars24on the repository
Pine versionv5runs as is
Lines of code113
Settings10inputs
LicenceMPL-2.0
Last update4 years ago5 Oct 2022

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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

113 lines of Pine Script v5 from ADX DMI Strategy.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

ADX DMI Strategy.pine
//@version=5
//
// Author: benso87
// benso87.com
//
// Credit to Alex Orekhov (everget) for Stoch crossovers
// Credit to SparkyFlary for ADX Historgram with DI Lines
// Credit to The_Caretaker for BBWP
// Credit to KVDB for the Advanced Stochastic indicator for inspiration
//
strategy("ADX/DMI Strategy", overlay=true, initial_capital=1000, default_qty_value=10, default_qty_type=strategy.percent_of_equity,process_orders_on_close=true)

//Dates
startDate    = input.time    (timestamp('1 Jan 2022 00:00'), title='Start', group='Dates')
endDate        = input.time    (timestamp('1 Jan 2100 00:00'), title='End', group='Dates')

///////////////////////////////////////////////////////////////////////////////
// ADX Histogram  with DI lines

// Inputs
length = input.int(14, title="ADX DI length", minval=1, group='ADX/DMI')
useRecentFlip = input.bool(false, title='Only enter after flip?', group='ADX/DMI')
flipLookback = input.int(10, title='# candles after flip', group='ADX/DMI')

// Calculations
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, length)
plus = fixnan(100 * ta.rma(plusDM, length) / trur)
minus = fixnan(100 * ta.rma(minusDM, length) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), length)
diff = plus - minus

dmiUp = diff > 0
dmiDown = diff < 0

adxRising = adx >= adx[1]
adxFalling = adx < adx[1]

adxTurnUp = adxRising and adxFalling[1]

// Check for DMI flips
dmiFlip = dmiUp != dmiUp[1] or dmiDown != dmiDown[1]
var flipArray = array.new_int(flipLookback)
recentFlip = array.sum(flipArray) > 0

///////////////////////////////////////////////////////////////////////////////
// BBWP

// inputs
priceSrc      = input.source  ( close,    'Price Source',                                                                         group='BBWP Properties')
basisType     = input.string  ( 'SMA',    'Basis Type',                       options=['SMA', 'EMA', 'VWMA'],                     group='BBWP Properties')
bbwpLen       = input.int     ( 13,       'Length',                           minval=1,                                           group='BBWP Properties')
bbwpLkbk      = input.int     ( 252,      'Lookback',                         minval=1,                                           group='BBWP Properties')
bbwpLimit     = input.int     ( 90,       'Limit',                            minval=0, maxval=100,                               group='BBWP Properties')

// function declarations
f_maType ( _price, _len, _type ) =>
    _type == 'SMA' ? ta.sma ( _price, _len ) : _type == 'EMA' ? ta.ema ( _price, _len ) : ta.vwma ( _price, _len )

f_bbwp ( _price, _bbwLen, _bbwpLen, _type ) =>
    float _basis = f_maType ( _price, _bbwLen, _type )
    float _dev = ta.stdev ( _price, _bbwLen )
    _bbw = ( _basis + _dev - ( _basis - _dev )) / _basis
    _bbwSum = 0.0
    _len = bar_index < _bbwpLen ? bar_index : _bbwpLen
    for _i = 1 to _len by 1
        _bbwSum += ( _bbw[_i] > _bbw ? 0 : 1 )
        _bbwSum
    _return = bar_index >= _bbwLen ? ( _bbwSum / _len) * 100 : na
    _return

/////////////////////////////////////////////////////////////////////////////// 
// calculations
bbwp        = f_bbwp ( priceSrc, bbwpLen, bbwpLkbk, basisType )


///////////////////////////////////////////////////////////////////////////////
// Strategy

// Long when DMI is positive, ADX is rising, and BBWP < bbwpLimit
longSignal = dmiUp and adxTurnUp and bbwp < 90 and (not useRecentFlip or recentFlip) and time >= startDate and time <= endDate

// Short when DMI is negative, ADX is rising, and BBWP < bbwpLimit
shortSignal = dmiDown and adxTurnUp and bbwp < 90 and (not useRecentFlip or recentFlip) and time >= startDate and time <= endDate

// TP1 when BBWP gets to BBWP limit or higher
tp1 = bbwp >= bbwpLimit

// TP2/exit when DMI flips or ADX falls
longExit = dmiDown or adxFalling
shortExit = dmiUp or adxFalling

strategy.entry("LONG", strategy.long, when=longSignal)
strategy.exit('TP1', 'LONG', limit=close, qty_percent=50, when=tp1, comment='TP1')
strategy.close("LONG", when=longExit)

strategy.entry("SHORT", strategy.short, when=shortSignal)
strategy.exit('TP1', 'SHORT', limit=close, qty_percent=50, when=tp1, comment='TP1')
strategy.close("SHORT", when=shortExit)

// Update flip array
array.push(flipArray, dmiFlip ? 1 : 0)

if array.size(flipArray) > flipLookback
    array.remove(flipArray, 0)
    
noColor = color.new(color.white, transp=100)
// Test array
plotchar(array.sum(flipArray), title='Array sum', char='.', color=noColor)

Overview

ADX/DMI Strategy tracks positive or negative DMI, rising or falling ADX, and an optional recent DMI flip within a set lookback. Settings change ADX length, flip timing, BBWP length, lookback, limit, basis type, and the backtest date window. Orders are processed on the close and drawn on the price chart, with size set as a percent of equity. The excerpt does not show exit rules or a stop loss.

Details

Published by

benso87 on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Oscillators & momentum, Volatility & bands

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Starttimetimestamp('1 Jan 2022 00:00')startDate
Endtimetimestamp('1 Jan 2100 00:00')endDate
ADX DI lengthint14length
Only enter after flip?boolfalseuseRecentFlip
# candles after flipint10flipLookback
Price SourcesourceclosepriceSrc
Basis TypestringSMAbasisType
Lengthint13bbwpLen
Lookbackint252bbwpLkbk
Limitint90bbwpLimit
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

106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL
57 stars

This strategy identifies trend reversals through market structure changes (CHoCH) filtered by MACD momentum. It initiates long positions on bullish structure breaks when MACD is positive and above its signal line, and short positions on bearish breaks when MAC

Strategy v6 SMC / ICT / price actionOscillators & momentum Repaints
Updated 1 year ago · Apache-2.0 GitHub repository of Market Structure MACD 4H + Trailing

CombinedBinHAndClucV6

by viktors1982
36 stars

CombinedBinHAndClucV6 is a trading strategy based on the popular BinHV45 and ClucMay72018 algorithms. It calculates dual Bollinger Bands, Exponential Moving Averages, Relative Strength Index, Average True Range, and volume metrics across primary and one-hour h

Strategy v4 Volatility & bandsOscillators & momentum Repaints
Updated 2 years ago · None stated GitHub repository of CombinedBinHAndClucV6
27 stars

LuxAlgo Hybrid Gold Scalper is a price-chart strategy aimed at gold. It stacks a fast, slow, trend and 200-period bias EMA to mark trend direction, then filters strength with RSI, ADX and an intraday VWAP. Swing highs and lows are marked from pivot length. Set

Strategy v5 TrendOscillators & momentum
Updated 5 months ago · None stated GitHub repository of LuxAlgo Hybrid Gold Scalper

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers