MQL4 - How to extract data of an string Array/JSON

 

Guys, I'm hitting myself to try to extract the data from the string below.

[{"type":"success","message":""},{"id":"14058","symbol":"EURUSD","tp":"1.2271","sl":"1.2217","direction":"buy","risk":"2"},{"id":"14059","symbol":"EURUSD","tp":"1.2260","sl":"1.2190","direction":"buy","risk":"2"}]

Note that it is an Array with JSON objects internally.

I tried using the lordy library as well, but with it's not worked to me.
Has anyone ever had this need and been able to solve it?

Thank you!
 
Do you really expect an answer? We can't see your broken code. There are no mind readers here and our crystal balls are cracked.
 

You can also just use csv.

 
Guys, thank you for your time.

whroeder1, I don't put the code here, because all my codes than I tried not worked.

Marco vd Heijden, I can't use csv file, because I receive the data from another software like that string above.

The software send to me by API that string, and I need to get that string and convert it to Array and then get the JSON.

It's possible?

 
ezequielgodoy: It's possible?
Of course it's possible, just parse the string. Show us your attempt (using CODE button) and state the nature of your problem.
          No free help
          urgent help.
 
whroeder1:
Of course it's possible, just parse the string. Show us your attempt (using CODE button) and state the nature of your problem.
          No free help
          urgent help.


   string cookie=NULL,headers;
   char post[],result[];
   int res;
   string resultString=NULL;
   
   int timeout=5000;
   res=WebRequest("GET","localhost/api/signal/fx?r=op",cookie,NULL,timeout,post,0,result,headers); 
 
   resultString = CharArrayToString(result);


The string resultString return that string below

[{"type":"success","message":""},{"id":"14058","symbol":"EURUSD","tp":"1.2271","sl":"1.2217","direction":"buy","risk":"2"},{"id":"14059","symbol":"EURUSD","tp":"1.2260","sl":"1.2190","direction":"buy","risk":"2"}]

I need get data from that string.

 
ezequielgodoy: I need get data from that string.

That is what you said in the first post. No one asked how you got the string. Show us your attempt at parsing the string and state the nature of your problem.

 
whroeder1:

That is what you said in the first post. No one asked how you got the string. Show us your attempt at parsing the string and state the nature of your problem.

But this my problem, I don't know how to do that.

I tried of different ways, but not work.

Neither compile.

 

learn to code it. If you don't learn MQL4/5, there is no common language for us to communicate. If we tell you what you need, you can't code it. If we give you the code, you don't know how to integrate it into yours.
or pay (Freelance) someone to code it.

We're not going to code it for you. We are willing to help you when you post your attempt (using CODE button) and state the nature of your problem.

          No free help
          urgent help.

 

You can also look in codebase using the search function.

https://www.mql5.com/en/code/11134

https://www.mql5.com/en/code/13663

JSON Parser
JSON Parser
  • votes: 19
  • 2014.02.24
  • ydrol
  • www.mql5.com
This parses mql4 strings that contain JSON code. It creates a JSONValue that can be used to retrieve the fields within the JSON structure. It also provides a JSONIterator class to loop over object keys. It parses the JSON using a...
 
Marco vd Heijden:

You can also look in codebase using the search function.

https://www.mql5.com/en/code/11134

https://www.mql5.com/en/code/13663

@Marco vd Heijden thank you for the links, helped me a lot.


Below my code.

It's working now, but I thing there's the best way for to do that.
Please, can you check?


#property strict

#include "hash.mqh"
#include "json.mqh"

//--- input parameters
input string   token    = "SHJ6767OIS29J";

string   urlBase        = "http://localhost/api/signal/fx";
string   urlToOpen      = urlBase + "?r=op&t=" + token;

int      lastTradeId    = NULL;
int      magicNumber    = 777;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Chama o event OnTimer a cada 20 segundos
   EventSetTimer(20);

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| The OnTimer() function is called when the Timer event occurs     |
//+------------------------------------------------------------------+
void OnTimer()
  {
      OpenSignals();
  }

