Coder Social home page Coder Social logo

node-bitstamp's Introduction

node-bitstamp

bitstamp REST and WS API Node.js client ๐Ÿ’ต

README Overview

Offers

  • version 1 and version 2 of the bistamp REST API
  • supports all new api endpoints
  • 100% promise based
  • optional full control of response status and headers
  • all bitstamp currencies available: Bitcoin, Ethereum, Litecoin, Ripple, XRP
  • also implements the websocket API v2 to listen for live trade, order book and live order events
  • streams reconnect automatically and respect Forced reconnection via bts:request_reconnect
  • takes care of signature and nonce automatically
  • takes care of max. request quotas automatically (prevents bans)
  • install via npm i node-bitstamp or yarn add node-bitstamp

Example

  • you can find a runnable api example here, run via yarn example:api
  • you can find a runnable stream example here, run via yarn example:stream
"use strict";

const {BitstampStream, Bitstamp, CURRENCY} = require("node-bitstamp");

//printing available currencies
console.log(CURRENCY);

/* STREAMS */
// @ https://www.bitstamp.net/websocket/v2/

// Live trades
const bitstampStream = new BitstampStream();

/*
    as the stream is re-usable (subscribe to multiple currencies and channel types)
    every subscribe actions returns a channel name, which is the actual event you
    can listen to after subscription
*/

bitstampStream.on("connected", () => {
    const ethEurTickerChannel = bitstampStream.subscribe(bitstampStream.CHANNEL_LIVE_TRADES, CURRENCY.ETH_EUR);
    bitstampStream.on(ethEurTickerChannel, ({ data, event }) => {
        console.log(data);
        /* e.g.
            { 
                amount: 0.01513062,
                buy_order_id: 297260696,
                sell_order_id: 297260910,
                amount_str: '0.01513062',
                price_str: '212.80',
                timestamp: '1505558814',
                price: 212.8,
                type: 1,
                id: 21565524,
                cost: 3.219795936
            }
        */
    });
});
bitstampStream.on("disconnected", () => {});

// Live orderBook updates
bitstampStream.on("connected", () => {
    const btcEurOrderBookChannel = bitstampStream.subscribe(bitstampStream.CHANNEL_ORDER_BOOK, CURRENCY.BTC_EUR);

    bitstampStream.on(btcEurOrderBookChannel, ({ data, event }) => {
        console.log(data);
        /* e.g.
            { bids:
            [ 
                [ '3284.06000000', '0.16927410' ],
                [ '3284.05000000', '1.00000000' ],
                [ '3284.02000000', '0.72755647' ],
                .....
            ],
            asks:
            [ 
                [ '3289.00000000', '3.16123001' ],
                [ '3291.99000000', '0.22000000' ],
                [ '3292.00000000', '49.94312963' ],
                .....
            ] }
        */
    });
});

bitstampStream.on("error", (e) => console.error(e));

bitstampStream.close();

/* REST-API */
// @ https://www.bitstamp.net/api/

// @ https://www.bitstamp.net/account/login/
// To get an API key, go to "Account", "Security" and then "API Access". 
// Set permissions and click "Generate key"
// Dont forget to active the key and confirm the email.
const key = "abc3def4ghi5jkl6mno7";
const secret = "abcdefghijklmno";
const clientId = "123123";

const bitstamp = new Bitstamp({
    key,
    secret,
    clientId,
    timeout: 5000,
    rateLimit: true //turned on by default
});

