Ứng dụng dòng lệnh REST API (NodeJS)

Cập nhật lần cuối: 31 thg 12, 2025

Ứng dụng khách dòng lệnh REST API trong NodeJS cho phép truy cập đầy đủ vào Kraken REST API thông qua dòng lệnh (chẳng hạn như Terminal trên macOS), do đó không yêu cầu kiến thức lập trình hoặc kinh nghiệm về API.

Tất cả các tính năng REST API đều có thể truy cập được, bao gồm:

  • điểm cuối dữ liệu thị trường công khai

  • điểm cuối quản lý tài khoản riêng tư

  • điểm cuối giao dịch

  • điểm cuối cấp vốn riêng tư

  • điểm cuối staking riêng tư*

Ứng dụng khách dòng lệnh có thể được sử dụng như một ứng dụng khách API độc lập hoặc có thể được gọi từ các chương trình khác (chẳng hạn như các ngôn ngữ thông dịch khác như tập lệnh Bash hoặc các ngôn ngữ biên dịch như C/C++).

Cài đặt

1. Cài đặt NodeJS (nếu cần).

  • macOS và Linux có thể đã cài đặt NodeJS.

  • Windows có thể chưa cài đặt NodeJS, nhưng có thể cài đặt từ https://www.nodejs.org/.

2. Tải xuống và lưu tệp krakenapi.js vào máy tính của bạn trong thư mục bạn chọn. Ví dụ:

Macintosh HD > Users > Satoshi > KrakenAPI


3. Mở dấu nhắc lệnh (chẳng hạn như Terminal của macOS) và điều hướng đến thư mục đã chọn ở bước trước.

Bạn có thể sử dụng lệnh "cd" (thay đổi thư mục) để điều hướng. Ví dụ:

cd /Users/Satoshi/KrakenAPI


4. Thêm khóa API của bạn vào cùng thư mục nơi bạn đang lưu tệp krakenapi.js.

Sao chép/dán khóa công khai API của bạn từ quản lý tài khoản vào một tệp văn bản thuần túy có tên "API_PUBLIC_KEY".

Sao chép/dán khóa riêng tư (bí mật) API của bạn vào một tệp văn bản thuần túy có tên "API_PRIVATE_KEY".

Chỉ cần khóa API nếu bạn định sử dụng các điểm cuối API riêng tư để truy cập tài khoản Kraken của mình (chẳng hạn như truy vấn số dư, đặt/hủy lệnh, xuất lịch sử tài khoản, v.v.).

Xem Cách tạo cặp khóa API? để biết thêm hướng dẫn.

Lệnh ví dụ

Cách sử dụng ứng dụng khách dòng lệnh REST API như sau:

bash

Bash

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

Mã NodeJS

bash

Bash

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();

*Tổng quan về tiêu chí đủ điều kiện (bao gồm các hạn chế về địa lý) để staking có thể được tìm thấy tại đây.

Bạn cần thêm trợ giúp?