blob: 81992a6e0a423e3b411a56c251c296a9c35fed89 (
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
|
// Stoch Rsi
//
// stoch_rsi
//
// Stochastic RSI
//
//
//
// Inputs: 1
// Outputs: 2
// Constants: 2
#include <math.h>
#include <stdlib.h>
#include "ts.h"
typedef struct {
uint_t rsi_period;
uint_t stoch_period;
} ts_stoch_rsi_params_t;
ts_parameter_t const ts_stoch_rsi_p = { .n_inputs = 1, .n_outputs = 2, .n_constants = 2, .params_size = sizeof(ts_stoch_rsi_params_t) };
uint_t ts_stoch_rsi_offset( ts_constant_t const *c )
{
( void )c;
return ( c ? ((ts_stoch_rsi_params_t *)c)->rsi_period + ((ts_stoch_rsi_params_t *)c)->stoch_period - 1 : 0 );
}
int ts_stoch_rsi(
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_stoch_rsi_p );
if ( !c ) return -1;
uint_t rsi_period = ((ts_stoch_rsi_params_t *)c)->rsi_period;
uint_t stoch_period = ((ts_stoch_rsi_params_t *)c)->stoch_period;
if (rsi_period == 0 || stoch_period == 0) return -1;
fp_t *rsi_values = NULL;
if( n > 0 )
{
rsi_values = calloc( n, sizeof( fp_t ) );
if( !rsi_values ) return -1;
}
for( uint_t i = rsi_period; i < n; ++i )
{
fp_t sum_gain = 0;
fp_t sum_loss = 0;
for( uint_t j = 0; j < rsi_period; ++j )
{
fp_t change = x[0][i - rsi_period + 1 + j] - x[0][i - rsi_period + j];
if( change > 0 )
sum_gain += change;
else if( change < 0 )
sum_loss += (-change);
}
if( sum_loss == 0 )
rsi_values[i] = 100.0;
else
{
fp_t rs = sum_gain / sum_loss;
rsi_values[i] = 100.0 - ( 100.0 / ( 1.0 + rs ) );
}
}
for (uint_t j = 0; j < n && j < rsi_period + stoch_period - 1; ++j) { y[0][j] = 0; y[1][j] = 0; }
for( uint_t i = rsi_period + stoch_period - 1; i < n; ++i )
{
fp_t rsi_min = rsi_values[i - stoch_period + 1];
fp_t rsi_max = rsi_values[i - stoch_period + 1];
for( uint_t j = 1; j < stoch_period; ++j )
{
rsi_min = fmin( rsi_min, rsi_values[i - stoch_period + 1 + j] );
rsi_max = fmax( rsi_max, rsi_values[i - stoch_period + 1 + j] );
}
fp_t denom = rsi_max - rsi_min;
fp_t stoch_k = denom != 0 ? ( rsi_values[i] - rsi_min ) / denom : 0;
fp_t stoch_d = stoch_k;
y[0][i] = stoch_k;
y[1][i] = stoch_d;
}
free( rsi_values );
return 0;
}
|