forked from cinar/indicatorts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomIndex.ts
85 lines (76 loc) · 2.06 KB
/
randomIndex.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) 2022 Onur Cinar. All Rights Reserved.
// https://github.com/cinar/indicatorts
import { divide, multiplyBy, subtract } from '../../helper/numArray';
import { mmin } from './movingMin';
import { mmax } from './movingMax';
import { sma } from './simpleMovingAverage';
/**
* KDJ result.
*/
export interface KDJResult {
k: number[];
d: number[];
j: number[];
}
/**
* Optional configuration of KDJ parameters.
*/
export interface KDJConfig {
rPeriod?: number;
kPeriod?: number;
dPeriod?: number;
}
/**
* The default configuration of KDJ.
*/
export const KDJDefaultConfig: Required<KDJConfig> = {
rPeriod: 9,
kPeriod: 3,
dPeriod: 3,
};
/**
* The kdj function calculates the KDJ indicator, also known as
* the Random Index. KDJ is calculated similar to the Stochastic
* Oscillator with the difference of having the J line. It is
* used to analyze the trend and entry points.
*
* The K and D lines show if the asset is overbought when they
* crosses above 80%, and oversold when they crosses below
* 20%. The J line represents the divergence.
*
* RSV = ((Closing - Min(Low, rPeriod))
* / (Max(High, rPeriod) - Min(Low, rPeriod))) * 100
* K = Sma(RSV, kPeriod)
* D = Sma(K, dPeriod)
* J = (3 * K) - (2 * D)
*
* @param highs high values.
* @param lows low values.
* @param closings closing values.
* @param config configuration.
* @return kdj result.
*/
export function kdj(
highs: number[],
lows: number[],
closings: number[],
config: KDJConfig = {}
): KDJResult {
const { rPeriod, kPeriod, dPeriod } = { ...KDJDefaultConfig, ...config };
const highest = mmax(highs, { period: rPeriod });
const lowest = mmin(lows, { period: rPeriod });
const rsv = multiplyBy(
100,
divide(subtract(closings, lowest), subtract(highest, lowest))
);
const kValue = sma(rsv, { period: kPeriod });
const dValue = sma(kValue, { period: dPeriod });
const jValue = subtract(multiplyBy(3, kValue), multiplyBy(2, dValue));
return {
k: kValue,
d: dValue,
j: jValue,
};
}
// Export full name
export { kdj as randomIndex };