1

我正在使用 CoinGecko API(https://www.coingecko.com/en/api/documentation),但在选择我需要的调用元素时遇到问题。代码如下:

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()

mhccex = cg.get_coin_ticker_by_id(id = 'metahash', exchange_ids='cex')

和输出:

{
  "name": "#MetaHash",
  "tickers": [
    {
      "base": "MHC",
      "target": "BTC",
      "market": {
        "name": "KuCoin",
        "identifier": "kucoin",
        "has_trading_incentive": false
      },
      "last": 1.448e-7,
      "volume": 9588907.27145872,
      "converted_last": {
        "btc": 1.448e-7,
        "eth": 0.00000207,
        "usd": 0.0051756
      },
      "converted_volume": {
        "btc": 1.388474,
        "eth": 19.865387,
        "usd": 49628
      },
      "trust_score": "green",
      "bid_ask_spread_percentage": 1.302262,
      "timestamp": "2022-01-23T12:40:31+00:00",
      "last_traded_at": "2022-01-23T12:40:31+00:00",
      "last_fetch_at": "2022-01-23T12:40:31+00:00",
      "is_anomaly": false,
      "is_stale": false,
      "trade_url": "https://www.kucoin.com/trade/MHC-BTC",
      "token_info_url": null,
      "coin_id": "metahash",
      "target_coin_id": "bitcoin"
    },
    {
      "base": "MHC",
      "target": "USDT",
      "market": {
        "name": "KuCoin",
        "identifier": "kucoin",
        "has_trading_incentive": false
      },
      "last": 0.005182,
      "volume": 8777124.90264143,
      "converted_last": {
        "btc": 1.45387e-7,
        "eth": 0.00000208,
        "usd": 0.00519658
      },
      "converted_volume": {
        "btc": 1.276079,
        "eth": 18.257313,
        "usd": 45611
      },
      "trust_score": "green",
      "bid_ask_spread_percentage": 0.944305,
      "timestamp": "2022-01-23T12:40:30+00:00",
      "last_traded_at": "2022-01-23T12:40:30+00:00",
      "last_fetch_at": "2022-01-23T12:40:30+00:00",
      "is_anomaly": false,
      "is_stale": false,
      "trade_url": "https://www.kucoin.com/trade/MHC-USDT",
      "token_info_url": null,
      "coin_id": "metahash",
      "target_coin_id": "tether"
    },
]
}

我需要访问与代码“目标”相关的“最后一个”字段:USDT。以下代码不起作用,因为每次 API 调用时“代码”的顺序会随机更改:

mhccex = cg.get_coin_ticker_by_id(id = 'metahash', exchange_ids='cex')['tickers'][1]['last']
4

1 回答 1

1

您可以使用在给定列表中filter查找项目:tickerstarget

from pycoingecko import CoinGeckoAPI

cg = CoinGeckoAPI()

mhccex = cg.get_coin_ticker_by_id(id = 'metahash', exchange_ids='cex')['tickers']

results = list(filter(lambda item: item['target'] == 'USD', mhccex))

print(results[0]['last'])

results将是一个列表,但对于任何给定的硬币和货币,大概只有一个交换组合。

于 2022-01-23T13:36:09.953 回答