-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindicatorCreation.cpp
More file actions
91 lines (70 loc) · 1.79 KB
/
Copy pathindicatorCreation.cpp
File metadata and controls
91 lines (70 loc) · 1.79 KB
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
#include <iostream>
#include <cstdint>
using TickFn = void(*)(void*, double);
struct IndicatorEntry {
void* ptr;
TickFn fn;
};
template<int N>
struct SMA {
double ring[N] = {};
double sum = 0.0;
int idx = 0;
inline void on_tick(double x) noexcept {
sum -= ring[idx];
ring[idx] = x;
sum += x;
idx = (idx + 1) & (N - 1);
double value = sum / N;
std::cout << "SMA<" << N << "> = " << value << "\n";
}
};
template<int N>
void sma_tick(void* p, double x) {
static_cast<SMA<N>*>(p)->on_tick(x);
}
struct EMA {
double alpha;
double value = 0.0;
EMA(double a) : alpha(a) {}
inline void on_tick(double x) noexcept {
value = alpha * x + (1.0 - alpha) * value;
std::cout << "EMA(alpha=" << alpha << ") = " << value << "\n";
}
};
void ema_tick(void* p, double x) {
static_cast<EMA*>(p)->on_tick(x);
}
SMA<8> sma8;
SMA<16> sma16;
EMA ema_fast(0.2);
EMA ema_slow(0.05);
IndicatorEntry make_sma(int window) {
switch (window) {
case 8: return {&sma8, &sma_tick<8>};
case 16: return {&sma16, &sma_tick<16>};
default:
throw std::runtime_error("Unsupported SMA window");
}
}
IndicatorEntry make_ema(double alpha) {
if (alpha == 0.2)
return {&ema_fast, &ema_tick};
else
return {&ema_slow, &ema_tick};
}
int main() {
IndicatorEntry table[10];
int count = 0;
table[count++] = make_sma(8);
table[count++] = make_sma(16);
table[count++] = make_ema(0.2);
double prices[] = {100, 101, 102, 103, 104, 105};
for (double price : prices) {
std::cout << "---- price = " << price << " ----\n";
for (int i = 0; i < count; i++) {
table[i].fn(table[i].ptr, price);
}
}
return 0;
}