-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathOrderFlowDelta.cs
680 lines (590 loc) · 18.9 KB
/
OrderFlowDelta.cs
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
[Gui.CategoryOrder("NetDelta", 1000100)]
[Gui.CategoryOrder("Entry&Exit", 1000200)]
[Gui.CategoryOrder("Profit&Loss", 1000300)]
[Gui.CategoryOrder("Trading", 1000400)]
[Gui.CategoryOrder("Display", 1000500)]
[Gui.CategoryOrder("ATM", 1000600)]
public class OrderFlowDelta : Strategy
{
#region Classes
private class PositionInfo : ICloneable
{
public MarketPosition PositionType { get; set; }
public double Price { get; set; }
public int Quantity { get; set; }
public double ExitPrice { get; set; }
public int ExitQuantity { get; set; }
public PositionInfo()
{
Reset();
}
public void Reset()
{
PositionType = MarketPosition.Flat;
Price = 0d;
Quantity = 0;
ExitPrice = 0d;
ExitQuantity = 0;
}
public object Clone()
{
return new PositionInfo
{
PositionType = PositionType,
Price = Price,
Quantity = Quantity,
ExitPrice = ExitPrice,
ExitQuantity = ExitQuantity
};
}
public override string ToString()
{
return string.Format("dir: {0}, p: {1}, q: {2}, ep: {3}, eq: {4}", PositionType, Price, Quantity, ExitPrice, ExitQuantity);
}
}
#endregion
#region Variables
private OrderFlowCumulativeDelta _OFCD;
private PositionInfo _positionInfo;
private PositionInfo _lastPositionInfo;
private double _totalLossAmount;
private double _totalProfitAmount;
private string _atmStrategyId;
private string _atmStrategyOrderId;
private bool _isAtmStrategyCreated;
private SimpleFont _markerFont;
private bool _isLongDisabled;
private bool _isShortDisabled;
#endregion
#region Initialization
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"OrderFlowDelta";
Name = "OrderFlowDelta";
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 0;
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
TraceOrders = false;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 20;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
NetDelta = 50;
Enable_Long = true;
Bars_Above_Trend_For_Long = 3;
Enable_Short = true;
Bars_Below_Trend_For_Short = 3;
Exit_By_First_Opposite_Bar = true;
Enable_Profit_Target = false;
Profit_Target_Ticks = 10;
Enable_Stop_Loss = false;
Stop_Loss_Ticks = 15;
Enable_Trading_Time = false;
Disable_Trading_By_Loss_Amount = false;
No_Trading_Loss_Amount = 0d;
Atm_Strategy_Template = string.Empty;
}
else if (State == State.Configure)
{
_OFCD = OrderFlowCumulativeDelta(CumulativeDeltaType.BidAsk, CumulativeDeltaPeriod.Bar, 0);
AddChartIndicator(_OFCD);
_positionInfo = new PositionInfo();
_lastPositionInfo = new PositionInfo();
_totalLossAmount = 0d;
_isAtmStrategyCreated = false;
if (string.IsNullOrEmpty(Atm_Strategy_Template))
{
if (Enable_Profit_Target)
{
SetProfitTarget(CalculationMode.Ticks, Profit_Target_Ticks);
}
if (Enable_Stop_Loss)
{
SetStopLoss(CalculationMode.Ticks, Stop_Loss_Ticks);
}
}
_markerFont = new SimpleFont("Arial", 10);
}
else if (State == State.Realtime)
{
}
}
#endregion
#region Private methods
private ISeries<double> GetSMASeries(PriceType priceType)
{
ISeries<double> result = new Series<double>(this, MaximumBarsLookBack.Infinite);
switch (priceType)
{
case PriceType.Open:
result = Open;
break;
case PriceType.Close:
result = Close;
break;
case PriceType.Median:
result = Median;
break;
case PriceType.Typical:
result = Typical;
break;
case PriceType.Weighted:
result = Weighted;
break;
case PriceType.High:
result = High;
break;
case PriceType.Low:
result = Low;
break;
}
return result;
}
private bool IsTradingTime()
{
var result = true;
var barTimestamp = Time[0].Hour * 60 + Time[0].Minute;
var startTimestamp = Start_Trading_Time.Hour * 60 + Start_Trading_Time.Minute;
var endTimestamp = End_Trading_Time.Hour * 60 + End_Trading_Time.Minute;
var isNoTradingTime = (barTimestamp < startTimestamp || barTimestamp >= endTimestamp) && Enable_Trading_Time;
if (isNoTradingTime)
{
if (_positionInfo.PositionType != MarketPosition.Flat)
{
if (string.IsNullOrEmpty(Atm_Strategy_Template))
{
if (_positionInfo.PositionType == MarketPosition.Long)
{
ExitLong();
}
else if (_positionInfo.PositionType == MarketPosition.Short)
{
ExitShort();
}
}
else
{
if (State == State.Realtime)
{
AtmStrategyClose(_atmStrategyId);
}
}
_positionInfo.Reset();
}
if (_positionInfo.PositionType == MarketPosition.Flat)
{
result = false;
}
}
return result;
}
private bool IsLongExit()
{
if (_positionInfo.PositionType == MarketPosition.Flat || CurrentBar < 1)
return false;
return _positionInfo.PositionType == MarketPosition.Long && Close[0] < Close[1] && Exit_By_First_Opposite_Bar;
}
private bool IsShortExit()
{
if (_positionInfo.PositionType == MarketPosition.Flat || CurrentBar < 1)
return false;
return _positionInfo.PositionType == MarketPosition.Short && Close[0] > Close[1] && Exit_By_First_Opposite_Bar;
}
private bool IsLongEntry()
{
if (_positionInfo.PositionType != MarketPosition.Flat || !Enable_Long)
return false;
if (CurrentBar < Bars_Above_Trend_For_Long)
return false;
var result = false;
if ((_OFCD.DeltaClose[0] > 0) && (Math.Abs(_OFCD.DeltaClose[0]) >= NetDelta) && (Close[0] < Open[0]))
{
result = true;
}
return result;
}
private bool IsShortEntry()
{
if (_positionInfo.PositionType != MarketPosition.Flat || !Enable_Short)
return false;
if (CurrentBar < Bars_Below_Trend_For_Short)
return false;
var result = false;
if ((_OFCD.DeltaClose[0] < 0) && (Math.Abs(_OFCD.DeltaClose[0]) >= NetDelta) && (Close[0] > Open[0]))
{
result = true;
}
return result;
}
private void PrintPositionChanged()
{
bool isFlat = _positionInfo.PositionType == MarketPosition.Flat;
Print(string.Format("{0}. Position changed: dir: {1}, q: {2}, p: {3}", Time[0], _positionInfo.PositionType, isFlat ? 0 : _positionInfo.Quantity, isFlat ? 0 : _positionInfo.Price));
}
private void DrawText(string tag, string text, double y, int offset = 0)
{
Draw.Text(this, tag, true, text, 0, y, offset, ChartControl.Properties.ChartText, _markerFont, System.Windows.TextAlignment.Center, Brushes.Transparent, Brushes.Transparent, 0);
}
private void CheckEntryDisabled(bool isExit)
{
if (isExit || _isLongDisabled)
{
_isLongDisabled = Close[0] > Close[1];
}
if (isExit || _isShortDisabled)
{
_isShortDisabled = Close[0] < Close[1];
}
}
#region ATM Strategy Processing
private void CreateATM(OrderAction orderAction)
{
if (!string.IsNullOrEmpty(Atm_Strategy_Template))
{
_atmStrategyId = GetAtmStrategyUniqueId();
_atmStrategyOrderId = GetAtmStrategyUniqueId();
_isAtmStrategyCreated = false;
AtmStrategyCreate(orderAction, OrderType.Market, 0, 0, TimeInForce.Day, _atmStrategyOrderId, Atm_Strategy_Template, _atmStrategyId,
(atmCallbackErrorCode, atmCallbackId) => {
if (atmCallbackId == _atmStrategyId)
{
if (atmCallbackErrorCode == Cbi.ErrorCode.NoError)
{
_isAtmStrategyCreated = true;
}
}
});
}
}
private void ProcessATM()
{
if (_totalLossAmount >= No_Trading_Loss_Amount && Disable_Trading_By_Loss_Amount)
return;
var exitDone = false;
if (IsLongExit() && !exitDone)
{
AtmStrategyClose(_atmStrategyId);
exitDone = true;
}
if (IsShortExit() && !exitDone)
{
AtmStrategyClose(_atmStrategyId);
exitDone = true;
}
UpdatePositionInfo();
CheckEntryDisabled(exitDone);
if (IsLongEntry() && !_isLongDisabled)
{
CreateATM(OrderAction.Buy);
}
if (IsShortEntry() && !_isShortDisabled)
{
CreateATM(OrderAction.SellShort);
}
UpdatePositionInfo();
if (_positionInfo.PositionType != MarketPosition.Flat)
{
var k = _positionInfo.PositionType == MarketPosition.Long ? 1 : -1;
if (!Enable_Stop_Loss)
{
var stopPrice = (k > 0 ? Low[0] : High[0]) - k * TickSize * Stop_Loss_Ticks;
AtmStrategyChangeStopTarget(0, stopPrice, "STOP1", _atmStrategyId);
}
if (!Enable_Profit_Target)
{
var targetPrice = (k < 0 ? Low[0] : High[0]) + k * TickSize * Profit_Target_Ticks;
AtmStrategyChangeStopTarget(targetPrice, 0, "TARGET1", _atmStrategyId);
}
}
}
private void UpdatePositionInfo()
{
if (string.IsNullOrEmpty(_atmStrategyId) || !_isAtmStrategyCreated)
return;
var positionInfo = new PositionInfo()
{
PositionType = GetAtmStrategyMarketPosition(_atmStrategyId),
Quantity = GetAtmStrategyPositionQuantity(_atmStrategyId),
Price = GetAtmStrategyPositionAveragePrice(_atmStrategyId)
};
if (_positionInfo.PositionType != positionInfo.PositionType ||
_positionInfo.Quantity != positionInfo.Quantity ||
_positionInfo.Price != positionInfo.Price)
{
if (_positionInfo.PositionType != positionInfo.PositionType)
{
DrawMarkers(positionInfo);
if (positionInfo.PositionType != MarketPosition.Flat)
{
var k = positionInfo.PositionType == MarketPosition.Long ? 1 : -1;
if (Enable_Stop_Loss)
{
var stopPrice = positionInfo.Price - k * TickSize * Stop_Loss_Ticks;
AtmStrategyChangeStopTarget(0, stopPrice, "STOP1", _atmStrategyId);
}
if (Enable_Profit_Target)
{
var targetPrice = Enable_Profit_Target ? positionInfo.Price + k * TickSize * Profit_Target_Ticks : double.MaxValue;
AtmStrategyChangeStopTarget(targetPrice, 0, "TARGET1", _atmStrategyId);
}
}
}
_positionInfo = positionInfo;
PrintPositionChanged();
}
}
private void DrawMarkers(PositionInfo newPositionInfo)
{
if (newPositionInfo.PositionType == MarketPosition.Long)
{
Draw.ArrowUp(this, "EntryLong" + CurrentBar.ToString(), false, 0, Low[0] - TickSize, Brushes.Blue, true);
var markerText = string.Format("Buy\nQ: {0}\nP: {1}", newPositionInfo.Quantity, newPositionInfo.Price);
DrawText("EntryLongLabel" + CurrentBar.ToString(), markerText, Low[0] - 2);
}
else if (newPositionInfo.PositionType == MarketPosition.Short)
{
Draw.ArrowDown(this, "EntryShort" + CurrentBar.ToString(), false, 0, High[0] + TickSize, Brushes.Red, true);
var markerText = string.Format("Sell\nQ: {0}\nP: {1}", newPositionInfo.Quantity, newPositionInfo.Price);
DrawText("EntryShortLabel" + CurrentBar.ToString(), markerText, High[0] + 2);
}
else if (newPositionInfo.PositionType == MarketPosition.Flat)
{
var pnl = GetAtmStrategyRealizedProfitLoss(_atmStrategyId);
if (_positionInfo.PositionType == MarketPosition.Long)
{
Draw.ArrowDown(this, "ExitLong" + CurrentBar.ToString(), false, 0, High[0] + TickSize, Brushes.Red, true);
var markerText = string.Format("Exit\nP&L {0}", pnl);
DrawText("ExitLongLabel" + CurrentBar.ToString(), markerText, High[0] + 2);
}
else
{
Draw.ArrowUp(this, "ExitShort" + CurrentBar.ToString(), false, 0, Low[0] - TickSize, Brushes.Blue, true);
var markerText = string.Format("Exit\nP&L {0}", pnl);
DrawText("ExitShortLabel" + CurrentBar.ToString(), markerText, Low[0] - 2);
}
if (pnl < 0)
{
_totalLossAmount += Math.Abs(pnl);
}
}
}
#endregion
#region NT8 Strategy Processing
private void ProcessNT8()
{
if (_positionInfo.PositionType == MarketPosition.Flat && _lastPositionInfo.PositionType != MarketPosition.Flat)
{
DrawPnL();
}
_lastPositionInfo = (PositionInfo)_positionInfo.Clone();
var exitDone = false;
if (IsLongExit() && !exitDone)
{
ExitLong();
exitDone = true;
}
if (IsShortExit() && !exitDone)
{
ExitShort();
exitDone = true;
}
CheckEntryDisabled(exitDone);
if (IsLongEntry() && !_isLongDisabled)
{
EnterLong();
}
if (IsShortEntry() && !_isShortDisabled)
{
EnterShort();
}
}
private void DrawPnL()
{
var tagPrefix = _lastPositionInfo.PositionType == MarketPosition.Long ? "ExitLongLabel" : "ExitShortLabel";
var pnl = _positionInfo.ExitQuantity * _positionInfo.ExitPrice - _lastPositionInfo.Quantity * _lastPositionInfo.Price;
var markerText = string.Format("P&L {0}", pnl);
var y = 0d;
if (_lastPositionInfo.PositionType == MarketPosition.Long)
{
DrawText(tagPrefix + CurrentBar.ToString(), markerText, High[0], 70);
}
else
{
DrawText(tagPrefix + CurrentBar.ToString(), markerText, Low[0], -70);
}
if (pnl < 0)
{
_totalLossAmount += Math.Abs(pnl);
}
}
#endregion
#endregion
#region Main
protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
{
Print(string.Format("{0}. Order '{1}' has been filled (q: {2}, p: {3})", execution.Order.Time, execution.Order.Name, quantity, price));
_lastPositionInfo = (PositionInfo)_positionInfo.Clone();
if (_positionInfo.PositionType == MarketPosition.Flat)
{
_positionInfo.PositionType = marketPosition;
_positionInfo.Price = price;
_positionInfo.Quantity = quantity;
}
else
{
if (_positionInfo.PositionType != marketPosition)
{
_positionInfo.Reset();
_positionInfo.ExitPrice = price;
_positionInfo.ExitQuantity = quantity;
}
}
PrintPositionChanged();
}
protected override void OnBarUpdate()
{
if (!(IsFirstTickOfBar || Calculate == Calculate.OnBarClose))
return;
if (!IsTradingTime())
return;
if (string.IsNullOrEmpty(Atm_Strategy_Template))
{
ProcessNT8();
}
else
{
if (State == State.Realtime)
{
ProcessATM();
}
}
}
#endregion
#region Properties
#region Delta
[NinjaScriptProperty]
[Range(0, Int32.MaxValue)]
[Display(Name="NetDelta", Description="Volume Net Delta", Order = 1, GroupName = "Delta")]
public int NetDelta
{
get; set;
}
#endregion
#region Entry&Exit
[NinjaScriptProperty]
[Display(Name="Enable Long Trades", Description="Enable Long Trades", Order = 1, GroupName="Entry&Exit")]
public bool Enable_Long
{ get; set; }
[NinjaScriptProperty]
[Range(1, Int32.MaxValue)]
[Display(Name="Bars Above Trend For Long Entry", Description="Bars Above Trend For Long Entry", Order = 2, GroupName = "Entry&Exit")]
public int Bars_Above_Trend_For_Long
{
get; set;
}
[NinjaScriptProperty]
[Display(Name="Enable Short Trades", Description="Enable Short Trades", Order = 3, GroupName="Entry&Exit")]
public bool Enable_Short
{ get; set; }
[NinjaScriptProperty]
[Range(1, Int32.MaxValue)]
[Display(Name="Bars Below Trend For Long Short", Description="Bars Below Trend For Long Short", Order = 4, GroupName = "Entry&Exit")]
public int Bars_Below_Trend_For_Short
{
get; set;
}
[NinjaScriptProperty]
[Display(Name="Exit by the First Opposite Bar", Description="Exit by the First Opposite Bar", Order = 5, GroupName="Entry&Exit")]
public bool Exit_By_First_Opposite_Bar
{ get; set; }
#endregion
#region Profit&Loss
[NinjaScriptProperty]
[Display(Name="Enable Profit Target", Description="Enable profit target", Order = 1, GroupName="Profit&Loss")]
public bool Enable_Profit_Target
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Profit Target Ticks", Description="Profit target ticks", Order = 2, GroupName="Profit&Loss")]
public int Profit_Target_Ticks
{ get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Stop Loss", Description="Enable stop loss", Order = 3, GroupName="Profit&Loss")]
public bool Enable_Stop_Loss
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Stop Loss Ticks", Description="Stop loss ticks", Order = 4, GroupName="Profit&Loss")]
public int Stop_Loss_Ticks
{ get; set; }
#endregion
#region Trading
[NinjaScriptProperty]
[Display(Name="Enable Trading Time", Description="Enable trading time", Order = 1, GroupName="Trading")]
public bool Enable_Trading_Time
{ get; set; }
[Gui.PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKey")]
[Display(Name="Start Time", Description="Start trading time", Order = 2, GroupName="Trading")]
public DateTime Start_Trading_Time { get; set; }
[Gui.PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKey")]
[Display(Name="End Time", Description="End trading time", Order = 3, GroupName="Trading")]
public DateTime End_Trading_Time { get; set; }
[NinjaScriptProperty]
[Display(Name="Disable Trading By Loss Amount", Description="Disable Trading By Loss Amount", Order = 4, GroupName="Trading")]
public bool Disable_Trading_By_Loss_Amount
{ get; set; }
[NinjaScriptProperty]
[Range(0, double.MaxValue)]
[Display(Name="Loss Amount", Description="Loss Amount", Order = 5, GroupName="Trading")]
public double No_Trading_Loss_Amount
{ get; set; }
#endregion
#region Display
#endregion
#region ATM
[NinjaScriptProperty]
[Display(Name="ATM Strategy Template", Description="ATM Strategy Template", Order = 1, GroupName="ATM")]
public string Atm_Strategy_Template
{ get; set; }
#endregion
#endregion
}
}