Download MetaTrader 5
To add comments, please log in or register
Freelance service: the safe way to order a trading robot. Try it!
Gordon Gekko
671
Gordon Gekko 2014.10.04 12:05 

Hi gurus,

Can you show me a solution for that?

I searched but couldn't find anything.

For example: I have a button on a chart, and it opens a buy order when I click on it.

Thx

Keith Watford
Moderator
8016
Keith Watford 2014.10.04 12:12  
I don't know what you are asking for.
Gordon Gekko
671
Gordon Gekko 2014.10.04 12:14  
GumRai:
I don't know what you are asking for.
See the title: Button BUY/SELL/CLOSE event
Keith Watford
Moderator
8016
Keith Watford 2014.10.04 13:34  
ggekko:
See the title: Button BUY/SELL/CLOSE event

That obviously means something to you, it means nothing to me and is certainly not a question.

Sorry, but I guess that my comprehension is lacking. :( 

Keith Watford
Moderator
8016
Keith Watford 2014.10.04 13:45  

Here's some code that uses buttons, you may find some of it useful.

It's something that I haven't quite completed, so any suggestions for improvements would be gratefully received.

I haven't done much with buttons and so copied the button function from the documentation

//+------------------------------------------------------------------+
//|                                               MultipleOrders.mq4 |
//|                                                           GumRai |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright " "
#property link      " "
#property version   "1.00"
#property strict

enum tradetype
  {
   Buy,
   Sell,
   //BuyLimit,
   //SellLimit,
  // BuySyop,
   //SellStop,
  };
 



input int MagicNumber=0;
input int num_of_trades=2; //Number of Trades
//input bool AddOn=false; //Only open additional trades
input int stoploss=30;
input int takeprofit=30;
input int Slippage=3;
input tradetype order_type=Buy;
input double lot=0.01;


double PipPoints;
int Diff_Y_Butt1;
int Diff_Y_Butt2;
int slip;

#include <stdlib.mqh>
#include <WinUser32.mqh>  

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
  
  if(Digits==3 || Digits==5)
     {
     PipPoints=Point*10;
     slip=Slippage*10;
     }
  else
     {
     PipPoints=Point;
     slip=Slippage;
     }
  
  ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,true);
  
  //Basic button settings
  string           InpName="TradeButton";       // Button name
  ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
  string           InpFont="Arial";             // Font
  int              InpFontSize=8;               // Font size
  color            InpColor=clrBlack;           // Text color
  color            InpBackColor=C'236,233,216'; // Background color
  color            InpBorderColor=clrNONE;      // Border color
  bool             InpState=false;              // Pressed/Released
  bool             InpBack=false;               // Background object
  bool             InpSelection=false;           // Highlight to move
  bool             InpHidden=true;              // Hidden in the object list
  long             InpZOrder=0;                 // Priority for mouse click
  
  //--- chart window size
   long x_distance;
   long y_distance;
//--- set window size
   if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
     {
      Print("Failed to get the chart width! Error code = ",GetLastError());
      //return(0);
     }
   if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
     {
      Print("Failed to get the chart height! Error code = ",GetLastError());
      //return(0);
     }
   int Err;
//--- set the button coordinates and its size
   int x=(int)(x_distance*0.85);
   int tby=(int)(y_distance*0.1);
   int x_size=100;
   int y_size=25;
//--- create the button
   if(!ButtonCreate(0,"TradeButton",0,x,tby,x_size,y_size,InpCorner,"Place Trades",InpFont,InpFontSize,
      InpColor,InpBackColor,InpBorderColor,InpState,InpBack,InpSelection,InpHidden,InpZOrder))
     {
      Err=GetLastError();
      Print("Error creating button. Error code ",Err,". ",ErrorDescription(Err));
     }
     
//--- set the 2nd button coordinates and its size
   int cay=(int)(y_distance*0.2);
//--- create the button
   if(!ButtonCreate(0,"CloseAll",0,x,cay,x_size,y_size,InpCorner,"Close All",InpFont,InpFontSize,
      InpColor,InpBackColor,InpBorderColor,InpState,InpBack,InpSelection,InpHidden,InpZOrder))
     {
      Err=GetLastError();
      Print("Error creating button. Error code ",Err,". ",ErrorDescription(Err));
     }
//--- set the move button coordinates and its size
   int y=(int)(y_distance*0.3);
//--- create the button
   if(!ButtonCreate(0,"Move",0,x,y,30,10,InpCorner,"Move",InpFont,6,
      InpColor,InpBackColor,InpBorderColor,InpState,InpBack,InpSelection,InpHidden,InpZOrder))
     {
      Err=GetLastError();
      Print("Error creating button. Error code ",Err,". ",ErrorDescription(Err));
     }
   
   Diff_Y_Butt1=y-tby;
   Diff_Y_Butt2=y-cay;
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
//--- reset the error value
   ResetLastError();