const run = async () => {

    /*
        Every api function returns a bluebird promise.
        The promise only rejects on network errors or timeouts.
        A successfull promise always resolves in an object containing status, headers and body.
        status is the http status code as number, headers is an object of http response headers
        and body is the parsed JSON response body of the api, you dont need to parse the results
        yourself you can simply continue by accessing the object.
    */

    /* PUBLIC */
    const ticker = await bitstamp.ticker(CURRENCY.ETH_BTC).then(({status, headers, body}) => console.log(body));
    await bitstamp.tickerHour(CURRENCY.ETH_BTC);
    await bitstamp.orderBook(CURRENCY.ETH_BTC);
    await bitstamp.transactions(CURRENCY.ETH_BTC, "hour");
    await bitstamp.conversionRate();

    /* PRIVATE */
    const balance = await bitstamp.balance().then(({body:data}) => data);
    await bitstamp.userTransaction(CURRENCY.ETH_BTC, {offset, limit, sort});

    await bitstamp.openOrders(CURRENCY.ETH_BTC);
    await bitstamp.openOrdersAll();
    await bitstamp.orderStatus(id);
    await bitstamp.cancelOrder(id);
    await bitstamp.cancelOrdersAll();

    await bitstamp.buyLimitOrder(amount, price, currency, limit_price, daily_order);
    await bitstamp.sellLimitOrder(amount, price, currency, limit_price, daily_order);
    await bitstamp.buyMarketOrder(amount, currency);
    await bitstamp.sellMarketOrder(amount, currency);

    await bitstamp.withDrawalRequests(timedelta);
    await bitstamp.bitcoinWithdrawal(amount, address, instant);
    await bitstamp.bchWithdrawal(amount, address);
    await bitstamp.litecoinWithdrawal(amount, address);
    await bitstamp.ethereumWithdrawal(amount, address);
    await bitstamp.rippleWithdrawal(amount, address, currency);
    await bitstamp.xrpWithdrawal(amount, address, destination_tag);

    await bitstamp.bitcoinDepositAdress().then(({body}) => console.log(body));
    await bitstamp.bchDepositAdress().then(({body}) => console.log(body));
    await bitstamp.litecoinDepositAdress().then(({body}) => console.log(body));
    await bitstamp.ethereumDepositAdress().then(({body}) => console.log(body));
    await bitstamp.rippleDepositAdress().then(({body}) => console.log(body));
    await bitstamp.xrpDepositAdress().then(({body}) => console.log(body));

    await bitstamp.unconfirmedBitcoinDeposits();
    await bitstamp.transferSubToMain(amount, currency, subAccount);
    await bitstamp.transferMainToSub(amount, currency, subAccount);

    await bitstamp.openBankWithdrawal(/* {..} */);
    await bitstamp.bankWithdrawalStatus(id);
    await bitstamp.cancelBankWithdrawal(id);

    await bitstamp.newLiquidationAddress(currency);
    await bitstamp.liquidationAddressInfo(address);
};

run().then(() => {
    console.log(bitstamp.getStats());
    bitstamp.close();
});

Debug Info

DEBUG=node-bitstamp:* npm start

A word on parallel requests

  • The client will never generate the same nonce for two requests.
  • But a new request must always contain a higher nonce, than the last request before.
  • When you make multiple calls in parallel (pretty easy in node..) there is a chance that the later calls reach the bitstamp api earlier than the first, causing the first requests to fail with an invalid nonce error.
  • To prevent this you should make these calls sequentially.
  • Besides chaining promises, this is another way to do it:
const async = require("async"); // npm i async or yarn add async

async.series([
    cb => bitstamp.bitcoinDepositAdress()
        .then(r => cb(null, "BTC: " + r.body)).catch(e => cb(e)),
    cb => bitstamp.ethereumDepositAdress()
        .then(r => cb(null, "ETH: " + r.body.address)).catch(e => cb(e)),
    cb => bitstamp.litecoinDepositAdress()
        .then(r => cb(null, "LTC: " + r.body.address)).catch(e => cb(e))
], (error, data) => {

    if(error){
        return console.error(error);
    }

    console.log(data); // [ "BTC: ..", "ETH: ..", "LTC: .." ]
});

License

MIT

node-bitstamp's People

Contributors

adityamertia avatar alinlacea avatar bitbitmap avatar danielgelling avatar electic avatar ilirhushi avatar jgordor avatar knskan3 avatar krystianity avatar nicolasgarnier avatar qbkjovfnek avatar sevenindirecto 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-bitstamp's Issues

improper handling of errors

For some reason Bitstamps returns the error below:

{
  "status": 403,
  "headers": { },
  "body": {
    "status": "error",
    "reason": "Invalid signature",
    "code": "API0005"
  }
}

It is expected to have the result returned as an error and be passed to catch, however it is resolved as successful and passed to then

The library does not work on the latest version of node

The library does not work on the latest version of node

node -v
v12.6.0

node index.js
i got this error:

Error: Parse Error
at TLSSocket.socketOnData (_http_client.js:452:22)
at TLSSocket.emit (events.js:203:13)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at TLSSocket.Readable.push (_stream_readable.js:210:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:166:17) {
bytesParsed: 480,
code: 'HPE_INVALID_HEADER_TOKEN',
reason: 'Invalid header value char'
}

This is the temporary workaround for executing the code:

node --http-parser=legacy index.js

invalid nonce error

