-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAdvanced_08_IntegratedSystem.cs
More file actions
253 lines (217 loc) · 8.27 KB
/
Copy pathAdvanced_08_IntegratedSystem.cs
File metadata and controls
253 lines (217 loc) · 8.27 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
using System;
using System.Collections.Generic;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
namespace NinjaTrader.NinjaScript.Indicators
{
public class IntegratedOrderFlowSystem : Indicator {
private IVolumeStrategy volStrat;
private TypeSafeCalculator calc;
private SnaphotBuffer snapBuf;
private RingBuffer deltaRing;
private readonly ConfigurationManager cfg;
private int barsProcessed = 0;
private double cumulativeDeviation = 0;
public IntegratedOrderFlowSystem() {
cfg = ConfigurationManager.Instance;
volStrat = new VolumeConcentrationStrategy(20);
}
protected override void OnStateChange() {
if (State == State.SetDefaults) {
Description = "Integrated Order Flow System - All concepts combined";
Name = "IntegratedOrderFlowSystem";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
DisplayInDataBox = true;
AddPlot(Brushes.DodgerBlue, "MainSignal");
AddPlot(Brushes.Green, "QualityScore");
AddPlot(Brushes.Red, "RiskLevel");
AddPlot(Brushes.Orange, "Efficiency");
AddPlot(Brushes.Purple, "Sentiment");
}
else if (State == State.Configure) {
cfg.Set("system_enabled", true);
calc = new TypeSafeCalculator();
snapBuf = new SnaphotBuffer(100);
deltaRing = new RingBuffer(30);
}
}
protected override void OnBarUpdate() {
try {
if (!ValidateInputs())
return;
ProcessBar();
CalculateMetrics();
UpdateSignals();
barsProcessed++;
}
catch (Exception ex) {
HandleCriticalError(ex);
}
}
private bool ValidateInputs() {
if (Close[0] <= 0 || Volume[0] <= 0)
return false;
if (CurrentBar < 5)
return false;
bool sysEnabled = (bool)(cfg.Get("system_enabled") ?? true);
return sysEnabled;
}
private void ProcessBar() {
double delta = Close[0] - (CurrentBar > 0 ? Close[1] : Close[0]);
deltaRing.Append(delta);
var snap = new OrderFlowSnapshot {
Timestamp = CurrentBar,
Close = Close[0],
Volume = Volume[0],
Delta = Math.Sign(delta) * Volume[0]
};
snapBuf.Add(snap);
}
private void CalculateMetrics() {
var priceArr = new double[5];
var volArr = new double[5];
for (int i = 0; i < 5; i++) {
if (CurrentBar >= i) {
priceArr[4 - i] = Closes[i];
volArr[4 - i] = Volumes[i];
}
}
var res = calc.CalculateDelta(priceArr, volArr);
double mainSignal = res.Match(
val => val / (volArr[4] + 0.0001),
err => 0
);
double concentration = volStrat.Calculate(volArr, priceArr);
double riskLevel = CalcRisk(concentration);
double efficiency = CalcEfficiency();
double sentiment = CalcSentiment();
Values[0][0] = mainSignal;
Values[1][0] = concentration;
Values[2][0] = riskLevel;
Values[3][0] = efficiency;
Values[4][0] = sentiment;
}
private void UpdateSignals() {
if (barsProcessed % 5 == 0) {
cumulativeDeviation = CalculateStats();
}
}
private double CalcRisk(double conc) {
double baseRisk = conc > 0.7 ? 0.8 : (conc > 0.5 ? 0.5 : 0.2);
double volRisk = Volume[0] > Volume[1] * 1.5 ? 0.3 : 0;
return Math.Min(baseRisk + volRisk, 1.0);
}
private double CalcEfficiency() {
double range = High[0] - Low[0];
double avgRange = 0;
for (int i = 0; i < 5; i++) {
if (CurrentBar >= i)
avgRange += (High[i] - Low[i]);
}
avgRange /= 5;
return avgRange > 0 ? range / avgRange : 0;
}
private double CalcSentiment() {
double bullish = 0;
for (int i = 0; i < 10; i++) {
if (CurrentBar >= i && Close[i] > Open[i])
bullish++;
}
return (bullish / 10) * 2 - 1;
}
private double CalculateStats() {
double sum = 0;
double count = 0;
for (int i = 0; i < 20; i++) {
if (CurrentBar >= i) {
sum += Math.Abs(Close[i] - Close[i + 1]);
count++;
}
}
return count > 0 ? sum / count : 0;
}
private void HandleCriticalError(Exception ex) {
Values[2][0] = 1.0;
}
public override string DisplayName => "Integrated Order Flow System";
~IntegratedOrderFlowSystem() {
snapBuf?.Clear();
deltaRing?.Clear();
}
}
public class AdvancedDemo : Indicator {
protected override void OnStateChange() {
if (State == State.SetDefaults) {
Description = "Advanced Demo - Shows all pattern applications";
Name = "AdvancedDemo";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
DisplayInDataBox = true;
AddPlot(Brushes.Blue, "Demo");
}
}
protected override void OnBarUpdate() {
if (CurrentBar < 10)
return;
DemoBasePatternsBase();
DemoMemoryMgmt();
DemoPolymorphism();
DemoErrorHandling();
double combined = CalculateFinal();
Values[0][0] = combined;
}
private void DemoBasePatternsBase() {
// Shows encapsulation, abstraction
var snap = new OrderFlowSnapshot {
Timestamp = CurrentBar,
Close = Close[0],
Volume = Volume[0],
Delta = Volume[0]
};
}
private void DemoMemoryMgmt() {
// Shows RAII, pooling
var pool = new ObjectPool<OrderFlowSnapshot>(10);
var item = pool.Rent();
pool.Return(item);
}
private void DemoPolymorphism() {
// Shows strategy pattern, virtual functions
IVolumeStrategy strat = new VolumeConcentrationStrategy(5);
var prices = new double[5];
var vols = new double[5];
for (int i = 0; i < 5; i++) {
if (CurrentBar >= i) {
prices[4 - i] = Closes[i];
vols[4 - i] = Volumes[i];
}
}
double res = strat.Calculate(vols, prices);
}
private void DemoErrorHandling() {
// Shows type-safe error handling
var calc = new TypeSafeCalculator();
var prices = new List<double> { Close[0], Close[1] };
var vols = new List<double> { Volume[0], Volume[1] };
var result = calc.CalculateDelta(prices, vols);
result.MatchVoid(
val => { },
err => { }
);
}
private double CalculateFinal() {
double score = 0;
if (Close[0] > Close[1]) score += 0.2;
if (Volume[0] > Volume[1]) score += 0.2;
if (High[0] > High[1]) score += 0.2;
if (Close[0] > Open[0]) score += 0.2;
if (Volume[0] > (Volume[1] + Volume[2]) / 2) score += 0.2;
return Math.Min(score, 1.0);
}
public override string DisplayName => "Advanced Demo";
}
}