programming
Now you are reading
MQL Practically. Panic Button, part II [Programming Course]
0

MQL Practically. Panic Button, part II [Programming Course]

created Radek Szafron29 March 2019

Welcome to the second part of Panic Button! This week, we'll look again at the code of our panic button. Our task today is to add what is most important, that is, the function of freeing us from the weight of open positions and freeing us from the constraints of constantly staring at the monitor.

We will develop the basic functionality with something else. We will make sure that the tool we design is safe and accidental clicks will be unshakeable and stoically calm. Like any serious button on our planet and ours will have a kind of fuse that will allow you to close the position only when the click is accompanied by pressing a key [Shift] on keyboard.


Be sure to read: MQL Practically. Panic Button, part I


We're opening an algorithm factory

So we turn on MetaEditor.

Let's go to editing the code of our application from last week. Open the file Panic Button.mq4 from the catalog Experts and let's take a look at the function OnInit (). Your function should look almost identical to the function placed below with a small difference. Today a new element of the code has appeared // comment .

int OnInit ()
{
if(IsDemo () == false)
{
 
return INIT_FAILED;
 
}
bool blue = false;
if(Tylko_ten_instrument == true)
{
 
blue = true;
 
}
Przycisku_utworz_sie (5, 15, blue);
// <- [This is how we make comments] EventSetMillisecondTimer(250); // End of novelty
return INIT_SUCCEEDED;
}
MQL4 code

Add the missing code to the function OnInit ().

We start the clock

The MQL API function added to the code above bool EventSetMillisecondTimer(int millisecond)allows you to configure the timer. Timer is a method that allows you to call another API function - OnTimer () every specific number of milliseconds. This solution allows us to run certain parts of the code periodically by placing them inside the function OnTimer (). In our case, 4 times per second, or what 250 milliseconds.

The clock is ticking, so let's write a new function.

void OnTimer()
{
 
Przycisku_badz_czujny ();
 
}
MQL4 code

Good job. You have just created an algorithm responsible for securing our button against accidental clicks. It was this difficult part. From now on, to click on the button you will need to hold down the key [Shift] on keyboard. Spins on electrons are unscrewed in function Przycisku_badz_czujny ()that we imported from the library Biblioteka_panic_button.ex4 last week.

The platform requires that the timer be turned off when we no longer need it. We can do this by adding the API function EventKillTimer () to function OnDeinit ()that we created in the previous section and which, as a reminder, will be called by the platform when closing our application. Let's modify the function OnDeinit ()make it look like the function below.

void OnDeinit(const int reason)
{
 
Przycisku_bye_bye ();
 
EventKillTimer ();
}
MQL4 code

You can start the application here and see how the algorithm responds by pressing a key [Shift].

We watch every move

The time has come to start thinking about the position closing function. To do this, we need to recognize the moment when the button is clicked. The API function helps us void OnChartEvent(const int id, const long & lParam const double & dparam, const string & SPAR).

Function OnChartEvent (...) it is called by the platform whenever an event occurs on the graph that may be relevant to the program's operation, for example the user clicks on the object or moves the mouse. Let's write the appropriate function.

void OnChartEvent(const int id, const long & lParam const double & dparam, const string & SPAR)
{
 
}
MQL4 code

Platform, calling function OnChartEvent (...) it provides additional information to it using parameters id, lParam, dparamand Spar. This allows us to identify what happened and the type of event is stored in the variable idwhich is type int, i.e. is an integer. Word const when the variable type means that a given variable can not be modified and is used only to read information.

Let us expand our function with another element.

void OnChartEvent(const int id, const long & lParam const double & dparam, const string & SPAR)
{
 
if(id == CHARTEVENT_OBJECT_CLICK)
{
 
}
 
}
MQL4 code

Using the operator if above we check if the variable id is equal == the value defined in the variable generated automatically by the name CHARTEVENT_OBJECT_CLICK. If so, we are sure that the user has clicked on an unspecified object on the graph on which our algorithm works.

We already know that when the operator conditional expression if it will be logically true that the code between the braces will be made {} belonging to this operator. Let's add to our code what should happen when the graph clicks on any object.

void OnChartEvent(const int id, const long & lParam const double & dparam, const string & SPAR)
{
 
if(id == CHARTEVENT_OBJECT_CLICK)
{
 
if(Button_you_you_t_click_turned (sparam) == true)
{
 
}
 
}
 
}
MQL4 code

