gferrin / bitfinex

node.js wrapper for bitfinex cryptocurrency exchange
26 stars 20 forks source link

better nonce generation #7

Closed FredericHeem closed 9 years ago

FredericHeem commented 9 years ago

The current nonce generation could be improved to support more requests per second, the nodejs bitstamp api https://github.com/askmike/bitstamp has a nice implementation:

// if you call new Date to fast it will generate // the same ms, helper to make sure the nonce is // truly unique (supports up to 999 calls per ms). Bitstamp.prototype._generateNonce = function() { var now = new Date().getTime();

if(now !== this.last) this.nonceIncr = -1;

this.last = now; this.nonceIncr++;

// add padding to nonce incr // @link https://stackoverflow.com/questions/6823592/numbers-in-the-form-of-001 var padding = this.nonceIncr < 10 ? '000' : this.nonceIncr < 100 ? '00' : this.nonceIncr < 1000 ? '0' : ''; return now + padding + this.nonceIncr; }

Would you use this implementation ?

gferrin commented 9 years ago

I'm not sure that this is better then what is currently being done. I only use time to initialize the nonce.

this.nonce = Math.ceil((new Date()).getTime() / 1000); 

After which I use always use this function to retrieve a nonce:

Bitfinex.prototype._nonce = function() {
      return ++this.nonce;
};

So no matter how many times you call this function a second, your always guaranteed to get a larger nonce.

Now if your running this process multiple times concurrently using the same API keys with each then you could run into some problems, but that can be solved by either using different API keys or by using redis or something like that to store your nonce value.

FredericHeem commented 9 years ago

Indeed, the issue is caused by using the same api key for the bot in local and pre-prod.