diff options
Diffstat (limited to 'lib/di_plus.c')
| -rw-r--r-- | lib/di_plus.c | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/lib/di_plus.c b/lib/di_plus.c new file mode 100644 index 0000000..fb3c076 --- /dev/null +++ b/lib/di_plus.c @@ -0,0 +1,69 @@ +// Plus Directional Indicator +// +// di_plus - DI+ +// +// 100 * EMA(+DM) / (EMA(+DM) + EMA(-DM)), measures upward pressure +// +// Inputs: 4 (OHLC) +// Outputs: 1 (DI+) +// Constants: 1 (period) + +#include <math.h> +#include <stdlib.h> +#include "ts.h" + +typedef struct { + uint_t k; +} ts_di_plus_params_t; + +ts_parameter_t const ts_di_plus_p = { .n_inputs = 4, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_di_plus_params_t) }; + +uint_t ts_di_plus_offset( ts_constant_t const *c ) +{ + ( void )c; + return ( c ? ((ts_di_plus_params_t *)c)->k : 0 ); +} + +int ts_di_plus( + fp_t * const *y, uint_t y_n, + fp_t const * const *x, uint_t x_n, + uint_t n, ts_constant_t const *c +) +{ + TS_PROLOGUE( ts_di_plus_p ); + if ( !c ) return -1; + uint_t k = ((ts_di_plus_params_t *)c)->k; + if (k == 0 || n < 2) return -1; + fp_t *ema_plus = calloc( n, sizeof( fp_t ) ); + fp_t *ema_minus = calloc( n, sizeof( fp_t ) ); + if( !ema_plus || !ema_minus ) { free( ema_plus ); free( ema_minus ); return -1; } + + for( uint_t i = 1; i < n; ++i ) + { + fp_t hdmd = ts_h( x, i ) - ts_h( x, i - 1 ); + fp_t ldml = ts_l( x, i - 1 ) - ts_l( x, i ); + + fp_t plus_dm = hdmd > ldml && hdmd > 0 ? hdmd : 0; + fp_t minus_dm = ldml > hdmd && ldml > 0 ? ldml : 0; + + ema_plus[i] = i == 1 ? plus_dm + : ema_plus[i - 1] + ( 1.0 / k ) * ( plus_dm - ema_plus[i - 1] ); + ema_minus[i] = i == 1 ? minus_dm + : ema_minus[i - 1] + ( 1.0 / k ) * ( minus_dm - ema_minus[i - 1] ); + } + + for (uint_t j = 0; j < n && j < k; ++j) y[0][j] = 0; + + for( uint_t i = k; i < n; ++i ) + { + fp_t denom = ema_plus[i] + ema_minus[i]; + y[0][i] = denom != 0 ? 100.0 * ema_plus[i] / denom : 0; + } + + free( ema_plus ); + free( ema_minus ); + return 0; +} + + + |