The code above checks whether it was our button that was clicked using the function bool Przycisku_czy_jestes_klikniety (string object_name)that comes from the imported library. The function as a parameter assumes a variable with data type string, which is a text variable that should contain the name of the object that was clicked by the user. The function compares the received value with the name of the graphic element of the button and the answer to the question whether our button was clicked will respond with the type value boolor value true and/ or false.

How do we know the name of the object that was clicked? Function OnChartEvent (...) receives from the platform the name of the last object clicked using the parameter string named Sparthat we can directly pass as a parameter for our function, oh yes Przycisku_czy_jestes_klikniety (SPAR).

We carry out the entrusted task [Konkrety]

When functionButton_or_jestes_klikniety (...) will return the value true we will know that there are no jokes, you have to save the situation.

Let's add to our code a function that will accomplish the main task of our algorithm, that is, close the position on the account. The function has the following declaration:

bool Zamknij_pozycje_i_zlecenia (bool tylko_ten_instrument),

In practice, we put it in the code as in the box below.

void OnChartEvent(const int id, const long & lParam const double & dparam, const string & SPAR)
{
 
if(id == CHARTEVENT_OBJECT_CLICK)
{
 
if(Button_you_you_t_click_turned (sparam) == true)
{
 
Zamknij_pozycje_i_zlecenia (Tylko_ten_instrument);
 
}
 
}
 
}
MQL4 code

Function Close_positions_and_commissions (...) takes a type variable as an argument boolwhich should carry information, true and/ or falseshould we close the positions of only the instrument on which the algorithm works. You remember the parameter Tylko_ten_instrument from the settings pane in the first part? We just came in handy. Depending on our choice in the settings, the program will close items that are compatible with the selected chart or all items in the account.


expert advisors


We create the main function

We start editing the file "Useful_functions.mqh" from the MQL4 \ Include \ Panic Button \ directory

Until now, we only used functions that come from the MQL API or are imported from the library Biblioteka_panic_button.ex4. In the real world, however, programming requires that we create the majority of functions ourselves, while supporting the entire spectrum of ready-made solutions. Functions Close_positions_and_commissions (...) , from which we use the above, you will find in the file Przydatne_funkcje.mqh, which in the previous part we placed in the catalog MQL4 \ Include \ Panic Button \ and we joined the code using the keyword #include. Open the file in MetaEditor because, surprise, the function that closes the entries is already in the file, but we still need to give it content.

Function definition

After opening the file Przydatne_funkcje.mqh you will see that he is in it definition position closing function. It looks just like the functions we have used so far with the difference that it is our own, and we can give it what kind of soul the name, type and set of parameters will want. Your function should look more or less like the function below:

bool Zamknij_pozycje_i_zlecenia (bool tylko_ten_instrument)
{
return true;
}
MQL4 code

Thus, in header , we have defined a function named Zamknij_pozycje_i_zlecenia returning the data type bool and taking one named parameter tylko_ten_instrument also about the type of data bool.

The content of the function

Everything we place between braces {} after the function header it consists of its content. So let's enrich our content with the first code.

bool Zamknij_pozycje_i_zlecenia (bool tylko_ten_instrument)
{
if(IsConnected() == false) return false;
int i = 0; int number_of_the_power_and = OrdersTotal();
if(number_of_content_and == 0) return true;
bool result = true;
return result;
}
MQL4 code

Above, first if, we check if we are connected to the server using the API function IsConnected() and in case of problems, we leave the function with the help of the operator return while returning the value falseto let you know that something is wrong. That's right after if there are no curly brackets, because we use a shortened record possible in situations when after the conditional expression we want to perform only one operation.

When we are online the algorithm goes further and creates two variables int about names i and liczba_pozycji_i_zlecen by assigning to the first value 0and the second value from the API function OrdersTotal(), which informs you about the number of open positions and orders in your account.

Another operator if checks whether sometimes all items are no longer closed, and the user clicks on the button only for fun or affection which results in leaving the function with the transfer of value truebecause everything is okay.

When a function still has something to do it creates a variable bool named result, which will later serve to provide information on whether all items have been properly closed using the end operator returnwhich we have slightly modified in this step.

For loop

