summaryrefslogtreecommitdiffstats
path: root/lib/adx.c
blob: 505732b921ba7bd892c3d055d878cd41b269f004 (plain)
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
// Adx
//
// adx
//
// Time series function
//
// See implementation
//
// Inputs:    4
// Outputs:   4
// Constants: 1


#include <math.h>
#include <stdint.h>
#include "ts.h"

typedef struct {
    uint_t k;
} ts_adx_params_t;

ts_parameter_t const ts_adx_p = { .n_inputs = 4, .n_outputs = 4, .n_constants = 1, .params_size = sizeof(ts_adx_params_t) };

uint_t ts_adx_offset( ts_constant_t const *c )
{
	( void )c;
	return ( c ? ((ts_adx_params_t *)c)->k + 1 : 0 );
}

int ts_adx(
	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_adx_p );
	if ( !c ) return -1;
	TS_CHECK_INPUT(x, x_n, n);
	uint_t k = ((ts_adx_params_t *)c)->k;
	if (k == 0) return -1;

	fp_t ema_plus = 0, ema_minus = 0, ema_tr = 0;
	fp_t prev_dx = 0;

	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;

		fp_t tr = fmax( ts_h( x, i ) - ts_l( x, i ),
		                fmax( fabs( ts_h( x, i ) - ts_c( x, i - 1 ) ),
		                      fabs( ts_l( x, i ) - ts_c( x, i - 1 ) ) ) );

		ema_plus = i == 1 ? plus_dm
		                  : ema_plus + ( 1.0 / k ) * ( plus_dm - ema_plus );
		ema_minus = i == 1 ? minus_dm
		                   : ema_minus + ( 1.0 / k ) * ( minus_dm - ema_minus );
		ema_tr = i == 1 ? tr
		                 : ema_tr + ( 1.0 / k ) * ( tr - ema_tr );

		if( i > k )
		{
			fp_t di_plus = ema_tr != 0 ? 100.0 * ema_plus / ema_tr : 0;
			fp_t di_minus = ema_tr != 0 ? 100.0 * ema_minus / ema_tr : 0;

			y[0][i] = di_plus;
			y[1][i] = di_minus;

			fp_t sum = di_plus + di_minus;
			fp_t dx = sum != 0 ? 100.0 * fabs( di_plus - di_minus ) / sum : 0;

			y[2][i] = dx;
			y[3][i] = i == k + 1 ? dx
			                         : prev_dx + ( 1.0 / k ) * ( dx - prev_dx );
			prev_dx = y[3][i];
		}
	}

	return 0;
}