IG Labs
FinanceIntegrating IG Trading APIs using JavaScript
If you are looking to integrate the IG Trading APIs into your JavaScript project, this guide is for you. IG Trading APIs provide secure, RESTful APIs for trading and accessing market data.
Getting Started
Before we begin, you need to register to access the API documentation. Once you have registered, you can find all the required information to start using the IG Trading APIs.
Authenticating with the APIs
To authenticate with the IG Trading APIs, you need to provide your API key
and API secret
. These are generated when you register for the API access.
const axios = require('axios');
const qs = require('qs');
const api_key = 'YOUR_API_KEY';
const api_secret = 'YOUR_API_SECRET';
const baseURL = 'https://labs.ig.com';
const username = 'YOUR_USERNAME';
const password = 'YOUR_PASSWORD';
const auth = {
username: api_key,
password: api_secret
}
const getAuthToken = async() => {
try {
const response = await axios.post(`${baseURL}/gateway/deal/session`, qs.stringify({
'identifier': username,
'password': password
}), {
auth,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
const AUTH_TOKEN = response.data.oauthToken.access_token;
return AUTH_TOKEN
} catch (error) {
console.error(error);
}
}
To get the authorization token, you need to call the getAuthToken()
function. This function uses the axios
library to make HTTP requests.
Market Data
With the IG Trading APIs, you can access real-time market data. Here is an example of how to get market data for EUR/USD
:
const getMarketData = async() => {
const authToken = await getAuthToken();
try {
const response = await axios.get(`${baseURL}/marketnavigation/charts/minchart/EUR/USD/10080`, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
}
})
console.log(response.data)
} catch (error) {
console.error(error);
}
}
Trading
The IG Trading APIs allow you to place trades programmatically. Here is an example of how to place a market order:
const placeMarketOrder = async() => {
const authToken = await getAuthToken();
try {
const response = await axios.post(`${baseURL}/gateway/deal/positions/otc`, {
'epic': 'CS.D.EURUSD.MINI.IP',
'expiry': '-',
'direction': 'BUY',
'size': '1',
'orderType': 'MARKET',
'level': null,
'timeInForce': null,
'guaranteedStop': false,
'stopLevel': null,
'stopDistance': null,
'limitLevel': null,
'limitDistance': null,
'currencyCode': 'USD',
'forceOpen': true,
'dealReference': null
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
}
})
console.log(response.data)
} catch (error) {
console.error(error);
}
}
Conclusion
The IG Trading APIs provide a lot of capabilities to access the market data and trade programmatically. This guide provides you with the basic information to get started with the IG Trading APIs using JavaScript. Check out the API documentation to learn more about the API capabilities.