Saturday, 9 February 2013

How to delete all objects from a MT4 chart?

If you'd like to skip right to a downloadable MT4 script that will clean your MT4 (Metatrader 4) chart, you can find Clean Up All Objects An MQL4 Script Using ObjectDelete here.

The three main functions that are needed to find and delete all objects from a MT4 chart are ObjectsTotal(), ObjectDelete() as and ObjectName(). The MQL4 help file offers the following with regards to ObjectsTotal():

int ObjectsTotal( int type=EMPTY) 
Returns total amount of objects of the specified type in the chart. 

The important thing to understand is that objects have a reference number, but they must be removed by name. ObjectsTotal() will give the total number of objects on a chart. The key is to loop through each object and delete it by referencing it by name. The ObjectName() function returns the name of each object as the code loops through each object but requires a reference number (provided by ObjectsTotal()). The ObjectDelete() function needs the ObjectName() in order to delete an object. The code for deletion of the zeroth object is as follows:
ObjectDelete(ObjectName(0));

A simple loop can be created to go through each object, starting at the highest down to zero, progressing in reverse order. This can be written as:
for(int i = ObjectsTotal() -1; i >=0; i--) {

}

Putting the single object deletion together with the for loop (similar to a while loop) looks like the following:
for(int i = ObjectsTotal() -1; i >=0; i--) {
   ObjectDelete(ObjectName(i));
}

Add in a line to eliminate the lingering Comment at the top left of a chart and you are done!
Comment("");

If you'd like to download the code in this sample as an MQ4 file for Metatrader, then you're in luck.

No comments:

Post a Comment