• Home
  • Free MQL4 Course
  • MQL4 Forums
Forex Mentor Pro
  • Free MQL4 Course
  • MQL4 Made Easy
  • MQL4 Programming
  • Expert Advisors
  • Articles

How to Create a Simple Toggle Button in MQL4

Recently I started using an indicator that had been written by another programmer and initially it was doing a pretty good job. However,eventually I started getting annoyed with one particular implementation...

...or rather lack of implementation.

The indicator itself was a pretty simple affair and in essence all it did was to draw a series of lines starting from a predefined point. I'd drop the indicator on the chart, drag the zero line and the rest of the lines would be redrawn automatically, relative to it's position.

The problem came when I wanted to change the orientation of the lines and make the zero line the top rather than the bottom. The way the original programmer had coded it meant that the user would have to go into the settings, scroll down the list, identify the correct setting and change it from true to false.

Now instead of drawing the lines from zero upwards, it would draw them from zero downwards.

What a long winded way to accomplish a simple task!

So I decided it would be much simpler - and cooler - to have a button on the chart that would toggle the settings state from true to false. That way I wouldn't have to mess around with settings and instead could change the value by the click of a button.

Sounds pretty sweet right?

Well here's how you can do it too...

First you need to start a new indicator project and make sure you include the OnChartEvent function by selecting the appropriate radio button during the setup wizard.

In MetaEditor choose File->New and follow the prompts by the setup wizard.

setup_wizard1

You can name it anything you want but as you'll see below; I named it something really exciting like 'Toggle_Example'; imaginative I know!

setup_wizard2

Don't forget to select the 'OnChartEvent' radio button too.

setup_wizard3

Then you need to add an external variable to hold the value that we are going to be toggling. This is only for demonstration purposes so the indicator won't have much functionality but you will understand how to code a button for your own projects.

#property copyright "Copyright 2015, Automated Trading Software"
#property link      "http://automatedtradingsoftware.co.uk"
#property version   "1.00"
#property strict
#property indicator_chart_window

extern bool value_to_toggle = true; // The Value to Toggle

We also need to give our button a unique name so that we can refer to it throughout our code. Again I let my creative juices run wild and came up with the amazing variable name of 'sButtonName' and set it's value to 'toggle_button'.

// unique identifier that we can access from multiple places throughout the code
string sButtonName = "toggle_button";

If you've downloaded the code provided below and are following along, scroll down to our 'Toggle' function.

I won't go into too much detail about what it does as it should be obvious just by looking at the code. The only thing that's interesting to note is the use of '!value_to_toggle' which is being assigned to itself. By assigning the negative of the value we are actually assigning the opposite value.

So basically if the value is true then it's negative will be false and vice-versa. It's just a shorthand way of toggling or flipping a boolean value.

void Toggle(){
// function to handle toggle
color cColor = clrLimeGreen;
uchar ucArrow = 233;
// use a string type if you need text on your button

if(value_to_toggle == true){
cColor = clrRed;
ucArrow = 234;
}

CreateButton(sButtonName,cColor,"Wingdings",CharToStr(ucArrow));
value_to_toggle = !value_to_toggle;

Comment("The value of value_to_toggle is ", value_to_toggle);

}

Below our 'Toggle' function you can see the 'CreateButton' function which is pretty standard. It just accepts whichever parameters we've decided to allow the user to change and then sets up the object.

void CreateButton(string sName, color cColor, string sFont = "Wingdings", string sText = ""){
// create a button on the chart

// many of these settings are hard coded below but you can easily have them as paramaters and pass them to the function
// just like I've done already with the color, font and text

   if(ObjectFind(sName)< 0){
      ObjectCreate(0,sName,OBJ_BUTTON,0,0,0);
   }
   
   // these could be external valiables to allow the user to create the button wherever they wanted
   ObjectSetInteger(0,sName,OBJPROP_XDISTANCE,75);
   ObjectSetInteger(0,sName,OBJPROP_YDISTANCE,25);
   ObjectSetInteger(0,sName,OBJPROP_XSIZE,50);
   ObjectSetInteger(0,sName,OBJPROP_YSIZE,50);
   ObjectSetInteger(0,sName,OBJPROP_CORNER,CORNER_RIGHT_UPPER);
   
   ObjectSetString(0,sName,OBJPROP_TEXT,sText);
   ObjectSetInteger(0,sName,OBJPROP_COLOR, cColor);
   // I'm setting the background and border to the same as the chart background
   // as I'm just using a wingding arrow
   long result;
   ChartGetInteger(0,CHART_COLOR_BACKGROUND,0,result);

   color cBack = (color) result;

   ObjectSetInteger(0,sName,OBJPROP_BGCOLOR, cBack);
   ObjectSetInteger(0,sName,OBJPROP_BORDER_COLOR,cBack);
   // make sure our object shows up in the 'Objects List'
   ObjectSetInteger(0,sName,OBJPROP_HIDDEN, false);
   // commmented out some settings as they are not used
   // I would have normally deleted them but left them for completeness
   //ObjectSetInteger(0,sName,OBJPROP_BORDER_TYPE,BORDER_FLAT);
   //ObjectSetInteger(0,sName,OBJPROP_STATE,false);
   ObjectSetString(0,sName,OBJPROP_FONT,sFont);
   ObjectSetInteger(0,sName,OBJPROP_FONTSIZE,28);
   
}

