1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

仮想通貨取引所に預けてる資産データを一括で全取得する

Last updated at Posted at 2024-02-04

趣旨

botを作っていると取引所に預けてある自分の資産のデータが必要になることが多いので、全データを一括で取得するためのコードを準備しました。

先物と現物の資産額を取得するためのコードです。先物の部分はまだ用意している段階です。

コード

fetchSpotBalance関数とfetchFuturesBalance関数に分けてコードを書いて、それらの関数を両方ともcheckAllBalances関数に入れています。
こうすることで1つの取引所のリストを代入して引数とするだけですべての現物資産と先物口座の資産が一挙に表示されるようになります。

javascript checkBalances.js
const ccxt = require('ccxt');
const { apiKeys } = require('./configLoader');

async function fetchSpotBalance(exchangeId) {
    const exchangeClass = ccxt[exchangeId];
    const credentials = apiKeys[exchangeId];
    const exchange = new exchangeClass({
        apiKey: credentials.apiKey,
        secret: credentials.secret,
        password: credentials.password,
        enableRateLimit: true
    });

    try {
        const balance = await exchange.fetchBalance();
        console.log(`${exchangeId} Spot Balance:`, balance.total);
        return balance.total;
    } catch (error) {
        console.error(`Failed to fetch spot balance for ${exchangeId}: ${error.message}`);
    }
}

async function fetchFuturesBalance(exchangeId) {
    console.log(`Fetching futures balance is not implemented for ${exchangeId}.`);
}

async function checkAllBalances(exchanges) {
    for (const exchangeId of exchanges) {
        console.log(`Checking balances for ${exchangeId}...`);
        await fetchSpotBalance(exchangeId);
        await fetchFuturesBalance(exchangeId);
    }
}

const exchanges = ['binance', 'bitget', 'bybit'];
checkAllBalances(exchanges);

config設定

config.jsonファイルを読み込むためのプログラムを別ファイルに保存してモジュール化しました。

javascript configLoader.js
const fs = require('fs');

function loadConfig() {
    const configPath = './config.json';
    if (fs.existsSync(configPath)) {
        const configFile = fs.readFileSync(configPath, 'utf8');
        return JSON.parse(configFile);
    } else {
        console.error('Config file not found.');
        return null;
    }
}

const config = loadConfig();
if (!config) {
    console.error('Failed to load config, exiting...');
    process.exit(1);
}

const apiKeys = config.apiKeys.reduce((acc, item) => {
    acc[item.exchange] = item;
    return acc;
}, {});

module.exports = {
    apiKeys: apiKeys,
    loadConfig: loadConfig,
};

実際のconfig.jsonの中身は以下のように記述する必要があります。

config.json
{
  "apiKeys": [
    {
      "exchange": "binance",
      "apiKey": "",
      "secret": ""
    },
    {
      "exchange": "okx",
      "apiKey": "",
      "secret": "",
      "password": ""
    },
    {
      "exchange": "bybit",
      "apiKey": "",
      "secret": ""
    },
    {
      "exchange": "bitget",
      "apiKey": "",
      "secret": "",
      "password": ""
    },
    {
      "exchange": "gate",
      "apiKey": "",
      "secret": ""
    }
  ]
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?