For information on changes for our US clients, please visit our Support Center article.

REST API command line client (NodeJS)
The REST API command line client in NodeJS allows full access to the Kraken REST API via the command line (such as Terminal on macOS), hence no programming knowledge or API experience is required.
All REST API features are accessible including:
  • public market data endpoints
  • private account management endpoints
  • trading endpoints
  • private funding endpoints
  • private staking endpoints*
The command line client can be used as a standalone API client, or can be called from other programs (such as other interpreted languages like Bash scripts, or compiled languages like C/C++).

Installation

1. Install NodeJS (if necessary).
  • macOS and Linux probably already have NodeJS installed.
  • Windows probably does not have NodeJS installed, but it can be installed from https://www.nodejs.org/.
2. Download and save the krakenapi.js file to your computer in the folder (directory) of your choosing. For example:
Macintosh HD > Users > Satoshi > KrakenAPI

3. Open a command prompt (such as macOS's Terminal), and navigate to the folder (directory) chosen in the previous step.
You can use the "cd" command (change directory) to navigate. For example:
cd /Users/Satoshi/KrakenAPI

4. Add your API keys to the same folder where you are keeping the krakenapi.js file.
Copy/paste your API public key from account management into a plain text file called "API_PUBLIC_KEY".
Copy/paste your API private (secret) key into a plain text file called "API_PRIVATE_KEY".
An API key is only needed if you plan to use the private API endpoints to access your Kraken account (such as balance inquiries, placing/cancelling orders, account history exports, etc).
See How to generate an API key pair? for additional instructions.

Example Commands

The REST API command line client usage is as follows:
javascript

Javascript

nodejs krakenapi.js endpoint [parameters]

The command line client supports all of the REST API endpoints. Here are a few example commands:

nodejs krakenapi.js Time
nodejs krakenapi.js Ticker pair=xbtusd
nodejs krakenapi.js Trades pair=etheur since=1574067140000000000
nodejs krakenapi.js Balance
nodejs krakenapi.js TradeBalance asset=xbt
nodejs krakenapi.js QueryOrders txid=O7MN22-ZCX7J-TGLQHD
nodejs krakenapi.js AddOrder pair=xbtusd type=buy ordertype=limit price=6500 volume=0.002 leverage=5
nodejs krakenapi.js CancelOrder txid=O7MN22-ZCX7J-TGLQHD

NodeJS Code

javascript

Javascript

const axios = require("axios");
const { clear } = require("console");
const crypto = require("crypto");
const fs = require("fs");

const main = async () => {
  let response = "";
  let apiMethod = "";
  let inputParameters = "";

  const api_private = [
    "Balance",
    "BalanceEx",
    "TradeBalance",
    "OpenOrders",
    "ClosedOrders",
    "QueryOrders",
    "TradesHistory",
    "QueryTrades",
    "OpenPositions",
    "Ledgers",
    "QueryLedgers",
    "TradeVolume",
    "AddExport",
    "ExportStatus",
    "RetrieveExport",
    "RemoveExport",
    "GetWebSocketsToken",
    "AddOrder",
    "AddOrderBatch",
    "EditOrder",
    "CancelOrder",
    "CancelAll",
    "CancelAllOrdersAfter",
    "DepositMethods",
    "DepositAddresses",
    "DepositStatus",
    "WithdrawInfo",
    "Withdraw",
    "WithdrawStatus",
    "WithdrawCancel",
    "WalletTransfer",
    "Staking/Assets",
    "Stake",
    "Unstake",
    "Staking/Pending",
    "Staking/Transactions",
  ];

  const api_public = [
    "Time",
    "Assets",
    "AssetPairs",
    "Ticker",
    "OHLC",
    "Depth",
    "Trades",
    "Spread",
    "SystemStatus",
  ];

  // Destructuring the input command
  if (process.argv.length < 3) {
    apiMethod = "Time";
  } else if (process.argv.length == 3) {
    apiMethod = process.argv[2];
  } else {
    apiMethod = process.argv[2];
    for (count = 3; count < process.argv.length; count++) {
      if (count == 3) {
        inputParameters = process.argv[count];
      } else {
        inputParameters = inputParameters + "&" + process.argv[count];
      }
    }
  }

  // Condition to check the private or public endpoints
  if (api_private.includes(apiMethod)) {
    response = await QueryPrivateEndpoint(apiMethod, inputParameters);

    if (apiMethod == "RetrieveExport") {
      try {
        fs.writeFileSync("Report.zip", response); // write the zip file response
        console.log("Report.zip file successfully received");
      } catch (err) {
        console.log(err);
      }
    } else {
      console.log(response.toString());
    }
  } else if (api_public.includes(apiMethod)) {
    response = await QueryPublicEndpoint(apiMethod, inputParameters);
    console.log(JSON.stringify(response));
  } else {
    console.log("Usage: app method [parameters]");
    console.log("Example: app OHLC pair=xbtusd interval=1440");
  }
};

// Public API Endpoint
async function QueryPublicEndpoint(endPointName, inputParameters) {
  let jsonData;
  const baseDomain = "https://api.kraken.com";
  const publicPath = "/0/public/";
  const apiEndpointFullURL = baseDomain + publicPath + endPointName + "?" + inputParameters;

  await axios
    .get(apiEndpointFullURL)
    .then((res) => {
      jsonData = res;
    })
    .catch((err) => {
      jsonData = err;
    });
  return jsonData.data;
}

// Private API Endpoint
async function QueryPrivateEndpoint(endPointName, inputParameters) {
  const baseDomain = "https://api.kraken.com";
  const privatePath = "/0/private/";

  const apiPublicKey = fs.readFileSync("API_PUBLIC_KEY").toString().trim(); // get data from API_PUBLIC_KEY text file
  const apiPrivateKey = fs.readFileSync("API_PRIVATE_KEY").toString().trim(); // get data from API_PRIVATE_KEY text file

  const apiEndpointFullURL = baseDomain + privatePath + endPointName;
  const nonce = Date.now().toString();
  const apiPostBodyData = "nonce=" + nonce + "&" + inputParameters;

  const signature = CreateAuthenticationSignature(
    apiPrivateKey,
    privatePath,
    endPointName,
    nonce,
    apiPostBodyData
  );
  const httpOptions = {
    headers: { "API-Key": apiPublicKey, "API-Sign": signature },
    responseType: "arraybuffer",
  };

  let jsonData;
  await axios
    .post(apiEndpointFullURL, apiPostBodyData, httpOptions)
    .then((res) => {
      jsonData = res;
    })
    .catch((err) => {
      jsonData = err;
    });

  return jsonData.data;
}

// Authentication algorithm
function CreateAuthenticationSignature(
  apiPrivateKey,
  apiPath,
  endPointName,
  nonce,
  apiPostBodyData
) {
  const apiPost = nonce + apiPostBodyData;
  const secret = Buffer.from(apiPrivateKey, "base64");
  const sha256 = crypto.createHash("sha256");
  const hash256 = sha256.update(apiPost).digest("binary");
  const hmac512 = crypto.createHmac("sha512", secret);
  const signatureString = hmac512
    .update(apiPath + endPointName + hash256, "binary")
    .digest("base64");
  return signatureString;
}

main();
*An overview of eligibility criteria (including geographic restrictions) for On-chain staking can be found here.