-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRoundLevels.mq4
More file actions
374 lines (346 loc) · 16.8 KB
/
RoundLevels.mq4
File metadata and controls
374 lines (346 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
//+------------------------------------------------------------------+
//| RoundLevels.mq4 |
//| Copyright © 2026, EarnForex.com |
//| https://www.earnforex.com/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2026 www.EarnForex.com"
#property link "https://www.earnforex.com/indicators/Round-Levels/"
#property version "1.04"
#property strict
#property description "Generates round level zone background shading on the chart, with optional horizontal lines, labels, alerts, and a hide/show button."
#property indicator_chart_window
#property indicator_plots 0
enum ENUM_BUTTON_CORNER
{
UpperLeft = CORNER_LEFT_UPPER, // Upper Left
LowerLeft = CORNER_LEFT_LOWER, // Lower Left
UpperRight = CORNER_RIGHT_UPPER, // Upper Right
LowerRight = CORNER_RIGHT_LOWER, // Lower Right
None // None (no button)
};
input string Comment_0 = "======================="; // Main
input int Levels = 5; // Levels - number of level zones in each direction.
input int Interval = 0; // Interval between zones in points. 0 = auto (based on visible chart range).
input int ZoneWidth = 0; // Zone width in points. 0 = auto (based on Interval).
input string ObjectPrefix = "RoundLevels";
input string Comment_1 = "======================="; // Visuals
input color ColorUp = clrFireBrick;
input color ColorDn = clrDarkGreen;
input bool InvertZones = false; // Invert zones to shade the areas between round numbers.
input bool ZonesAsBackground = true;
input bool DrawLines = false; // Draw lines on levels.
input color LineColor = clrDarkGray;
input int LineWidth = 1;
input ENUM_LINE_STYLE LineStyle = STYLE_DASHDOT;
input bool LinesAsBackground = false;
input bool ShowLineLabels = false;
input color LineLabelColor = clrWhite;
input ENUM_BUTTON_CORNER ButtonCorner = None; // Chart corner for the Hide/Show button.
input string Comment_2 = "======================="; // Notifications
input bool EnableNotify = false; // Enable Notifications Feature
input bool SendAlert = true; // Send Alert Notification
input bool SendApp = false; // Send Notification to Mobile
input bool SendEmail = false; // Send Notification via Email
input bool SendSound = false; // Sound Alert
input string SoundFile = "alert.wav"; // Sound File
input int AlertDelay = 5; // Alert Delay, seconds
enum direction
{
Up,
Down
};
int EffectiveInterval; // User-provided Interval, or auto-computed if Interval == 0.
int EffectiveZoneWidth; // User-provided ZoneWidth, or auto-computed if ZoneWidth == 0.
datetime LastNotificationTime;
string ButtonName;
string StateVarName;
bool Hidden = false;
double Multiplier; // Multiplier for getting number of points in the price.
double PrevLevel = 0;
double DPIScale; // Scaling factor for the Hide/Show button based on the screen DPI (1.0 at the standard 96 DPI).
void OnInit()
{
if (Interval < 0) Alert("Interval should be non-negative (0 = auto). Interval = ", Interval);
if (ZoneWidth < 0) Alert("ZoneWidth should be non-negative (0 = auto). ZoneWidth = ", ZoneWidth);
if (Levels <= 0) Alert("Levels should be a positive number. Levels = ", Levels);
Multiplier = MathPow(10, _Digits);
// Compute the effective Interval (auto when the input is 0).
if (Interval > 0)
{
EffectiveInterval = Interval;
}
else
{
double price_max = ChartGetDouble(0, CHART_PRICE_MAX);
double price_min = ChartGetDouble(0, CHART_PRICE_MIN);
double range_points = (price_max - price_min) / _Point;
// Target one interval per ~2*Levels zones, so the visible range roughly accommodates the requested number of levels above and below.
double target = range_points / (2.0 * MathMax(Levels, 1));
EffectiveInterval = SnapToNice(target);
if (EffectiveInterval < 1) EffectiveInterval = 1;
Print("RoundLevels: auto Interval = ", EffectiveInterval, " points (visible range = ", DoubleToString(range_points, 0), " points).");
}
// Compute the effective ZoneWidth (auto when the input is 0).
if (ZoneWidth > 0)
{
EffectiveZoneWidth = ZoneWidth;
}
else
{
EffectiveZoneWidth = EffectiveInterval / 5;
if (EffectiveZoneWidth < 1) EffectiveZoneWidth = 1;
Print("RoundLevels: auto ZoneWidth = ", EffectiveZoneWidth, " points.");
}
LastNotificationTime = TimeCurrent();
if (ButtonCorner != None)
{
ButtonName = ObjectPrefix + "_Button";
StateVarName = ObjectPrefix + "_Hidden_" + IntegerToString(ChartID());
DPIScale = (double)TerminalInfoInteger(TERMINAL_SCREEN_DPI) / 96.0;
// Restore hidden/shown state saved by a previous deinit (timeframe change, recompile, etc.), then delete the variable.
if (GlobalVariableCheck(StateVarName))
{
Hidden = (GlobalVariableGet(StateVarName) != 0);
GlobalVariableDel(StateVarName);
}
CreateButton();
}
}
void OnDeinit(const int reason)
{
if (ButtonCorner != None)
{
// Preserve hidden/shown state across reinitializations (timeframe change, recompile, parameter change, etc.).
// Do NOT save it when the user removes the indicator or closes the chart, so a fresh load starts from the default.
if (reason != REASON_REMOVE && reason != REASON_CHARTCLOSE)
{
GlobalVariableSet(StateVarName, Hidden ? 1 : 0);
}
}
ObjectsDeleteAll(0, ObjectPrefix + "_");
}
void OnChartEvent(const int id,
const long& lparam,
const double& dparam,
const string& sparam)
{
if (id != CHARTEVENT_OBJECT_CLICK) return;
if (sparam != ButtonName) return;
Hidden = !Hidden;
ObjectSetInteger(0, ButtonName, OBJPROP_STATE, false);
ObjectSetString(0, ButtonName, OBJPROP_TEXT, Hidden ? "Show Lines" : "Hide Lines");
ObjectSetString(0, ButtonName, OBJPROP_TOOLTIP, Hidden ? "Show Round Levels indicator lines/zones" : "Hide Round Levels indicator lines/zones");
SetLevelsVisibility(!Hidden);
ChartRedraw();
}
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 (EffectiveInterval <= 0) return 0;
double starting_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double check_level = FindNextLevel(starting_price, Down); // To verify that levels haven't changed.
if (MathAbs(check_level - PrevLevel) < _Point / 2 && (!EnableNotify || (!SendAlert && !SendApp && !SendEmail && !SendSound))) return rates_total; // Prevent recalculation on the same price.
PrevLevel = check_level;
for (int i = 0; i < Levels; i++)
{
// Calculate price levels below and above the current price.
double lvl_down = FindNextLevel(starting_price - i * EffectiveInterval * _Point, Down);
double lvl_up = FindNextLevel(starting_price + i * EffectiveInterval * _Point, Up);
// Calculate and draw rectangle below current price.
string name = ObjectPrefix + "_D" + IntegerToString(i);
double price1, price2;
if (InvertZones)
{
price1 = lvl_down - (EffectiveZoneWidth / 2 * _Point);
price2 = lvl_down - ((EffectiveInterval - EffectiveZoneWidth / 2) * _Point);
}
else
{
price1 = lvl_down + (EffectiveZoneWidth / 2 * _Point);
price2 = lvl_down - (EffectiveZoneWidth / 2 * _Point);
}
DrawRectangle(name, price1, price2, ColorDn);
name = ObjectPrefix + "_LD" + IntegerToString(i);
if (DrawLines) DrawLine(name, lvl_down);
Notify(price1, price2);
// Calculate and draw rectangle above current price.
name = ObjectPrefix + "_U" + IntegerToString(i);
if (InvertZones)
{
price1 = lvl_up + ((EffectiveInterval - EffectiveZoneWidth / 2) * _Point);
price2 = lvl_up + (EffectiveZoneWidth / 2 * _Point);
}
else
{
price1 = lvl_up + (EffectiveZoneWidth / 2 * _Point);
price2 = lvl_up - (EffectiveZoneWidth / 2 * _Point);
}
DrawRectangle(name, price1, price2, ColorUp);
name = ObjectPrefix + "_LU" + IntegerToString(i);
if (DrawLines) DrawLine(name, lvl_up);
Notify(price1, price2);
}
// Center level required for inverted zones.
if (InvertZones)
{
double lvl_down = FindNextLevel(starting_price, Down);
double lvl_up = FindNextLevel(starting_price, Up);
string name = ObjectPrefix + "_C";
double price1 = lvl_up - (EffectiveZoneWidth / 2 * _Point);
double price2 = lvl_down + (EffectiveZoneWidth / 2 * _Point);
DrawRectangle(name, price1, price2, (ColorDn + ColorUp) / 2);
Notify(price1, price2);
}
return rates_total;
}
double FindNextLevel(const double sp, const direction dir)
{
// Integer price (nubmer of points in the price).
int integer_price = (int)MathRound(sp * Multiplier);
// Distance from the next round number down.
int distance = integer_price % EffectiveInterval;
if (dir == Down)
{
return NormalizeDouble((integer_price - distance) / Multiplier, _Digits);
}
else if (dir == Up)
{
return NormalizeDouble((integer_price + (EffectiveInterval - distance)) / Multiplier, _Digits);
}
return EMPTY_VALUE;
}
void DrawRectangle(const string name, const double price1, const double price2, const color colour)
{
ObjectCreate(0, name, OBJ_RECTANGLE, 0, 0, 0);
ObjectSetDouble(0, name, OBJPROP_PRICE, 0, price1);
ObjectSetDouble(0, name, OBJPROP_PRICE, 1, price2);
ObjectSetInteger(0, name, OBJPROP_TIME, 0, D'1970.01.01');
ObjectSetInteger(0, name, OBJPROP_TIME, 1, INT_MAX);
ObjectSetInteger(0, name, OBJPROP_COLOR, colour);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, name, OBJPROP_BACK, ZonesAsBackground);
ObjectSetInteger(0, name, OBJPROP_FILL, true);
ObjectSetInteger(0, name, OBJPROP_TIMEFRAMES, Hidden ? OBJ_NO_PERIODS : OBJ_ALL_PERIODS);
if (!DrawLines && ShowLineLabels)
{
DrawLineLabel(name + "_LL", (price1 + price2) / 2);
}
}
void DrawLine(const string name, const double price)
{
ObjectCreate(0, name, OBJ_HLINE, 0, 0, 0);
ObjectSetDouble(0, name, OBJPROP_PRICE, 0, price);
ObjectSetInteger(0, name, OBJPROP_COLOR, LineColor);
ObjectSetInteger(0, name, OBJPROP_STYLE, LineStyle);
ObjectSetInteger(0, name, OBJPROP_WIDTH, LineWidth);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, name, OBJPROP_BACK, LinesAsBackground);
ObjectSetInteger(0, name, OBJPROP_TIMEFRAMES, Hidden ? OBJ_NO_PERIODS : OBJ_ALL_PERIODS);
if (ShowLineLabels)
{
DrawLineLabel(name + "_LL", price);
}
}
void DrawLineLabel(const string name, const double price)
{
ObjectCreate(0, name, OBJ_ARROW_RIGHT_PRICE, 0, 0, 0);
ObjectSetDouble(0, name, OBJPROP_PRICE, 0, price);
ObjectSetInteger(0, name, OBJPROP_TIME, 0, iTime(Symbol(), Period(), 0));
ObjectSetInteger(0, name, OBJPROP_COLOR, LineLabelColor);
ObjectSetInteger(0, name, OBJPROP_WIDTH, LineWidth);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, name, OBJPROP_BACK, false);
ObjectSetInteger(0, name, OBJPROP_TIMEFRAMES, Hidden ? OBJ_NO_PERIODS : OBJ_ALL_PERIODS);
}
void Notify(double price1, double price2)
{
if (!EnableNotify || (!SendAlert && !SendApp && !SendEmail && !SendSound)) return;
if (TimeCurrent() - LastNotificationTime < AlertDelay) return;
if (SymbolInfoDouble(Symbol(), SYMBOL_BID) > MathMax(price2, price1) || SymbolInfoDouble(Symbol(), SYMBOL_BID) < MathMin(price2, price1)) return;
string EmailSubject = "RoundLevels " + Symbol() + " Notification";
string EmailBody = AccountInfoString(ACCOUNT_COMPANY) + " - " + AccountInfoString(ACCOUNT_NAME) + " - " + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "\r\nRoundLevels Notification for " + Symbol() + " @ " + EnumToString((ENUM_TIMEFRAMES)Period()) + "\r\n";
string AlertText = "RoundLevels - " + Symbol() + " @ " + EnumToString((ENUM_TIMEFRAMES)Period()) + " ";
string AppText = AccountInfoString(ACCOUNT_COMPANY) + " - " + AccountInfoString(ACCOUNT_NAME) + " - " + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + " - RoundLevels - " + Symbol() + " @ " + EnumToString((ENUM_TIMEFRAMES)Period()) + " - ";
string Text = "Bid Price (" + DoubleToString(SymbolInfoDouble(Symbol(), SYMBOL_BID), _Digits) + ") inside a Zone (" + DoubleToString(price2, _Digits) + "-" + DoubleToString(price1, _Digits) + ")";
EmailBody += Text;
AlertText += Text;
AppText += Text;
if (SendAlert) Alert(AlertText);
if (SendEmail)
{
if (!SendMail(EmailSubject, EmailBody)) Print("Error sending an email: " + IntegerToString(GetLastError()));
}
if (SendApp)
{
if (!SendNotification(AppText)) Print("Error sending a push notification: " + IntegerToString(GetLastError()));
}
if (SendSound)
{
if (!PlaySound(SoundFile)) Print("Error playing a sound: " + IntegerToString(GetLastError()));
}
LastNotificationTime = TimeCurrent();
}
void CreateButton()
{
ObjectCreate(0, ButtonName, OBJ_BUTTON, 0, 0, 0);
int button_width = (int)MathRound(75 * DPIScale);
int button_height = (int)MathRound(20 * DPIScale);
int margin = (int)MathRound(10 * DPIScale);
int font_size = (int)MathRound(10 * DPIScale);
int xdist = margin;
int ydist = margin;
// Compensate for the anchor point (top-left of the button) so the button stays fully on-chart for right/bottom corners.
if (ButtonCorner == UpperRight || ButtonCorner == LowerRight) xdist = button_width + margin;
if (ButtonCorner == LowerLeft || ButtonCorner == LowerRight) ydist = button_height + margin;
ObjectSetInteger(0, ButtonName, OBJPROP_CORNER, ButtonCorner);
ObjectSetInteger(0, ButtonName, OBJPROP_XDISTANCE, xdist);
ObjectSetInteger(0, ButtonName, OBJPROP_YDISTANCE, ydist);
ObjectSetInteger(0, ButtonName, OBJPROP_XSIZE, button_width);
ObjectSetInteger(0, ButtonName, OBJPROP_YSIZE, button_height);
ObjectSetInteger(0, ButtonName, OBJPROP_FONTSIZE, font_size);
ObjectSetInteger(0, ButtonName, OBJPROP_BGCOLOR, clrDarkGray);
ObjectSetInteger(0, ButtonName, OBJPROP_COLOR, clrWhite);
ObjectSetInteger(0, ButtonName, OBJPROP_BORDER_COLOR, clrBlack);
ObjectSetInteger(0, ButtonName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, ButtonName, OBJPROP_STATE, false);
ObjectSetString(0, ButtonName, OBJPROP_TEXT, Hidden ? "Show Lines" : "Hide Lines");
ObjectSetString(0, ButtonName, OBJPROP_TOOLTIP, Hidden ? "Show Round Levels indicator lines/zones" : "Hide Round Levels indicator lines/zones");
}
void SetLevelsVisibility(const bool visible)
{
// OBJ_ALL_PERIODS shows the object on every timeframe; a value with none of the period bits set (0) hides it on all of them.
long tf = visible ? OBJ_ALL_PERIODS : OBJ_NO_PERIODS;
int total = ObjectsTotal(0, -1, -1);
for (int i = total - 1; i >= 0; i--)
{
string name = ObjectName(0, i, -1, -1);
// Toggle visibility of every object created by this indicator except the button itself.
if (StringFind(name, ObjectPrefix + "_") == 0 && name != ButtonName)
{
ObjectSetInteger(0, name, OBJPROP_TIMEFRAMES, tf);
}
}
}
// Snap a positive number to the nearest value in the 1-2-5 sequence at the appropriate power of 10 (e.g. 33 -> 20, 70 -> 50, 150 -> 100).
// Uses geometric midpoints so each bucket covers an equal log-distance.
int SnapToNice(const double value)
{
if (value < 1) return 1;
double magnitude = MathPow(10, MathFloor(MathLog(value) / MathLog(10.0)));
double normalized = value / magnitude;
int nice;
if (normalized < 1.414) nice = 1; // sqrt(2)
else if (normalized < 3.162) nice = 2; // sqrt(10)
else if (normalized < 7.071) nice = 5; // sqrt(50)
else nice = 10;
return (int)(nice * magnitude);
}
//+------------------------------------------------------------------+