Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including node-ig-api with all npm packages installed. Try it out:

var nodeIgApi = require("node-ig-api")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

node-ig-api v2.0.4

Node.js IG REST Trading & Streaming API

NODE-IG-API 0.x

This is the first exhaustive Node.js IG REST Trading & Streaming API. Similar APIs are available out there, however they all lack of key functionalities and proper documentation.

Installation & Setup

Make a new directory for your project and cd into it.

$ npm install node-ig-api

Create environment variables for your IG credentials. This can be done in your OSX/LINUX CLI as:

$ export IG_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
$ export IG_IDENTIFIER=xxxxxxxxxxxx
$ export IG_PASSWORD=xxxxxxxxxxxx
$ export IG_DEMO=TRUE

or in your Windows CLI as:

$ SET IG_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
$ SET IG_IDENTIFIER=xxxxxxxxxxxx
$ SET IG_PASSWORD=xxxxxxxxxxxx
$ SET IG_DEMO=TRUE

(clearly the "x" values should be your actual IG credentials and IG_DEMO should be FALSE for the live version!)

Create a test.js file which requires the package and calls the methods described in the documentation.

Documentation

Please make yourself familiar with the REST Trading API Reference and Streaming API Reference available at https://labs.ig.com before getting started.

All modules (except connectToLightstreamer and subscribeToLightstreamer) return a promise that resolve and reject always into a Json object. When the request is successful the Json file will contain only the response body, whereas on failure it will contain the response status, header and body.

Method Summary

MethodDescription
loginLog in (retrieve client and session tokens)
logoutLog out (disable retrieved client and session tokens)
switchAcctSwitch Account
acctInfoReturns a list of accounts belonging to the logged-in client
acctActivityReturns the account activity history
acctTransactionReturns the transaction history
apiInfoList of client-owned applications
showOpenPositionsReturns all open positions for the active account.
dealCreates an OTC position
editPositionAttach order to open position
closePositionCloses an open position
closeAllPositionsCloses all open positions
showWorkingOrdersReturns all open working orders for the active account
createOrderCreate a working order
deleteOrderDelete existing working order
deleteAllOrdersDelete all existing working orders
searchSearch a contract
igVolumeClient sentiment (IG volume)
marketNodeMarket node content
histPrcHistorical prices
epicDetailsShows all details of a contract (epic)
watchlistsWatchlists summary and watchlist content
createWatchlistCreate a new watchlist
deleteWatchlistDelete entire watchlist
addEpicWatchlistInsert single epic to watchlist
removeEpicWatchlistRemove single epic to watchlist
getGet request on IG api
delDelete request on IG api
putPut request on IG api
postPost request on IG api
connectToLightstreamerConnect to Lightstreamer (Streaming of data)
subscribeToLightstreamerSubscribe to Lightstreamer (Streaming of data)


Method Detail

Account

login(encryption)

Store in the file system a Json file containing the IG tokens valid for 12 hours. After the first log-in, this API will allow you to run other IG Rest requests without the need to log-in again. It is pivotal that you log-in before any request.

PropertyDescriptionTypeDefault
encryptionencrypting the password before logging-inBooleanfalse


logout()

Destroy the IG tokens stored in the file system and disable them within the IG account.



switchAcct(accountId)

Switch between different accounts (e.g. from CFD to Spread Betting)

PropertyDescriptionTypeDefault
accountIdAccount code IDString


acctInfo()

Returns a list of accounts belonging to the logged-in client



acctActivity(from, to, detailed, dealId, pageSize)

Returns the account activity history

PropertyDescriptionTypeDefault
fromHas to have format: YYYY-MM-DDString1990-01-01
toHas to have format: YYYY-MM-DDString2099-01-01
detailedDetailed outputStringfalse
dealIdActivity on specific deaString
pageSizeOutput page sizeNumber500


acctTransactions(type, from, to, pageSize, pageNumber)

Returns the transaction history for the specified transaction type and period