Operator for, which in its popularity is likely to give way only to the operator if, is used to perform a certain set of operations a specified number of repetitions. Ideally suited to situations like ours, because we have to perform a closing operation for each order separately. Let's add a loop to our function for.

bool Zamknij_pozycje_i_zlecenia (bool tylko_ten_instrument)
{
if(IsConnected() == false) return false;
int i = 0; int number_of_the_power_and = OrdersTotal();
if(number_of_content_and == 0) return true;
bool result = true;
for(i = number_of_items_i_ orders - 1; i> = 0; i--)
{
 
}
return result;
}
MQL4 code

W headerafter the operator for we see a mysterious record: (i = number_of_items_i_ orders - 1; i> = 0; i--) .

The record means that the loop starts with the variable we created earlier i equal to the variable liczba_pozycji_i_zlecen minus one and will repeat the operation between braces {} as long as variable i is greater than or equal to zero [i> = 0], and after the end of each cycle will reduce the variable i by one [i--] so that the loop has a chance to end sometime. Simple, uncomplicated and comfortable to read.

Speaking in the language of people, the loop for performs the operation in brackets {} as many times as we have open positions.

Let's add content to our loop.

bool Zamknij_pozycje_i_zlecenia (bool tylko_ten_instrument)
{
if(IsConnected() == false) return false;
int i = 0; int number_of_the_power_and = OrdersTotal();
if(number_of_content_and == 0) return true;
bool result = true;
for(i = number_of_items_i_ orders - 1; i> = 0; i--)
{
if(OrderSelect(and, SELECT_BY_POS) == false)
{
result = false; keep on going;
}
if(only_ten_instrument == true && OrderSymbol()! = Symbol() keep on going;
if(OrderType() == OP_BUY || OrderType() == OP_SELL)
{
if(OrderClose(OrderTicket() OrderLots() OrderClosePrice() 0) == false)
{
result = false; keep on going;
}
}
else if(OrderDelete(OrderTicket()) == false) result = false;
}
return result;
}
MQL4 code

Rocket physics

Let's analyze step by step what is happening inside our loop forwhich we have written bravely in the previous stage.

In the first step using the API function OrderSelect(...) we choose an order from the terminal using the number of its position on the list of orders (the first order in the list has the number zero). We have a variable for this purpose ithat changes the value with each loop. In case of failure, we write the error in the variable result and inform the loop for using the operator keep on goingthat she should stop at this point and start a new cycle with a variable i minus one [i--].

When everything goes well, another operator if will use, novelty, logical operation "and" &&that returns a value true only if both expressions, on each of its pages, return a value true. Thus, when the instrument of the selected order [OrderSymbol()] does not respond [!=] a chart instrument [Symbol()], and variable tylko_ten_instrument has a value true, we ignore the given order and using the operator keep on going we go to the next cycle of the loop for. In all other cases, the algorithm goes below.

Then our program checks what order we have the pleasure of, and does it using the API function OrderType() and logical operation "or" ||that returns a value truewhen at least one of the expressions on each of its pages returns a value true. Otherwise, when the operator's logical expression if as a whole, it will return the value false the operator will be executed else ifthat works with the first if'em and serves him as plan B, when he can not agree with his own logical expression.

Depending on the type of order first if when dealing with a market buy order [OP_BUY] or market sell [OP_SELL] will close the position using the API function OrderClose(...)and the other if, actually else if cancels pending orders using the function OrderDelete(...).

I bow, the program is ready!

We save changes to the file Przydatne_funkcje.mqh, we return to the main application code Panic Button.mq4 and enthusiastic, full of energy and curiosity resulting from the willingness to test a new work, press ... Compile! Then we correct the mistakes and see you next week! 🙂

DOWNLOAD A SET OF MQL FILES

What do you think?
I like it
95%
Interesting
8%
Heh ...
0%
Shock!
0%
I do not like
0%
Detriment
0%
About the Author
Radek Szafron
The author of the publication is Radek Szafron, owner of the Expert Advisors company, which for many years has been supporting investors by providing technologies dedicated to the FOREX market. The author is a graduate of the Warsaw School of Economics with the specialization "Financial markets" and a programmer with almost 20 summer experience. The company implements designs of algorithms and applications written in all languages ​​from the "C" family, including popular platforms Meta Trader 4 and 5. Expert Advisors can be found at www.expertadvisors.pl.
Comments

Leave a Response