//+------------------------------------------------------------------+
//| Get Open Signals                                                 |
//+------------------------------------------------------------------+
void OpenSignals() 
  {
      string comment    = NULL;
      int tradeID       = NULL;
      string symbol     = NULL;
      double price      = NULL;
      double stoploss   = NULL;
      double takeprofit = NULL;
      string direction  = NULL;
      double Risk       = NULL;
      double RiskInPips = NULL;
      double Lots       = NULL;
      
      string messageType= NULL;
      string messageBody= NULL;

      string resultAPI = RequestDataFromWebsite("GET",urlToOpen);

      // Split {
      string sep="#";
      ushort u_sep;
      string result[];
      //--- Get the separator code
      u_sep=StringGetCharacter(sep,0);
      //--- Split the string to substrings
      int k=StringSplit(resultAPI,u_sep,result);
      //--- Now output all obtained strings
      if(k>0) {
         for(int i=0;i<k;i++) {
            // ------------------------------------------------ JSON
             string s = result[i];
   
             JSONParser *parser = new JSONParser();
             JSONValue *jv = parser.parse(s);

             if (jv == NULL) {
                 Print("error:"+(string)parser.getErrorCode()+parser.getErrorMessage());
             } else {
                 if (jv.isObject()) {
                     JSONObject *jo = jv;
 
                     // Safe access in case JSON data is missing or different.
                     if(jo.getString("type",s))          messageType = s;
                     if(jo.getString("message",s) )      messageBody = s;

                     if(messageType!=NULL && messageBody!=NULL) {
                        ShowMessage(messageType, messageBody);
                        messageBody = messageType = NULL;
                     }

                     if(jo.getString("id",s) )           tradeID    = (int)s;

                     if(tradeID!=NULL && tradeID>lastTradeId) {
                        if(jo.getString("id",s) )        comment    = "PlenusFX.com "+tradeID;
                        if(jo.getString("symbol",s) )    symbol     = s;
                        if(jo.getString("tp",s) )        takeprofit = (double) s;
                        if(jo.getString("sl",s) )        stoploss   = (double) s;
                        if(jo.getString("direction",s) ) direction  = s;
                        if(jo.getString("risk",s) )      Risk       = (double) s;
                        
                        RiskInPips = DiffInPips(symbol, stoploss, direction);
                        Lots = CalcLotSize(symbol, Risk, RiskInPips);

                        if(direction=="buy") {
                           price = MarketInfo(symbol,MODE_ASK);
                           OrderSend(symbol,OP_BUY,Lots,price,3,stoploss,takeprofit,comment,magicNumber,0,clrGreen);
                           lastTradeId = tradeID;
                        }
                        
                        if(direction=="sell") {
                           price = MarketInfo(symbol,MODE_BID);
                           OrderSend(symbol,OP_SELL,Lots,price,3,stoploss,takeprofit,comment,magicNumber,0,clrGreen);
                           lastTradeId = tradeID;
                        }
                     }
                     tradeID = NULL;
                 }
                 delete jv;
             }
             delete parser;
            // -------------------------------------------- JSON END
         }
      }
  }