PropertyDescriptionTypeDefault
typeALL, ALL_DEAL, DEPOSIT, WITHDRAWALStringALL
fromHas to have format: YYYY-MM-DDString1990-01-01
toHas to have format: YYYY-MM-DDString2099-01-01
pageSizeOutput page sizeNumber500
pageNumberOutput page sizeNumber1


apiInfo()

Returns details of all the API Key of the logged-in client



Dealing

showOpenPositions()

Returns all open positions for the active account



deal(ticket)

Execute a market order in the active account

PropertyDescriptionTypeDefault
ticketSee example belowJson object
ticket = {
    'currencyCode': 'GBP',
    'direction': 'BUY', // 'BUY' or 'SELL'
    'epic': 'CC.D.LCO.USS.IP',
    'expiry': 'DFB',
    'size': 2,
    'forceOpen': true, // if true a new order will not cancel out existing one; has to be true for any LIMIT order type
    'orderType': 'MARKET', // 'LIMIT' or 'MARKET'
    'level': null, // specify only when orderType = LIMIT
    'limitDistance': null, // close when profit exceeds limitDistance points
    'limitLevel': null, // close at profit when price close to limitLevel price
    'stopDistance': null, // close when loss exceeds stopDistance points
    'stopLevel': null, // close at loss when price close to limitLevel price
    'guaranteedStop': false,
    'timeInForce': 'FILL_OR_KILL', // 'FILL_OR_KILL' or 'EXECUTE_AND_ELIMINATE'
        // 'FILL_OR_KILL': will try to fill this entire order within the constraints set by {order_type} and {level}, however if this is not possible then the order will not be filled at all
        // 'EXECUTE_AND_ELIMINATE': will fill this order as much as possible within the constraints set by {order_type} and {level}
    'trailingStop': null,
    'trailingStopIncrement': null
};


editPosition(dial_id, ticket)

Attach and order to an existing position

PropertyDescriptionTypeDefault
dial_idID code of open positionString
ticketSee example belowJson object
ticket = {
    'limitLevel': 5700, // close position at profit when price hit 5700 level
    'stopLevel': 5000, // close position at loss when price hit 5000 level
    'trailingStop': false,
    'trailingStopDistance': null,
    'trailingStopIncrement': null
};


closePosition(dealId)

Close an existing position at available market price (i.e. 'orderType': 'MARKET')

PropertyDescriptionTypeDefault
dealIdID code of open positionJson object


closeAllPositions() Closing all open positions at available market price (i.e. 'orderType': 'MARKET')



Working orders

showWorkingOrders()

Returns any active working order for the active account


createOrder(ticket)

Create a working order

PropertyDescriptionTypeDefault
ticketSee example belowJson object
let ticket = {
    'currencyCode': 'GBP',
    'direction': 'BUY', // 'BUY' or 'SELL'
    'epic': 'IX.D.FTSE.DAILY.IP',
    'expiry': 'DFB',
    'size': 1.5,
    'forceOpen': true, // if true a new order will not cancel out existing one; has to be true for any LIMIT order type
    'type': 'LIMIT', //'LIMIT' or 'STOP'
    // LIMIT: enter when PRC <= LEVEL
    // STOP: enter when PRC >= LEVEL
    // e.g. if PRC = 7200
    // BUY LIMIT 7000 -> will enter when PRC <= 7000
    // BUY LIMIT 7500 -> REJECTED because would enter immediately 
    // BUY STOP 7000 -> REJECTED because would enter immediately
    // BUY STOP 7500 -> will enter the position when PRC >= 7500
    'level': 7000, // specify only when orderType = LIMIT
    'limitDistance': null, // close when profit exceeds limitDistance points
    'limitLevel': 7250, // close at profit when price close to limitLevel price
    'stopDistance': null, // close when loss exceeds stopDistance points
    'stopLevel': null, // close at loss when price close to limitLevel price
    'guaranteedStop': false,
    'timeInForce': 'GOOD_TILL_CANCELLED', // or 'GOOD_TILL_DATE'; if timeInForce equals GOOD_TILL_DATE, then set goodTillDate
    'goodTillDate': null // yyyy/mm/dd hh:mm:ss in UTC Time or Unix Timestamp in milliseconds
};


