-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathstochasticOscillator.ts
74 lines (65 loc) · 1.71 KB
/
stochasticOscillator.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
// Copyright (c) 2022 Onur Cinar. All Rights Reserved.
// https://github.com/cinar/indicatorts
import { divide, multiplyBy, subtract } from '../../helper/numArray';
import { mmin } from '../trend/movingMin';
import { mmax } from '../trend/movingMax';
import { sma } from '../trend/simpleMovingAverage';
/**
* Stochastic oscillator result object.
*/
export interface StochResult {
k: number[];
d: number[];
}
/**
* Optional configuration of stochastic oscillator parameters.
*/
export interface StochConfig {
kPeriod?: number;
dPeriod?: number;
}
/**
* The default configuration of stochastic oscillator.
*/
export const StochDefaultConfig: Required<StochConfig> = {
kPeriod: 14,
dPeriod: 3,
};
/**
* Stochastic Oscillator. It is a momentum indicator that shows the
* location of the closing relative to high-low range over a
* set number of periods.
*
* K = (Closing - Lowest Low) / (Highest High - Lowest Low) * 100
* D = 3-Period SMA of K
*
* @param highs high values.
* @param lows low values.
* @param closings closing values.
* @param config configuration.
* @return stochastic oscillator result object.
*/
export function stoch(
highs: number[],
lows: number[],
closings: number[],
config: StochConfig = {}
): StochResult {
const { kPeriod, dPeriod } = {
...StochDefaultConfig,
...config,
};
const highestHigh = mmax(highs, { period: kPeriod });
const lowestLow = mmin(lows, { period: kPeriod });
const kValue = multiplyBy(
100,
divide(subtract(closings, lowestLow), subtract(highestHigh, lowestLow))
);
const dValue = sma(kValue, { period: dPeriod });
return {
k: kValue,
d: dValue,
};
}
// Export full name
export { stoch as stochasticOscillator };