//+------------------------------------------------------------------+
//| Request Data From Website                                        |
//+------------------------------------------------------------------+
string RequestDataFromWebsite(string method, string urlFrom)
  {
   string cookie=NULL,headers;
   char post[],result[];
   int res;
   string resultString=NULL;
   
   //--- Redefinir o último código de erro 
   ResetLastError(); 

   //--- Carregando uma página html
   //--- Tempo limite inferior a 1000 (1 seg.) Não é suficiente para ligação à Internet lenta 
   int timeout=10000; // 10 seconds
   res=WebRequest(method,urlFrom,cookie,NULL,timeout,post,0,result,headers); 

   //--- Checando erros 
   if(res==-1) 
     { 
      Print("Erro no WebRequest. Error code  =",GetLastError()); 
      //--- Talvez o URL não esteja listado, exiba uma mensagem sobre a necessidade de adicionar o endereço 
      MessageBox("Add the address '"+urlFrom+"' na lista de URLs permitidos na guia 'Expert Advisors'","Error",MB_ICONINFORMATION); 
     } 
   else 
     {  
       resultString = CharArrayToString(result);

       // Remove [ & ]
       StringReplace(resultString,"[","");
       StringReplace(resultString,"]","");

       // Split {
       string sep="{";
       ushort u_sep;
       string result[];

       //--- Get the separator code
       u_sep=StringGetCharacter(sep,0);

       //--- Split the string to substrings
       int k=StringSplit(resultString,u_sep,result);

       resultString = "";
       //--- Now output all obtained strings
       if(k>0)
        {
         for(int i=0;i<k;i++)
           {
             // Remove }, & }
             StringReplace(result[i],"},","");
             StringReplace(result[i],"}","");
             
             result[i] = "{"+result[i]+"}";

             if(result[i]!="{}") {
               resultString += result[i];
               if(i!=k-1) resultString += "#";
             }
           }
       }
     }
     return resultString;
  }

//+------------------------------------------------------------------+
//| Calculate Lot Size Per Trade                                     |
//+------------------------------------------------------------------+
double CalcLotSize(string symbol, double RiskPercent, double RiskInPips)
{
   double LotSize = 0;

   //We get the value of a tick
   double nTickValue = MarketInfo(symbol, MODE_TICKVALUE);
   double _digits    = MarketInfo(symbol, MODE_DIGITS);

   //If the digits are 3 or 5 we normalize multiplying by 10
   if(_digits==3 || _digits==5){
      nTickValue=nTickValue*10;
   }
   
   // Lots = Equity * Risk% / (Stop Loss in Pips * Pip Value) / 100
   LotSize = NormalizeDouble(AccountEquity()*(RiskPercent/100)/RiskInPips*nTickValue,_digits);
   LotSize = MathRound(LotSize/MarketInfo(symbol,MODE_LOTSTEP))*MarketInfo(symbol,MODE_LOTSTEP);
   
   if(LotSize<0.01) LotSize=0.01;

   return(LotSize);
}

//+------------------------------------------------------------------+
//| Calculate Difference in Pips from current price to SL            |
//+------------------------------------------------------------------+
double DiffInPips(string symbol, double stoploss, string direction)
{
   // Este calculo nao funciona para o par NZDJPY
   double DiffPips = 0;
   double _digits  = MarketInfo(symbol, MODE_DIGITS);
   double _point   = MarketInfo(symbol, MODE_POINT);

   if(direction == "buy") {
      double priceAsk   = MarketInfo(symbol, MODE_ASK);

      DiffPips = MathAbs(NormalizeDouble(priceAsk-stoploss,_digits)/_point);
   } 

   if(direction == "sell") {
      double priceBid   = MarketInfo(symbol, MODE_BID);

      DiffPips = MathAbs(NormalizeDouble(stoploss-priceBid,_digits)/_point);
   } 

   return(DiffPips);
}

//+------------------------------------------------------------------+
//| Show message                                                     |
//+------------------------------------------------------------------+
void ShowMessage(string type, string message)
{

}


for to test, just comment this line

//res=WebRequest(method,urlFrom,cookie,NULL,timeout,post,0,result,headers); 


The line below

resultString = CharArrayToString(result);

You must replace for this 

resultString   = "[{\"type\":\"success\",\"message\":\"\"},{\"id\":\"14058\",\"symbol\":\"EURUSD\",\"tp\":\"1.2518\",\"sl\":\"1.1911\",\"direction\":\"buy\",\"risk\":\"2\"},{\"id\":\"14059\",\"symbol\":\"USDCAD\",\"tp\":\"1.2420\",\"sl\":\"1.2930\",\"direction\":\"buy\",\"risk\":\"2\"}]";
Reason: