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
86
87
88
89
90
91
|
// Mass Index
//
// mass_index
//
// Mass Index
//
// SMA of EMA(H/L) ratio, reversal when > threshold
//
// Inputs: 5
// Outputs: 1
// Constants: 0
#include <stdlib.h>
#include "ts.h"
ts_parameter_t const ts_mass_index_p = { .n_inputs = 4, .n_outputs = 1, .n_constants = 0, .params_size = 0 };
uint_t ts_mass_index_offset( ts_constant_t const *c )
{
( void )c;
return ( 26 );
}
int ts_mass_index(
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_mass_index_p );
(void)c;
uint_t ema_period = 9;
uint_t sum_period = 26;
if (n < sum_period) return -1;
fp_t *hl = calloc( n, sizeof( fp_t ) );
fp_t *ema1 = calloc( n, sizeof( fp_t ) );
fp_t *ema2 = calloc( n, sizeof( fp_t ) );
fp_t *ratio = calloc( n, sizeof( fp_t ) );
if ( !hl || !ema1 || !ema2 || !ratio )
{
free( hl ); free( ema1 ); free( ema2 ); free( ratio );
return -1;
}
fp_t a1 = 2.0 / ( ( fp_t )ema_period + 1.0 );
for ( uint_t i = 0; i < n; ++i )
{
hl[i] = ts_h( x, i ) - ts_l( x, i );
}
ema1[0] = hl[0];
for ( uint_t i = 1; i < n; ++i )
{
ema1[i] = ema1[i - 1] + a1 * ( hl[i] - ema1[i - 1] );
}
ema2[0] = ema1[0];
for ( uint_t i = 1; i < n; ++i )
{
ema2[i] = ema2[i - 1] + a1 * ( ema1[i] - ema2[i - 1] );
}
for ( uint_t i = 0; i < n; ++i )
{
ratio[i] = ema2[i] != 0 ? ema1[i] / ema2[i] : 0;
}
fp_t sum = 0;
for ( uint_t i = 0; i < sum_period; ++i )
{
sum += ratio[i];
}
for ( uint_t j = 0; j < sum_period - 1; ++j ) y[0][j] = 0;
y[0][sum_period - 1] = sum;
for ( uint_t i = sum_period; i < n; ++i )
{
sum = sum - ratio[i - sum_period] + ratio[i];
y[0][i] = sum;
}
free( hl ); free( ema1 ); free( ema2 ); free( ratio );
return 0;
}
|