-
Notifications
You must be signed in to change notification settings - Fork 68
/
MarketProfile.cs
3823 lines (3225 loc) · 190 KB
/
MarketProfile.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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -------------------------------------------------------------------------------
//
// Displays the Market Profile indicator for intraday, daily, weekly, or monthly trading sessions.
// Daily - should be attached to M5-M30 timeframes. M30 is recommended.
// Weekly - should be attached to M30-H4 timeframes. H1 is recommended.
// Weeks start on Sunday.
// Monthly - should be attached to H1-D1 timeframes. H4 is recommended.
// Intraday - should be attached to M1-M15 timeframes. M5 is recommended.
// Designed for major currency pairs, but should work also with exotic pairs, CFDs, or commodities.
//
// Version 1.23
// Copyright 2010-2024, EarnForex.com
// https://www.earnforex.com/metatrader-indicators/MarketProfile/
// -------------------------------------------------------------------------------
using cAlgo.API;
using cAlgo.API.Internals;
using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
public class MarketProfile : Indicator
{
#region Parameters
[Parameter("=== Main", DefaultValue = "=================")]
public string MainSettings { get; set; }
[Parameter("Session", DefaultValue = session_period.Daily)]
public session_period Session { get; set; }
[Parameter("StartFromDate: lower priority.", DefaultValue = "")]
public string StartFromDate { get; set; }
[Parameter("StartFromCurrentSession: higher priority.", DefaultValue = true)]
public bool StartFromCurrentSession { get; set; }
[Parameter("SessionsToCount: Number of sessions to count Market Profile.", DefaultValue = 2)]
public int SessionsToCount { get; set; }
[Parameter("SeamlessScrollingMode: show sessions on current screen.", DefaultValue = false)]
public bool SeamlessScrollingMode { get; set; }
[Parameter("Enable Developing POC.", DefaultValue = false)]
public bool EnableDevelopingPOC { get; set; }
[Parameter("Enable Developing VAH/VAL.", DefaultValue = false)]
public bool EnableDevelopingVAHVAL { get; set; }
[Parameter("ValueAreaPercentage: Percentage of TPO's inside Value Area.", DefaultValue = 70)]
public int ValueAreaPercentage { get; set; }
[Parameter("=== Colors and looks", DefaultValue = "=================")]
public string ColorsAndLooksSettings { get; set; }
[Parameter("ColorScheme", DefaultValue = color_scheme.Blue_to_Red)]
public color_scheme ColorScheme { get; set; }
[Parameter("Opacity", DefaultValue = 60, MaxValue = 100, MinValue = 0)]
public int ColorOpacity { get; set; }
[Parameter("SingleColor: if ColorScheme is set to Single_Color.", DefaultValue = "Blue")]
public Color SingleColor { get; set; }
[Parameter("ColorBullBear: If true, colors are from bars' direction.", DefaultValue = false)]
public bool ColorBullBear { get; set; }
[Parameter("MedianColor", DefaultValue = "White")]
public Color MedianColor { get; set; }
[Parameter("ValueAreaSidesColor", DefaultValue = "White")]
public Color ValueAreaSidesColor { get; set; }
[Parameter("ValueAreaHighLowColor", DefaultValue = "White")]
public Color ValueAreaHighLowColor { get; set; }
[Parameter("MedianStyle", DefaultValue = LineStyle.Solid)]
public LineStyle MedianStyle { get; set; }
[Parameter("MedianRayStyle", DefaultValue = LineStyle.Lines)]
public LineStyle MedianRayStyle { get; set; }
[Parameter("ValueAreaSidesStyle", DefaultValue = LineStyle.Solid)]
public LineStyle ValueAreaSidesStyle { get; set; }
[Parameter("ValueAreaHighLowStyle", DefaultValue = LineStyle.Solid)]
public LineStyle ValueAreaHighLowStyle { get; set; }
[Parameter("ValueAreaRayHighLowStyle", DefaultValue = LineStyle.Dots)]
public LineStyle ValueAreaRayHighLowStyle { get; set; }
[Parameter("MedianWidth", DefaultValue = 1)]
public int MedianWidth { get; set; }
[Parameter("MedianRayWidth", DefaultValue = 1)]
public int MedianRayWidth { get; set; }
[Parameter("ValueAreaSidesWidth", DefaultValue = 1)]
public int ValueAreaSidesWidth { get; set; }
[Parameter("ValueAreaHighLowWidth", DefaultValue = 1)]
public int ValueAreaHighLowWidth { get; set; }
[Parameter("ValueAreaRayHighLowWidth", DefaultValue = 1)]
public int ValueAreaRayHighLowWidth { get; set; }
[Parameter("ShowValueAreaRays: draw previous value area high/low rays.", DefaultValue = sessions_to_draw_rays.None)]
public sessions_to_draw_rays ShowValueAreaRays { get; set; }
[Parameter("ShowMedianRays: draw previous median rays.", DefaultValue = sessions_to_draw_rays.None)]
public sessions_to_draw_rays ShowMedianRays { get; set; }
[Parameter("RaysUntilIntersection: which rays stop when hit another MP.", DefaultValue = ways_to_stop_rays.Stop_No_Rays)]
public ways_to_stop_rays RaysUntilIntersection { get; set; }
[Parameter("HideRaysFromInvisibleSessions: hide rays from behind the screen.", DefaultValue = false)]
public bool HideRaysFromInvisibleSessions { get; set; }
[Parameter("TimeShiftMinutes: shift session + to the left, - to the right.", DefaultValue = 0)]
public int TimeShiftMinutes { get; set; }
[Parameter("ShowKeyValues: print out VAH, VAL, POC on chart.", DefaultValue = true)]
public bool ShowKeyValues { get; set; }
[Parameter("KeyValuesColor: color for VAH, VAL, POC printout.", DefaultValue = "White")]
public Color KeyValuesColor { get; set; }
[Parameter("KeyValuesSize: font size for VAH, VAL, POC printout.", DefaultValue = 12)]
public int KeyValuesSize { get; set; }
[Parameter("ShowSinglePrint: mark Single Print profile levels.", DefaultValue = single_print_type.No)]
public single_print_type ShowSinglePrint { get; set; }
[Parameter("SinglePrintColor", DefaultValue = "Gold")]
public Color SinglePrintColor { get; set; }
[Parameter("SinglePrintRays: mark Single Print edges with rays.", DefaultValue = false)]
public bool SinglePrintRays { get; set; }
[Parameter("SinglePrintRayStyle", DefaultValue = LineStyle.Solid)]
public LineStyle SinglePrintRayStyle { get; set; }
[Parameter("SinglePrintRayWidth", DefaultValue = 1)]
public int SinglePrintRayWidth { get; set; }
[Parameter("ProminentMedianColor", DefaultValue = "Yellow")]
public Color ProminentMedianColor { get; set; }
[Parameter("ProminentMedianStyle", DefaultValue = LineStyle.Solid)]
public LineStyle ProminentMedianStyle { get; set; }
[Parameter("ProminentMedianWidth", DefaultValue = 4)]
public int ProminentMedianWidth { get; set; }
[Parameter("RightToLeft: Draw histogram from right to left.", DefaultValue = false)]
public bool RightToLeft { get; set; }
[Parameter("=== Performance", DefaultValue = "=================")]
public string PerformanceSettings { get; set; }
[Parameter("PointMultiplier: higher value = fewer objects. 0 - adaptive.", DefaultValue = 0)]
public int PointMultiplier { get; set; }
[Parameter("ThrottleRedraw: delay (in seconds) for updating Market Profile.", DefaultValue = 0)]
public int ThrottleRedraw { get; set; }
[Parameter("DisableHistogram: do not draw profile, VAH, VAL, and POC still visible.", DefaultValue = false)]
public bool DisableHistogram { get; set; }
[Parameter("=== Alerts", DefaultValue = "=================")]
public string AlertsSettings { get; set; }
[Parameter("AlertNative: issue native pop-up alerts.", DefaultValue = false)]
public bool AlertNative { get; set; }
[Parameter("AlertNative: sound file.", DefaultValue = "")]
public string AlertNativeSoundFile { get; set; }
[Parameter("AlertEmail: issue email alerts.", DefaultValue = false)]
public bool AlertEmail { get; set; }
[Parameter("AlertEmail: Email From.", DefaultValue = "")]
public string AlertEmailFrom { get; set; }
[Parameter("AlertEmail: Email To.", DefaultValue = "")]
public string AlertEmailTo { get; set; }
[Parameter("AlertArrows: draw chart arrows on alerts.", DefaultValue = false)]
public bool AlertArrows { get; set; }
[Parameter("AlertCheckBar: which bar to check for alerts?", DefaultValue = alert_check_bar.CheckPreviousBar)]
public alert_check_bar AlertCheckBar { get; set; }
[Parameter("AlertForValueArea: alerts for Value Area (VAH, VAL) rays.", DefaultValue = false)]
public bool AlertForValueArea { get; set; }
[Parameter("AlertForMedian: alerts for POC (Median) rays' crossing.", DefaultValue = false)]
public bool AlertForMedian { get; set; }
[Parameter("AlertForSinglePrint: alerts for single print rays' crossing.", DefaultValue = false)]
public bool AlertForSinglePrint { get; set; }
[Parameter("AlertOnPriceBreak: price breaking above/below the ray.", DefaultValue = false)]
public bool AlertOnPriceBreak { get; set; }
[Parameter("AlertOnCandleClose: candle closing above/below the ray.", DefaultValue = false)]
public bool AlertOnCandleClose { get; set; }
[Parameter("AlertOnGapCross: bar gap above/below the ray.", DefaultValue = false)]
public bool AlertOnGapCross { get; set; }
[Parameter("AlertArrowColorPB: arrow color for price break alerts.", DefaultValue = "Red")]
public Color AlertArrowColorPB { get; set; }
[Parameter("AlertArrowColorCC: arrow color for candle close alerts.", DefaultValue = "Blue")]
public Color AlertArrowColorCC { get; set; }
[Parameter("AlertArrowColorGC: arrow color for gap crossover alerts.", DefaultValue = "Yellow")]
public Color AlertArrowColorGC { get; set; }
[Parameter("=== Intraday settings", DefaultValue = "=================")]
public string IntradaySettings { get; set; }
[Parameter("EnableIntradaySession1", DefaultValue = true)]
public bool EnableIntradaySession1 { get; set; }
[Parameter("IntradaySession1StartTime", DefaultValue = "00:00")]
public string IntradaySession1StartTime { get; set; }
[Parameter("IntradaySession1EndTime", DefaultValue = "06:00")]
public string IntradaySession1EndTime { get; set; }
[Parameter("IntradaySession1ColorScheme", DefaultValue = color_scheme.Blue_to_Red)]
public color_scheme IntradaySession1ColorScheme { get; set; }
[Parameter("EnableIntradaySession2", DefaultValue = true)]
public bool EnableIntradaySession2 { get; set; }
[Parameter("IntradaySession2StartTime", DefaultValue = "06:00")]
public string IntradaySession2StartTime { get; set; }
[Parameter("IntradaySession2EndTime", DefaultValue = "12:00")]
public string IntradaySession2EndTime { get; set; }
[Parameter("IntradaySession2ColorScheme", DefaultValue = color_scheme.Red_to_Green)]
public color_scheme IntradaySession2ColorScheme { get; set; }
[Parameter("EnableIntradaySession3", DefaultValue = true)]
public bool EnableIntradaySession3 { get; set; }
[Parameter("IntradaySession3StartTime", DefaultValue = "12:00")]
public string IntradaySession3StartTime { get; set; }
[Parameter("IntradaySession3EndTime", DefaultValue = "18:00")]
public string IntradaySession3EndTime { get; set; }
[Parameter("IntradaySession3ColorScheme", DefaultValue = color_scheme.Green_to_Blue)]
public color_scheme IntradaySession3ColorScheme { get; set; }
[Parameter("EnableIntradaySession4", DefaultValue = true)]
public bool EnableIntradaySession4 { get; set; }
[Parameter("IntradaySession4StartTime", DefaultValue = "18:00")]
public string IntradaySession4StartTime { get; set; }
[Parameter("IntradaySession4EndTime", DefaultValue = "00:00")]
public string IntradaySession4EndTime { get; set; }
[Parameter("IntradaySession4ColorScheme", DefaultValue = color_scheme.Yellow_to_Cyan)]
public color_scheme IntradaySession4ColorScheme { get; set; }
[Parameter("=== Miscellaneous", DefaultValue = "=================")]
public string MiscellaneousSettings { get; set; }
[Parameter("SaturdaySunday", DefaultValue = sat_sun_solution.Saturday_Sunday_Normal_Days)]
public sat_sun_solution SaturdaySunday { get; set; }
[Parameter("Disable alerts on wrong timeframes.", DefaultValue = false)]
public bool DisableAlertsOnWrongTimeframes { get; set; }
[Parameter("Percentage of Median TPOs out of total for a Prominent one.", DefaultValue = 101)]
public int ProminentMedianPercentage { get; set; }
#endregion
#region Outputs
[Output("Developing POC 1", LineColor = "Green", LineStyle = LineStyle.Solid, PlotType = PlotType.DiscontinuousLine, Thickness = 5)]
public IndicatorDataSeries DevelopingPOC_1 { get; set; }
[Output("Developing POC 2", LineColor = "Green", LineStyle = LineStyle.Solid, PlotType = PlotType.DiscontinuousLine, Thickness = 5)]
public IndicatorDataSeries DevelopingPOC_2 { get; set; }
[Output("Developing VAH 1", LineColor = "Goldenrod", LineStyle = LineStyle.Solid, PlotType = PlotType.DiscontinuousLine, Thickness = 5)]
public IndicatorDataSeries DevelopingVAH_1 { get; set; }
[Output("Developing VAH 2", LineColor = "Goldenrod", LineStyle = LineStyle.Solid, PlotType = PlotType.DiscontinuousLine, Thickness = 5)]
public IndicatorDataSeries DevelopingVAH_2 { get; set; }
[Output("Developing VAL 1", LineColor = "Salmon", LineStyle = LineStyle.Solid, PlotType = PlotType.DiscontinuousLine, Thickness = 5)]
public IndicatorDataSeries DevelopingVAL_1 { get; set; }
[Output("Developing VAL 2", LineColor = "Salmon", LineStyle = LineStyle.Solid, PlotType = PlotType.DiscontinuousLine, Thickness = 5)]
public IndicatorDataSeries DevelopingVAL_2 { get; set; }
#endregion
#region Enums
public enum color_scheme
{
Blue_to_Red,
// Blue to Red
Red_to_Green,
// Red to Green
Green_to_Blue,
// Green to Blue
Yellow_to_Cyan,
// Yellow to Cyan
Magenta_to_Yellow,
// Magenta to Yellow
Cyan_to_Magenta,
// Cyan to Magenta
Single_Color
// Single Color
}
public enum session_period
{
Daily,
Weekly,
Monthly,
Intraday,
Rectangle
}
public enum sat_sun_solution
{
Saturday_Sunday_Normal_Days,
// Normal sessions
Ignore_Saturday_Sunday,
// Ignore Saturday and Sunday
Append_Saturday_Sunday
// Append Saturday and Sunday
}
public enum sessions_to_draw_rays
{
None,
Previous,
Current,
PreviousCurrent,
// Previous & Current
AllPrevious,
// All Previous
All
}
public enum ways_to_stop_rays
{
Stop_No_Rays,
// Stop no rays
Stop_All_Rays,
// Stop all rays
Stop_All_Rays_Except_Prev_Session,
// Stop all rays except previous session
Stop_Only_Previous_Session
// Stop only previous session's rays
}
// Only for dot coloring choice in PutDot() when ColorBullBear == true.
enum bar_direction
{
Bullish,
Bearish,
Neutral
}
public enum single_print_type
{
No,
Leftside,
Rightside
}
public enum alert_check_bar
{
CheckCurrentBar,
// Current
CheckPreviousBar
// Previous
}
enum alert_types
{
// Required to type a parameter of DoAlerts().
PriceBreak,
// Price Break
CandleCloseCrossover,
// Candle Close Crossover
GapCrossover
// Gap Crossover
}
#endregion
#region Classes
private class SessionInfo
{
public double Max;
public double Min;
public DateTime Start;
public DateTime End;
public string Suffix;
public SessionInfo() { }
}
private class CRectangleMP
{
public DateTime prev_Time0;
public double prev_High;
public double prev_Low;
public double prev_RectanglePriceMax;
public double prev_RectanglePriceMin;
public int Number; // Order number of the rectangle;
public double RectanglePriceMax;
public double RectanglePriceMin;
public DateTime RectangleTimeMax;
public DateTime RectangleTimeMin;
public DateTime t1;
public DateTime t2; // To avoid reading object properties in Process() after sorting was done.
public string name;
public CRectangleMP(string given_name)
{
name = given_name;
RectanglePriceMax = double.MinValue;
RectanglePriceMin = double.MaxValue;
prev_RectanglePriceMax = double.MinValue;
prev_RectanglePriceMin = double.MaxValue;
RectangleTimeMax = DateTime.MinValue;
RectangleTimeMin = DateTime.MaxValue;
prev_Time0 = DateTime.MinValue;
prev_High = double.MinValue;
prev_Low = double.MaxValue;
Number = -1;
}
}
private class Intraday
{
public int StartHours;
public int StartMinutes;
public int StartTime;
public int EndHours;
public int EndMinutes;
public int EndTime;
public color_scheme ColorScheme;
public Intraday()
{
StartHours = 0;
StartMinutes = 0;
StartTime = 0;
EndHours = 0;
EndMinutes = 0;
EndTime = 0;
ColorScheme = color_scheme.Single_Color;
}
}
#endregion
#region Variables
private int PointMultiplier_calculated; // Will have to be calculated based number digits in a quote if PointMultiplier input is 0.
private int DigitsM; // Number of digits normalized based on PointMultiplier_calculated.
private bool InitFailed; // Used for soft INIT_FAILED. Hard INIT_FAILED resets input parameters.
private DateTime StartDate; // Will hold either StartFromDate or Time[0].
private double onetick; // One normalized pip.
private bool FirstRunDone = false; // If true - OnCalculate() was already executed once.
private string Suffix = "_"; // Will store object name suffix depending on timeframe.
private color_scheme CurrentColorScheme; // Required due to intraday sessions.
private int Max_number_of_bars_in_a_session = 1;
private DateTime _Timer = DateTime.MinValue; // For throttling updates of market profiles in slow systems.
private bool NeedToRestartDrawing = false; // Global flag for RightToLeft redrawing;
private double ValueAreaPercentage_double = 0.7; // Will be calculated based on the input parameter in OnInit().
private DateTime LastAlertTime_CandleCross = DateTime.MinValue;
private DateTime LastAlertTime_GapCross = DateTime.MinValue; // For CheckCurrentBar alerts.
private DateTime LastAlertTime = DateTime.MinValue; // For CheckPreviousBar alerts;
private double Close_prev = double.NaN; // Previous price value for Price Break alerts.
private int ArrowsCounter = 0; // Counter for naming of alert arrows.
// Used for ColorBullBear.
private bar_direction CurrentBarDirection = bar_direction.Neutral;
private bar_direction PreviousBarDirection = bar_direction.Neutral;
private bool NeedToReviewColors = false;
// For intraday sessions' start and end times.
private Intraday[] ID;
private int IntradaySessionCount = 0;
private int _SessionsToCount;
private int IntradayCrossSessionDefined = -1; // For special case used only with Ignore_Saturday_Sunday on Monday.
// We need to know where each session starts and its price range for when RaysUntilIntersection != Stop_No_Rays.
// These are used also when RaysUntilIntersection == Stop_No_Rays for Intraday sessions counting.
private int SessionsNumber = 0; // Different from _SessionsToCount when working with Intraday sessions and for RaysUntilIntersection != Stop_No_Rays.
private List<SessionInfo> RememberSession;
private List<CRectangleMP> MPR_Array;
private DateTime LastRecalculationTime = DateTime.MinValue;
private DateTime LastBarTime = DateTime.MinValue;
private DateTime prev_time_start_bar;
private double PreviousSessionMax;
private DateTime PreviousSessionStartTime;
private DateTime prev_converted_time;
#endregion
#region Initialize
protected override void Initialize()
{
InitFailed = false;
// Sessions to count for the object creation.
_SessionsToCount = SessionsToCount;
// Check for user Session settings.
if (Session == session_period.Daily)
{
Suffix = "_D";
if (TimeFrame < TimeFrame.Minute5 || TimeFrame > TimeFrame.Minute30)
{
string alert_text = "Timeframe should be between M5 and M30 for a Daily session.";
if (!DisableAlertsOnWrongTimeframes)
Alert(alert_text);
else
Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (Session == session_period.Weekly)
{
Suffix = "_W";
if (TimeFrame < TimeFrame.Minute30 || TimeFrame > TimeFrame.Hour4)
{
string alert_text = "Timeframe should be between M30 and H4 for a Weekly session.";
if (!DisableAlertsOnWrongTimeframes)
Alert(alert_text);
else
Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (Session == session_period.Monthly)
{
Suffix = "_M";
if (TimeFrame < TimeFrame.Hour || TimeFrame > TimeFrame.Daily)
{
string alert_text = "Timeframe should be between H1 and D1 for a Monthly session.";
if (!DisableAlertsOnWrongTimeframes)
Alert(alert_text);
else
Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (Session == session_period.Intraday)
{
if (TimeFrame > TimeFrame.Minute15)
{
string alert_text = "Timeframe should not be higher than M15 for an Intraday sessions.";
if (!DisableAlertsOnWrongTimeframes)
Alert(alert_text);
else
Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
ID = new Intraday[4];
// Check if intraday user settings are valid.
IntradaySessionCount = 0;
if (!CheckIntradaySession(EnableIntradaySession1, IntradaySession1StartTime, IntradaySession1EndTime, IntradaySession1ColorScheme))
InitFailed = true;
if (!CheckIntradaySession(EnableIntradaySession2, IntradaySession2StartTime, IntradaySession2EndTime, IntradaySession2ColorScheme))
InitFailed = true;
if (!CheckIntradaySession(EnableIntradaySession3, IntradaySession3StartTime, IntradaySession3EndTime, IntradaySession3ColorScheme))
InitFailed = true;
if (!CheckIntradaySession(EnableIntradaySession4, IntradaySession4StartTime, IntradaySession4EndTime, IntradaySession4ColorScheme))
InitFailed = true;
// Warn user about Intraday mode.
if (IntradaySessionCount == 0)
{
string alert_text = "Enable at least one intraday session if you want to use Intraday mode.";
if (!DisableAlertsOnWrongTimeframes)
Alert(alert_text);
else
Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if ((Session == session_period.Rectangle) && SeamlessScrollingMode) // No point in seamless scrolling mode with rectangle sessions.
{
string alert_text = "Seamless scrolling mode doesn't work with Rectangle sessions.";
if (!DisableAlertsOnWrongTimeframes)
Alert(alert_text);
else
Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
// Adaptive point multiplier. Calculate based on number of digits in quote (before plus after the dot).
if (PointMultiplier == 0)
{
double quote = Ask;
string s = quote.ToString("F" + Symbol.Digits.ToString());
int total_digits = s.Length;
// If there is a dot in a quote.
if (s.Contains(",") || s.Contains("."))
total_digits--; // Decrease the count of digits by one.
if (total_digits <= 5)
PointMultiplier_calculated = 1;
else
PointMultiplier_calculated = (int)Math.Pow(10, total_digits - 5);
}
else // Normal point multiplier.
{
PointMultiplier_calculated = PointMultiplier;
}
// Based on number of digits in PointMultiplier_calculated. -1 because if PointMultiplier_calculated < 10, it does not modify the number of digits.
DigitsM = Math.Max(0, Symbol.Digits - (PointMultiplier_calculated.ToString().Length - 1));
onetick = Math.Round(Symbol.TickSize * PointMultiplier_calculated, DigitsM);
// Adjust for TickSize granularity if needed.
double TickSize = Symbol.TickSize;
if (onetick < TickSize)
{
DigitsM = Symbol.Digits - (((int)Math.Round(TickSize / Symbol.TickSize)).ToString().Length - 1);
onetick = Math.Round(TickSize, DigitsM);
}
// Get color scheme from user input.
CurrentColorScheme = ColorScheme;
// To clean up potential leftovers when applying a chart template.
ObjectCleanup();
// Check if user wants Session mode as Rectangle or if it is a right-to-left session, or if rays should be constantly monitored, or seamless scrolling is on.
if (Session == session_period.Rectangle || RightToLeft || HideRaysFromInvisibleSessions || SeamlessScrollingMode)
{
Timer.Start(new TimeSpan(0, 0, 0, 0, 500));
}
ValueAreaPercentage_double = ValueAreaPercentage * 0.01;
MPR_Array = new List<CRectangleMP>();
RememberSession = new List<SessionInfo>();
PreviousSessionMax = double.MinValue;
PreviousSessionStartTime = DateTime.MinValue;
prev_time_start_bar = DateTime.MinValue;
Chart.KeyDown += Chart_KeyDown;
}
private void Chart_KeyDown(ChartKeyboardEventArgs a)
{
if (Session != session_period.Rectangle)
return;
if (a.Key != Key.R)
return;
// Find the next untaken MPR rectangle name.
for (int i = 0; i < 1000; i++) // No more than 1000 rectangles!
{
string name = "MPR" + i.ToString();
if (Chart.FindObject(name) != null)
continue;
int x1 = Chart.FirstVisibleBarIndex + (int)((Chart.LastVisibleBarIndex - Chart.FirstVisibleBarIndex) / 5);
int x2 = Chart.LastVisibleBarIndex - (int)((Chart.LastVisibleBarIndex - Chart.FirstVisibleBarIndex) / 5);
double max_price = Bars[GetHighestHighIdx(x1, x2)].High;
double min_price = Bars[GetLowestLowIdx(x1, x2)].Low;
double y1 = max_price;
double y2 = min_price;
ChartRectangle cr = Chart.DrawRectangle(name, x1, y1, x2, y2, Color.Blue);
cr.IsInteractive = true;
MPR_Array.Add(new CRectangleMP(name));
break;
}
}
#endregion
#region OnDestroy
protected override void OnDestroy()
{
Timer.Stop();
if (Session == session_period.Rectangle)
{
for (int i = 0; i < MPR_Array.Count; i++)
{
ObjectCleanup(MPR_Array[i].name + "_");
MPR_Array.Clear();
}
}
else
ObjectCleanup();
}
#endregion
#region Calculate
public override void Calculate(int index)
{
if (InitFailed)
{
if (!DisableAlertsOnWrongTimeframes)
Print("Initialization failed. Please see the alert message for details.");
return;
}
if (!IsLastBar)
return;
CheckAlerts(index);
// Check if seamless scrolling mode should be on, else if user requests current session, else a specific date.
if (SeamlessScrollingMode)
{
int last_visible_bar = Chart.LastVisibleBarIndex;
if (last_visible_bar >= Bars.Count)
last_visible_bar = Bars.Count - 1;
StartDate = Bars[last_visible_bar].OpenTime;
}
else if (StartFromCurrentSession)
StartDate = Bars[index].OpenTime;
else
{
if (!DateTime.TryParse(StartFromDate, out StartDate))
StartDate = Bars[index].OpenTime;
}
// Adjust date if Ignore_Saturday_Sunday is set.
if (SaturdaySunday == sat_sun_solution.Ignore_Saturday_Sunday)
{
// Saturday? Switch to Friday.
if (StartDate.DayOfWeek == DayOfWeek.Saturday)
StartDate.AddDays(-1);
// Sunday? Switch to Friday too.
else if (StartDate.DayOfWeek == DayOfWeek.Sunday)
StartDate.AddDays(-2);
}
// If we calculate profiles for the past sessions, no need to run it again.
if (FirstRunDone && StartDate != Bars[index].OpenTime)
return;
// Delay the update of Market Profile if ThrottleRedraw is given.
if (ThrottleRedraw > 0 && _Timer > DateTime.MinValue)
{
if (DateTime.Now.Subtract(_Timer).TotalSeconds < ThrottleRedraw)
return;
}
// Calculate rectangle.
if (Session == session_period.Rectangle) // Everything becomes very simple if rectangle sessions are used.
{
CheckRectangles();
_Timer = DateTime.Now;
return;
}
bool new_bar = false;
if (LastBarTime != Bars.LastBar.OpenTime)
{
LastBarTime = Bars.LastBar.OpenTime;
new_bar = true;
}
// Recalculate everything if there were missing bars or something like that. Or if RightToLeft is on and a new right-most session arrived.
if (new_bar || NeedToRestartDrawing)
{
FirstRunDone = false;
ObjectCleanup();
NeedToRestartDrawing = false;
}
// Get start and end bar numbers of the given session.
int sessionend = FindSessionEndByDate(StartDate);
int sessionstart = FindSessionStart(sessionend);
if (sessionstart == -1)
{
Print("Something went wrong! Waiting for data to load.");
return;
}
int SessionToStart = 0;
// If all sessions have already been counted, jump to the current one.
if (FirstRunDone)
SessionToStart = _SessionsToCount - 1;
else
{
// Move back to the oldest session to count to start from it.
for (int i = 1; i < _SessionsToCount; i++)
{
sessionend = sessionstart - 1;
if (sessionend < 0)
return;
if (SaturdaySunday == sat_sun_solution.Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while (Bars[sessionend].OpenTime.DayOfWeek == DayOfWeek.Sunday || Bars[sessionend].OpenTime.DayOfWeek == DayOfWeek.Saturday)
{
sessionend--;
if (sessionend < 0)
break;
}
}
sessionstart = FindSessionStart(sessionend);
}
}
// We begin from the oldest session coming to the current session or to StartFromDate.
for (int i = SessionToStart; i < _SessionsToCount; i++)
{
if (Session == session_period.Intraday)
{
if (!ProcessIntradaySession(sessionstart, sessionend, i))
return;
}
else
{
if (Session == session_period.Daily)
Max_number_of_bars_in_a_session = PeriodSeconds(TimeFrame.Daily) / PeriodSeconds(TimeFrame);
else if (Session == session_period.Weekly)
Max_number_of_bars_in_a_session = 604800 / PeriodSeconds(TimeFrame);
else if (Session == session_period.Monthly)
Max_number_of_bars_in_a_session = 2678400 / PeriodSeconds(TimeFrame);
if (SaturdaySunday == sat_sun_solution.Append_Saturday_Sunday)
{
// The start is on Sunday - add remaining time.
if ((int)Bars[sessionstart].OpenTime.DayOfWeek == 0)
Max_number_of_bars_in_a_session += (24 * 3600 - (Bars[sessionstart].OpenTime.Hour * 3600 + Bars[sessionstart].OpenTime.Minute * 60)) / PeriodSeconds(TimeFrame);
// The end is on Saturday. +1 because even 0:00 bar deserves a bar.
if ((int)Bars[sessionstart].OpenTime.DayOfWeek == 6)
Max_number_of_bars_in_a_session += (Bars[sessionstart].OpenTime.Hour * 3600 + Bars[sessionstart].OpenTime.Minute * 60) / PeriodSeconds(TimeFrame) + 1;
}
if (!ProcessSession(sessionstart, sessionend, i, null))
return;
}
// Go to the newer session only if there is one or more left.
if (_SessionsToCount - i > 1)
{
sessionstart = sessionend + 1;
if (SaturdaySunday == sat_sun_solution.Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while (Bars[sessionstart].OpenTime.DayOfWeek == DayOfWeek.Sunday || Bars[sessionstart].OpenTime.DayOfWeek == DayOfWeek.Saturday)
{
sessionstart++;
if (sessionstart == Bars.Count - 1)
break;
}
}
sessionend = FindSessionEndByDate(Bars[sessionstart].OpenTime);
}
}
if ((ShowValueAreaRays != sessions_to_draw_rays.None) || (ShowMedianRays != sessions_to_draw_rays.None) || ((HideRaysFromInvisibleSessions) && (SinglePrintRays)))
CheckRays();
FirstRunDone = true;
_Timer = DateTime.Now;
}
#endregion
#region OnTimer
protected override void OnTimer()
{
base.OnTimer();
if (DateTime.Now.Subtract(LastRecalculationTime).TotalMilliseconds < 500)
return; // Do not recalculate on timer if less than 500 ms passed.
if (HideRaysFromInvisibleSessions)
CheckRays(); // Should be checked regularly if the input parameter requires ray hiding/unhiding.
if (Session == session_period.Rectangle)
{
CheckRectangles();
return; // No need to call RedrawLastSession() even if RightToLeft is on because in that case all Rectangles are all right-to-left and are redrawn as needed.
}
if ((!RightToLeft && !SeamlessScrollingMode) || !FirstRunDone)
return; // Need to finish normal drawing before reacting to timer.
// This what goes below works for RightToLeft mode and for seamless scrolling mode, but only after the first run has been finished.
DateTime converted_time = Bars[Chart.LastVisibleBarIndex].OpenTime;
if (converted_time == prev_converted_time)
return; // Do not call RedrawLastSession() if the screen hasn't been scrolled.
prev_converted_time = converted_time;
if (SeamlessScrollingMode)
{
ObjectCleanup(); // Delete everything to make sure there are no leftover sessions behind the screen.
if (Session == session_period.Intraday)
FirstRunDone = false; // Turn off because FirstRunDone should be false for Intraday sessions to draw properly in the past.
if ((EnableDevelopingPOC) || (EnableDevelopingVAHVAL))
{
for (int i = Bars.Count - 1; i >= 0; i--) // Clean indicator buffers.
{
DevelopingPOC_1[i] = double.NaN;
DevelopingPOC_2[i] = double.NaN;
DevelopingVAH_1[i] = double.NaN;
DevelopingVAH_2[i] = double.NaN;
DevelopingVAL_1[i] = double.NaN;
DevelopingVAL_2[i] = double.NaN;
}
}
}
// Check right-most time - did it change?
RedrawLastSession();
if (SeamlessScrollingMode && Session == session_period.Intraday)
FirstRunDone = true; // Turn back on after processing Intraday sessions.
LastRecalculationTime = DateTime.Now; // Remember last calculation time.
}
#endregion
#region Tools
#region FindSessionStart
//+------------------------------------------------------------------+
//| Finds the session's starting bar number for any given bar number.|
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
private int FindSessionStart(int n)
{
if (Session == session_period.Daily)
return FindDayStart(n);
else if (Session == session_period.Weekly)
return FindWeekStart(n);
else if (Session == session_period.Monthly)
return FindMonthStart(n);
else if (Session == session_period.Intraday)
{
// A special case when Append_Saturday_Sunday is on and n is on Monday.
if (SaturdaySunday == sat_sun_solution.Append_Saturday_Sunday && Bars[n].OpenTime.AddMinutes(TimeShiftMinutes).DayOfWeek == DayOfWeek.Monday)