//--- delete the button
   if(!ObjectDelete(0,"TradeButton"))
     {
      Print(__FUNCTION__,
            ": failed to delete TradeButton! Error code = ",GetLastError());
     }
//--- reset the error value
   ResetLastError();
//--- delete the button
   if(!ObjectDelete(0,"CloseAll"))
     {
      Print(__FUNCTION__,
            ": failed to delete CloseAll! Error code = ",GetLastError());
     }
//--- reset the error value
   ResetLastError();
//--- delete the button
   if(!ObjectDelete(0,"Move"))
     {
      Print(__FUNCTION__,
            ": failed to delete CloseAll! Error code = ",GetLastError());
     }

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   /*
   //Check for open trades
   int total=0;
   if(AddOn)
   {
   for(int index=OrdersTotal()-1;index>=0;index--)
     {
      if(!OrderSelect(index,SELECT_BY_POS,MODE_TRADES))
        {
         Print("Error with OrderSelect-",ErrorDescription(GetLastError()));
         continue;
        }
      if(OrderMagicNumber()==MagicNumber && OrderSymbol()==Symbol())
         total++;
     }
   }
   */

  }
//+------------------------------------------------------------------+

void buy()
{
  for(int i=0;i<num_of_trades;i++)
   {
   double a= MarketInfo(Symbol(),MODE_ASK);
   double s_l;
   double t_p;
   if(stoploss==0)
      s_l=0;
   else
      s_l=a-(stoploss*PipPoints);
   if(takeprofit==0)
      t_p=0;
   else
      t_p=a+(takeprofit*PipPoints);
   int ticket= OrderSend(NULL,OP_BUY,lot(),a,slip,s_l,t_p,NULL,MagicNumber,0,clrBlue);
   if(ticket<=0)
     {
     string s=DoubleToStr(s_l,Digits);
     string t=DoubleToStr(t_p,Digits);
     string ls=DoubleToStr(lot(),2);
     string en=DoubleToStr(a,Digits);
     string bd=DoubleToStr(MarketInfo(Symbol(),MODE_BID),Digits);
     string s_level= (string)MarketInfo(Symbol(),MODE_STOPLEVEL);
     string txt= " BUY, "+ls+" at "+en+" SL="+s+" TP="+t+" StopLevel="+s_level+" Bid="+bd ;
     Print(TimeCurrent()," Error with Opening Order-",ErrorDescription(GetLastError() ));
     Print(txt);
     }
   }
}
void sell()
{
  for(int i=0;i<num_of_trades;i++)
   {
   double b= MarketInfo(Symbol(),MODE_BID);
   double s_l=b+(stoploss*PipPoints);
   double t_p=b-(takeprofit*PipPoints);
   int ticket= OrderSend(NULL,OP_SELL,lot(),b,slip,s_l,t_p,NULL,MagicNumber,0,clrBlue);
   if(ticket<=0)
     {
     string s=DoubleToStr(s_l,Digits);
     string t=DoubleToStr(t_p,Digits);
     string ls=DoubleToStr(lot(),2);
     string en=DoubleToStr(b,Digits);
     string s_level= (string)MarketInfo(Symbol(),MODE_STOPLEVEL);
     string as=DoubleToStr(MarketInfo(Symbol(),MODE_ASK),Digits);
     string txt= " SELL, "+ls+" at "+en+" SL="+s+" TP="+t+" StopLevel="+s_level+" Ask="+as ;
     Print(TimeCurrent()," Error with Opening Order-",ErrorDescription(GetLastError() ));
     Print(txt);
     }
   }
}

double lot()
{
   return lot;
}


//+------------------------------------------------------------------+

void CloseAllTrades()
 {
  int Attempts=0;
  bool AllClosed=false;
  while(AllClosed==false && Attempts<5)
   { 
   int counter =0;
   for(int index=OrdersTotal()-1;index>=0;index--)
     {
      if(!OrderSelect(index,SELECT_BY_POS,MODE_TRADES))
        {
         Print("Error with OrderSelect-",ErrorDescription(GetLastError()));
         counter++;
         continue;
        }
      if(OrderMagicNumber()==MagicNumber && OrderSymbol()==Symbol())
         {
         if(OrderType()==OP_BUY || OrderType()==OP_SELL)
            {
            if(!OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),50,clrRed))
               {
               int Err=GetLastError();
               Print("Error closing order ",OrderTicket(),". Error code ",Err,". ",ErrorDescription(Err));
               counter++;
               }
            }
         /*
         else
            {
            if(!OrderDelete(OrderTicket()))
               {
               int Err=GetLastError();
               Print("Error deleting order ",OrderTicket(),". Error code ",Err,". ",ErrorDescription(Err));
               counter++;
               }
            
            }
         */
         }
     }
  Attempts++ ;
  if(counter==0)
    AllClosed=true;
  else
    Sleep(5000);
  }
 }

