-
Notifications
You must be signed in to change notification settings - Fork 66
/
MarketProfile.mq5
3391 lines (3085 loc) · 172 KB
/
MarketProfile.mq5
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
//+------------------------------------------------------------------+
//| MarketProfile.mq5 |
//| Copyright © 2010-2024, EarnForex.com |
//| https://www.earnforex.com/ |
//+------------------------------------------------------------------+
#property copyright "EarnForex.com"
#property link "https://www.earnforex.com/metatrader-indicators/MarketProfile/"
#property version "1.23"
#property description "Displays the Market Profile indicator for intraday, daily, weekly, or monthly trading sessions."
#property description "Daily - should be attached to M5-M30 timeframes. M30 is recommended."
#property description "Weekly - should be attached to M30-H4 timeframes. H1 is recommended."
#property description "Weeks start on Sunday."
#property description "Monthly - should be attached to H1-D1 timeframes. H4 is recommended."
#property description "Intraday - should be attached to M1-M15 timeframes. M5 is recommended.\r\n"
#property description "Designed for major currency pairs, but should work also with exotic pairs, CFDs, or commodities."
//+------------------------------------------------------------------+
// Rectangle session - a rectangle's name should start with 'MPR' and must not contain an underscore ('_').
//+------------------------------------------------------------------+
#property indicator_chart_window
// Two buffers are used for the Developing POC and Developing VAH/VAL display because a single buffer wouldn't support an interrupting line.
#property indicator_plots 6
#property indicator_buffers 6
#property indicator_color1 clrGreen
#property indicator_color2 clrGreen
#property indicator_width1 5
#property indicator_width2 5
#property indicator_type1 DRAW_LINE
#property indicator_type2 DRAW_LINE
#property indicator_style1 STYLE_SOLID
#property indicator_style2 STYLE_SOLID
#property indicator_label1 "Developing POC"
#property indicator_label2 "Developing POC"
#property indicator_color3 clrGoldenrod
#property indicator_color4 clrGoldenrod
#property indicator_width3 5
#property indicator_width4 5
#property indicator_type3 DRAW_LINE
#property indicator_type4 DRAW_LINE
#property indicator_style3 STYLE_SOLID
#property indicator_style4 STYLE_SOLID
#property indicator_label3 "Developing VAH"
#property indicator_label4 "Developing VAH"
#property indicator_color5 clrSalmon
#property indicator_color6 clrSalmon
#property indicator_width5 5
#property indicator_width6 5
#property indicator_type5 DRAW_LINE
#property indicator_type6 DRAW_LINE
#property indicator_style5 STYLE_SOLID
#property indicator_style6 STYLE_SOLID
#property indicator_label5 "Developing VAL"
#property indicator_label6 "Developing VAL"
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
};
enum session_period
{
Daily,
Weekly,
Monthly,
Intraday,
Rectangle
};
enum sat_sun_solution
{
Saturday_Sunday_Normal_Days, // Normal sessions
Ignore_Saturday_Sunday, // Ignore Saturday and Sunday
Append_Saturday_Sunday // Append Saturday and Sunday
};
enum sessions_to_draw_rays
{
None,
Previous,
Current,
PreviousCurrent, // Previous & Current
AllPrevious, // All Previous
All
};
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
};
enum single_print_type
{
No,
Leftside,
Rightside
};
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
};
input group "Main"
input session_period Session = Daily;
input datetime StartFromDate = __DATE__; // StartFromDate: lower priority.
input bool StartFromCurrentSession = true; // StartFromCurrentSession: higher priority.
input int SessionsToCount = 2; // SessionsToCount: Number of sessions to count Market Profile.
input bool SeamlessScrollingMode = false; // SeamlessScrollingMode: Show sessions on current screen.
input bool EnableDevelopingPOC = false; // Enable Developing POC
input bool EnableDevelopingVAHVAL = false; // Enable Developing VAH/VAL
input int ValueAreaPercentage = 70; // ValueAreaPercentage: Percentage of TPO's inside Value Area.
input group "Colors and looks"
input color_scheme ColorScheme = Blue_to_Red;
input color SingleColor = clrBlue; // SingleColor: if ColorScheme is set to Single Color.
input bool ColorBullBear = false; // ColorBullBear: If true, colors are from bars' direction.
input color MedianColor = clrWhite;
input color ValueAreaSidesColor = clrWhite;
input color ValueAreaHighLowColor = clrWhite;
input ENUM_LINE_STYLE MedianStyle = STYLE_SOLID;
input ENUM_LINE_STYLE MedianRayStyle = STYLE_DASH;
input ENUM_LINE_STYLE ValueAreaSidesStyle = STYLE_SOLID;
input ENUM_LINE_STYLE ValueAreaHighLowStyle = STYLE_SOLID;
input ENUM_LINE_STYLE ValueAreaRayHighLowStyle= STYLE_DOT;
input int MedianWidth = 1;
input int MedianRayWidth = 1;
input int ValueAreaSidesWidth = 1;
input int ValueAreaHighLowWidth = 1;
input int ValueAreaRayHighLowWidth = 1;
input sessions_to_draw_rays ShowValueAreaRays = None; // ShowValueAreaRays: draw previous value area high/low rays.
input sessions_to_draw_rays ShowMedianRays = None; // ShowMedianRays: draw previous median rays.
input ways_to_stop_rays RaysUntilIntersection = Stop_No_Rays; // RaysUntilIntersection: which rays stop when hit another MP.
input bool HideRaysFromInvisibleSessions = false; // HideRaysFromInvisibleSessions: hide rays from behind the screen.
input int TimeShiftMinutes = 0; // TimeShiftMinutes: shift session + to the left, - to the right.
input bool ShowKeyValues = true; // ShowKeyValues: print out VAH, VAL, POC on chart.
input color KeyValuesColor = clrWhite; // KeyValuesColor: color for VAH, VAL, POC printout.
input int KeyValuesSize = 8; // KeyValuesSize: font size for VAH, VAL, POC printout.
input single_print_type ShowSinglePrint = No; // ShowSinglePrint: mark Single Print profile levels.
input bool SinglePrintRays = false; // SinglePrintRays: mark Single Print edges with rays.
input color SinglePrintColor = clrGold;
input ENUM_LINE_STYLE SinglePrintRayStyle = STYLE_SOLID;
input int SinglePrintRayWidth = 1;
input color ProminentMedianColor = clrYellow;
input ENUM_LINE_STYLE ProminentMedianStyle = STYLE_SOLID;
input int ProminentMedianWidth = 4;
input bool RightToLeft = false; // RightToLeft: Draw histogram from right to left.
input group "Performance"
input int PointMultiplier = 0; // PointMultiplier: higher value = fewer objects. 0 - adaptive.
input int ThrottleRedraw = 0; // ThrottleRedraw: delay (in seconds) for updating Market Profile.
input bool DisableHistogram = false; // DisableHistogram: do not draw profile, VAH, VAL, and POC still visible.
input group "Alerts"
input bool AlertNative = false; // AlertNative: issue native pop-up alerts.
input bool AlertEmail = false; // AlertEmail: issue email alerts.
input bool AlertPush = false; // AlertPush: issue push-notification alerts.
input bool AlertArrows = false; // AlertArrows: draw chart arrows on alerts.
input alert_check_bar AlertCheckBar = CheckPreviousBar;// AlertCheckBar: which bar to check for alerts?
input bool AlertForValueArea = false; // AlertForValueArea: alerts for Value Area (VAH, VAL) rays.
input bool AlertForMedian = false; // AlertForMedian: alerts for POC (Median) rays' crossing.
input bool AlertForSinglePrint = false; // AlertForSinglePrint: alerts for single print rays' crossing.
input bool AlertOnPriceBreak = false; // AlertOnPriceBreak: price breaking above/below the ray.
input bool AlertOnCandleClose = false; // AlertOnCandleClose: candle closing above/below the ray.
input bool AlertOnGapCross = false; // AlertOnGapCross: bar gap above/below the ray.
input int AlertArrowCodePB = 108; // AlertArrowCodePB: arrow code for price break alerts.
input int AlertArrowCodeCC = 110; // AlertArrowCodeCC: arrow code for candle close alerts.
input int AlertArrowCodeGC = 117; // AlertArrowCodeGC: arrow code for gap crossover alerts.
input color AlertArrowColorPB = clrRed; // AlertArrowColorPB: arrow color for price break alerts.
input color AlertArrowColorCC = clrBlue; // AlertArrowColorCC: arrow color for candle close alerts.
input color AlertArrowColorGC = clrYellow; // AlertArrowColorGC: arrow color for gap crossover alerts.
input int AlertArrowWidthPB = 1; // AlertArrowWidthPB: arrow width for price break alerts.
input int AlertArrowWidthCC = 1; // AlertArrowWidthCC: arrow width for candle close alerts.
input int AlertArrowWidthGC = 1; // AlertArrowWidthGC: arrow width for gap crossover alerts.
input group "Intraday settings"
input bool EnableIntradaySession1 = true;
input string IntradaySession1StartTime = "00:00";
input string IntradaySession1EndTime = "06:00";
input color_scheme IntradaySession1ColorScheme = Blue_to_Red;
input bool EnableIntradaySession2 = true;
input string IntradaySession2StartTime = "06:00";
input string IntradaySession2EndTime = "12:00";
input color_scheme IntradaySession2ColorScheme = Red_to_Green;
input bool EnableIntradaySession3 = true;
input string IntradaySession3StartTime = "12:00";
input string IntradaySession3EndTime = "18:00";
input color_scheme IntradaySession3ColorScheme = Green_to_Blue;
input bool EnableIntradaySession4 = true;
input string IntradaySession4StartTime = "18:00";
input string IntradaySession4EndTime = "00:00";
input color_scheme IntradaySession4ColorScheme = Yellow_to_Cyan;
input group "Miscellaneous"
input sat_sun_solution SaturdaySunday = Saturday_Sunday_Normal_Days;
input bool DisableAlertsOnWrongTimeframes = false; // Disable alerts on wrong timeframes.
input int ProminentMedianPercentage = 101; // Percentage of Median TPOs out of total for a Prominent one.
int PointMultiplier_calculated; // Will have to be calculated based number digits in a quote if PointMultiplier input is 0.
int DigitsM; // Number of digits normalized based on PointMultiplier_calculated.
bool InitFailed; // Used for soft INIT_FAILED. Hard INIT_FAILED resets input parameters.
datetime StartDate; // Will hold either StartFromDate or Time[0].
double onetick; // One normalized pip.
bool FirstRunDone = false; // If true - OnCalculate() was already executed once.
string Suffix = "_"; // Will store object name suffix depending on timeframe.
color_scheme CurrentColorScheme; // Required due to intraday sessions.
int Max_number_of_bars_in_a_session = 1;
int Timer = 0; // For throttling updates of market profiles in slow systems.
bool NeedToRestartDrawing = false; // Global flag for RightToLeft redrawing;
int CleanedUpOn = 0; // To prevent cleaning up the buffers again and again when the platform just starts.
double ValueAreaPercentage_double = 0.7; // Will be calculated based on the input parameter in OnInit().
// Used for ColorBullBear.
bar_direction CurrentBarDirection = Neutral;
bar_direction PreviousBarDirection = Neutral;
bool NeedToReviewColors = false;
// For intraday sessions' start and end times.
int IDStartHours[4];
int IDStartMinutes[4];
int IDStartTime[4]; // Stores IDStartHours x 60 + IDStartMinutes for comparison purposes.
int IDEndHours[4];
int IDEndMinutes[4];
int IDEndTime[4]; // Stores IDEndHours x 60 + IDEndMinutes for comparison purposes.
color_scheme IDColorScheme[4];
int IntradaySessionCount = 0;
int _SessionsToCount;
int IntradayCrossSessionDefined = -1; // For special case used only with Ignore_Saturday_Sunday on Monday.
datetime LastAlertTime_CandleCross = 0, LastAlertTime_GapCross = 0; // For CheckCurrentBar alerts.
datetime LastAlertTime = 0; // For CheckPreviousBar alerts;
double Close_prev = EMPTY_VALUE; // Previous price value for Price Break alerts.
int ArrowsCounter = 0; // Counter for naming of alert arrows.
// 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.
double RememberSessionMax[], RememberSessionMin[];
datetime RememberSessionStart[];
datetime RememberSessionEnd[]; // Used only for Arrows.
string RememberSessionSuffix[];
int SessionsNumber = 0; // Different from _SessionsToCount when working with Intraday sessions and for RaysUntilIntersection != Stop_No_Rays.
// Rectangle variables:
class CRectangleMP
{
private:
datetime prev_Time0;
double prev_High, prev_Low;
double prev_RectanglePriceMax, prev_RectanglePriceMin;
int Number; // Order number of the rectangle;
public:
double RectanglePriceMax, RectanglePriceMin;
datetime RectangleTimeMax, RectangleTimeMin;
datetime t1, t2; // To avoid reading object properties in Process() after sorting was done.
string name;
CRectangleMP(string);
~CRectangleMP(void) {};
void Process(int, const double& High[], const double& Low[], const datetime& Time[], const int rates_total);
void ResetPrevTime0();
};
CRectangleMP* MPR_Array[];
int mpr_total = 0;
uint LastRecalculationTime = 0;
double DevelopingPOC_1[], DevelopingPOC_2[], DevelopingVAH_1[], DevelopingVAH_2[], DevelopingVAL_1[], DevelopingVAL_2[]; // Indicator buffers for Developing POC and VAH/VAL.
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
InitFailed = false;
// Sessions to count for the object creation.
_SessionsToCount = SessionsToCount;
// Check for user Session settings.
if (Session == Daily)
{
Suffix = "_D";
if ((PeriodSeconds() < PeriodSeconds(PERIOD_M5)) || (PeriodSeconds() > PeriodSeconds(PERIOD_M30)))
{
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 == Weekly)
{
Suffix = "_W";
if ((PeriodSeconds() < PeriodSeconds(PERIOD_M30)) || (PeriodSeconds() > PeriodSeconds(PERIOD_H4)))
{
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 == Monthly)
{
Suffix = "_M";
if ((PeriodSeconds() < PeriodSeconds(PERIOD_H1)) || (PeriodSeconds() > PeriodSeconds(PERIOD_D1)))
{
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 == Intraday)
{
if (PeriodSeconds() > PeriodSeconds(PERIOD_M15))
{
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.
}
// Check if intraday user settings are valid.
IntradaySessionCount = 0;
if (!CheckIntradaySession(EnableIntradaySession1, IntradaySession1StartTime, IntradaySession1EndTime, IntradaySession1ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession2, IntradaySession2StartTime, IntradaySession2EndTime, IntradaySession2ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession3, IntradaySession3StartTime, IntradaySession3EndTime, IntradaySession3ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession4, IntradaySession4StartTime, IntradaySession4EndTime, IntradaySession4ColorScheme)) return INIT_PARAMETERS_INCORRECT;
// 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 == 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.
}
// Indicator Name.
IndicatorSetString(INDICATOR_SHORTNAME, "MarketProfile " + EnumToString(Session));
// Adaptive point multiplier. Calculate based on number of digits in the quote (before plus after the dot).
if (PointMultiplier == 0)
{
double quote;
bool success = SymbolInfoDouble(Symbol(), SYMBOL_ASK, quote);
if (!success)
{
Print("Failed to get price data. Error #", GetLastError(), ". Using PointMultiplier = 1.");
PointMultiplier_calculated = 1;
}
else
{
string s = DoubleToString(quote, _Digits);
StringReplace(s, "-", ""); // Remove the minus sign for a negative price.
int total_digits = StringLen(s);
// If there is a dot in a quote.
if (StringFind(s, ".") != -1) total_digits--; // Decrease the count of digits by one.
if (total_digits <= 5) PointMultiplier_calculated = 1;
else PointMultiplier_calculated = (int)MathPow(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 = _Digits - (StringLen(IntegerToString(PointMultiplier_calculated)) - 1);
onetick = NormalizeDouble(_Point * PointMultiplier_calculated, DigitsM);
// Adjust for TickSize granularity if needed.
double TickSize = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE);
if (onetick < TickSize)
{
DigitsM = _Digits - (StringLen(IntegerToString((int)MathRound(TickSize / _Point))) - 1);
onetick = NormalizeDouble(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 == Rectangle) || (RightToLeft) || (HideRaysFromInvisibleSessions) || (SeamlessScrollingMode))
{
EventSetMillisecondTimer(1000);
}
if (!EnableDevelopingPOC)
{
PlotIndexSetInteger(0, PLOT_LINE_COLOR, clrNONE);
PlotIndexSetInteger(1, PLOT_LINE_COLOR, clrNONE);
}
// Better do this unconditionally to avoid buffer errors.
SetIndexBuffer(0, DevelopingPOC_1, INDICATOR_DATA);
ArraySetAsSeries(DevelopingPOC_1, true);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
SetIndexBuffer(1, DevelopingPOC_2, INDICATOR_DATA);
ArraySetAsSeries(DevelopingPOC_2, true);
PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
SetIndexBuffer(2, DevelopingVAH_1, INDICATOR_DATA);
PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
ArraySetAsSeries(DevelopingVAH_1, true);
SetIndexBuffer(3, DevelopingVAH_2, INDICATOR_DATA);
PlotIndexSetDouble(3, PLOT_EMPTY_VALUE, EMPTY_VALUE);
ArraySetAsSeries(DevelopingVAH_2, true);
SetIndexBuffer(4, DevelopingVAL_1, INDICATOR_DATA);
PlotIndexSetDouble(4, PLOT_EMPTY_VALUE, EMPTY_VALUE);
ArraySetAsSeries(DevelopingVAL_1, true);
SetIndexBuffer(5, DevelopingVAL_2, INDICATOR_DATA);
PlotIndexSetDouble(5, PLOT_EMPTY_VALUE, EMPTY_VALUE);
ArraySetAsSeries(DevelopingVAL_2, true);
ValueAreaPercentage_double = ValueAreaPercentage * 0.01;
// Initialization successful
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if (Session == Rectangle)
{
for (int i = 0; i < mpr_total; i++)
{
ObjectCleanup(MPR_Array[i].name + "_");
delete MPR_Array[i];
}
}
else ObjectCleanup();
}
//+------------------------------------------------------------------+
//| Custom Market Profile main iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime& Time[],
const double& Open[],
const double& High[],
const double& Low[],
const double& Close[],
const long& tick_volume[],
const long& volume[],
const int& spread[]
)
{
if (InitFailed)
{
if (!DisableAlertsOnWrongTimeframes) Print("Initialization failed. Please see the alert message for details.");
return 0;
}
// New bars arrived?
if (((EnableDevelopingPOC) || (EnableDevelopingVAHVAL)) && (rates_total - prev_calculated > 1) && (CleanedUpOn != rates_total))
{
// Initialize the indicator buffers.
for (int i = prev_calculated; i < rates_total; i++)
{
DevelopingPOC_1[i] = EMPTY_VALUE;
DevelopingPOC_2[i] = EMPTY_VALUE;
DevelopingVAH_1[i] = EMPTY_VALUE;
DevelopingVAH_2[i] = EMPTY_VALUE;
DevelopingVAL_1[i] = EMPTY_VALUE;
DevelopingVAL_2[i] = EMPTY_VALUE;
}
if ((prev_calculated == 0) && (Session == Rectangle)) // If prev_calculated got reset for some reason, reset the rectangles.
{
for (int i = mpr_total - 1; i >= 0 ; i--)
{
MPR_Array[i].ResetPrevTime0();
}
}
CleanedUpOn = rates_total; // To prevent cleaning up the buffers again and again when the platform just starts.
}
// Use buffers as Timeseries and not ArrayNotSeries.
ArraySetAsSeries(Open, true);
ArraySetAsSeries(High, true);
ArraySetAsSeries(Low, true);
ArraySetAsSeries(Close, true);
ArraySetAsSeries(Time, true);
CheckAlerts(Open, High, Low, Close, Time);
// Check if seamless scrolling mode should be on, else if user requests current session, else a specific date.
if (SeamlessScrollingMode)
{
int last_visible_bar = (int)ChartGetInteger(ChartID(), CHART_FIRST_VISIBLE_BAR) - (int)ChartGetInteger(ChartID(), CHART_WIDTH_IN_BARS) + 1;
if (last_visible_bar < 0) last_visible_bar = 0;
StartDate = Time[last_visible_bar];
}
else if (StartFromCurrentSession) StartDate = Time[0];
else StartDate = StartFromDate;
// Adjust date if Ignore_Saturday_Sunday is set.
if (SaturdaySunday == Ignore_Saturday_Sunday)
{
// Saturday? Switch to Friday.
if (TimeDayOfWeek(StartDate) == 6) StartDate -= 86400;
// Sunday? Switch to Friday too.
else if (TimeDayOfWeek(StartDate) == 0) StartDate -= 2 * 86400;
}
// If we calculate profiles for the past sessions, no need to run it again.
if ((FirstRunDone) && (StartDate != Time[0])) return rates_total;
// Delay the update of Market Profile if ThrottleRedraw is given.
if ((ThrottleRedraw > 0) && (Timer > 0))
{
if ((int)TimeLocal() - Timer < ThrottleRedraw) return rates_total;
}
// Calculate rectangle.
if (Session == Rectangle) // Everything becomes very simple if rectangle sessions are used.
{
CheckRectangles(High, Low, Time, rates_total);
Timer = (int)TimeLocal();
return rates_total;
}
// Recalculate everything if there were missing bars or something like that. Or if RightToLeft is on and a new right-most session arrived.
if ((rates_total - prev_calculated > 1) || (NeedToRestartDrawing))
{
FirstRunDone = false;
ObjectCleanup();
NeedToRestartDrawing = false;
if (EnableDevelopingPOC)
{
// Initialize the DPOC buffers.
ArrayInitialize(DevelopingPOC_1, EMPTY_VALUE);
ArrayInitialize(DevelopingPOC_2, EMPTY_VALUE);
}
}
// Get start and end bar numbers of the given session.
int sessionend = FindSessionEndByDate(Time, StartDate, rates_total); // Finding the session's right-most bar using the date of the previous session or starting date.
int sessionstart = FindSessionStart(Time, sessionend, rates_total); // Finding the session's left-most bar using its end (right-most) bar.
if (sessionstart == -1)
{
Print("Something went wrong! Waiting for data to load.");
return prev_calculated;
}
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 >= rates_total) return prev_calculated;
if (SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(Time[sessionend]) == 0) || (TimeDayOfWeek(Time[sessionend]) == 6))
{
sessionend++;
if (sessionend >= rates_total) break;
}
}
sessionstart = FindSessionStart(Time, sessionend, rates_total);
}
}
// We begin from the oldest session coming to the current session or to StartFromDate.
for (int i = SessionToStart; i < _SessionsToCount; i++)
{
if (Session == Intraday)
{
if (!ProcessIntradaySession(sessionstart, sessionend, i, High, Low, Time, rates_total)) return 0;
}
else
{
if (Session == Daily) Max_number_of_bars_in_a_session = PeriodSeconds(PERIOD_D1) / PeriodSeconds();
else if (Session == Weekly) Max_number_of_bars_in_a_session = 604800 / PeriodSeconds();
else if (Session == Monthly) Max_number_of_bars_in_a_session = 2678400 / PeriodSeconds();
if (SaturdaySunday == Append_Saturday_Sunday)
{
// The start is on Sunday - add remaining time.
if (TimeDayOfWeek(Time[sessionstart]) == 0) Max_number_of_bars_in_a_session += (24 * 3600 - (TimeHour(Time[sessionstart]) * 3600 + TimeMinute(Time[sessionstart]) * 60)) / PeriodSeconds();
// The end is on Saturday. +1 because even 0:00 bar deserves a bar.
if (TimeDayOfWeek(Time[sessionend]) == 6) Max_number_of_bars_in_a_session += ((TimeHour(Time[sessionend]) * 3600 + TimeMinute(Time[sessionend]) * 60)) / PeriodSeconds() + 1;
}
if (!ProcessSession(sessionstart, sessionend, i, High, Low, Time, rates_total)) return 0;
}
// Go to the newer session only if there is one or more left.
if (_SessionsToCount - i > 1)
{
sessionstart = sessionend - 1;
if (SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(Time[sessionstart]) == 0) || (TimeDayOfWeek(Time[sessionstart]) == 6))
{
sessionstart--;
if (sessionstart == 0) break;
}
}
sessionend = FindSessionEndByDate(Time, Time[sessionstart], rates_total);
}
}
if ((ShowValueAreaRays != None) || (ShowMedianRays != None) || ((HideRaysFromInvisibleSessions) && (SinglePrintRays))) CheckRays();
FirstRunDone = true;
Timer = (int)TimeLocal();
return rates_total;
}
//+------------------------------------------------------------------+
//| Finds the session's starting bar number for any given bar number.|
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindSessionStart(const datetime &Time[], const int n, const int rates_total)
{
if (Session == Daily) return FindDayStart(Time, n, rates_total);
else if (Session == Weekly) return FindWeekStart(Time, n, rates_total);
else if (Session == Monthly) return FindMonthStart(Time, n, rates_total);
else if (Session == Intraday)
{
// A special case when Append_Saturday_Sunday is on and n is on Monday.
if ((SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[n] + TimeShiftMinutes * 60) == 1))
{
// One of the intraday sessions should start at 00:00 or have end < start.
for (int intraday_i = 0; intraday_i < IntradaySessionCount; intraday_i++)
{
if ((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// "Monday" part of the day. Effective only for "end < start" sessions.
if ((TimeHour(Time[n]) * 60 + TimeMinute(Time[n]) >= IDEndTime[intraday_i]) && (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// Find the first bar on Monday after the borderline session.
int x = n;
while ((x < rates_total) && (TimeHour(Time[x]) * 60 + TimeMinute(Time[x]) >= IDEndTime[intraday_i]))
{
x++;
// If there is no Sunday session (stepped into Saturday or another non-Sunday/non-Monday day, return normal day start.
if (TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) > 1) return FindDayStart(Time, n, rates_total);
}
return (x - 1);
}
else
{
// Find the first Sunday bar.
int x = n;
while ((x < rates_total) && ((TimeDayOfYear(Time[n] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[x] + TimeShiftMinutes * 60)) || (TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) == 0))) x++;
// Number of sessions should be increased as we "lose" one session to Sunday.
_SessionsToCount++;
return (x - 1);
}
}
}
}
return FindDayStart(Time, n, rates_total);
}
return -1;
}
//+------------------------------------------------------------------+
//| Finds the day's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindDayStart(const datetime &Time[], const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
int time_n_day_of_week = time_x_day_of_week;
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or it is Friday but the bar n is on Saturday.
while ((TimeDayOfYear(Time[n] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[x] + TimeShiftMinutes * 60)) || ((SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_x_day_of_week == 5) && (time_n_day_of_week == 6)))))
{
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the week's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindWeekStart(const datetime &Time[], const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday.
while ((SameWeek(Time[n] + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60)) || ((SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)))
{
// If Ignore_Saturday_Sunday is on and we stepped into Sunday, stop.
if ((SaturdaySunday == Ignore_Saturday_Sunday) && (time_x_day_of_week == 0)) break;
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the month's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindMonthStart(const datetime &Time[], const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(Time[n] + TimeShiftMinutes * 60);
int time_n_day = TimeDay(Time[n] + TimeShiftMinutes * 60);
int time_n_month = TimeMonth(Time[n] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of month.
while ((time_n_month == TimeMonth(Time[x] + TimeShiftMinutes * 60)) || ((SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (time_n_day == 1)))))
{
// If month distance somehow becomes greater than 1, break.
int month_distance = time_n_month - TimeMonth(Time[x] + TimeShiftMinutes * 60);
if (month_distance < 0) month_distance = 12 - month_distance;
if (month_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of month. Despite it being current month, it should be skipped because it is appended to the previous month. Unless it is the sessionend day, which is the Saturday of the next month attached to this session.
if (SaturdaySunday == Append_Saturday_Sunday)
{
if ((time_x_day_of_week == 6) && (TimeDay(Time[x] + TimeShiftMinutes * 60) == 1) && (time_n_day != TimeDay(Time[x] + TimeShiftMinutes * 60))) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of month. Despite it being current month, it should be skipped because it is ignored.
if (SaturdaySunday == Ignore_Saturday_Sunday)
{
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && ((TimeDay(Time[x] + TimeShiftMinutes * 60) == 1) || (TimeDay(Time[x] + TimeShiftMinutes * 60) == 2))) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the session's end bar by the session's date. |
//+------------------------------------------------------------------+
int FindSessionEndByDate(const datetime &Time[], const datetime date, const int rates_total)
{
if (Session == Daily) return FindDayEndByDate(Time, date, rates_total);
else if (Session == Weekly) return FindWeekEndByDate(Time, date, rates_total);
else if (Session == Monthly) return FindMonthEndByDate(Time, date, rates_total);
else if (Session == Intraday)
{
// A special case when Append_Saturday_Sunday is on and the date is on Sunday.
if ((SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0))
{
// One of the intraday sessions should start at 00:00 or have end < start.
for (int intraday_i = 0; intraday_i < IntradaySessionCount; intraday_i++)
{
if ((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// Find the last bar of this intraday session and return it as sessionend.
int x = 0;
int abs_day = TimeAbsoluteDay(date + TimeShiftMinutes * 60);
// TimeAbsoluteDay is used for cases when the given date is Dec 30 (#364) and the current date is Jan 1 (#1) for example.
while ((x < rates_total) && (abs_day < TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60))) // It's Sunday.
{
// On Monday.
if (TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60) == abs_day + 1)
{
// Inside the session.
if (TimeHour(Time[x]) * 60 + TimeMinute(Time[x]) < IDEndTime[intraday_i]) break;
// Break out earlier (on Monday's end bar) if working with 00:00-XX:XX session.
if (IDStartTime[intraday_i] == 0) break;
}
x++;
}
return x;
}
}
}
return FindDayEndByDate(Time, date, rates_total);
}
return -1;
}
//+------------------------------------------------------------------+
//| Finds the day's end bar by the day's date. |
//+------------------------------------------------------------------+
int FindDayEndByDate(const datetime &Time[], const datetime date, const int rates_total)
{
int x = 0;
// TimeAbsoluteDay is used for cases when the given date is Dec 30 (#364) and the current date is Jan 1 (#1) for example.
while ((x < rates_total) && (TimeAbsoluteDay(date + TimeShiftMinutes * 60) < TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60)))
{
// Check if Append_Saturday_Sunday is on and if the found end of the day is on Saturday and the given date is the previous Friday; or it is a Monday and the sought date is the previous Sunday.
if (SaturdaySunday == Append_Saturday_Sunday)
{
if (((TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) == 6) || (TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) == 1)) && (TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60) - TimeAbsoluteDay(date + TimeShiftMinutes * 60) == 1)) break;
}
x++;
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the week's end bar by the week's date. |
//+------------------------------------------------------------------+
int FindWeekEndByDate(const datetime &Time[], const datetime date, const int rates_total)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameWeek(date + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60) != true) || ((SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the month's end bar by the month's date. |
//+------------------------------------------------------------------+
int FindMonthEndByDate(const datetime &Time[], const datetime date, const int rates_total)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameMonth(date + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60) != true) || ((SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (SaturdaySunday == Append_Saturday_Sunday)
{
// Today is Saturday the 1st day of the next month. Despite it being in a next month, it should be appended to the current month.
if ((time_x_day_of_week == 6) && (TimeDay(Time[x] + TimeShiftMinutes * 60) == 1) && (TimeYear(Time[x] + TimeShiftMinutes * 60) * 12 + TimeMonth(Time[x] + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60) * 12 - TimeMonth(date + TimeShiftMinutes * 60) == 1)) break;
// Given date is Sunday of a previous month. It was rejected in the previous month and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the month.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (TimeYear(Time[x] + TimeShiftMinutes * 60) * 12 + TimeMonth(Time[x] + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60) * 12 - TimeMonth(date + TimeShiftMinutes * 60) == 1)) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same week. |
//+------------------------------------------------------------------+
int SameWeek(const datetime date1, const datetime date2)
{
MqlDateTime dt1, dt2;
TimeToStruct(date1, dt1);
TimeToStruct(date2, dt2);
int seconds_from_start = dt1.day_of_week * 24 * 3600 + dt1.hour * 3600 + dt1.min * 60 + dt1.sec;
if (date1 == date2) return true;
else if (date2 < date1)
{
if (date1 - date2 <= seconds_from_start) return true;
}
// 604800 - seconds in one week.
else if (date2 - date1 < 604800 - seconds_from_start) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same month. |
//+------------------------------------------------------------------+
int SameMonth(const datetime date1, const datetime date2)
{
MqlDateTime dt1, dt2;
TimeToStruct(date1, dt1);
TimeToStruct(date2, dt2);
if ((dt1.mon == dt2.mon) && (dt1.year == dt2.year)) return true;
return false;
}
//+------------------------------------------------------------------+
//| Puts a dot (rectangle) at a given position and color. |
//| price and time are coordinates. |
//| range is for the second coordinate. |
//| bar is to determine the color of the dot. |
//| Returns inverted end time only for the RightToLeft session. |
//+------------------------------------------------------------------+
datetime PutDot(const double price, const int start_bar, const int range, const int bar, const datetime &Time[], string rectangle_prefix = "", datetime converted_time = 0)
{
double divisor, color_shift;
color colour = -1;
// All dots are with the same date/time for a given origin bar, but with a different price.
string LastNameStart = " " + TimeToString(Time[bar + start_bar]) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
if (ColorBullBear) colour = CalculateProperColor();
// Bull/bear coloring part.
if (NeedToReviewColors)
{
// Finding all dots (rectangle objects) with proper suffix and start of last name (date + time of the bar, but not price).
// This is needed to change their color if candle changed its direction.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_RECTANGLE);
for (int i = obj_total - 1; i >= 0; i--)
{
string obj = ObjectName(ChartID(), i, -1, OBJ_RECTANGLE);
// Probably some other object.
if (StringSubstr(obj, 0, StringLen(rectangle_prefix + "MP" + Suffix)) != rectangle_prefix + "MP" + Suffix) continue;
// Previous bar's dot found.
if (StringSubstr(obj, 0, StringLen(rectangle_prefix + "MP" + Suffix + LastNameStart)) != rectangle_prefix + "MP" + Suffix + LastNameStart) break;
// Change color.
ObjectSetInteger(0, obj, OBJPROP_COLOR, colour);
}
}
if (ObjectFind(0, rectangle_prefix + "MP" + Suffix + LastName) >= 0)
{
if ((!RightToLeft) || (converted_time == 0)) return 0; // Normal case;
}
datetime time_end, time_start;
datetime prev_time = converted_time; // For drawing, we need two times.
if (converted_time != 0) // This is the right-to-left mode and the right-most session.
{
// Check if we have started a new right-most session, so the previous one should be cleaned up.
static datetime prev_time_start_bar = 0;
if ((Time[start_bar] != prev_time_start_bar) && (prev_time_start_bar != 0)) // New right-most session arrived - recalculate everything.
{
NeedToRestartDrawing = true;
}
prev_time_start_bar = Time[start_bar];
// Find the time:
int x = -1;
for (int i = range + 1; i > 0; i--) // + 1 to get a bit "lefter" time in converted_time, and actual dot's time into prev_time.
{
prev_time = converted_time;
if (converted_time == Time[0]) // First time stepped into existing candles.
{