Giter VIP home page Giter VIP logo

blinktradejs's Introduction

BlinkTradeJS SDK

travis npm version Known Vulnerabilities

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 = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({ currency: "BRL" });

blinktrade.ticker().then((ticker) => {
  console.log(ticker)
})

Response

  {
    "high": 1900,
    "vol": 4.87859418,
    "buy": 1891.89,
    "last": 1891.89,
    "low": 1891.89,
    "pair": "BTCBRL",
    "sell": 1910,
    "vol_brl": 9250.19572651
  }

OrderBook

const BlinkTradeRest = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({ currency: "BRL" });

blinktrade.orderbook().then((orderbook) => {
  console.log(orderbook)
})

Response

{
  "pair": "BTCBRL",
  "bids": [
    [ 1891.89, 0.16314699, 90800027 ],
    [ 1880, 0.20712, 90800027 ]
  ],
  "asks": [
    [ 1910, 3.28046533, 90800027 ],
    [ 1919.99, 1.95046354, 90800027 ]
  ]
}

Last Trades

const BlinkTradeRest = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({ currency: "BRL" });

blinktrade.trades().then((trades) => {
  console.log(trades)
})

Response

 [{
    "tid": 16093,
    "date": 1472278473,
    "price": 1891.89,
    "amount": 0.1,
    "side": "sell"
  }, {
    "tid": 16094,
    "date": 1472278477,
    "price": 1891.89,
    "amount": 0.1,
    "side": "sell"
  }, {
    "tid": 16095,
    "date": 1472278668,
    "price": 1891.89,
    "amount": 0.1,
    "side": "sell"
 }]

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 = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({
  prod: false,
  key: "YOUR_API_KEY_GENERATED_IN_API_MODULE",
  secret: "YOUR_SECRET_KEY_GENERATED_IN_API_MODULE",
  currency: "BRL",
});

blinktrade.sendOrder({
  side: "BUY",
  price: parseInt(1800 * 1e8).toFixed(0),
  amount: parseInt(0.5 * 1e8).toFixed(0),
  symbol: "BTCBRL",
}).then((order) => {
    console.log(order)
})

Response

{
    "OrderID": 1459028830811,
    "ExecID": 740972,
    "ExecType": "0",
    "OrdStatus": "0",
    "CumQty": 0,
    "Symbol": "BTCUSD",
    "OrderQty": 5000000,
    "LastShares": 0,
    "LastPx": 0,
    "Price": 180000000000,
    "TimeInForce": "1",
    "LeavesQty": 50000000,
    "MsgType": "8",
    "ExecSide": "1",
    "OrdType": "2",
    "CxlQty": 0,
    "Side": "1",
    "ClOrdID": 3251968,
    "AvgPx": 0
}

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 = require("blinktrade").BlinkTradeWS;
const blinktrade = new BlinkTradeWS({ prod: true });

blinktrade.connect().then(() => {
  // Connected
  return blinktrade.login({ username: "<API_KEY>", password: "<API_SECRET>" });
}).then((logged) => {});

Requesting Balance

Will request your balance for each broker.

blinktrade.balance().then((balance) => {
  console.log(balance);
});

You can pass a callback to receive balance updates.

blinktrade.balance(null, (err, balance) => {
  console.log(balance);
});

EXAMPLE RESPONSE

{
    "5": {
        "BTC_locked": 0,
        "USD": 177911657052760,
        "BTC": 1468038442214,
        "USD_locked": 96750050000
    },
    "MsgType": "U3",
    "ClientID": 90800003,
    "BalanceReqID": 5019624
}

Subscribe to OrderBook

blinktrade.subscribeMarketData(["BTCBRL"]).then((orderbook) => {
  console.log(orderbook)
})

EXAMPLE RESPONSE

{
  "MDReqID": 9894272,
  "Symbol": "BTCUSD",
  "MsgType": "W",
  "MarketDepth": 0,
  "MDFullGrp": {
    "BTCUSD": {
      "bids": [{
        "MDEntryPositionNo": 1,
        "MDEntrySize": 50000000,
        "MDEntryPx": 1150600000000,
        "MDEntryID": 1459030492064,
        "MDEntryTime": "05:50:13",
        "MDEntryDate": "2018-02-03",
        "UserID": 90800000,
        "OrderID": 1459000000000,
        "MDEntryType": "0",
      }],
      "asks": [{
        "MDEntryPositionNo": 1,
        "MDEntrySize": 50000000,
        "MDEntryPx": 1150700000000,
        "MDEntryID": 1459030492064,
        "MDEntryTime": "05:50:13",
        "MDEntryDate": "2018-02-03",
        "UserID": 90800000,
        "OrderID": 1459000000000,
        "MDEntryType": "1",
      }]
    }
  }
}

To unsubscribe from orderbook, you should pass the MDReqID on unSubscribeOrderbook().

blinktrade.subscribeMarketData(["BTCBRL"]).then((orderbook) => {
  blinktrade.unSubscribeOrderbook(orderbook.MDReqID);
});

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.syncOrderbook(["BTCBRL"]).then(() => {
  console.log(blinktrade.orderbook);
})

The blinktrade.orderbook is a object like this

{
  "BTCUSD": {
    "bids": [{
      "MDEntryPositionNo": 1,
      "MDEntrySize": 50000000,
      "MDEntryPx": 1150600000000,
      "MDEntryID": 1459030492064,
      "MDEntryTime": "05:50:13",
      "MDEntryDate": "2018-02-03",
      "UserID": 90800000,
      "OrderID": 1459000000000,
      "MDEntryType": "0",
    }],
    "asks": [{
      "MDEntryPositionNo": 1,
      "MDEntrySize": 50000000,
      "MDEntryPx": 1150700000000,
      "MDEntryID": 1459030492064,
      "MDEntryTime": "05:50:13",
      "MDEntryDate": "2018-02-03",
      "UserID": 90800000,
      "OrderID": 1459000000000,
      "MDEntryType": "1",
    }]
  }
}

Subscribe to ticker

You can subscribe on one or more market symbols.

blinktrade.subscribeTicker(["BLINK:BTCBRL"]).then((ticker) => {
  console.log(ticker);
});

To unsubscribe from ticker, you do the same as unSubscribeOrderbook, but passing SecurityStatusReqID to unSubscribeTicker().

blinktrade.subscribeTicker(["BLINK:BTCBRL"]).then((ticker) => {
  blinktrade.unSubscribeTicker(ticker.SecurityStatusReqID);
});

Send and cancelling orders

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.sendOrder({
  side: "BUY",
  price: parseInt((550 * 1e8).toFixed(0)),
  amount: parseInt((0.05 * 1e8).toFixed(0)),
  symbol: "BTCUSD",
}).then((order) => {
  // Sent
});

Advanced Orders (MARKET, LIMIT, STOP)

Market

Market orders automatically execute your order at the current price.

blinktrade.sendOrder({
  side: 'BUY',
  type: 'MARKET',
  symbol: 'BTCBRL',
  amount: parseInt(0.01 * 1e8),
})

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.sendOrder({
  side: 'SELL',
  type: 'LIMIT',
  symbol: 'BTCBRL',
  price: parseInt(16000 * 1e8),
  amount: parseInt(0.01 * 1e8),
})

Post Only

Post Only ensures that your order will be added to the order book and not match with a existing order.

blinktrade.sendOrder({
  side: 'BUY',
  type: 'LIMIT',
  symbol: 'BTCBRL',
  price: parseInt(16000 * 1e8),
  amount: parseInt(0.01 * 1e8),
  postOnly: true,
})

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.sendOrder({
  side: 'SELL',
  type: 'STOP',
  symbol: 'BTCBRL',
  stopPrice: parseInt(16000 * 1e8), // Price bellow the best bid
  amount: parseInt(0.01 * 1e8),
})

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.sendOrder({
  side: 'SELL',
  type: 'STOP_LIMIT',
  symbol: 'BTCBRL',
  price: parseInt(15900 * 1e8), // Limit price
  stopPrice: parseInt(16000 * 1e8), // Price bellow the best bid
  amount: parseInt(0.01 * 1e8),
})

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.

{
    "OrderID": 1459028830811,
    "ExecID": 740972,
    "ExecType": "0",
    "OrdStatus": "0",
    "CumQty": 0,
    "Symbol": "BTCUSD",
    "OrderQty": 5000000,
    "LastShares": 0,
    "LastPx": 0,
    "Price": 55000000000,
    "TimeInForce": "1",
    "LeavesQty": 5000000,
    "MsgType": "8",
    "ExecSide": "1",
    "OrdType": "2",
    "CxlQty": 0,
    "Side": "1",
    "ClOrdID": 3251968,
    "AvgPx": 0
}

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.cancelOrder({ orderId: order.OrderID, clientId: order.ClOrdID }).then((order) => {
  console.log("Order Cancelled");
})

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.trades({ limit: 100, since: 2270000 }).then((data) => {
  console.log("Trades", data);
})

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.requestDeposit().then((deposit) => {
  console.log(deposit)
})

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.requestDeposit({
  value: parseInt(200 * 1e8),
  currency: "BRL",
  depositMethodId: 502,
}).then((deposit) => {
  console.log(deposit)
})

Response

Both responses for bitcoin and fiat deposits are quite similar.

{
    "DepositMethodName": "deposit_btc",
    "UserID": 90800003,
    "ControlNumber": null,
    "State": "UNCONFIRMED",
    "Type": "CRY",
    "PercentFee": 0,
    "Username": "user",
    "CreditProvided": 0,
    "DepositReqID": 7302188,
    "DepositID": "2a6b5e322fd24574a4d9f988681a542f",
    "Reason": null,
    "AccountID": 90800003,
    "Data": {
        "InputAddress": "mjjVMr8WcYQwVGzYc8HpaRyAZc89ngTdKV",
        "Destination": "n19ZAH1WGoUkQhubQw71fH11BenifxpBxf"
    },
    "ClOrdID": "7302188",
    "Status": "0",
    "Created": "2016-09-03 23:08:26",
    "DepositMethodID": null,
    "Value": 0,
    "BrokerID": 5,
    "PaidValue": 0,
    "Currency": "BTC",
    "ReasonID": null,
    "MsgType": "U23",
    "FixedFee": 0
}

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.requestWithdraw({
  amount: parseInt(400 * 1e8),
  currency: "BRL",
  method: "bradesco",
  data: {
    AccountBranch: "111",
    AccountNumber: "4444-5",
    AccountType: "corrente",
    CPF_CNPJ: "00000000000"
  }
})

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.confirmWithdraw({
    withdrawId: 523,
    confirmationToken: 'TOKEN'
})

Response

{
    "Username": "user",
    "Status": "1",
    "SecondFactorType": "",
    "Created": "2016-09-03 23:42:06",
    "PaidAmount": 50000000,
    "UserID": 90800003,
    "Reason": null,
    "Currency": "BRL",
    "Amount": 50000000,
    "ReasonID": null,
    "BrokerID": 5,
    "ClOrdID": "3332623",
    "WithdrawID": 523,
    "WithdrawReqID": 3332623,
    "MsgType": "U7",
    "Data": {
        "Instant": "NO",
        "AccountBranch": "111",
        "AccountNumber": "4444-5",
        "AccountType": "corrente", 
        "CPF_CNPJ": "00000000000"
    },
    "Method": "bradesco",
    "FixedFee": 0,
    "PercentFee": 0
}

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.connect()
  .on('OPEN',  (e) => {})
  .on('CLOSE', (e, lastMessageSent) => {})
  .on('ERROR', (error, lastMessageSent) => {})
  .then(() => {
    console.log('Connected')
  })

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.subscribeTicker(["UOL:USDBRT", "BLINK:BTCUSD", "BLINK:BTCBRL"])
  .on("UOL:USDBRT",   (usdbrt) => {})
  .on("BLINK:BTCUSD", (btcusd) => {})
  .on("BLINK:BTCBRL", (btcbrl) => {})

You can easily match all symbols at the same listener.

blinktrade.subscribeTicker(["UOL:USDBRT", "BLINK:BTCUSD", "BLINK:BTCBRL"])
.on("BLINK:*", (ticker) => {})

Event Market Data

To get realtime updates on order book, you should listen to the following events.

blinktrade.subscribeMarketData(["BTCUSD"])
  .on("OB:NEW_ORDER", (order) => {})
  .on("OB:UPDATE_ORDER", (order) => {})
  .on("OB:DELETE_ORDER", (order) => {})
  .on("OB:DELETE_ORDERS_THRU", (order) => {})
  .on("OB:TRADE_NEW", (order) => {})

You can still return a promise when listen events.

blinktrade.subscribeMarketData(["BTCBRL"])
.on("OB:NEW_ORDER", (order) => {
  console.log("New order received")
}).then((orderbook) => {
  console.log("Full orderbook", orderbook)
})

Event Balance

You listen to the BALANCE event to receive balance updates.

blinktrade.balance().on("BALANCE", (balance) => console.log(balance))

Execution Reports

In order the get when a order is executed, you can listen to the execution report.

blinktrade.executionReport()
  .on("EXECUTION_REPORT:NEW", (data) => {})
  .on("EXECUTION_REPORT:PARTIAL", (data) => {})
  .on("EXECUTION_REPORT:EXECUTION", (data) => {})
  .on("EXECUTION_REPORT:CANCELED", (data) => {})
  .on("EXECUTION_REPORT:REJECTED", (data) => {})

Withdraw and Deposit Refresh

To get deposit and withdraw updates, you can listen to DEPOSIT_REFRESH and WITHDRAW_REFRESH respectively.

blinktrade.requestDeposit().on('DEPOSIT_REFRESH', (deposit) => {
  console.log(deposit)
})

blinktrade.requestWithdraw().on('WITHDRAW_REFRESH', (withdraw) => {
  console.log(withdraw)
})

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.onDepositRefresh((deposit) => {
  console.log(deposit)
})

blinktrade.onWithdrawRefresh((withdraw) => {
  console.log(withdraw)
})

Handling WebSocket Reconnections

A simple connection pool

const blinktrade = new BlinkTradeWS({
  prod: false,
  brokerId: 11,
  reconnect: true,
  reconnectInterval: 3000,
})

blinktrade.connect().on('OPEN', () => {
  console.log('connected');
  blinktrade.login({
    username: '<API_KEY>'
    password: '<API_PASSWORD>'
  }).then(() => {
    // Manually disconnect WebSocket connection
    blinktrade.disconnect()
  })
})

API

Public REST API

WebSocket

Trade Rest / Websocket

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
side String Cancel all orders of the side e.g.: "BUY, "SELL" or "1" = BUY, "2" = SELL

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

LICENSE

LICENSE GPLv3

blinktradejs's People

Contributors

cesardeazevedo avatar elias19r avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blinktradejs's Issues

Minor: `.sendOrder` only accepts Integer amounts

This is a minor annoyance and nothing more. Please feel free to close this and any of my requests that you don't agree with under a won't fix label :)

Typing this:

