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
|
// ATR Trailing Stops
//
// atr_trailing_stops - ATR stops
//
// Upper stop: max(prev, (H+L)/2 + mult*ATR)
// Lower stop: min(prev, (H+L)/2 - mult*ATR)
//
// Inputs: 4 (OHLC)
// Outputs: 2 (Upper Stop, Lower Stop)
// Constants: 2 (period, multiplier)
#include <math.h>
#include "ts.h"
typedef struct {
uint_t k;
fp_t mult;
} ts_atr_trailing_stops_params_t;
ts_parameter_t const ts_atr_trailing_stops_p = { .n_inputs = 4, .n_outputs = 2, .n_constants = 2, .params_size = sizeof(ts_atr_trailing_stops_params_t) };
uint_t ts_atr_trailing_stops_offset( ts_constant_t const *c )
{
( void )c;
return ( c ? ((ts_atr_trailing_stops_params_t *)c)->k : 0 );
}
int ts_atr_trailing_stops(
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_atr_trailing_stops_p );
if ( !c ) return -1;
uint_t k = ((ts_atr_trailing_stops_params_t *)c)->k;
if (k == 0) return -1;
if (n < k + 1) return -1;
fp_t mult = ((ts_atr_trailing_stops_params_t *)c)->mult;
fp_t tr_sum = 0;
fp_t atr = 0;
for( uint_t i = 1; i < n; ++i )
{
fp_t tr = fmax( ts_h( x, i ) - ts_l( x, i ), fmax( fabs( ts_h( x, i ) - ts_c( x, i - 1 ) ), fabs( ts_l( x, i ) - ts_c( x, i - 1 ) ) ) );
if( i < k )
{
tr_sum += tr;
atr = tr_sum / (fp_t)i;
}
else if( i == k )
{
tr_sum += tr;
atr = tr_sum / (fp_t)k;
}
else
{
atr = ( atr * ( k - 1 ) + tr ) / k;
}
if( i >= k )
{
fp_t mid = ( ts_h( x, i ) + ts_l( x, i ) ) / 2.0;
fp_t calc_upper = mid + mult * atr;
fp_t calc_lower = mid - mult * atr;
if( i == k )
{
y[0][i] = calc_upper;
y[1][i] = calc_lower;
}
else
{
y[0][i] = fmax( y[0][i - 1], calc_upper );
y[1][i] = fmin( y[1][i - 1], calc_lower );
}
}
}
return 0;
}
|