dev-resources.site
for different kinds of informations.
Calculating DMI (Directional Movement Index) with JavaScript
Published at
12/19/2022
Categories
algorithmictrading
javascript
trading
Author
Mustafa Onur Γelik
DMI (Directional Movement Index) is a technical analysis indicator that shows the strength of a price trend. It is calculated using the following steps:
- Calculate the positive directional index (PDI) and the negative directional index (NDI).
- Calculate the average true range (ATR).
- Calculate the directional movement index (DMI).
Here is some example code in JavaScript that demonstrates how to calculate DMI using the above steps:
function calculateDMI(prices, periods) {
let pdi = [];
let ndi = [];
let atr = [];
let dmi = [];
for (let i = 0; i < prices.length; i++) {
// Calculate the positive directional index (PDI)
let upMove = prices[i].high - prices[i - 1].high;
let downMove = prices[i - 1].low - prices[i].low;
let pdiValue = 0;
if (upMove > downMove && upMove > 0) {
pdiValue = upMove;
}
pdi.push(pdiValue);
// Calculate the negative directional index (NDI)
let ndiValue = 0;
if (downMove > upMove && downMove > 0) {
ndiValue = downMove;
}
ndi.push(ndiValue);
// Calculate the average true range (ATR)
let tr = Math.max(
prices[i].high - prices[i].low,
Math.abs(prices[i].high - prices[i - 1].close),
Math.abs(prices[i].low - prices[i - 1].close)
);
let atrValue = 0;
if (i < periods) {
atrValue = tr;
} else {
atrValue = (atr[i - 1] * (periods - 1) + tr) / periods;
}
atr.push(atrValue);
// Calculate the directional movement index (DMI)
let dmiValue = 0;
if (atrValue > 0) {
dmiValue = (pdi[i] / atrValue) - (ndi[i] / atrValue);
}
dmi.push(dmiValue);
}
return { pdi, ndi, atr, dmi };
}
In this example, the calculateDMI function takes an array of price data and the number of periods to use in the calculation as input, and returns an object with the PDI, NDI, ATR, and DMI arrays.
You can use this function to calculate DMI for any security by passing in an array of its historical price data and the desired number of periods.
Articles
12 articles in total
Backtesting a trading strategy with JavaScript
read article
How to predict direction with orderbook data
read article
How to calculate Average Directional Index (ADX) using JavaScript
read article
Calculating DMI (Directional Movement Index) with JavaScript
currently reading
Calculating ATR (Average True Range) using JavaScript
read article
What is Algorithmic Trading
read article
Algorithmic Trading Strategies
read article
How to make an arbitrage trade
read article
Calculating the Exponential Moving Average (EMA) with JavaScript
read article
Calculate the Fear and Greed Index with JavaScript
read article
Calculating the Stochastic Oscillator (STOCH) with JavaScript
read article
Calculating the Moving Average Convergence Divergence (MACD) with JavaScript
read article
Featured ones: