OPEN-SOURCE SCRIPT
Atualizado DMI ForLoop [InvestorUnknown]

Overview
This indicator utilizes the Directional Movement Index (DMI) combined with a for-loop to provide a robust trend analysis (ADX is not a part of this indicator).
Settings
DMI ForLoop Settings:
Start Length (a): The initial length for DMI calculation (inclusive).
End Length (b):The final length for DMI calculation (inclusive).
EMA Length (c): The length for the Exponential Moving Average applied to the DMI values, in order so smoothen the signal.
Signal Settings:
Signal Mode: Determines the mode of signal calculation. Options are "Fast", "Slow", "Thresholds Crossing", and "Fast Threshold". Default is "Fast".
1. Slow: is a simple crossing of the midline (0).
2. Fast: positive signal depends if the current "DMIema" is above "DMIema[1]" or above 0.99, otherwise the signal is negative.
3. Thresholds Crossing: simple ta.crossover and ta.crossunder of the user defined threshold for Long and Short.
4. Fast Threshold: signal changes if the value of "DMIema" changes by more than user defined threshold against the current signal.
Functionality
The DMI ForLoop indicator calculates an array of DMI values over a specified range of lengths, then averages these values and applies an EMA for smoothing. The result is a dynamic trend indicator that adapts to market conditions.
DMI Calculation:
The indicator iterates through lengths from Start Length to End Length, calculating the positive and negative directional movement (DM) for each period and calculates the average of all the signals at the end. A custom function version of the DMI is used here in order to use DMI with "series" inputs.
This indicator is versatile and can be tailored to fit various trading/investing strategies by adjusting the input parameters and signal modes.
This indicator utilizes the Directional Movement Index (DMI) combined with a for-loop to provide a robust trend analysis (ADX is not a part of this indicator).
Settings
DMI ForLoop Settings:
Start Length (a): The initial length for DMI calculation (inclusive).
End Length (b):The final length for DMI calculation (inclusive).
EMA Length (c): The length for the Exponential Moving Average applied to the DMI values, in order so smoothen the signal.
Signal Settings:
Signal Mode: Determines the mode of signal calculation. Options are "Fast", "Slow", "Thresholds Crossing", and "Fast Threshold". Default is "Fast".
1. Slow: is a simple crossing of the midline (0).
2. Fast: positive signal depends if the current "DMIema" is above "DMIema[1]" or above 0.99, otherwise the signal is negative.
3. Thresholds Crossing: simple ta.crossover and ta.crossunder of the user defined threshold for Long and Short.
4. Fast Threshold: signal changes if the value of "DMIema" changes by more than user defined threshold against the current signal.
Pine Script®
// Slow
dmicol1 = DMIema > 0 ? colup : coldn
// Fast
dmicol2 = DMIema > DMIema[1] or DMIema > 0.99 ? colup : coldn
// Thresholds Crossing
var color dmicol3 = na
if ta.crossover(DMIema,longth)
dmicol3 := colup
if ta.crossunder(DMIema,shortth)
dmicol3 := coldn
// Fast Threshold
var color dmicol4 = na
if (DMIema > DMIema[1] + fastth)
dmicol4 := colup
if (DMIema < DMIema[1] - fastth)
dmicol4 := coldn
color dmicol = na
if sigmode == "Slow"
dmicol := dmicol1
if sigmode == "Fast"
dmicol := dmicol2
if sigmode == "Thresholds Crossing"
dmicol := dmicol3
if sigmode == "Fast Threshold"
dmicol := dmicol4
else
na
dmicol1 = DMIema > 0 ? colup : coldn
// Fast
dmicol2 = DMIema > DMIema[1] or DMIema > 0.99 ? colup : coldn
// Thresholds Crossing
var color dmicol3 = na
if ta.crossover(DMIema,longth)
dmicol3 := colup
if ta.crossunder(DMIema,shortth)
dmicol3 := coldn
// Fast Threshold
var color dmicol4 = na
if (DMIema > DMIema[1] + fastth)
dmicol4 := colup
if (DMIema < DMIema[1] - fastth)
dmicol4 := coldn
color dmicol = na
if sigmode == "Slow"
dmicol := dmicol1
if sigmode == "Fast"
dmicol := dmicol2
if sigmode == "Thresholds Crossing"
dmicol := dmicol3
if sigmode == "Fast Threshold"
dmicol := dmicol4
else
na
Functionality
The DMI ForLoop indicator calculates an array of DMI values over a specified range of lengths, then averages these values and applies an EMA for smoothing. The result is a dynamic trend indicator that adapts to market conditions.
DMI Calculation:
The indicator iterates through lengths from Start Length to End Length, calculating the positive and negative directional movement (DM) for each period and calculates the average of all the signals at the end. A custom function version of the DMI is used here in order to use DMI with "series" inputs.
Pine Script®
// Function to calculate an array of DMI values over a range of lengths
DMIArray(a, b, c) =>
// Initialize an array to store DMI values, with size based on the range (b - a + 1)
var dmiArray = array.new_float(b - a + 1, 0.0)
// Loop through each length from a to b
for x = 0 to (b - a)
// Calculate the smoothing factor alpha for the current length
alpha = 1.0 / (a + x)
// Initialize variables for positive and negative DM
float plus = na
float minus = na
// Calculate the up and down movements
up = ta.change(high)
down = -ta.change(low)
// Determine the positive DM (plusDM)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
// Determine the negative DM (minusDM)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
// Calculate the smoothed positive DM using either SMA or EMA
plus := na(plus[1]) ? ta.sma(plusDM, (a + x)) : alpha * plusDM + (1 - alpha) * nz(plus[1])
// Calculate the smoothed negative DM using either SMA or EMA
minus := na(minus[1]) ? ta.sma(minusDM, (a + x)) : alpha * minusDM + (1 - alpha) * nz(minus[1])
// Determine the trend direction: 1 for positive trend, -1 for negative trend, 0 for no trend
trend = plus > minus ? 1 : plus < minus ? -1 : 0
// Store the trend value in the DMI array
array.set(dmiArray, x, trend)
// Calculate the average of the DMI array
dmiAvg = array.avg(dmiArray)
// Apply an EMA to the average DMI value
DMIema = ta.ema(dmiAvg, c)
// Return the DMI array, its average, and the EMA of the average
[dmiArray, dmiAvg, DMIema]
// Call the DMIArray function with the input parameters and assign the results to variables
[dmiArray, dmiAvg, DMIema] = DMIArray(a, b, c)
DMIArray(a, b, c) =>
// Initialize an array to store DMI values, with size based on the range (b - a + 1)
var dmiArray = array.new_float(b - a + 1, 0.0)
// Loop through each length from a to b
for x = 0 to (b - a)
// Calculate the smoothing factor alpha for the current length
alpha = 1.0 / (a + x)
// Initialize variables for positive and negative DM
float plus = na
float minus = na
// Calculate the up and down movements
up = ta.change(high)
down = -ta.change(low)
// Determine the positive DM (plusDM)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
// Determine the negative DM (minusDM)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
// Calculate the smoothed positive DM using either SMA or EMA
plus := na(plus[1]) ? ta.sma(plusDM, (a + x)) : alpha * plusDM + (1 - alpha) * nz(plus[1])
// Calculate the smoothed negative DM using either SMA or EMA
minus := na(minus[1]) ? ta.sma(minusDM, (a + x)) : alpha * minusDM + (1 - alpha) * nz(minus[1])
// Determine the trend direction: 1 for positive trend, -1 for negative trend, 0 for no trend
trend = plus > minus ? 1 : plus < minus ? -1 : 0
// Store the trend value in the DMI array
array.set(dmiArray, x, trend)
// Calculate the average of the DMI array
dmiAvg = array.avg(dmiArray)
// Apply an EMA to the average DMI value
DMIema = ta.ema(dmiAvg, c)
// Return the DMI array, its average, and the EMA of the average
[dmiArray, dmiAvg, DMIema]
// Call the DMIArray function with the input parameters and assign the results to variables
[dmiArray, dmiAvg, DMIema] = DMIArray(a, b, c)
This indicator is versatile and can be tailored to fit various trading/investing strategies by adjusting the input parameters and signal modes.
Notas de Lançamento
Update:- option to choose different type of Moving Average
Pine Script®
maType = input.string("EMA", "MA Type", ["EMA", "SMA", "WMA", "VWMA","TMA"], group = "DMI ForLoop Settings", inline = "M")
DMIArray(a, b, c) =>
var dmiArray = array.new_float(b - a + 1, 0.0)
for x = 0 to (b - a)
alpha = 1.0 / (a + x)
float plus = na
float minus = na
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)
plus := na(plus[1]) ? ta.sma(plusDM, (a + x)) : alpha * plusDM + (1 - alpha) * nz(plus[1])
minus := na(minus[1]) ? ta.sma(minusDM, (a + x)) : alpha * minusDM + (1 - alpha) * nz(minus[1])
trend = plus > minus ? 1 : plus < minus ? -1 : 0
array.set(dmiArray, x, trend)
dmiAvg = array.avg(dmiArray)
float DMIma = switch maType
"EMA" => ta.ema(dmiAvg, c)
"SMA" => ta.sma(dmiAvg, c)
"WMA" => ta.wma(dmiAvg, c)
"VWMA" => ta.vwma(dmiAvg, c)
"TMA" => ta.trima(dmiAvg, c)
=>
runtime.error("No matching MA type found.")
float(na)
[dmiArray,dmiAvg, DMIma]
DMIArray(a, b, c) =>
var dmiArray = array.new_float(b - a + 1, 0.0)
for x = 0 to (b - a)
alpha = 1.0 / (a + x)
float plus = na
float minus = na
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)
plus := na(plus[1]) ? ta.sma(plusDM, (a + x)) : alpha * plusDM + (1 - alpha) * nz(plus[1])
minus := na(minus[1]) ? ta.sma(minusDM, (a + x)) : alpha * minusDM + (1 - alpha) * nz(minus[1])
trend = plus > minus ? 1 : plus < minus ? -1 : 0
array.set(dmiArray, x, trend)
dmiAvg = array.avg(dmiArray)
float DMIma = switch maType
"EMA" => ta.ema(dmiAvg, c)
"SMA" => ta.sma(dmiAvg, c)
"WMA" => ta.wma(dmiAvg, c)
"VWMA" => ta.vwma(dmiAvg, c)
"TMA" => ta.trima(dmiAvg, c)
=>
runtime.error("No matching MA type found.")
float(na)
[dmiArray,dmiAvg, DMIma]
- Adjusted signal calculation for the "Fast" signal to work well with different types of the Moving Average
Pine Script®
var color dmicol2 = na
if DMIma > DMIma[1] or DMIma > 0.99
dmicol2 := colup
if DMIma < DMIma[1] or DMIma < -0.99
dmicol2 := coldn
if DMIma > DMIma[1] or DMIma > 0.99
dmicol2 := colup
if DMIma < DMIma[1] or DMIma < -0.99
dmicol2 := coldn
- Added Alerts
Pine Script®
barconfirm = input.bool(false, "Wait for bar close for Alert?", group = "Alert Settings")
var int alertsignal = na
if dmicol == colup
alertsignal := 1
if dmicol == coldn
alertsignal := -1
Long = ta.crossover(alertsignal, 0)
Short = ta.crossunder(alertsignal, 0)
alertcondition(barconfirm ? Long[1] : Long, "LONG", "DMI ForLoop went Long")
alertcondition(barconfirm ? Short[1] : Short,"SHORT", "DMI ForLoop went SHORT")
var int alertsignal = na
if dmicol == colup
alertsignal := 1
if dmicol == coldn
alertsignal := -1
Long = ta.crossover(alertsignal, 0)
Short = ta.crossunder(alertsignal, 0)
alertcondition(barconfirm ? Long[1] : Long, "LONG", "DMI ForLoop went Long")
alertcondition(barconfirm ? Short[1] : Short,"SHORT", "DMI ForLoop went SHORT")
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Para acesso rápido no gráfico, adicione esse script para seus favoritos — saiba mais aqui.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Para acesso rápido no gráfico, adicione esse script para seus favoritos — saiba mais aqui.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.