To enhance your BB_Cross.mq4 indicator by drawing vertical lines at the same positions as the Buy and Sell arrows, you can modify the OnCalculate function to include the creation of vertical lines (OBJ_VLINE). These lines will match the color of the respective arrows, providing a clear visual representation of Buy and Sell signals on your chart.
Below are the steps and the modified code to achieve this functionality:
1. Define Line Properties
First, define properties for the Buy and Sell lines, such as colors and line styles. This makes your code cleaner and easier to manage.
//--- Vertical line properties
#define BUY_LINE_COLOR 0xFFAA00 // Same as Buy arrow
#define SELL_LINE_COLOR 0x0000FF // Same as Sell arrow
#define LINE_STYLE STYLE_SOLID
#define LINE_WIDTH 1
2. Modify the OnCalculate Function
Within the OnCalculate function, after detecting a Buy or Sell signal, create a vertical line at the corresponding bar's time. To ensure that each line has a unique name and to prevent cluttering the chart with too many lines, you can name the lines based on the signal type and the bar index.
Here's the updated portion of the OnCalculate function with the necessary additions:
//+------------------------------------------------------------------+
//| Custom indicator 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[])
{
int limit = rates_total - prev_calculated;
//--- counting from 0 to rates_total
ArraySetAsSeries(Buffer1, true);
ArraySetAsSeries(Buffer2, true);
//--- initial zero
if (prev_calculated < 1)
{
ArrayInitialize(Buffer1, EMPTY_VALUE);
ArrayInitialize(Buffer2, EMPTY_VALUE);
}
else
limit++;
//--- main loop
for (int i = limit - 1; i >= 1; i--)
{
if (i >= MathMin(PLOT_MAXIMUM_BARS_BACK-1, rates_total-1-OMIT_OLDEST_BARS)) continue; //omit some old rates to prevent "Array out of range" or slow calculation
// Check for Buy signal
if (Close[i] > iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, i)
&& Close[i + 1] < iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, i + 1)
&& !isBuySignal) // Only set if not already a buy signal
{
Buffer1[i] = Low[i] - iATR(NULL, PERIOD_CURRENT, 14, i);
if (i == 1 && Time[1] != time_alert) myAlert("", "Buy"); // Alert on next bar open
isBuySignal = true;
isSellSignal = false; // Reset sell signal
time_alert = Time[1];
// Create Buy vertical line
string buyLineName = "BuyLine_" + IntegerToString(i);
if(!ObjectCreate(0, buyLineName, OBJ_VLINE, 0, Time[i], 0))
{
myAlert("error", "Failed to create Buy vertical line.");
}
else
{
ObjectSetInteger(0, buyLineName, OBJPROP_COLOR, BUY_LINE_COLOR);
ObjectSetInteger(0, buyLineName, OBJPROP_STYLE, LINE_STYLE);
ObjectSetInteger(0, buyLineName, OBJPROP_WIDTH, LINE_WIDTH);
}
}
else
{
Buffer1[i] = EMPTY_VALUE;
}
// Check for Sell signal
if (Close[i] < iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, i)
&& Close[i + 1] > iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, i + 1)
&& !isSellSignal) // Only set if not already a sell signal
{
Buffer2[i] = High[i] + iATR(NULL, PERIOD_CURRENT, 14, i);
if (i == 1 && Time[1] != time_alert) myAlert("", "Sell"); // Alert on next bar open
isSellSignal = true;
isBuySignal = false; // Reset buy signal
time_alert = Time[1];
// Create Sell vertical line
string sellLineName = "SellLine_" + IntegerToString(i);
if(!ObjectCreate(0, sellLineName, OBJ_VLINE, 0, Time[i], 0))
{
myAlert("error", "Failed to create Sell vertical line.");
}
else
{
ObjectSetInteger(0, sellLineName, OBJPROP_COLOR, SELL_LINE_COLOR);
ObjectSetInteger(0, sellLineName, OBJPROP_STYLE, LINE_STYLE);
ObjectSetInteger(0, sellLineName, OBJPROP_WIDTH, LINE_WIDTH);
}
}
else
{
Buffer2[i] = EMPTY_VALUE;
}
}
// Optional: Remove old lines to prevent clutter (e.g., keep last 100 lines)
// This section is optional and can be adjusted based on your preferences
int maxLines = 100;
int totalObjects = ObjectsTotal(0, OBJ_VLINE, 0, 0);
if(totalObjects > maxLines)
{
for(int j = 0; j < (totalObjects - maxLines); j++)
{
string objName = ObjectName(0, j);
if(StringFind(objName, "BuyLine_") == 0 || StringFind(objName, "SellLine_") == 0)
{
ObjectDelete(0, objName);
}
}
}
return(rates_total);
}
3. Explanation of the Modifications
4. Complete Modified Indicator Code
For your convenience, here's the complete modified BB_Cross.mq4 indicator code with the added vertical line functionality:
//+------------------------------------------------------------------+
//| Indicator: BB_Cross.mq4 |
//| Created with EABuilder.com |
//| https://www.eabuilder.com |
//+------------------------------------------------------------------+
#property copyright "Created with EABuilder.com"
#property link "https://www.eabuilder.com"
#property version "1.00"
#property description ""
#include <stdlib.mqh>
#include <stderror.mqh>
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_type1 DRAW_ARROW
#property indicator_width1 3
#property indicator_color1 0xFFAA00
#property indicator_label1 "Buy"
#property indicator_type2 DRAW_ARROW
#property indicator_width2 3
#property indicator_color2 0x0000FF
#property indicator_label2 "Sell"
#define PLOT_MAXIMUM_BARS_BACK 5000
#define OMIT_OLDEST_BARS 5000
//--- indicator buffers
double Buffer1[];
double Buffer2[];
extern int Period_BB = 20;
extern double Deviations = 1;
datetime time_alert; //used when sending alert
extern bool Audible_Alerts = true;
extern bool Push_Notifications = true;
double myPoint; //initialized in OnInit
bool isBuySignal = false;
bool isSellSignal = false;
//--- Vertical line properties
#define BUY_LINE_COLOR 0xFFAA00 // Same as Buy arrow
#define SELL_LINE_COLOR 0x0000FF // Same as Sell arrow
#define LINE_STYLE STYLE_SOLID
#define LINE_WIDTH 1
void myAlert(string type, string message)
{
if(type == "print")
Print(message);
else if(type == "error")
{
Print(type + " | BB_Cross @ " + Symbol() + "," + IntegerToString(Period()) + " | " + message);
}
else if(type == "order")
{
}
else if(type == "modify")
{
}
else if(type == "indicator")
{
if(Audible_Alerts) Alert(type + " | BB_Cross @ " + Symbol() + "," + IntegerToString(Period()) + " | " + message);
if(Push_Notifications) SendNotification(type + " | BB_Cross @ " + Symbol() + "," + IntegerToString(Period()) + " | " + message);
}
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
IndicatorBuffers(2);
SetIndexBuffer(0, Buffer1);
SetIndexEmptyValue(0, EMPTY_VALUE);
SetIndexDrawBegin(0, MathMax(Bars(Symbol(), PERIOD_CURRENT) - PLOT_MAXIMUM_BARS_BACK + 1, OMIT_OLDEST_BARS + 1));
SetIndexArrow(0, 241);
SetIndexBuffer(1, Buffer2);
SetIndexEmptyValue(1, EMPTY_VALUE);
SetIndexDrawBegin(1, MathMax(Bars(Symbol(), PERIOD_CURRENT) - PLOT_MAXIMUM_BARS_BACK + 1, OMIT_OLDEST_BARS + 1));
SetIndexArrow(1, 242);
//initialize myPoint
myPoint = Point();
if(Digits() == 5 || Digits() == 3)
{
myPoint *= 10;
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator 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[])
{
int limit = rates_total - prev_calculated;
//--- counting from 0 to rates_total
ArraySetAsSeries(Buffer1, true);
ArraySetAsSeries(Buffer2, true);
//--- initial zero
if(prev_calculated < 1)
{
ArrayInitialize(Buffer1, EMPTY_VALUE);
ArrayInitialize(Buffer2, EMPTY_VALUE);
}
else
limit++;
//--- main loop
for(int i = limit - 1; i >= 1; i--)
{
if(i >= MathMin(PLOT_MAXIMUM_BARS_BACK-1, rates_total-1-OMIT_OLDEST_BARS)) continue; //omit some old rates to prevent "Array out of range" or slow calculation
// Check for Buy signal
if(Close[i] > iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, i)
&& Close[i + 1] < iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, i + 1)
&& !isBuySignal) // Only set if not already a buy signal
{
Buffer1[i] = Low[i] - iATR(NULL, PERIOD_CURRENT, 14, i);
if(i == 1 && Time[1] != time_alert) myAlert("", "Buy"); // Alert on next bar open
isBuySignal = true;
isSellSignal = false; // Reset sell signal
time_alert = Time[1];
// Create Buy vertical line
string buyLineName = "BuyLine_" + IntegerToString(i);
if(!ObjectCreate(0, buyLineName, OBJ_VLINE, 0, Time[i], 0))
{
myAlert("error", "Failed to create Buy vertical line.");
}
else
{
ObjectSetInteger(0, buyLineName, OBJPROP_COLOR, BUY_LINE_COLOR);
ObjectSetInteger(0, buyLineName, OBJPROP_STYLE, LINE_STYLE);
ObjectSetInteger(0, buyLineName, OBJPROP_WIDTH, LINE_WIDTH);
}
}
else
{
Buffer1[i] = EMPTY_VALUE;
}
// Check for Sell signal
if(Close[i] < iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, i)
&& Close[i + 1] > iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, i + 1)
&& !isSellSignal) // Only set if not already a sell signal
{
Buffer2[i] = High[i] + iATR(NULL, PERIOD_CURRENT, 14, i);
if(i == 1 && Time[1] != time_alert) myAlert("", "Sell"); // Alert on next bar open
isSellSignal = true;
isBuySignal = false; // Reset buy signal
time_alert = Time[1];
// Create Sell vertical line
string sellLineName = "SellLine_" + IntegerToString(i);
if(!ObjectCreate(0, sellLineName, OBJ_VLINE, 0, Time[i], 0))
{
myAlert("error", "Failed to create Sell vertical line.");
}
else
{
ObjectSetInteger(0, sellLineName, OBJPROP_COLOR, SELL_LINE_COLOR);
ObjectSetInteger(0, sellLineName, OBJPROP_STYLE, LINE_STYLE);
ObjectSetInteger(0, sellLineName, OBJPROP_WIDTH, LINE_WIDTH);
}
}
else
{
Buffer2[i] = EMPTY_VALUE;
}
}
// Optional: Remove old lines to prevent clutter (e.g., keep last 100 lines)
// Adjust based on your preferences
int maxLines = 100;
int totalObjects = ObjectsTotal(0, OBJ_VLINE, 0, 0);
if(totalObjects > maxLines)
{
for(int j = 0; j < (totalObjects - maxLines); j++)
{
string objName = ObjectName(0, j);
if(StringFind(objName, "BuyLine_") == 0 || StringFind(objName, "SellLine_") == 0)
{
ObjectDelete(0, objName);
}
}
}
return(rates_total);
}
//+------------------------------------------------------------------+
5. Additional Recommendations
-
Object Naming Convention: By naming each vertical line uniquely (e.g., BuyLine_1234), you ensure that multiple lines can coexist without conflicts. This approach also makes it easier to manage (update or delete) specific lines if needed.
-
Performance Considerations: Drawing many objects on a chart can impact performance, especially if the maxLines limit is set too high. Adjust the maxLines variable to balance between visual information and performance.
-
Customization: Feel free to adjust the BUY_LINE_COLOR, SELL_LINE_COLOR, LINE_STYLE, and LINE_WIDTH definitions to match your personal preferences or to better integrate with your chart's color scheme.
-
Error Handling: The myAlert function handles errors related to object creation. Ensure that your alert settings are configured correctly to receive these notifications.
6. Testing the Indicator
After implementing the above modifications:
-
Compile the Indicator:
- Open MetaEditor.
- Paste the modified code into the
BB_Cross.mq4 file.
- Compile the code (F7) and ensure there are no errors.
-
Attach to Chart:
- In MetaTrader 4, navigate to the
Navigator panel.
- Under
Indicators, find BB_Cross and drag it onto your desired chart.
-
Verify Functionality:
- Look for Buy and Sell arrows along with corresponding vertical lines when conditions are met.
- Ensure that alerts are functioning as expected.
By following these steps, your BB_Cross indicator will now display vertical lines at the same positions as the Buy and Sell arrows, enhancing visual clarity and aiding in better decision-making during trading.