// Mesa Sine Wave // // mesa_sine_wave // // Mesa Sine Wave // // Adaptive sine wave following price trends // // Inputs: 1 // Outputs: 2 // Constants: 1 #include #include #include "ts.h" typedef struct { uint_t k; } ts_mesa_sine_wave_params_t; ts_parameter_t const ts_mesa_sine_wave_p = { .n_inputs = 1, .n_outputs = 2, .n_constants = 1, .params_size = sizeof(ts_mesa_sine_wave_params_t) }; uint_t ts_mesa_sine_wave_offset( ts_constant_t const *c ) { ( void )c; return ( c ? ((ts_mesa_sine_wave_params_t *)c)->k : 0 ); } int ts_mesa_sine_wave( 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_mesa_sine_wave_p ); if ( !c ) return -1; uint_t k = ((ts_mesa_sine_wave_params_t *)c)->k; if (k < 2 || n < k) return -1; fp_t *sma = calloc(n, sizeof(fp_t)); if (!sma) return -1; for (uint_t i = 0; i < n; ++i) { if (i < k - 1) { fp_t sum = 0; for (uint_t j = 0; j <= i; ++j) sum += x[0][j]; sma[i] = sum / (i + 1); } else { fp_t sum = 0; for (uint_t j = i - k + 1; j <= i; ++j) sum += x[0][j]; sma[i] = sum / k; } } fp_t ema_roc = 0; uint_t ema_period = 5; fp_t ema_a = 2.0 / (ema_period + 1); fp_t phase = 0; int_t first = 1; for (uint_t j = 0; j < n && j < k; ++j) { y[0][j] = 0; y[1][j] = 0; } for (uint_t i = k; i < n; ++i) { fp_t roc = sma[i] - sma[i - 2]; if (first) { ema_roc = roc; first = 0; } else { ema_roc = ema_roc + ema_a * (roc - ema_roc); } fp_t smoothed = ema_roc; if (smoothed > 1.0) smoothed = 1.0; if (smoothed < 0.01) smoothed = 0.01; fp_t wperiod = 2 * PI / smoothed; if (wperiod < 5) wperiod = 5; if (wperiod > 12) wperiod = 12; if (smoothed >= 1.0) { phase = 0; } else if (smoothed <= 0.01) { phase = 2 * PI; } else { phase += 2 * PI / wperiod; } while (phase > 2 * PI) phase -= 2 * PI; y[0][i] = cos(phase); y[1][i] = cos(phase + PI / 2); } free(sma); return 0; }