blinktrade.sendOrder({
    "side": "2", // Sell
    "price": parseInt(1 * 1e8), // 1 PKR
    "amount": "519153",
    "symbol": "BTCPKR",
})

Will result in the following error:

Error: Error: Invalid value tag(OrderQty)=519153 Invalid message
    at BlinkTradeWS.onMessage (/Users/gilani/Sandbox/payload-urdubit/node_modules/blinktrade/lib/wsTransport.js:165:15)
    at WebSocket.onMessage (/Users/gilani/Sandbox/payload-urdubit/node_modules/ws/lib/WebSocket.js:442:14)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:191:7)
    at Receiver.ontext (/Users/gilani/Sandbox/payload-urdubit/node_modules/ws/lib/WebSocket.js:841:10)
    at /Users/gilani/Sandbox/payload-urdubit/node_modules/ws/lib/Receiver.js:536:18
    at Receiver.applyExtensions (/Users/gilani/Sandbox/payload-urdubit/node_modules/ws/lib/Receiver.js:371:5)
    at /Users/gilani/Sandbox/payload-urdubit/node_modules/ws/lib/Receiver.js:508:14
    at Receiver.flush (/Users/gilani/Sandbox/payload-urdubit/node_modules/ws/lib/Receiver.js:347:3)

Because the API expects a strict integer. However, typing the following will work:

blinktrade.sendOrder({
    "side": "2", // Sell
    "price": parseInt(1 * 1e8), // 1 PKR
    "amount": parseInt("519153"),
    "symbol": "BTCPKR",
})

Deposit - REST not working

The requestDeposit function is not working in the BlinkTradeRest API.

The follow response is returned:
{ Status: 500,
Description: 'Not possible to generate a deposit address at this time. Please try again later.',
Result: {} }

How to know rejection reasons?

Hello again!
I am still testing things and another problem comes out: there is no documentation about rejection reasons. I am trying to blinktrade.sendOrder() with no success.
This is the returned message:

{ 
  OrderID: null,
  Volume: 0,
  ExecID: null,
  ExecType: '8',
  OrdStatus: '8',
  LeavesQty: 0,
  Price: 371930000000,
  OrderQty: 369265,
  LastShares: 0,
  LastPx: 0,
  CxlQty: 0,
  TimeInForce: '1',
  CumQty: 0,
  MsgType: '8',
  ClOrdID: 9667187,
  OrdType: '2',
  OrdRejReason: '3',
  Side: '1',
  Symbol: 'BTCBRL',
  ExecSide: '1',
  AvgPx: 0
}

How to know what OrdRejReason: '3' means?

Getting error using BlinkTradeJS in new node application

Hi Guys,

I'm testing the API.

In a new node application:

npm init
npm install blinktrade

Then when running this code:

var BlinkTradeWS = require('blinktrade').BlinkTradeWS;

var blinktrade = new BlinkTradeWS();

blinktrade.connect().then(function() {
  return blinktrade.login({ username: 'rodrigo', password: 'abc12345' });
}).then(function(logged) {
  console.log(logged);
}).catch(function(err) {
  console.log(err);
});

Get this error:

throw new Error('Error: ' + data.Detail + ' ' + data.Description);
        ^
Error: Error: Missing tag BrokerID Invalid message
at WebSocketTransport.onMessage (.../blockchain/blinktrade_examples/node_modules/blinktrade/lib/transpo
rts/websocket.js:156:15)
    at WebSocket.onMessage (.../blinktrade_examples/node_modules/ws/lib/EventTarget.js:99:16)
    at WebSocket.emit (events.js:160:13)

If I try execute any code in node_modules/examples folder, run correctly!

Could you have any advices about this ?

Thanks

Cancel failure over websocket

Hi,

How are we supposed to catch cancel failures ?
In the docs the standard OrderCancelReject is not documented, is it sent ?

Thx

No `Latency` in `heartbeat()` callback

The .Latency in the heartbeat callback is undefined unlike the .Latency in the promise

            blinktrade.heartbeat()
                .then(function(beat) {
                    console.log(beat.Latency); //=> this returns the latency in ms
                });

            blinktrade.heartbeat(function(err, beat) {
                    console.log(beat.Latency); //=> this returns `undefined`
                });

[Question] Error Too many messages per second

I've been receiving the following error a lot:
Error: 16 messages in the last second Too many messages per second

Could you please explain a bit more of this issue? Is my application sending more than 16 messages per second (which is not happening based on my tests) or the server is trying to send me all this messages?
How can I avoid this issue?

Balance call fails

Hi,

Since today, when i call balance it fails with

{ FetchError: invalid json response body at https://api.blinktrade.com/tapi/v1/message reason: Unexpected token < in JSON at position 0
    at /Users/matthieuachard/Documents/bitcoin/arnaud-bitcoin-trader/node_modules/node-fetch/lib/body.js:48:31
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
  name: 'FetchError',
  message: 'invalid json response body at https://api.blinktrade.com/tapi/v1/message reason: Unexpected token < in JSON at position 0',
  type: 'invalid-json' }

Any idea ?

`onWithdrawRefresh()` doesn't work