Hi,
I am getting error:
{"status": "error", "reason": "Invalid nonce", "code": "API0004"}
when i try to call 2 API calls at once. Even if i do it at interval of 100ms apart still i get this error sometimes.
As far as quoted by the library, nonce is taken care by library itself, then why should it happen.
Following is the code called in parallel:

const run = async () => {
      var balance = await bitstampBalance();
      ltcBalanceBts = parseFloat(balance.ltc_balance);
      //logger.info(`BTS Balance: LTC: ${balance.ltc_balance}, BTC: ${balance.btc_balance}`);
    };
    run().then(() => {})

Error:

(node:27758) UnhandledPromiseRejectionWarning: Error: With body: {"status": "error", "reason": "Invalid nonce", "code": "API0004"}
4|tradeCom |     at Request.request [as _callback] (/home/ec2-user/crypto_arbitrage_latest/bitstamp_bothside/node_modules/node-bitstamp/lib/Bitstamp.js:107:35)
4|tradeCom |     at Request.self.callback (/home/ec2-user/crypto_arbitrage_latest/bitstamp_bothside/node_modules/request/request.js:186:22)
4|tradeCom |     at Request.emit (events.js:160:13)
4|tradeCom |     at Request.<anonymous> (/home/ec2-user/crypto_arbitrage_latest/bitstamp_bothside/node_modules/request/request.js:1163:10)

As mentioned in the library there can still be a chance that nonce error can be generated if two calls fall at same timestamp. Does this mean there is no chance of calling 2 API in parallel in bitstamp?
If i have to call 2 APIs at once i can still do that using async.series but if the APIs are called from different parts of the code which happened to be called at once, bitstamp library should take care of nonce (is what my understanding is) which isn't happening.

order status check via API throws error

Hi,
Whenever i check for an orders status using
await bitstamp.orderStatus(orderId).then(({status, headers, body}) => body);
I keep getting following error even if i run it at 5 sec intervals:

(node:879) UnhandledPromiseRejectionWarning: Error: Must not exceed 60 calls per 60000 ms.
13|tradeBi |     at Promise (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/node-bitstamp/lib/Bitstamp.js:85:31)
13|tradeBi |     at Promise._execute (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/bluebird/js/release/debuggability.js:303:9)
13|tradeBi |     at Promise._resolveFromExecutor (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/bluebird/js/release/promise.js:483:18)
13|tradeBi |     at new Promise (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/bluebird/js/release/promise.js:79:10)
13|tradeBi |     at Bitstamp.call (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/node-bitstamp/lib/Bitstamp.js:79:16)
13|tradeBi |     at Bitstamp.orderStatus (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/node-bitstamp/lib/Bitstamp.js:218:21)
13|tradeBi |     at checkOrderStatus (/home/ec2-user/crypto_arbitrage_latest/bitstamp/tradeBitstamp.js:195:36)
13|tradeBi |     at Timeout._onTimeout (/home/ec2-user/crypto_arbitrage_latest/bitstamp/tradeBitstamp.js:90:31)
13|tradeBi |     at ontimeout (timers.js:458:11)
13|tradeBi |     at tryOnTimeout (timers.js:296:5)
13|tradeBi |     at Timer.listOnTimeout (timers.js:259:5)
13|tradeBi | (node:879) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 41)

Its run 15 times in 60000ms still i get this error. what could be wrong here?

API respose error lost in catch()

I'm triggering an API response error by having more than 8 decimals in my marketBuy call, and I noticed the catch() call in the promise returns unusable info:
screenshot 2018-12-03 at 13 24 33

Debugging the stack trace leads me to this:
screenshot 2018-12-03 at 13 22 00

The information is there, can't we just reject(body.reason)?

The new Error seems redundant, and prevents the info being passed back to the caller, meaning the root cause can't be pinned/logged without debugging this module.

BTC_USD Not working

It's not pulling the info for BTC_USD

`// Live trades
const tickerStream = new TickerStream();
const tickerTopic = tickerStream.subscribe(CURRENCY.BTC_USD);
const tickerTopicTwo = tickerStream.subscribe(CURRENCY.ETH_USD);

/*
as tickers are re-usable (subscribe to multiple currencies)
every subscribe actions returns a topic name, which is the actual event you
can listen to after subscription
*/

tickerStream.on("connected", () => {
console.log("Connected");
});
tickerStream.on("disconnected", () => {
console.log("Disconnect");
});

/*
sadly pusher-js does not really expose errors in an acceptable manner
therefore you will have to trust its automatic re-connect handling
in case of disconnections and network errors
*/

tickerStream.on(tickerTopic, data => {
console.log(data);
console.log("============New Data==========");
/* e.g.
{
amount: 0.01513062,
buy_order_id: 297260696,
sell_order_id: 297260910,
amount_str: '0.01513062',
price_str: '212.80',
timestamp: '1505558814',
price: 212.8,
type: 1,
id: 21565524,
cost: 3.219795936
}
*/
});`

