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.
Top comments (0)