The code that watches state change of withdrawals never executes, but the watcher for the specific withdrawals does.

// this doesn't ever execute
blinktrade.onWithdrawRefresh(function(withdraw) {
  console.log(withdraw);
});

// this works for `new` and `cancelled` withdrawals
blinktrade.requestWithdraw({
    "amount": parseInt(1200 * 1e8),
    "currency": "PKR",
    "method": "BankIslami",
    "data": {
        "AccountName": "A Girl Is No One",
        "AccountNumber": "123477",
    }
}).on('WITHDRAW_REFRESH', function(withdraw) {
    console.log(withdraw);
});

Make REST API Stable

I totally understand this isn't a priority for you guys so I'm only creating this to be notified when the API becomes stable.

Since there's only a stable nodejs client for the websockets API, I'm using it to create an HTTP API service for my internal use and would love to know when the stable API is out so that I can switch to it.

Please close this issue whenever the REST endpoints become stable πŸ‘

UnhandledPromiseRejectionWarning: Unhandled promise rejection

blinktrade.connect().then(function() {
	return blinktrade.login({ username: config.key, password: config.password });
}).then(function(logged) {
	console.log("Connected BlinkTradeWS")
})

My node is v8.9.4 and npm 5.6.0, and I am using the latest version of BlinkTrade, when I was running the code, i got the error as shown below.

(node:9502) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): undefined
(node:9502) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

New API info

Hi, is there some news about new Foxbit API for multiple currencies?
Can you give us an feedback?
Thanks

subscribeToOrderbook returning undefined values (WebSocket API)

I receive callbacks from the subscription, but It returns orders with undefined values, so it's impossible to update my orderbook.

Examples:
delete Order: { index: 3,
price: NaN,
size: NaN,
side: 'sell',
userId: undefined,
orderId: undefined,
symbol: 'BTCBRL',
time: 'Invalid Date',
type: 'OB:DELETE_ORDER' }

delete order thru: { index: 1,
price: NaN,
size: NaN,
side: 'buy',
userId: undefined,
orderId: undefined,
symbol: 'BTCBRL',
time: 'Invalid Date',
type: 'OB:DELETE_ORDERS_THRU' }

Invalid broker

I'm trying to connect via websocket to see data from froxbit (BROKER ID = 4) but I'm facing an error:
image

What happened? I looked at blinktrade docs and I saw the Foxbit name with a scratched...
image

Did something happen with foxbit api? thanks for your help

Post only orders

Hi,

Can I ensure I do post only ?
Currently I send TimeInForce='P' but I do see fees on VBTC which is supposed to have no maker fees.

Thank you

Wrong fiat balance

The REST API seem to be returning the wrong fiat balance.
Currently I have 0 BRL and 0 BTC at FoxBit (4), but when asking the REST API for my balance:

let BlinkTradeRest = require('blinktrade').BlinkTradeRest;

let rest = new BlinkTradeRest({
  prod: true,
  key: 'mykey',
  secret: 'mysecret',
  currency: 'BRL',
  brokerId: 4
});

rest.balance().then(function(balance) {
  console.log(balance);
});

I get this:

{ '4': { BTC_locked: 0, BRL: 233915, BTC: 0, BRL_locked: 0 },
  MsgType: 'U3',
  ClientID: 123456,
  BalanceReqID: 123456,
  Available: { BRL: 233915, BTC: 0 } }

233915 BRL! Am I richer than I thought?! πŸ˜›

REST Api returning Wrong Value

I'm using the REST Api with C++ application that I`m developing, but the rest API is returning the wrong value.
For example, if I request this url "https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC" I receive this response:
{"high": 64800.0, "vol": 1626.534244, "buy": 54800.11, "last": 54800.1, "low": 49000.0, "pair": "BTCBRL", "sell": 54849.99, "vol_brl": 95239499.81959416}.
But, if I enter on foxbit website, the cotation is between 49999 and 50000.
The same happens with the order book.
What is wrong?

Server error 500 shows SQLite error message

I managed to get a server error 500 while canceling an order using BlinkTradeRest.cancelOrder() and got a SQLite message of the error in the Description field instead of a user-friendly message.

Example:

let BlinkTradeRest = require("blinktrade").BlinkTradeRest;

let blinktrade = new BlinkTradeRest({
    prod: true,
    key: MY_KEY,
    secret: MY_SECRET,
    currency: "BRL"
});

blinktrade.cancelOrder({
    orderID: 0, clientId: 0 // or null, undefined, []
})
.then((order) => {
    console.log(order);
})
.catch((err) => {
    console.error(err);
});

Confirmation Withdraw

Hello

When I make a withdrawal request through WebSocket it asks me for the secondFactor since I have activated it in my account, and for Rest it sends me an email with a code to confirm.
There is no way you do not need any code to confirm the withdrawals, as an example in other exchanges that if they enable the API service they do not need confirmation?

Unhandled error: ENOTFOUND stunserver.org

A script that was working perfectly before just started throwing errors.

$ node index.js
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo ENOTFOUND stunserver.org
    at errnoException (dns.js:27:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:78:26)

The index.js file only contains the following lines:

// Setup BlinkTrade
var BlinkTrade = require('blinktrade');
var BlinkTradeWS = BlinkTrade.BlinkTradeWS;
var blinktrade = new BlinkTradeWS({
    prod: true
});

Know if a trade has been done as taker

Hi,

Is the AggressorIndicator flag present in the report when a fill happen ?
If not how can I know if the trade was done as a taker or a maker ?

Thx

Add Access-Control-Allow-Origin to response headers

I'm building an web app that consumes BTC prices from exchanges from Brazil. Since I don't need everything inside blinktrade package and browsers need things lean and slim, I'd like to make a simple XHR cross domain request to fetch ticker prices. The problem is Access-Control-Allow-Origin response header is missing, throwing an error in the console:

Failed to load https://api.blinktrade.com/api/v1/BRL/ticker: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Do you have plans to support this header on public API responses?

[Question] ExecutionReport not working

Hi guys,

i'm trying to subscribe into ExecutionReport from your WS API but the callbacks never return any response, even if i go to the exchange site and perform the operations manually. I'm wondering if it is a new issue or it is something related to my particullar broker (Foxbit).

The package version being used is: 0.1.0-beta.4 (Latest)

Do you know if there is other users with the same issue?

Just for peace of mind, below you can find sample code extracted from my original source.

If you need any other information, let me know. I really apreciatte any relevant information about the topic. Thanks in advance.

import { BlinkTradeWS , BlinkTradeRest } from "blinktrade";

export class FoxbotConfig
{
    userName : string = 'SUPER_SECRET_TOKEN';
    password : string = 'TOKEN_PASSWORD';
    symbol : string =  'BTCBRL';
    brokerId: number = 4;
}

export class Foxbot
{    
    private blinktrade : any;
    private loginInfo : any;

    constructor(private _config : FoxbotConfig)
    {
        this.blinktrade = new BlinkTradeWS({ 
            prod: true , 
            brokerId : _config.brokerId  
        });

        this.loginInfo = { 
            username: this._config.userName, 
            password: this._config.password , 
            brokerId : _config.brokerId 
        };
    }

    public Start()
    {
        // Opens WS API Connection
        this.blinktrade.connect()
        // Logs In the exchange 
        .then(x => { return this.blinktrade.login(this.loginInfo) })
        .then(info => { console.log(info) })
        // Start sending HeartBeats to keep connection alive
        .then(x => { this.HeartBeat(); })
        // Execute Test Operations
        .then(x => { this.Test() })
        // Catch any error if it occurs
        .catch(err => 
        { 
            console.log('Error:');
            console.log(err);
        });
    }

    public Test()
    {
        this.blinktrade.executionReport()
        .on("EXECUTION_REPORT:NEW", o => { console.log(1); })
        .on("EXECUTION_REPORT:PARTIAL", o => { console.log(2); })
        .on("EXECUTION_REPORT:EXECUTION", o => { console.log(3); })
        .on("EXECUTION_REPORT:CANCELED", o => { console.log(4); })
        .on("EXECUTION_REPORT:REJECTED", o => { console.log(5); });

        setTimeout(() => {

            console.log('CREATING BUY ORDER');
            this.CreateBuyOrder(1000, 0.001 , true).then(x =>
            {
                console.log('BUY ORDER CREATED')
                this.CancelOrder(x['OrderID'] , x['ClOrdID'])
                .then(y => { console.log('BUY ORDER CANCELLED') });
            });
    
        }, 3000);

        setTimeout(() => {
            
            console.log('CREATING SELL ORDER');
            this.CreateSellOrder(100000, 0.001 , true).then(x =>
            {
                console.log('SELL ORDER CREATED')
                this.CancelOrder(x['OrderID'] , x['ClOrdID'])
                .then(y => { console.log('SELL ORDER CANCELLED') });
            });

        }, 6000);
    }

    private HeartBeat()
    { 
        let i = setInterval( x => { 
            console.log('HEART BEAT ...');
            this.blinktrade.heartbeat(); 
        }  , 5000);
    }

    // Creates an BUY Order
    private CreateBuyOrder(reais: number , btc : number, isRealValue : boolean = false)
    {
        let x = parseInt((isRealValue ?  reais * 1e8 : reais ).toFixed(0));
        let y = parseInt((isRealValue ? btc * 1e8 : btc).toFixed(0));
        
        return this.blinktrade.sendOrder({
        "side": "1",
        "price": x,
        "amount": y,
        "symbol": this._config.symbol
        });
    }

    // Creates an SELL Order
    private CreateSellOrder(reais: number , btc : number , isRealValue : boolean = false)
    {
        let x = parseInt((isRealValue ? reais * 1e8 : reais).toFixed(0));
        let y = parseInt((isRealValue ?  btc * 1e8 : btc).toFixed(0));

        return this.blinktrade.sendOrder({
        "side": "2",
        "price": x,
        "amount": y,
        "symbol": this._config.symbol
        });
    }

    private CancelOrder(orderId:number , orderClientId)
    {
        let x = { orderID: orderId, clientId: orderClientId }
        return this.blinktrade.cancelOrder(x);
    }
}

