BlinkTradeJS SDK
BlinkTradeJS WebSocket and REST Official JavasScript client for node.js and browser.
Getting Started
BlinkTrade provides a simple and robust WebSocket API to integrate our platform, we strongly recommend you to use it over the RESTful API.
Install
$ yarn add blinktrade
using npm.
$ npm install blinktrade
Documentation
You can also check our Full API Documentation.
Examples
More examples can be found in the examples directory.
Usage
All SDK supports either promises and callbacks, if a callback is provided as the last argument, it will be called as callback(error, result)
,
otherwise it will just return the original promise, we also provide event emitters that you can use to get realtime updates through our WebSocket API,
you can check the Event Emitters section.
NOTE We impose cross origin policy (cors), even though our SDK can work on the browser, it won’t work due our origin policy, so and we recommend you use on server side instead. Only the public rest is available on the browser, and other environments only works on testnet and you won’t be able use to use production environment on the browser, this might change in the future.
Public REST API
The most simple way to get the ticker, orderbook and trades, is through our public RESTful API, which doesn't require authentication.
Ticker
const BlinkTradeRest = BlinkTradeRest;const blinktrade = currency: "BRL" ; blinktrade
Response
OrderBook
const BlinkTradeRest = BlinkTradeRest;const blinktrade = currency: "BRL" ; blinktrade
Response
Last Trades
const BlinkTradeRest = BlinkTradeRest;const blinktrade = currency: "BRL" ; blinktrade
Response
Trade REST / WebSocket
On our RESTful API, we provide a trade endpoint that you're allowed to send and cancel orders, request deposits and withdrawals. You need to create an API Key through our platform and set their respective permission that gives you access to it.
The Trade endpoint is internaly a bridge to our WebSocket
API, so you can access it both on REST
and WebSocket
API.
Be aware that our RESTful trade endpoint can be changed at any time, we strongly recommend using the WebSocket
API over the RESTful
API.
NOTE that when generate the API Key and the API Secret, it will be only shown once, you should save it securely. The API Password is only used in the WebSocket API.
const BlinkTradeRest = BlinkTradeRest;const blinktrade = prod: false key: "YOUR_API_KEY_GENERATED_IN_API_MODULE" secret: "YOUR_SECRET_KEY_GENERATED_IN_API_MODULE" currency: "BRL"; blinktrade
Response
Usage WebSocket
Authenticating
Make sure that you're connected to send messages through WebSocket, most of the message also require that you're authenticated.
const BlinkTradeWS = BlinkTradeWS;const blinktrade = prod: true ; blinktrade;
Requesting Balance
Will request your balance for each broker.
blinktrade;
You can pass a callback to receive balance updates.
blinktrade;
EXAMPLE RESPONSE
Subscribe to OrderBook
blinktrade
EXAMPLE RESPONSE
To unsubscribe from orderbook, you should pass the MDReqID
on unSubscribeOrderbook()
.
blinktrade;
Note that there's no return when unsubscribe from orderbook.
Syncronize orderbook
The syncOrderbook
function automatically handles the event system to keep the order book syncronized
for you, you can access the order book at anywhere in your application with blinktrade.orderbook
blinktrade
The blinktrade.orderbook
is a object like this
Subscribe to ticker
You can subscribe on one or more market symbols.
blinktrade;
To unsubscribe from ticker, you do the same as unSubscribeOrderbook
, but passing SecurityStatusReqID
to unSubscribeTicker()
.
blinktrade;
Send and cancelling orders
Floats are Evil!
Converting Floats to Integers can be dangerous. Different programming languages can get weird rounding errors and imprecisions, so all API returns prices and bitcoin values as Integers and in "satoshis" format. We also expect Integers as input, make sure that you're formatting the values properly to avoid precision issues.
e.g.:
// Wrong
0.57 * 1e8 => 56999999.99999999
// Correct
parseInt((0.57 * 1e8).toFixed(0)) => 57000000
blinktrade;
Advanced Orders (MARKET, LIMIT, STOP)
Market
Market orders automatically execute your order at the current price.
blinktrade
NOTE Market orders will execute indenpendently of the price of the other side, so be careful on low liquidity scenarios.
Limit
Limit order allows you specified your own price.
blinktrade
Post Only
Post Only ensures that your order will be added to the order book and not match with a existing order.
blinktrade
Stop
Stop order allow you place an order only when the price reaches the stop price, your order won't be visible on the book until it triggered.
blinktrade
NOTE STOP order will act as a MARKET order, if you want yo specify a limit price use STOP_LIMIT instead.
Stop Limit
Stop Limit order allow you specified a limit price toghether with the stop price.
blinktrade
Response
The response is the same as the Execution Report, if you're using it with rest transport, it will response as an array together with the balance response.
To cancel a order, you need to pass the orderId
, you'll also need to pass the clientId
in order to get a response,
if you didn't provide orderId
, all open orders will be cancelled.
blinktrade
The response will be the same as the sendOrder with
ExecType: "4"
Last Trades
List the latest trades executed on an exchange since a chosen date.
blinktrade
Requesting Deposits
You can generate either bitcoin or FIAT deposits, if any arguments was passed, it will generate a bitcoin deposit along with the address.
Generate bitcoin address to deposit
blinktrade
Fiat deposit
To generate a FIAT deposit, you need to pass the depositMethodId
which correspond the method of deposit of your broker, you can get these informations calling requestDepositMethods()
blinktrade
Response
Both responses for bitcoin and fiat deposits are quite similar.
NOTE The Data.InputAddress
is the address that you have to deposit. DO NOT DEPOSIT on Data.Destination
address.
Requesting Withdraws
To request withdraws, you need to pass a "data" information, which represents the information to your withdraw, it's related to bank accounts, numbers, or a bitcoin address. This information is dynamically and different for every broker.
blinktrade
Confirm Withdraws (two-factor)
After requesting a withdraw, you might get an error asking for two factor authentication,
you should call confirmWithdraw
passing the confirmationToken
that was sent to your email,
or secondFactor
if needed.
blinktrade
Response
Event Emitters
Using event emitters is easy and expressive way to keep you updated through our WebSocket
API,
you can listen to individual events to match your needs, you can listen to new orders, execution reports, tickers and balance changes.
Event emitters can also be used as promises to keep it chained, event emitters are implemented with EventEmitter2
,
which gives you more flexibility to match events with multi-level wildcards and extends events such as .onAny
, .once
, .many
and so on.
Connection Events
You can listem to OPEN
, CLOSE
, and ERROR
events to get WebSocket events and error handling.
blinktrade
The OPEN
event is useful to handle reconnections, since the promise is already resolved.
The ERROR
event is where you can do all the error handling, both from WebSocket errors or an
error raised by the backend due some invalid message, both CLOSE
and ERROR
will give you
the last message that you sent as the second argument.
You can also listen them by just blinktrade.on('OPEN', (e) => {})
that works just fine.
Event Ticker
To keep ticker update on new events, you can return a event emitter and match with the market.
blinktrade
You can easily match all symbols at the same listener.
blinktrade
Event Market Data
To get realtime updates on order book, you should listen to the following events.
blinktrade
You can still return a promise when listen events.
blinktrade
Event Balance
You listen to the BALANCE
event to receive balance updates.
blinktrade
Execution Reports
In order the get when a order is executed, you can listen to the execution report.
blinktrade
Withdraw and Deposit Refresh
To get deposit and withdraw updates, you can listen to DEPOSIT_REFRESH
and WITHDRAW_REFRESH
respectively.
blinktrade blinktrade
NOTE that these events will only be called to the current deposit / withdraw created.
If you want to listen to any deposit / withdraw updates, you should use onDepositRefresh(callback)
and onWithdrawRefresh()
instead.
blinktrade blinktrade
Handling WebSocket Reconnections
A simple connection pool
const blinktrade = prod: false brokerId: 11 reconnect: true reconnectInterval: 3000 blinktrade
API
Public REST API
WebSocket
- connect
- heartbeat
- login
- logout
- profile
- subscribeTicker
- unSubscribeTicker
- subscribeMarketData
- unSubscribeOrderbook
- executionReport
- tradeHistory
Trade Rest / Websocket
- balance
- sendOrder
- cancelOrder
- myOrders
- requestLedger
- requestWithdrawList
- requestWithdraw
- confirmWithdraw
- cancelWithdraw
- onWithdrawRefresh
- requestDepositList
- requestDeposit
- requestDepositMethods
- onDepositRefresh
Public REST
Constructor [rest]
new BlinkTradeRest(params: Object)
Arguments
Name | Type | Description |
---|---|---|
prod | Boolean | Production environment, default to false |
brokerId | Number | see brokers list |
key | String | API Key generated on our platform, it only needed on the Trade endpoint |
secret | String | API Secret generated on our platform, it only needed on the Trade endpoint |
currency | String | Currency symbol to fetch public endpoint |
ticker [rest]
ticker(callback?: Function)
=> Promise / callback
trades [rest]
trades(params: Object, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description |
---|---|---|
limit | Number | Limit of trades that will be returned. should be a positive integer. Optional; defaults to 100 trades |
since | Number | tid (TradeID) which must be fetched from. Optional; defaults to the date of the first executed trade |
orderbook [rest]
orderbook(callback?: Function)
=> Promise / callback
WebSocket
constructor [websocket]
new BlinkTradeWS(params?: Object)
Arguments
Name | Type | Description |
---|---|---|
prod | Boolean | Production environment, default to false |
brokerId | Number | see brokers list |
url | String | Custom url in case if you're using a custom backend url |
headers | String | Custom headers to pass to WebSocket constructor if it supported, (useful on react-native) |
fingerPrint | String | Custom fingerprint if you are not using in either a browser or node (useful on react-native) |
reconnect | Boolean | Automatically reconnects WebSocket after disconnected, to receive the reconnection event you should listen to the OPEN since the promise is already resolved |
reconnectInterval | Number | Reconnection Interval in miliseconds |
connect [websocket]
Connect to our WebSocket.
connect(callback?: Function)
=> Promise / callback
Connection Events
Event | Description |
---|---|
OPEN | Callback when WebSocket connects, by using this approach instead of a promise, you can benefit of reconnection events |
CLOSE | Callback when WebSocket closes |
ERROR | Callback when an error occured on both WebSocket or an error raised by the backend |
heartbeat [websocket]
Used as test request to check the latency connection.
heartbeat(callback?: Function)
=> Promise / callback
login [websocket]
login(params: Object, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description |
---|---|---|
username | String | Account username or API_Key |
password | String | Account password or API_Password |
secondFactor | String | Optional. If the authentication require second factor, you'll receive an error with NeedSecondFactor = true , NOTE: Is recommended that you use an API Key / API Password instead, which don't required second factor |
brokerId | Number | Optional. Overwrites the broker id provided by the constructor |
cancelOnDisconnect | Boolean | Optional. If it's true, all orders sent by the session will be cancelled when the WebSocket disconnects |
logout [websocket]
logout(callback?: Function)
=> Promise / callback
profile [websocket]
Available only on WebSocket
.
profile(callback?: Function)
=> Promise / callback
subscribeTicker [websocket]
subscribeTicker(Array<string> symbols, Function? callback)
=> Promise / callback
Symbols Available:
Name | Description |
---|---|
BLINK:BTCUSD | BTC <-> Testnet (USD) |
BLINK:BTCBRL | BTC <-> Brazil Reals (BRL) |
BLINK:BTCCLP | BTC <-> Chilean Pesos |
BLINK:BTCVND | BTC <-> Vietnamise Dongs |
UOL:USDBRT | Dólar Turismo |
UOL:USDBRL | Dólar Comercial |
subscribeOrderbook [websocket]
** DEPRECATED ** Use subscribeMarketData instead
subscribeMarketData [websocket]
subscribeMarketData(options: Object | Array<string>, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description |
---|---|---|
options | Object | Array |
columns | Array | Optional; Array of columns that you want to received, note that you will also receive the same columns on incremental updates e.g.: ['MDEntryType', 'MDEntryPx', 'MDEntrySize'] |
entryTypes | Array<0 | 1 |
marketDepth | number | Optional; Number of orders to be returned from orderbook e.g.: 0 = Full Book, 1 = Top of book, N > 1 = Number of orders to be returned |
Events
Event | Description |
---|---|
OB:NEW_ORDER | Callback when receives a new order |
OB:UPDATE_ORDER | Callback when an order has been updated |
OB:DELETE_ORDER | Callback when an order has been deleted |
OB:DELETE_ORDERS_THRU | Callback when one or more orders has been executed and deleted from the book |
syncOrderbook [websocket]
syncOrderbook(options: Object | Array<string>)
=> Promise
See subscribeMarketData
options
executionReport [websocket]
executionReport(callback?: Function)
=> Promise / callback
Events
An event emitter to get execution reports.
Event | Description |
---|---|
EXECUTION_REPORT:NEW | Callback when you send a new order |
EXECUTION_REPORT:PARTIAL | Callback when your order has been partially executed |
EXECUTION_REPORT:EXECUTION | Callback when an order has been successfully executed |
EXECUTION_REPORT:CANCELED | Callback when your order has been canceled |
EXECUTION_REPORT:REJECTED | Callback when order has been rejected |
tradeHistory [websocket]
tradeHistory(params: Object, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description |
---|---|---|
page | Number | Current page to fetch, defaults to 0 |
pageSize | Number | Number of trades, limits to 100 |
since | Number | TradeID or Date which executed trades must be fetched from. is in Unix Time date format. Optional; defaults to the date of the first executed trade. |
symbols | Array | List of symbols, e.g.: ["BTCVND", "BTCCLP"] |
Trade REST / Websocket
These methods bellow are both availabe under REST and WebSocket API.
balance [websocket, rest]
balance(clientId?: string, callback?: Function)
=> Promise / callback
Events
balance().on("BALANCE", (balance) => {})
=> Promise
sendOrder [websocket, rest]
sendOrder(params: Object, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description |
---|---|---|
type | String | "MARKET", "LIMIT", "STOP" or "STOP_LIMIT" |
side | String | "BUY, "SELL" or "1" = BUY, "2" = SELL |
price | Number | Price in "satoshis". e.g.: 1800 * 1e8 |
stopPrice | Number | Stop price used by order type "STOP" or "STOP_LIMIT" |
amount | Number | Amount to be sent in satoshis. e.g.: 0.5 * 1e8 |
symbol | String | Currency pair symbol, check symbols table |
postOnly | Boolean | If true, ensures that your order will be added to the order book and not match with a existing order |
clientId | String | Optional clientId, if doens't provided, will be used the requestId instead |
cancelOrder [websocket, rest]
cancelOrder(params: { orderId?: number, clientId?: string } | number, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description |
---|---|---|
orderId | Number | Required Order ID to be canceled |
clientId | Number | You need to pass the clientId (ClOrdID ) to get a response |
myOrders [websocket, rest]
myOrders(params: Object, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description |
---|---|---|
page | Number | Current page to fetch, defaults to 0 |
pageSize | Number | Number of orders, limits to 40 |
filter | Array | Optional; Open: ['has_leaves_qty eq 1'], Filled: ['has_cum_qty eq 1'], Cancelled: ['has_cxl_qty eq 1'] |
requestLedger [websocket, rest]
requestLedger(params: Object, callback?: Function)
=> Promise / callback
Arguments
Name | Type | Description/Value |
---|---|---|
page | number | Optional; defaults to 0 |
pageSize | number | Optional; defaults to 20 |
brokerID | number | Optional; <BROKER_ID> |
currency | string | Optional; Currency code. (.e.g: BTC) |
requestWithdrawList [websocket, rest]
requestWithdrawList(params: Object, callback?: Function)
=> Promise / callback
Name | Type | Description |
---|---|---|
page | Number | Current page to fetch, defaults to 0 |
pageSize | Number | Number of withdraws, limits to 20 |
status | Array | 1-Pending, 2-In Progress, 4-Completed, 8-Cancelled |
requestWithdraw [websocket, rest]
requestWithdraw(params: Object, callback?: Function)
=> Promise / callback
Name | Type | Description |
---|---|---|
data | Object | Withdraw required fields |
amount | Number | Amount of the withdraw |
method | Array | Method name of withdraw, check with your broker, defaults to bitcoin |
currency | String | Currency pair symbol to withdraw, defaults to BTC |
Events
Event | Description |
---|---|
WITHDRAW_REFRESH | Callback when withdraw refresh |
confirmWithdraw [websocket, rest]
confirmWithdraw(params: Object, callback?: Function)
=> Promise / callback
Name | Type | Description |
---|---|---|
withdrawId | String | Withdraw ID to confirm |
confirmationToken | String | Optional Confirmation Token sent by email |
secondFactor | String | Optional Second Factor Authentication code generated by authy |
cancelWithdraw [websocket, rest]
cancelWithdraw(withdrawId: number, callback?: Function)
=> Promise / callback
onWithdrawRefresh [websocket]
onWithdrawRefresh(callback: Function)
=> Promise
requestDepositList [websocket, rest]
requestDepositList(params: Object, callback?: Function)
=> Promise / callback
Name | Type | Description |
---|---|---|
page | Number | Current page to fetch, defaults to 0 |
pageSize | Number | Number of deposits, limits to 20 |
status | Array | 1-Pending, 2-In Progress, 4-Completed, 8-Cancelled |
requestDeposit [websocket, rest]
requestDeposit(params: Object, callback?: Function)
=> Promise / callback
Name | Type | Description |
---|---|---|
value | Number | Value amount to deposit |
currency | String | Currency pair symbol to withdraw, defaults to BTC |
depositMethodId | Number | Method ID to deposit, check requestDepositMethods |
Events
Event | Description |
---|---|
DEPOSIT_REFRESH | Callback when deposit refresh |
requestDepositMethods [websocket, rest]
requestDepositMethods(callback?: Function)
=> Promise / callback
onDepositRefresh [websocket]
onDepositRefresh(callback: Function)
=> Promise