To actually allow our user to interact with the button object we just need to add one line of code to the 'OnChartEvent' function.

This function is fired every time there is an event on the chart and we are able to intercept it and see what it is. In this case we're only interested in trapping events from our button so we check the 'sparam' parameter and see if it matches the name of our button.

void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---
   // if the sparam passed to the function is the unique id of the button then toggle it
   if(sparam==sButtonName) Toggle();
   
  }

When you place the indicator on a chart you should see an arrow in the top-right  corner and a comment in the top-left. Try clicking on the arrow and watch what happens to the comment. You should see the value of the 'value_to_toggle' variable change between true and false on each click.

That's all there is to it and you can now add toggle buttons to any indicator or expert advisor that you wish. You'll need to decide how the variable you've toggled is used in your indicator or EA and may have to add some more code in the 'Toggle' function to accommodate it.

In my case I had to add a line of code that would force the indicator to redraw itself so that the new value would be reflected. Exactly how you do that will be dependent on your particular situation and is beyond the scope of this article.

Another thing to notice in the code is that I decided to use an arrow as the button. I didn't like the way the standard button looked and felt it was too much for my particular situation. If you decide to use a text button just make sure to change the type of the text variable in the 'Toggle' function to string rather than uchar as it is in my example.

Well I hope that's helped a little and have fun coding your projects.

Download the complete indicator with MQL4 source here.

Don't forget that if you ever get confused whilst coding your own indicators or Expert Advisors in MQL4 you can just place your cursor on any function name, click to select and then hit  'F1'. That will pull up the help file and take you directly to the section that gives more information about the function you were interested in.

This trick only works for built-in functions that MetaEditor is aware of and won't work on custom functions that you write yourself.

Aug 30, 2015Steve Fleming

Steve Fleming

Steve Fleming has been a professional programmer for over 20 years and has programmed in MQL4 almost exclusively since 2007. He has coded 100's of EA's and indicators for his growing list of satisfied clients and has helped 1000's of people learn how to code their own EA's.

If you would like to have your strategy coded by Steve Fleming or receive one-on-one training, then please send an email to [email protected] .

More Posts



Keltner Pro
Does The Perfect EA Really Exist?Instantly Save Yourself $200

Leave a Reply Cancel reply

August 30, 2015 MQL4 Programming button, mql4, toggle11,920
Forex Mentor Pro
Start Learning MQL4 Today!
Recent Posts
  • Instantly Save Yourself $200
  • How to Create a Simple Toggle Button in MQL4
  • Does The Perfect EA Really Exist?
  • Improved Input Settings in MQL4 – Part 2
  • How to Install MQL4 Experts Advisors, Indicators and Scripts
Recent Comments
  • Steve Fleming on Free Tool to Help With Pair Trading
  • Pedro Paredinha on Free Tool to Help With Pair Trading
  • shelton colds jr on R.E.A.D – A Simple Template Approach to Coding in MQL4
  • Steve Fleming on Improved Input Settings in MQL4 – Part 2
  • Dulcy Tsosie on Improved Input Settings in MQL4 – Part 2
Tags
mql4expert advisorsbuild 600metatraderforexexpert advisortutorialarraymarketplaceautomated trading software
GPS Forex Robot
MQL4 Programming

Learning to code in MQL4 can seem difficult at first but once you get the hang of it you'll find it quite easy. The best way to get started is with a free course and you'll find a great one [...]

| 6 Comments Learn More
Testimonials
After extensively researching around for a coach to fast-track my ability to code Expert Advisors, I came across Steve Fleming. Right from the beginning I found Steve to be very helpful and motivating, within five weeks of coaching I am coding my first EA. Programming is just like any other skill in life, it takes time to learn and I know without a coach like Steve, it would have taken me months to learn MQL. Most importantly what I found in Steve is someone who wants to see you succeed as a … Read more
DeonBrisbane
Working with Steve has really cleared the fog for me as it relates to writing my own EA’s. I had no prior code writing experience. Prior to working with Steve, I had bought every book available on MQL, read lots of blogs and downloaded pdf lessons. But, none of these resources could answer any of my questions. Working with Steve has given me a much broader understanding of how to write code. He not only teaches you how to write an EA, but explains the best coding practices so you are writing cod… Read more
MichaelIdaho
I came to Steve with the aim of learning how to write expert advisors. With his great teaching style and structured course I have been able to learn an enormous amount and have been able to write a number of expert advisors myself. As I develop various systems and sometimes come across issues Steve is always a great source of help. I look forward to developing more expert advisors and using Steve as a mentor as and when required.
AlanSingapore
Market Hours
© Automated Trading Software  2008 - 
Contact |  Sitemap |  Risk Warning |  Privacy |  T & C

Free MQL4 Course

Enter your best email address in the box below and get my 5 day MQL4 course immediately!

Arrow