blob: 8ed5fa6b5e51d3acd8c5c7d5ee4f1081e73e3f5b (
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
// Mesa Sine Wave
//
// mesa_sine_wave
//
// Mesa Sine Wave
//
// Adaptive sine wave following price trends
//
// Inputs: 1
// Outputs: 2
// Constants: 1
#include <math.h>
#include <stdlib.h>
#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;
}
|