// ------------------------------------------------------------------------------
let bot = new Foxbot(new FoxbotConfig());
bot.Start();

WebSocket API not working

I am trying generate new btc deposit address but its giving me error.
What I am doing wrong ?
Thanks

bl
bl1

Cannot convert undefined or null to object

Hello all,
I am calling blinktrade.balance() and this error is thrown:

TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at /home/uli/Projetos/blinktrade_tests/node_modules/blinktrade/lib/baseTransport.js:91:18
    at process._tickCallback (internal/process/next_tick.js:109:7)

Anyone else having this problem? Is this an error in the SDK or I am just missing something?

Response No JSON object could be decoded

Hello guys, I am trying to make a request, but I have not had any success, I always send my fix in Json format but I always get the same answer, how can I solve this?

The small code is written in php using the laravel framework 5.4.3

    $nonce = strval(time());
    $signature = hash_hmac("sha256", $nonce, $this->secret); 
    $array = [
        "MsgType" => "U2",
        "BalanceReqID" => 1,
    ];
    $message = json_encode($array);
    $client = new \GuzzleHttp\Client(array( "curl" => array(CURLOPT_SSL_VERIFYPEER => false)));
    $response = $client->request(
                "POST", "https://api.testnet.blinktrade.com/tapi/v1/message", [
                    'headers' => [
                        "User-Agent" => "testing/1.0",
                        "Content-Type"     => "application/json",
                        "Nonce"      => $nonce,
                        "Signature" => $signature,
                        "APIKey" => $this->key
                    ]
                ],  $message

    );
    $response = json_decode($response->getBody()->getContents());
    return  response()->json($response);   

Thank you very much for your help

Public REST API returning Content-Type: text/html

The server is returning header Content-Type: text/html instead of Content-Type: application/json for Ticker and Trades public REST API.

See:

curl --head 'https://api.blinktrade.com/api/v1/BRL/ticker'
curl --head 'https://api.blinktrade.com/api/v1/BRL/trades'

Trade api sendOrder creates the orders but response of promise don't comes.

Hi,

Because I can't use the testnet platform I trying some tests in production.

I guess when I'm create the order the promise should responds with OrdStatus: New, but nothing hapens.

My order enter in the order book but my code doesn't receive any response or errors it simple stucks.

opera instantaneo_2017-10-27_023152_foxbit exchange

Follow the section of the code:

const BlinkTradeWS = require("blinktrade").BlinkTradeWS;
  let prod = true
  let blinktrade = new BlinkTradeWS({ prod: prod });
//
// I'm abreviated the code to
//... connect ...
//.. login
//..

let options = { 
  msgType: 'D',
  side: '2', //sell
  price: (30000 * 1e8).toFixed(0), //R$ 30000
  amount: (0.0001 * 1e8).toFixed(0), // 0.0001
  brokerID: '4', //foxbit
  symbol: 'BTCBRL',
  ordType: '2', // limited
  clOrdID: '1' 
}

 blinktrade.sendOrder(options).then(function(order) {
           console.log(order); // this code doesn't executes
       }).catch(function(...args){
           console.log(args); //this code doesn't executes too
       });