works with ETH_EUR

Empty error

Very often when there is an error, the promise returns an empty error, but never happened to me before.
Is it Bitstamp side or might it be in this:
if (response.statusCode < 200 || response.statusCode > 299) { return reject(new Error(body)); }
where body is empty and the error is in another field?

Can't use the PRIVATE part of api

UnhandledPromiseRejectionWarning: TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
at Function.Buffer.from (buffer.js:183:11)
at new Buffer (buffer.js:158:17)
at Signature._createSignature (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/lib/Signature.js:52:52)
at Signature.signBody (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/lib/Signature.js:75:41)
at Bitstamp._getOptions (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/lib/Bitstamp.js:68:39)
at Promise (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/lib/Bitstamp.js:90:34)
at Promise._execute (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/node_modules/bluebird/js/release/debuggability.js:313:9)
at Promise._resolveFromExecutor (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/node_modules/bluebird/js/release/promise.js:488:18)
at new Promise (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/node_modules/bluebird/js/release/promise.js:79:10)
at Bitstamp.call (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/lib/Bitstamp.js:79:16)
at Bitstamp.balance (/Users/justinnothling/Code/nibit/node_modules/node-bitstamp/lib/Bitstamp.js:198:21)
at test (/Users/justinnothling/Code/nibit/bitesting.js:23:36)
at Object. (/Users/justinnothling/Code/nibit/bitesting.js:40:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)

Error not thrown properly by node-bitstamp

Hi,
This seems to be a regression from the latest changes done 2 days back. Kindly confirm. I am getting following errors if there is insufficient balance.

13|tradeBi | (node:12851) UnhandledPromiseRejectionWarning: Error: [object Object]
13|tradeBi |     at Request.request [as _callback] (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/node-bitstamp/lib/Bitstamp.js:115:35)
13|tradeBi |     at Request.self.callback (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/request/request.js:186:22)
13|tradeBi |     at Request.emit (events.js:160:13)
13|tradeBi |     at Request.<anonymous> (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/request/request.js:1163:10)
13|tradeBi |     at Request.emit (events.js:160:13)
13|tradeBi |     at IncomingMessage.<anonymous> (/home/ec2-user/crypto_arbitrage_latest/bitstamp/node_modules/request/request.js:1085:12)
13|tradeBi |     at Object.onceWrapper (events.js:255:19)
13|tradeBi |     at IncomingMessage.emit (events.js:165:20)
13|tradeBi |     at endReadableNT (_stream_readable.js:1101:12)
13|tradeBi |     at process._tickCallback (internal/process/next_tick.js:152:19)
13|tradeBi | (node:12851) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)

@krystianity @nicolasgarnier kindly confirm.

Bitcoin withdrawal

The third parameter for instant bitcoin withdrawal needs to be an integer.

Instant parameter needs to be an integer (0 - false or 1 - true)

The current default is false.

Ripple_withdrawal

ripple withdrawal returns: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
I wasn't able to debug, since it seems correct.

bitstamp.sellMarketOrder() - anyone else noticed this sometimes doesn't sell 100%?

Bit of a vague question, has anyone noticed that sellMarketOrder doesn't always sell 100% of the desired amount?

Pseudo-example:

var amount = 5000;
var asset = "xrpeur";

console.log(`Selling ${amount}`);
bitstamp.sellMarketOrder(amount, asset)
  .then(orderResponse => logicToSumAmountSoldFromAPIResponse(orderResponse))
  .then(amountSold => console.log(`Sold ${amountSold}`));

It doesn't happen every time, but I've noticed this twice in two or three weeks. The output might look something like:

Selling 5000
Sold 2145

I've eliminated my own logic from the scenario, and even the API response from binance shows the order finished ("status": "Finished") and the fills only partially match what I wanted to sell.

On bitstamp, I see I'm still holding the remaining assets and there's no open order. It just didn't sell everything I wanted it to. Contacted bitstamp support too.

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.