Search code examples
pythonbitcoinnonce

Python bitstamp api invalid nonce error


A python script was running and now it is not.

                public_client = bitstamp.client.Public()

                data=backTestBitCoin.getHistoricalPrices();

                trading_client = bitstamp.client.Trading(username='AAA', key='BBB', secret='CCC')
                tick=trading_client.ticker();

                lastBid = float(tick['bid']);
                lastAsk = float(tick['ask']);
                balances = trading_client.account_balance(); #error thrown from this line

I am getting the following error:

                    return self._post("balance/", return_json=True)
                  File "/Library/Python/2.7/site-packages/bitstamp/client.py", line 47, in _post
                    return self._request(requests.post, *args, **kwargs)
                  File "/Library/Python/2.7/site-packages/bitstamp/client.py", line 80, in _request
                    raise BitstampError(error)
                bitstamp.client.BitstampError: Invalid nonce

Has anyone ever experienced this? Not that familiar with the library therefore not sure what is causing it.


Solution

  • Generating a new api key/secret fixed this problem. I believe it was caused by using a mix of the php api and the python api or the iphone Bitstamp app. I will confirm this suspicion, but the overall solution was to unplug it and plug it back in.


    Abbreviated solution: My issue was coming from using the following php and python libraries,

    php python

    Both are A+ great and easy to use.

    The error is created because of the following discrepancy in their methods of creating the nonce (neither is more "right" in my opinion, just different).

    php:

                    // generate a nonce as microtime, with as-string handling to avoid problems with 32bits systems
                    $mt = explode(' ', microtime());
                    $req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
                    $req['key'] = $key;
                    $req['signature'] = $this->get_signature($req['nonce']);
    

    python:

                    self._nonce = max(int(time.time()), nonce)
    

    Where time.time() gives you: 1403366728.072785 and microtime() gives you: 1403366859731819.

    The solution I put in place is to change the python code to:

    self._nonce = max(int(time.time()*1000000), nonce) and the error is solved.