`

Include example of WITHDRAW_REFRESH

Hello

Can you please provide an example of WITHDRAW_REFRESH

  • Does this event fire upon both a pending and successful withdrawal?
  • Is the schema different for BTC and FIAT?
  • Is the schema different for different brokers?

Making an app, only pieces left to automate are trading and withdrawals πŸ˜„

Not working with create-react-app

I am trying to use the sdk in a pwa app created with create-react-app, but I'm getting those errors after yarn add blinktrade

The version installed of the sdk is 0.0.7

Error in ./~/blinktrade/lib/util/stun.js
Module not found: 'dgram' in /media/dados/workspace/pwa-experiment/node_modules/blinktrade/lib/util

 @ ./~/blinktrade/lib/util/stun.js 37:13-29

Error in ./~/macaddress/lib/windows.js
Module not found: 'child_process' in /media/dados/workspace/pwa-experiment/node_modules/macaddress/lib

 @ ./~/macaddress/lib/windows.js 1:11-35

Error in ./~/macaddress/lib/linux.js
Module not found: 'child_process' in /media/dados/workspace/pwa-experiment/node_modules/macaddress/lib

 @ ./~/macaddress/lib/linux.js 1:11-35

Error in ./~/macaddress/lib/unix.js
Module not found: 'child_process' in /media/dados/workspace/pwa-experiment/node_modules/macaddress/lib

 @ ./~/macaddress/lib/unix.js 1:11-35

Websocket disconnects me sometimes

Hi,

it seems like the websocket disconnects me when the rate of the commands i send is too high.
However I remain under the documented limit (12 instead of 16)
Or is it because of something else ?

Thx

How do I fetch order by OrderId?

Hello, I've noticed that the execution report doesn't seem to show the settlement price, e.g.:

{ OrderID: 1459146238526, 
  ExecID: 566318, 
  ExecType: '2', 
  OrdStatus: '2', 
  CumQty: 1254716, 
  Symbol: 'BTCPKR', 
  OrderQty: 1254716, 
  LastShares: 1254716, 
  LastPx: 7851100000000, 
  Price: 100000000, 
  TimeInForce: '1', 
  LeavesQty: 0, 
  MsgType: '8', 
  ExecSide: '2', 
  OrdType: '2', 
  CxlQty: 0, 
  Side: '2', 
  ClOrdID: 4743461, 
  AvgPx: 7851100000000 } 

Is there anyway for me to lookup a specific order status by OrderID? The current myOrders method returns a list of orders, and it's paginated by 40 orders each. I can't use that since if over 40 of my orders are executed near simultaneously, the list will not contain them.

MSG_LOGIN_ERROR_INVALID_USERNAME_OR_PASSWORD

Hi.
Im experiencing some problems trying to login with WS, returning MSG_LOGIN_ERROR_INVALID_USERNAME_OR_PASSWORD. The strange thing is, minutes after this error, I'll look at my API keys registered, and its no-more available!
My impression is that after some failed attempts, the KEY is removed.

Can you help?
(Of course I'm using a valid API key, it was working fine until today.)
Response:
{"Username": "APIKEY***", "NeedSecondFactor": false, "UserStatusText": "MSG_LOGIN_ERROR_INVALID_USERNAME_OR_PASSWORD", "SecondFactorType": null, "UserReqID": 1530032211, "UserStatus": 3, "MsgType": "BF"}

EDIT
My mistake, closing...

TakerTransactionFeeBuy value

Hello,

For exemple Vbtc returns TakerTransactionFeeBuy: 25
By how much should I divide to get the percentage between 0 and 1 ? in other words, actual fee is 0.025 or 0.0025 ?

Thank you

Add documentation on rate limit

I just hit Error: 16 messages in the last second Too many messages per second this should totally be included in the documentation ;)

Balance requests always return SyntaxError in JSON

When I run the code below to request the balance,
blinktrade.balance({ MsgType: "U2", BalanceReqID: 1 }).then(function(balance) { console.log(balance); });

I always receive the following error message:
SyntaxError: Unexpected token ? in JSON at position 0

Also, the request only does NOT return the error below after a few tries (normally 'works' on second try):
> Error: Error: U2 Not authorized at BlinkTradeWS.onMessage (C:\Users\.....\blinktrade\lib\wsTransport.js:164:15) at WebSocket.onMessage (C:\Users\.....\ws\lib\EventTarget.js:99:16) at emitOne (events.js:116:13) at WebSocket.emit (events.js:211:7) at Receiver._receiver.onmessage (C:\Users\.....\ws\lib\WebSocket.js:141:47) at Receiver.dataMessage (C:\Users\.....\ws\lib\Receiver.js:389:14) at Receiver.getData (C:\Users\.....\ws\lib\Receiver.js:330:12) at Receiver.startLoop (C:\Users\.....\ws\lib\Receiver.js:165:16 ) at Receiver.add (C:\Users\.....\ws\lib\Receiver.js:139:10) at TLSSocket._ultron.on (C:\Users\.....\ws\lib\WebSocket.js:138:22)

But that isn't the trouble. Even when I get past it, I can't find a way to read (balance).
Is there a way I can remove the "?" ? Some method? Something I'm missing?
By the way, I'm running the code on Node.js. Could it have something to do with it?
I don't think so, but who knows?
I don't recall doing anything different than the examples given in the docs.
Every other kind of request or operation I did worked. The account at hand has zero balance and is in the testnet.

Thanks.
Sorry people. I found a way to make balance work. I still don't understand very well how everything happened, but all is fine now.

withdraw from API key

Maybe something is wrong with BTC withdrawals from websocket API.
My test was done with Python and testnet (https://testnet.blinktrade.com/).
API key / pass / secret was created with user "user" with password described in home page.
After successful logon in websocket with message "BE" / "BF", I send "B6" message:

{"MsgType": "U6", "WithdrawReqID": 314, "Method": "bitcoin", "Amount": 100086099, "Currency": "BTC", "Data": {"Wallet": "173D1zQQyzvCCCek9b1SpDvh7JikBEdtRJ", "Memo": "Testnet saque BTC"}}

API always answer with "Not Authorized" message:

{"Request": {"Origin": "https://testnet.blinktrade.com", "GatewayID": "demo-1:ws_gateway_8443", "Currency": "BTC", "Amount": 100086099, "RemoteIP": "<sanitized_IPV6>", "WithdrawReqID": 314, "Data": {"Wallet": "173D1zQQyzvCCCek9b1SpDvh7JikBEdtRJ", "Memo": "Testnet saque BTC"}, "Method": "bitcoin"}, "MsgType": "ERROR", "Description": "Not authorized", "Detail": "U6"}

Thanks in advance!

BE not authorized

Hi guys,

i'm running a program using your api and eventually i get an error with the message "BE not authorized". I really don't know what the error means, cause the message doesn't say to much about the root cause (At least to me ). Do you know anything about? I could just write some code to retry/restart the the process, but a really want to know if i'm doing something wrong related to the api usage instead write a lot more code to just "workaround" the situation.

Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.