What is a nonce?

A nonce is a number that uniquely identifies each call to the API. A nonce is required for all calls to the private REST API endpoints, including the account management endpoints (such as Balance, QueryOrders, QueryLedgers, etc.) and the trading endpoints (AddOrder and CancelOrder).

Our nonce is implemented as a counter that must be unique and must increase with each call to the API. For example, assuming a starting nonce of 0, valid subsequent nonce values would be 1, 2, 3, and so on.

While a simple counter would provide a valid nonce, a more usual method of generating valid nonce values is to use a UNIX timestamp in milliseconds (in other words, the number of milliseconds since the 1st of January 1970). Using a high resolution UNIX timestamp for the nonce guarantees that all of the requirements of a valid nonce are met (uniqueness and always increasing), and provides sufficient values for market makers and high frequency traders.

Some examples of generating valid nonce values in different programming languages are as follows:

Python

nonce = str(int(time.time()*1000))

PHP

$nonce explode(' ', microtime());
$request['nonce'] = $nonce[1] . str_pad(substr($nonce[0], 2, 6), 6, '0');

Javascript

let timestamp = (new Date()).getTime();
return timestamp + ('0000' + nonce++).slice(-5);

 

Each API key has a separate nonce, and the nonce value is persistent, so the most recently used nonce will remain the same even if an API key is not used for some time.

Note that it is not possible to reset the nonce for a specific key back to 0. In the event that a nonce value becomes invalid (such as accidentally using a UNIX timestamp far into the future), the solution would be to delete the relevant API key and create a new API key with a new starting nonce value of 0.