Hot key to close an open and close a trade

 

Hi guys

I have newly started using mql5 and trying to figure out hotkeys to close and open positions.

Please look at my simple code:

#include <Trade\Trade.mqh>                  // trade position object
CTrade         trade;                      // trading object
double Ask, Bid;
input double mylots = 1;
input double st = 20;


void OnTick()
{
      Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
      Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
}

 void OnChartEvent(
                     const int EventID,
                     const long& lparam,
                     const double& dparam,
                     const string& sparam       
                    )
 
 {
   if (EventID==CHARTEVENT_KEYDOWN)
   {
      short k=TranslateKey((int)lparam);

//For testing if key pressing is caught as chartevent.. 
//MessageBox("The key is: "+ShortToString(k),NULL,MB_OK);
      
      //Key stroke "1" for buy order
      if(StringCompare(ShortToString(k),"1",false) == 0)
      {
         trade.Buy(mylots, NULL, Ask, (Ask - st), 0.0, NULL);
      }

      //Key stroke "2" for sell order
      if(StringCompare(ShortToString(k),"2",false) == 0)
      {
         trade.Sell(mylots, NULL, Ask, (Ask + st), 0.0, NULL);
      }

      //Key stroke "0" for closing all positions
      if(StringCompare(ShortToString(k),"0",false) == 0)
      {
         closePosition();
      }
       
     }
 }
 
void closePosition()
   {
      for(int i=PositionsTotal()-1;i>=0;i--)
      {
         int ticket=PositionGetTicket(i);
         trade.PositionClose(ticket);
      }
   }

I see using the messagebox that the key entry on chart is caught.

The buy or sell or close doesn't get triggered. Could anybody point out why..

Thanks!

 
Press numbers on the main keyboard.