//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---
   if(id==CHARTEVENT_OBJECT_CLICK)
     {
      if(sparam=="TradeButton")
         {
         string txt;
         if(order_type==Buy)
           txt="Click on Yes to open BUY trades";
         else
           txt="Click on Yes to open SELL trades";
         int ret=MessageBox(txt,"CONFIRM OPEN NEW TRADES", MB_YESNO); // Message box
         if(ret ==IDYES)
            if(order_type==Buy) buy();
            else                sell();
         ObjectSetInteger(0,"TradeButton",OBJPROP_STATE,false);
         }
      if(sparam=="CloseAll")
         {
         string txt="Click on Yes to Close All trades";
         int ret=MessageBox(txt,"CONFIRM CLOSE ALL", MB_YESNO); // Message box
         if(ret ==IDYES)
            CloseAllTrades();
         ObjectSetInteger(0,"CloseAll",OBJPROP_STATE,false);
         }
      
      
     }
   
   if(id==CHARTEVENT_MOUSE_MOVE)
     {
      if(ObjectGetInteger(0,"Move",OBJPROP_STATE))
        {
         int cw=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
         int      newx=(int)(lparam)-15; // X-coordinate
         int      newy=(int)dparam-5; // Y-coordinate
         
         ObjectSet("Move",OBJPROP_XDISTANCE,newx);// X coordinate
         ObjectSet("Move",OBJPROP_YDISTANCE,newy);// Y coordinate
         ObjectSet("TradeButton",OBJPROP_XDISTANCE,newx);// X coordinate
         ObjectSet("TradeButton",OBJPROP_YDISTANCE,newy-Diff_Y_Butt1);// Y coordinate
         ObjectSet("CloseAll",OBJPROP_XDISTANCE,newx);// X coordinate
         ObjectSet("CloseAll",OBJPROP_YDISTANCE,newy-Diff_Y_Butt2);// Y coordinate

         
         ChartRedraw();

        }

     }
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Create the button                                                |
//+------------------------------------------------------------------+
bool ButtonCreate(const long              chart_ID=0,               // chart's ID
                  const string            name="Button",            // button name
                  const int               sub_window=0,             // subwindow index
                  const int               x=0,                      // X coordinate
                  const int               y=0,                      // Y coordinate
                  const int               width=50,                 // button width
                  const int               height=18,                // button height
                  const ENUM_BASE_CORNER  corner=CORNER_LEFT_UPPER, // chart corner for anchoring
                  const string            text="Button",            // text
                  const string            font="Arial",             // font
                  const int               font_size=10,             // font size
                  const color             clr=clrBlack,             // text color
                  const color             back_clr=C'236,233,216',  // background color
                  const color             border_clr=clrNONE,       // border color
                  const bool              state=false,              // pressed/released
                  const bool              back=false,               // in the background
                  const bool              selection=false,          // highlight to move
                  const bool              hidden=true,              // hidden in the object list
                  const long              z_order=0)                // priority for mouse click
  {
  
  
//--- reset the error value
   ResetLastError();
//--- create the button
   if(!ObjectCreate(chart_ID,name,OBJ_BUTTON,sub_window,0,0))
     {
      Print(__FUNCTION__,
            ": failed to create the button! Error code = ",GetLastError());
      return(false);
     }
//--- set button coordinates
   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set button size
   ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
   ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the chart's corner, relative to which point coordinates are defined
   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the text
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
   ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set text color
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set background color
   ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border color
   ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
//--- display in the foreground (false) or background (true)
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- set button state
   ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
//--- enable (true) or disable (false) the mode of moving the button by mouse
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
   return(true);
  }
Gordon Gekko
671
Gordon Gekko 2014.10.04 13:45  
GumRai:

That obviously means something to you, it means nothing to me and is certainly not a question.

Sorry, but I guess that my comprehension is lacking. :( 

What do not you understand?!

I need a code that handles button (OBJ_BUTTON) events. For example if I click on this button it opens a buy order. I can not explain it better.

UPDATE: thank you for the code, I will study it.

Keith Watford
Moderator
8016
Keith Watford 2014.10.04 13:54  
ggekko:

What do not you understand?!

I need a code that handles button (OBJ_BUTTON) events. For example if I click on this button it opens a buy order. I can not explain it better.

Now you have explained properly
Gordon Gekko
671
Gordon Gekko 2014.10.04 14:22  
GumRai:
Now you have explained properly
That code is exactly what I need. Thanks!
/
To add comments, please log in or register