// Mass Index // // mass_index // // Mass Index // // SMA of EMA(H/L) ratio, reversal when > threshold // // Inputs: 5 // Outputs: 1 // Constants: 0 #include #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; }