Crypto Portfolio API

加密货币投资组合追踪完整教程 2026

什么是投资组合API?

加密货币投资组合API帮助您追踪多个钱包和交易所的资产,计算总价值、盈亏和资产配置。

价格API

API 免费额度 特点
CoinGecko 10-50次/分钟 免费,最全面
CoinMarketCap 333次/天 专业数据
Binance API 无限制 实时价格

Python投资组合追踪器

import requests
import json

class Portfolio:
    def __init__(self):
        self.holdings = {}
        self.prices = {}
    
    def add_holding(self, symbol, amount):
        """添加持仓"""
        self.holdings[symbol.upper()] = amount
    
    def update_prices(self):
        """更新价格"""
        url = "https://api.coingecko.com/api/v3/simple/price"
        ids = self._get_coingecko_ids()
        params = {
            'ids': ','.join(ids),
            'vs_currencies': 'usd'
        }
        response = requests.get(url, params=params)
        self.prices = response.json()
    
    def get_total_value(self):
        """计算总价值"""
        total = 0
        for symbol, amount in self.holdings.items():
            coin_id = self._get_coingecko_id(symbol)
            if coin_id in self.prices:
                price = self.prices[coin_id]['usd']
                total += amount * price
        return total
    
    def get_allocation(self):
        """获取资产配置"""
        total = self.get_total_value()
        allocation = {}
        for symbol, amount in self.holdings.items():
            coin_id = self._get_coingecko_id(symbol)
            if coin_id in self.prices:
                value = amount * self.prices[coin_id]['usd']
                allocation[symbol] = (value / total) * 100
        return allocation

# 使用示例
# portfolio = Portfolio()
# portfolio.add_holding('BTC', 0.5)
# portfolio.add_holding('ETH', 10)
# portfolio.update_prices()
# print(f"Total: ${portfolio.get_total_value():,.2f}")

JavaScript实时价格

const axios = require('axios');

class PriceTracker {
    constructor() {
        this.prices = new Map();
    }
    
    async getPrice(symbols) {
        const url = 'https://api.coingecko.com/api/v3/simple/price';
        const ids = symbols.map(s => this.toCoinGeckoId(s));
        const response = await axios.get(url, {
            params: {
                ids: ids.join(','),
                vs_currencies: 'usd'
            }
        });
        return response.data;
    }
    
    toCoinGeckoId(symbol) {
        const map = {
            'BTC': 'bitcoin',
            'ETH': 'ethereum',
            'SOL': 'solana',
            'BNB': 'binancecoin'
        };
        return map[symbol.toUpperCase()] || symbol.toLowerCase();
    }
}

// 使用
const tracker = new PriceTracker();
tracker.getPrice(['BTC', 'ETH']).then(console.log);

开始投资

交易加密货币:注册OKX