deleteOrder(orderId)

Delete a specific existing working orders


deleteAllOrders()

Delete all existing working orders



Markets info

search(searchTerm)

Search a contract with a specific word

PropertyDescriptionTypeDefault
searchTermSearch termString


igVolume(epics)

Shows IG clients' percentage long/short positions per contract group

PropertyDescriptionTypeDefault
epicsList of epicsString Array


marketNode(id)

IG API is grouping all their product into three nodes. So you will obtain a generic specification of all contracts by running marketNode(). Thereafter you will find more details by moving into a tree structure with marketNode(id).

PropertyDescriptionTypeDefault
idNode IDNumber0


histPrc(epic, resolution, from, to)

IG historical prices for a specific contract (IG API policy allows you to obtain no more than 10000 historical data points per week)

PropertyDescriptionTypeDefault
epicepic code of contractString
resolutionDAY, HOUR, HOUR_2, HOUR_3, HOUR_4, MINUTE, MINUTE_10, MINUTE_15, MINUTE_2, MINUTE_3,MINUTE_30, MINUTE_5, MONTH, SECOND, WEEKString
fromHas to have format: YYYY-MM-DDTHH:MM:SSString
toHas to have format: YYYY-MM-DDTHH:MM:SSString


epicDetails(epics)

Shows all details of a contract (epic) or a list of contracts (list of epics)

PropertyDescriptionTypeDefault
epicsList of epicsString Array


Watchilists


watchlists(id)

When id is undefined the module returns a summary list of all existing watchlists. Otherwise the module will return details of a specific watchlist

PropertyDescriptionTypeDefault
idWatchilist IDStringundefined


createWatchlist(name, epics)

Create a new watchlist

PropertyDescriptionTypeDefault
nameName of the watchlist that is being createdString
epicsList of epics to be added in the newly created watchlistString Array


deleteWatchlist(id)

Delete entire watchlist

PropertyDescriptionTypeDefault
idWatchilist IDString


addEpicWatchlist(epic, watchlistID)

Insert single epic to watchlist

PropertyDescriptionTypeDefault
epicEpics to be added to the watchlistString
watchlistIDWatchilist IDString


removeEpicWatchlist(epic, watchlistID)

Remove single epic from a specific watchlist

PropertyDescriptionTypeDefault
epicEpics to be removed from the watchlistString
watchlistIDWatchilist IDString


Generic IG REST Requester

get(url, version)

del(url, payload, version)

put(url, payload, version)

post(url, payload, version)

PropertyDescriptionTypeDefault
urlurl for REST requestString
payloadbody of the requestJson Object
versionIG version for specific requestNumber1


Generic IG REST Requester

These modules should be used as starting point for your personal IG streaming API. This is probably the first and only implementation of the IG REST Streaming API.

connectToLightstreamer()

Create a Lightstreamer session by using the tokes that have been retrieved with login(). This will allow you to create a Subscription


subscribeToLightstreamer(subscriptionMode, items, fields, maxFreq)

Subscribe to Lightstreamer. In other words, you subscribe to a list of contracts in Lightstreamer and this will stream live data (e.g. price) in your console. You can edit this module to store data in database or automate some trades.

PropertyDescriptionTypeDefault
subscriptionModeMERGE, DISTINCT, RAW, COMMANDArray
itemsList of epicsString Array
fieldsMID_OPEN, HIGH, LOW, CHANGE, CHANGE_PCT, UPDATE_TIME, MARKET_DELAY, MARKET_STATE, BID, OFFER, STRIKE_PRICE, ODDSString
maxFreqNumber of maximum updates per second per epicNumberinfinite
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free