/
MarketProfile.mq4
2094 lines (1894 loc) · 195 KB
/
MarketProfile.mq4
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.mq4 |
//| Copyright © 2010-2020, EarnForex.com |
//| https://www.earnforex.com/ |
//+------------------------------------------------------------------+
#property copyright "EarnForex.com"
#property link "https://www.earnforex.com/metatrader-indicators/MarketProfile/"
#property version "1.145"
#property strict
#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 undersrcore ('_').
#property indicator_chart_window
#property indicator_plots 0
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_All_Rays,
Stop_All_Rays_Except_Prev_Session,
Stop_Only_Previous_Session,
};
// Only for dot coloring choice in PutDot() when ColorBullBear == true.
enum bar_direction
{
Bullish,
Bearish,
Neutral
};
//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 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 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 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 bool ShowSinglePrint = false; // ShowSinglePrint: mark Single Print profile levels.
input color SinglePrintColor = clrGold;
input color ProminentMedianColor = clrYellow;
//input group "Performance"
input int PointMultiplier = 1; // PointMultiplier: the higher it is, the fewer chart objects.
input int ThrottleRedraw = 0; // ThrottleRedraw: delay (in seconds) for updating Market Profile.
//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 DigitsM; // Number of digits normalized based on TickMultiplier.
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.
// 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];
bool IntradayCheckPassed = false;
int IntradaySessionCount = 0;
int _SessionsToCount;
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.
double RememberSessionMax[], RememberSessionMin[];
datetime RememberSessionStart[];
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);
};
CRectangleMP* MPR_Array[];
int mpr_total = 0;
uint LastRecalculationTime = 0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
InitFailed = false;
_SessionsToCount = SessionsToCount;
if (Session == Daily)
{
Suffix = "_D";
if ((Period() < PERIOD_M5) || (Period() > 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 ((Period() < PERIOD_M30) || (Period() > 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 ((Period() < PERIOD_H1) || (Period() > PERIOD_D1))
{
string alert_text = "Timeframe should be between H1 and D1 for a Monthly session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print(alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (Session == Intraday)
{
if (Period() > 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.
}
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);
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)
{
EventSetMillisecondTimer(500);
}
IndicatorShortName("MarketProfile " + EnumToString(Session));
// Based on number of digits in PointMultiplier. -1 because if PointMultiplier < 10, it does not modify the number of digits.
DigitsM = _Digits - (StringLen(IntegerToString(PointMultiplier)) - 1);
onetick = NormalizeDouble(_Point * PointMultiplier, DigitsM);
// Adjust for TickSize granularity if needed.
double TickSize = MarketInfo(Symbol(), MODE_TICKSIZE);
if (onetick < TickSize)
{
DigitsM = _Digits - (StringLen(IntegerToString((int)MathRound(TickSize / _Point))) - 1);
onetick = NormalizeDouble(TickSize, DigitsM);
}
CurrentColorScheme = ColorScheme;
// To clean up potential leftovers when applying a chart template.
ObjectCleanup();
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_timeseries[],
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);
}
if (StartFromCurrentSession) StartDate = Time[0];
else StartDate = StartFromDate;
// Adjust 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(0);
// Delay the update of Market Profile if ThrottleRedraw is given.
if ((ThrottleRedraw > 0) && (Timer > 0))
{
if ((int)TimeLocal() - Timer < ThrottleRedraw) return(rates_total);
}
if (Session == Rectangle) // Everything becomes very simple if rectangle sessions are used.
{
CheckRectangles();
Timer = (int)TimeLocal();
return(rates_total);
}
// Recalculate everything if there were missing bars or something like that.
if (rates_total - prev_calculated > 1)
{
FirstRunDone = false;
ObjectCleanup();
}
// 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(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 >= Bars) 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 >= Bars) 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 == Intraday)
{
if (!ProcessIntradaySession(sessionstart, sessionend, i)) 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)) 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[sessionstart]);
}
}
if ((ShowValueAreaRays != None) || (ShowMedianRays != None)) 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 int n)
{
if (Session == Daily) return(FindDayStart(n));
else if (Session == Weekly) return(FindWeekStart(n));
else if (Session == Monthly) return(FindMonthStart(n));
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 < Bars) && (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(n));
}
return(x - 1);
}
else
{
// Find the first Sunday bar.
int x = n;
while ((x < Bars) && ((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(n));
}
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 int n)
{
if (n >= Bars) 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 >= Bars) 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 int n)
{
if (n >= Bars) 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 >= Bars) 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 int n)
{
if (n >= Bars) 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 >= Bars) 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 date)
{
if (Session == Daily) return(FindDayEndByDate(date));
else if (Session == Weekly) return(FindWeekEndByDate(date));
else if (Session == Monthly) return(FindMonthEndByDate(date));
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 < Bars) && (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(date));
}
return(-1);
}
//+------------------------------------------------------------------+
//| Finds the day's end bar by the day's date. |
//+------------------------------------------------------------------+
int FindDayEndByDate(const datetime date)
{
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 < Bars) && (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 date)
{
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 >= Bars) 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 date)
{
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 >= Bars) 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)
{
int seconds_from_start = TimeDayOfWeek(date1) * 24 * 3600 + TimeHour(date1) * 3600 + TimeMinute(date1) * 60 + TimeSeconds(date1);
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)
{
if ((TimeMonth(date1) == TimeMonth(date2)) && (TimeYear(date1) == TimeYear(date2))) 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. |
//+------------------------------------------------------------------+
void PutDot(const double price, const int start_bar, const int range, const int bar, string rectangle_prefix = "")
{
double divisor, color_shift;
int 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(0, -1, -1);
for (int i = obj_total - 1; i >= 0; i--)
{
string obj = ObjectName(i);
// Not a rectangle.
if (ObjectGetInteger(0, obj, OBJPROP_TYPE) != OBJ_RECTANGLE) continue;
// 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) return;
// Protection from 'Array out of range' error.
datetime time_end;
if (start_bar - (range + 1) < 0) time_end = Time[0] + PeriodSeconds();
else time_end = Time[start_bar - (range + 1)];
ObjectCreate(0, rectangle_prefix + "MP" + Suffix + LastName, OBJ_RECTANGLE, 0, Time[start_bar - range], price, time_end, price - onetick);
if (!ColorBullBear) // Otherwise, colour is already calculated.
{
// Color switching depending on the distance of the bar from the session's beginning.
int offset1, offset2;
// Using 3 as a step for color switching because MT4 has buggy invalid color codes that mess up with the chart.
// Anyway, the number of supported colors is much lower than we get here, even with step = 3.
switch(CurrentColorScheme)
{
case Blue_to_Red:
colour = 0xFF0000; // clrBlue;
offset1 = 0x030000;
offset2 = 0x000003;
break;
case Red_to_Green:
colour = 0x0000FF; // clrDarkRed;
offset1 = 0x000003;
offset2 = 0x000300;
break;
case Green_to_Blue:
colour = 0x00FF00; // clrDarkGreen;
offset1 = 0x000300;
offset2 = 0x030000;
break;
case Yellow_to_Cyan:
colour = 0x00FFFF; // clrYellow;
offset1 = 0x000003;
offset2 = 0x030000;
break;
case Magenta_to_Yellow:
colour = 0xFF00FF; // clrMagenta;
offset1 = 0x030000;
offset2 = 0x000300;
break;
case Cyan_to_Magenta:
colour = 0xFFFF00; // clrCyan;
offset1 = 0x000300;
offset2 = 0x000003;
break;
case Single_Color:
colour = SingleColor;
offset1 = 0;
offset2 = 0;
break;
default:
colour = SingleColor;
offset1 = 0;
offset2 = 0;
break;
}
// No need to do these calculations if plain color is used.
if (CurrentColorScheme != Single_Color)
{
divisor = 3.0 / 0xFF * (double)Max_number_of_bars_in_a_session;
// bar is negative.
color_shift = MathFloor((double)bar / divisor);
// Prevents color overflow.
if ((int)color_shift < -0xFF) color_shift = -0xFF;
colour += (int)color_shift * offset1;
colour -= (int)color_shift * offset2;
}
}
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_COLOR, colour);
// Fills rectangle.
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_FILL, true);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_HIDDEN, true);
}
//+------------------------------------------------------------------+
//| Deletes all chart objects created by the indicator. |
//+------------------------------------------------------------------+
void ObjectCleanup(string rectangle_prefix = "")
{
// Delete all rectangles with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "MP" + Suffix, EMPTY, OBJ_RECTANGLE);
ObjectsDeleteAll(0, rectangle_prefix + "Median" + Suffix, EMPTY, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_LeftSide" + Suffix, EMPTY, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_RightSide" + Suffix, EMPTY, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_Top" + Suffix, EMPTY, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_Bottom" + Suffix, EMPTY, OBJ_TREND);
if (ShowValueAreaRays != None)
{
// Delete all trendlines with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "Value Area HighRay" + Suffix, EMPTY, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "Value Area LowRay" + Suffix, EMPTY, OBJ_TREND);
}
if (ShowMedianRays != None)
{
// Delete all trendlines with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "Median Ray" + Suffix, EMPTY, OBJ_TREND);
}
if (ShowKeyValues)
{
// Delete all text labels with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "VAH" + Suffix, EMPTY, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "VAL" + Suffix, EMPTY, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "POC" + Suffix, EMPTY, OBJ_TEXT);
}
if (ShowSinglePrint)
{
// Delete all Single Print marks.
ObjectsDeleteAll(0, rectangle_prefix + "MPSP" + Suffix, EMPTY, OBJ_RECTANGLE);
}
}
//+------------------------------------------------------------------+
//| Extract hours and minutes from a time string. |
//| Returns false in case of an error. |
//+------------------------------------------------------------------+
bool GetHoursAndMinutes(string time_string, int& hours, int& minutes, int& time)
{
if (StringLen(time_string) == 4) time_string = "0" + time_string;
if (
// Wrong length.
(StringLen(time_string) != 5) ||
// Wrong separator.
(time_string[2] != ':') ||
// Wrong first number (only 24 hours in a day).
((time_string[0] < '0') || (time_string[0] > '2')) ||
// 00 to 09 and 10 to 19.
(((time_string[0] == '0') || (time_string[0] == '1')) && ((time_string[1] < '0') || (time_string[1] > '9'))) ||
// 20 to 23.
((time_string[0] == '2') && ((time_string[1] < '0') || (time_string[1] > '3'))) ||
// 0M to 5M.
((time_string[3] < '0') || (time_string[3] > '5')) ||
// M0 to M9.
((time_string[4] < '0') || (time_string[4] > '9'))
)
{
Print("Wrong time string: ", time_string, ". Please use HH:MM format.");
return(false);
}
string result[];
int number_of_substrings = StringSplit(time_string, ':', result);
hours = (int)StringToInteger(result[0]);
minutes = (int)StringToInteger(result[1]);
time = hours * 60 + minutes;
return(true);
}
//+------------------------------------------------------------------+
//| Extract hours and minutes from a time string. |
//| Returns false in case of an error. |
//+------------------------------------------------------------------+
bool CheckIntradaySession(const bool enable, const string start_time, const string end_time, const color_scheme cs)
{
if (enable)
{
if (!GetHoursAndMinutes(start_time, IDStartHours[IntradaySessionCount], IDStartMinutes[IntradaySessionCount], IDStartTime[IntradaySessionCount]))
{
Alert("Wrong time string format: ", start_time, ".");
return(false);
}
if (!GetHoursAndMinutes(end_time, IDEndHours[IntradaySessionCount], IDEndMinutes[IntradaySessionCount], IDEndTime[IntradaySessionCount]))
{
Alert("Wrong time string format: ", end_time, ".");
return(false);
}
// Special case of the intraday session ending at "00:00".
if (IDEndTime[IntradaySessionCount] == 0)
{
// Turn it into "24:00".
IDEndHours[IntradaySessionCount] = 24;
IDEndMinutes[IntradaySessionCount] = 0;
IDEndTime[IntradaySessionCount] = 24 * 60;
}
IDColorScheme[IntradaySessionCount] = cs;
// For special case used only with Ignore_Saturday_Sunday on Monday.
if (IDEndTime[IntradaySessionCount] < IDStartTime[IntradaySessionCount]) IntradayCrossSessionDefined = IntradaySessionCount;
IntradaySessionCount++;
}
return(true);
}
//+------------------------------------------------------------------+
//| Main procedure to draw the Market Profile based on a session |
//| start bar and session end bar. |
//| i - session number with 0 being the oldest one. |
//| Returns true on success, false - on failure. |
//+------------------------------------------------------------------+
bool ProcessSession(const int sessionstart, const int sessionend, const int i, CRectangleMP* rectangle = NULL)
{
string rectangle_prefix = ""; // Only for rectangle sessions.
if (sessionstart >= Bars) return(false); // Data not yet ready.
double SessionMax = DBL_MIN, SessionMin = DBL_MAX;
// Find the session's high and low.
for (int bar = sessionstart; bar >= sessionend; bar--)
{
if (High[bar] > SessionMax) SessionMax = High[bar];
if (Low[bar] < SessionMin) SessionMin = Low[bar];
}
SessionMax = NormalizeDouble(SessionMax, DigitsM);
SessionMin = NormalizeDouble(SessionMin, DigitsM);
if (Session == Rectangle)
{
rectangle_prefix = rectangle.name + "_";
if (SessionMax > rectangle.RectanglePriceMax) SessionMax = NormalizeDouble(rectangle.RectanglePriceMax, DigitsM);
if (SessionMin < rectangle.RectanglePriceMin) SessionMin = NormalizeDouble(rectangle.RectanglePriceMin, DigitsM);
}
int session_counter = i;
// Find Time[sessionstart] among RememberSessionStart[].
bool need_to_increment = true;
for (int j = 0; j < SessionsNumber; j++)
{
if (RememberSessionStart[j] == Time[sessionstart])
{
need_to_increment = false;
session_counter = j; // Real number of the session.
break;
}
}
// Raise the number of sessions and resize arrays.
if (need_to_increment)
{
SessionsNumber++;
session_counter = SessionsNumber - 1; // Newest session.
ArrayResize(RememberSessionMax, SessionsNumber);
ArrayResize(RememberSessionMin, SessionsNumber);
ArrayResize(RememberSessionStart, SessionsNumber);
ArrayResize(RememberSessionSuffix, SessionsNumber);
}
RememberSessionMax[session_counter] = SessionMax;
RememberSessionMin[session_counter] = SessionMin;
RememberSessionStart[session_counter] = Time[sessionstart];
RememberSessionSuffix[session_counter] = Suffix;
// Used to make sure that SessionMax increments only by 'onetick' increments.
// This is needed only when updating the latest trading session and PointMultiplier > 1.