Open/Read URL (NinjaTrader)

Read response of link (from Indicator)

In NinjaTrader 8 (and probably for version 7 too, but I havent checked it for that), whenever you want to open a web-page and read a data/response from it, you can simply use the native methods (instead of using external dll files, like curl, Newton-soft or other libraries).

Simply use this example code:

using System.Net.Http; 

public string Get_URL_response(string url)
{
	string response_Text="";
	try{
		using (var readerr = new System.IO.StreamReader( ((HttpWebResponse)((HttpWebRequest)WebRequest.Create(url)).GetResponse()).GetResponseStream(), ASCIIEncoding.ASCII))
		{
			response_Text = readerr.ReadToEnd();
		}
	}
	catch (Exception e){ 
		Print("Happened HttpWebRequest Error:"+e.ToString());
	}
	return response_Text; 
}

This is quite simpler than the solutions someone might used in the past with previous versions of NT (i.e. NT6, NT7).

Using with initial variable

You should better to use that function only once per call. You should not call it in OnBarUpdate because it might cause to execute function (thus open that web-site) on every tick, which will drastically affect the performance of the script/indicator/strategy or any application :

1) if you need it only once, when Application starts, then use something like this:

if (State == State.Configure){
   ... here grab data from site
}

2) if you need only once in a bar, then do it using  FirstTickOfBar  :

protected override void OnBarUpdate(){
   //exclude execution on historical/backtesting data, thus, allowing calling only in real-time
   if(!Historical && FirstTickOfBar) { 
        myResponse = Get_URL_response(myURL);
   }
   .....
}

Compile the NinjaScript and that’s all. You can now open any link or get a response from a page, but note, this is a typical GET method. Once I’ll come across to POST method, I’ll add that here (If you know that, you can notify that in comments below).

Leave a Reply

Your email address will not be published. Required fields are marked *