MQL4: How to Draw Objects as Background?

Introduction to Drawing Objects as Backgrounds in MQL4

Understanding the Concept of Background Objects

In MQL4, drawing objects as backgrounds involves creating graphical objects that reside behind the price chart, indicators, and other foreground elements. This provides a way to visually enhance the chart without interfering with the core trading information. Think of it as wallpaper for your trading chart.

Why Use Background Objects?

  • Visual Enhancement: Add static or dynamic visual cues for better chart readability.
  • Highlighting Key Areas: Clearly mark support/resistance levels, trading sessions, or specific price ranges.
  • Information Display: Display non-interactive information such as market sentiment or custom indicators visually.
  • Aesthetic Appeal: Improve the overall visual appearance of the chart.

Basic Requirements and Considerations

Before diving into the code, consider the following:

  • Object Naming: Use unique names for each background object to avoid conflicts.
  • Chart ID: Be aware that objects are tied to the specific chart they are created on.
  • Object Limits: MQL4 has limitations on the number of objects that can be created on a chart, so manage them carefully.

Implementing Background Objects Using ObjectCreate

The primary function for creating objects in MQL4 is ObjectCreate(). The key to placing an object in the background lies in manipulating its properties, specifically the OBJPROP_BACK property.

Setting OBJPROP_BACK Style for Object Creation

After creating an object using ObjectCreate(), you need to set its OBJPROP_BACK property to true. This moves the object behind the other chart elements.

Object Types Suitable for Backgrounds (Rectangles, Labels, etc.)

Several object types are well-suited for backgrounds:

  • Rectangles: Ideal for highlighting specific price ranges or time periods.
  • Labels: Suitable for displaying static text information.
  • Lines: Used for drawing support/resistance levels or trendlines.
  • Bitmaps: Display custom images as background elements. Note: Bitmaps might be resource intensive.

Example: Drawing a Simple Rectangle as Background

Here’s a basic example of drawing a rectangle as a background:

int OnInit()
{
   string objectName = "BackgroundRect";
   double priceHigh = iHigh(NULL, 0, 0);
   double priceLow = iLow(NULL, 0, 0);
   datetime timeStart = iTime(NULL, 0, 10); // Time of the 10th bar from the end.
   datetime timeEnd = TimeCurrent(); // Current time.

   if(ObjectCreate(0, objectName, OBJ_RECTANGLE, 0, timeStart, priceHigh, timeEnd, priceLow)) {
    ObjectSetInteger(0, objectName, OBJPROP_BACK, true);
    ObjectSetInteger(0, objectName, OBJPROP_COLOR, clrLightBlue);
    ObjectSetInteger(0, objectName, OBJPROP_STYLE, STYLE_SOLID);
    ObjectSetInteger(0, objectName, OBJPROP_WIDTH, 1);
    ObjectSetInteger(0, objectName, OBJPROP_ZORDER, 0);  //Ensure background
    return(INIT_SUCCEEDED);
   }
   else {
      Print("Error creating object: ", GetLastError());
      return(INIT_FAILED);
   }
}

void OnDeinit(const int reason)
{
   ObjectDelete(0, "BackgroundRect");
}

Object Properties and Customization for Backgrounds

Adjusting Object Colors and Styles

Use ObjectSetInteger() and ObjectSetDouble() to customize the appearance of your background objects. Common properties include:

  • OBJPROP_COLOR: Sets the object’s color.
  • OBJPROP_STYLE: Defines the line style (solid, dashed, etc.).
  • OBJPROP_WIDTH: Sets the line thickness.
  • OBJPROP_FILL: Fills the object with color if applicable.

Managing Z-Order and Visibility

  • OBJPROP_ZORDER: This is crucial. By setting it to a low value (e.g., 0), you ensure the background object stays behind other objects.
  • OBJPROP_HIDDEN: Use this to temporarily hide or show the background object.

Ensuring Object Persistence Across Chart Changes

Objects are typically deleted when the chart is changed (e.g., timeframe switch, symbol change). To prevent this, use ChartSetInteger(0, CHART_OBJECTS_SELECT, true);. This adds all the object to the selection and save it when switching timeframes.

Advanced Techniques for Dynamic Backgrounds

Creating Responsive Backgrounds (Adjusting to Chart Size)

Use ChartGetInteger(0, CHART_WIDTH_IN_PIXELS) and ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS) to get the chart’s current dimensions. Then, adjust the object’s coordinates accordingly during the OnCalculate() or OnTimer() function.

Using Timers to Update Background Objects Dynamically

Set a timer using EventSetTimer() to periodically update the background object. This is useful for creating animated effects or updating the background based on real-time market data.

Example: Animated Background Elements

int OnInit()
{
   EventSetTimer(1); // Set timer for 1-second intervals
   // ... (create background object)
   return(INIT_SUCCEEDED);
}

void OnTimer()
{
   // Modify object properties to create animation
   // For instance, change the OBJPROP_COLOR or OBJPROP_XDISTANCE
   static int counter = 0;
   string objectName = "BackgroundRect";
   ObjectSetInteger(0, objectName, OBJPROP_COLOR, ColorByCounter(counter));
   counter++;

   if(counter > 255){
     counter = 0;
   }
   ChartRedraw(0);
}

int ColorByCounter(int counter){
   return(ColorByInteger(counter,0, 255-counter));
}

int ColorByInteger(int r, int g, int b){
   return(NormalizeColor(r,g,b));
}

void OnDeinit(const int reason)
{
   EventKillTimer();
   ObjectDelete(0, "BackgroundRect");
}

Best Practices and Optimization

Efficient Object Handling to Minimize Performance Impact

  • Limit Object Count: Avoid creating too many objects, as it can slow down the chart.
  • Optimize Updates: Only update object properties when necessary.
  • Use Object Groups (where applicable): Although MQL4 doesn’t have native group object management, you can implement custom functions to handle groups of objects for easier manipulation.

Proper Object Deletion and Resource Management

Always delete objects in the OnDeinit() function using ObjectDelete() to free up resources and prevent memory leaks.

Troubleshooting Common Issues with Background Objects

  • Object Not Visible: Ensure OBJPROP_BACK is set to true and OBJPROP_ZORDER is appropriately set.
  • Object Disappears on Chart Change: Use ChartSetInteger(0, CHART_OBJECTS_SELECT, true);.
  • Performance Issues: Reduce the number of objects or optimize update frequency.

By understanding these concepts and applying best practices, you can effectively utilize background objects to create visually appealing and informative MQL4 charts. While MQL5 offers more advanced object-oriented features and enhanced graphical capabilities, the fundamental principles of creating and managing background objects remain similar. Remember to adapt and extend these techniques to suit your specific trading needs and preferences.


Leave a Reply