Questrade API sample code with nodejs and request

Questrade released an API to retrieve account information, market data, and even making trades. That’s awesome! They have helpful documentation and even a developer console to make the API calls. Here is some sample code to use their API. Remember to paste your own refresh token (their Getting Started page provides instructions on how to generate it)

var request = require('request');

var refresh_token='YOUR TOKEN HERE';

// This gets us the access token for authorizing subsequent requests
console.log("getting access token");
request.get(
	{url:'https://login.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token=' + refresh_token},
	function(err, response, body){
		if(err){
			console.log(err);
			return;
		}

		console.log(response.statusCode);

		if(response.statusCode != 200){
			console.log(body); // If we get here, it is likely to be a 'bad request' because we are using the same refresh_token more than once
			return;
		}

		b = JSON.parse(body)
		var access_token = b.access_token;
		var api_server = b.api_server;

		// Let's try to get our account information
		if(response.statusCode == 200)
		{
			console.log('Make a request');
			request.get(
				{
					url: api_server + 'v1/accounts',
					auth:{
						bearer : access_token
					}
				},
				function(err, response, body){
					if(err){
						console.log(err);
						return;
					}
					console.log(response.statusCode);
					console.log(body);
				}
			);
		}
	}
);

This code redeems the refresh token for an access token, and then use the access token to make a get request to v1/accounts to get account information. You should be able to reuse the access token for other requests; however you can only use the refresh token once. If you use it more than once, you will get a 400 bad request.

Advertisements

One thought on “Questrade API sample code with nodejs and request

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s