Skip to content

ccxt是最强大的交易所交易api的工具。

Notifications You must be signed in to change notification settings

liuzemei/studyCcxt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

说明

此文档为 cctx 的详细接口解释文档,仅做学习用途。

下面直接进入正题

1. 自有属性

export const version: string;  // cctx 的版本号
export const exchanges: string[]; // cctx 当前支持的所有交易所

2. 数据结构(依赖)

  1. 基础货币:要买入的货币 | 报价货币:要卖出的货币如BTC/USDT = 10000 BTC是基础货币,USDT是报价货币

1. 基础变量 数据结构

export interface MinMax {
    max: number;
    min: number;
}

export interface Tickers {
    info: any;
    [symbol: string]: Ticker;
}

export interface Currency {
    id: string;
    code: string;
}

export interface Balance {
    free: number;
    used: number;
    total: number;
}

export interface PartialBalances {
    [currency: string]: number;
}

export interface Balances {
    info: any;
    [key: string]: Balance;
}

export interface DepositAddress {
    currency: string;
    address: string;
    status: string;
    info: any;
}

export interface Fee {
    type: 'taker' | 'maker';
    currency: string;
    rate: number;
    cost: number;
}

export interface WithdrawalResponse {
    info: any;
    id: string;
}

export interface DepositAddressResponse {
    currency: string;
    address: string;
    info: any;
    tag?: string;
}

// timestamp, open, high, low, close, volume
export type OHLCV = [number, number, number, number, number, number];

2. 交易对 数据结构

原版接口:

export interface Market {
    [key: string]: any
    id: string;
    symbol: string;
    base: string;
    quote: string;
    active: boolean;
    precision: { amount: number, price: number, cost: number };
    limits: { amount: MinMax, price: MinMax, cost?: MinMax };
    info: any;
}

接口介绍:

{
    'id':     ' btcusd',  // 在交易中引用的代币字符串
    'symbol':  'BTC/USD', // 一对货币的大写字符串文字
    'base':    'BTC',     // 大写字符串。统一的基本货币代码
    'quote':   'USD',     // 大写字符串。统一的报价货币代码
    'active': true,       // 布尔值。 市场的状态
    'precision': {        // 小数点后的小数位数(精度)
        'price': 8,       // 整型。 如果交易所不支持,则可能丢失精度
        'amount': 8,      // 整型。 如果交易所不支持,则可能丢失精度
        'cost': 8,        // 整型。 很少交易所支持
    },
    'limits': {           // 下单限制
        'amount': {
            'min': 0.01,  // 订单数量应该大于这个值
            'max': 1000,  // 订单数量应该小于这个值
        },
        'price': { ... }, // 同上的min/max 表示订单的最高价和最低价
        'cost':  { ... }, // 同上的min/max 表示订单的金额(amount * price)
    },
    'info':      { ... }, // 交易所原始未解析的市场信息
}

3. 订单 数据结构

export interface Order {
    id: string;
    datetime: string;
    timestamp: number;
    lastTradeTimestamp: number;
    status: 'open' | 'closed' | 'canceled';
    symbol: string;
    type: 'market' | 'limit';
    side: 'buy' | 'sell';
    price: number;
    amount: number;
    filled: number;
    remaining: number;
    cost: number;
    trades: Trade[];
    fee: Fee;
    info: {};
}

接口介绍:

{
    'id': '12345-67890:09876/54321', // 订单的唯一标识
    'datetime': '2017-08-17 12:42:48.000', // ISO8601 时间戳
    'timestamp': 1502962946216, // 时间戳
    'lastTradeTimestamp': 1502962956216, // 此订单上最后交易的时间戳
    'status': 'open',         // 'open', 'closed', 'canceled'  //订单状态:分别为:打开/关闭/取消
    'symbol': 'ETH/BTC',      // 交易对信息
    'type': 'limit',        // 'market', 'limit'  //  交易方式: 市价交易   现价交易
    'side': 'buy',          // 'buy', 'sell' // 交易方向: 买入 卖出
    'price': 0.06917684,    // 基础货币/报价货币  的浮动价格
    'amount': 1.5,           // 下单数量(基于报价货币)
    'filled': 1.1,           // 成交数量(基于报价货币)
    'remaining': 0.4,           // 未成交数量(基于报价货币)
    'cost': 0.076094524,   // 'filled' * 'price' (总花费金额(基于报价货币))
    'trades': [... ],         // 这笔订单交易执行的列表(可能有多笔交易)
    'fee': {                      // 手续费
        'currency': 'BTC',        // 手续费计价货币(通常是报价)
        'cost': 0.0009,           // 实际手续费用
        'rate': 0.002,            // 费率
    },
    'info': { ... },              // 原始未解析的数据
}

4. 订单列表 数据结构

export interface OrderBook {
    asks: [number, number][];
    bids: [number, number][];
    datetime: string;
    timestamp: number;
    nonce: number;
}

接口介绍:

{
    'asks': [ // 询问价格 -> 买入价格 (询问数组)
        [ price, amount ], // 价格 , 数量
        [ price, amount ],
        ...
    ],
    'bids': [ // 投标价格 -> 卖出价格
        [ price, amount ], // [ float, float ]
        [ price, amount ],
        ...
    ],
    'timestamp': 1499280391811, // Unix Timestamp in milliseconds (seconds * 1000)
    'datetime': '2017-07-05T18:47:14.692Z', // ISO8601 datetime string with milliseconds
}

价格和金额是浮动的。投标数组按价格降序排列。最佳(最高)投标价格是第一个要素,最差(最低)投标价格是最后一个要素。询问数组按价格升序排序。最佳(最低)要价是第一个要素,最差(最高)要价是最后一个要素。如果在交易所的订单簿中没有对应的订单,则出价/要价数组可以为空。

交易所可能会返回各个层次的订单堆栈的详细信息以供分析。它要么包含每个订单的详细信息,要么包含稍微少一点的详细信息,其中订单按价格和数量进行分组和合并。拥有更多的细节需要更多的流量和带宽,一般来说速度较慢,但具有更高的精度。拥有更少的细节通常更快,但在某些非常特殊的情况下可能还不够。

5. 交易信息 数据结构

export interface Trade {
    amount: number;                  // amount of base currency
    datetime: string;                // ISO8601 datetime with milliseconds;
    id: string;                      // string trade id
    info: {};                        // the original decoded JSON as is
    order?: string;                  // string order id or undefined/None/null
    price: number;                   // float price in quote currency
    timestamp: number;               // Unix timestamp in milliseconds
    type?: 'market' | 'limit';       // order type, 'market', 'limit' or undefined/None/null
    side: 'buy' | 'sell';            // direction of the trade, 'buy' or 'sell'
    symbol: string;                  // symbol in CCXT format
    takerOrMaker: 'taker' | 'maker'; // string, 'taker' or 'maker'
    cost: number;                    // total cost (including fees), `price * amount`
    fee: Fee;
}

接口介绍:

{
    'info': { ... }, // 原始的JSON返回信息
    'id': '12345-67890:09876/54321',  // 交易ID
    'timestamp': 1502962946216, // 时间戳
    'datetime': '2017-08-17 12:42:48.000',  // ISO8601 时间
    'symbol': 'ETH/BTC',   // 交易对
    'order': '12345-67890:09876/54321',  // string/None/None/undefined
    'type': 'limit', // 订单类型, 'market', 'limit' or undefined/None/null
    'side': 'buy', // 交易方向, 'buy' or 'sell'
    'takerOrMaker': 'taker', // string, 'taker' or 'maker' 订单接受者 / 订单创建者
    'price': 0.06917684,  // 基础货币/报价货币 的浮动价格
    'amount': 1.5,  // 基于报价货币
    'cost': 0.10376526, // 总花费(包括手续费) price * amount
    'fee': { // 同上(3.订单接口)
        'cost': 0.0015,
        'currency': 'ETH',
        'rate': 0.002
    },
}

6. 行情信息 数据结构

export interface Ticker {
    symbol: string;
    info: object;
    timestamp: number;
    datetime: string;
    high: number;
    low: number;
    bid: number;
    bidVolume?: number;
    ask: number;
    askVolume?: number;
    vwap?: number;
    open?: number;
    close?: number;
    last?: number;
    previousClose?: number;
    change?: number;
    percentage?: number;
    average?: number;
    quoteVolume?: number;
    baseVolume?: number;
}
{
    'symbol':        // eg.('BTC/USD', 'ETH/BTC', ...)
    'info':          // 交易所API返回原始的数据
    'timestamp':     // 时间戳
    'datetime':      //  ISO8601 时间
    'high':          float, // 最高价
    'low':           float, // 最低价
    'bid':           float, // 当前最高买价
    'bidVolume':     float, // 最高买价深度(可能为undefined)
    'ask':           float, // 当前最高卖价
    'askVolume':     float, // 最高卖价深度(可能为undefined)
    'vwap':          float, // 成交量加权平均价格
    'open':          float, // 开盘价
    'close':         float, // 上次成交价格(本期收盘价)
    'last':          float, // 与'close'一样,方便复制= =
    'previousClose': float, // 前期收市价
    'change':        float, // 涨跌金额 (上次成交价-开盘价)
    'percentage':    float, // 涨跌幅度 (上次成交价/开盘价 * 100%)
    'average':       float, // 平均价格 (上次成交价+开盘价)/2
    'baseVolume':    float, // 24小时基本货币交易量
    'quoteVolume':   float, // 24小时报价货币交易量
}

7. 链上信息 交易结构

export interface Transaction {
    info: {};
    id: string;
    txid?: string;
    timestamp: number;
    datetime: string;
    address: string;
    type: "deposit" | "withdrawal";
    amount: number;
    currency: string;
    status: "pending" | "ok";
    updated: number;
    fee: Fee;
}

接口详情:

{
    'info':      { ... },    // 交易所原始信息
    'id':       '123456',    // 交易所提供的id
    'txid':     '0x68bfb29821c50ca35ef3762f887fd3211e4405aba1a94e448a4f218b850358f0',//事务ID
    'timestamp': 1534081184515,
    'datetime': '2018-08-12T13:39:44.515Z',
    'addressFrom': '0x38b1F8644ED1Dbd5DcAedb3610301Bf5fa640D6f', // 发送者
    'address':  '0x02b0a9b7b4cDe774af0f8e47cb4f1c2ccdEa0806', // "from" or "to"
    'addressTo': '0x304C68D441EF7EB0E2c056E836E8293BD28F8129', // 接收者
    'tagFrom', '0xabcdef', // "tag" or "memo" or "payment_id" 与发送者相关
    'tag':      '0xabcdef' // "tag" or "memo" or "payment_id" associated with the address
    'tagTo': '0xhijgklmn', // "tag" or "memo" or "payment_id" 与接收者相关
    'type':     'deposit',   // or 'withdrawal', string 存入或者取出
    'amount':    1.2345,     // float (不包含手续费)
    'currency': 'ETH',       // a common unified currency code, string
    'status':   'pending',   // 'ok', 'failed', 'canceled', string 状态
    'updated':   undefined,  // 状态最后更改的UTC时间戳(精确到ms)
    'comment':  '由用于定义的注释或消息',
    'fee': {                 // 同上
        'currency': 'ETH',   
        'cost': 0.1234,      
        'rate': undefined
    },
}

3. 交易所数据结构(核心)

export class Exchange {
    constructor(config?: {[key in keyof Exchange]?: Exchange[key]});
    // allow dynamic keys
    [key: string]: any;
    // properties
    hash: any;
    hmac: any;
    jwt: any;
    binaryConcat: any;
    stringToBinary: any;
    stringToBase64: any;
    base64ToBinary: any;
    base64ToString: any;
    binaryToString: any;
    utf16ToBase64: any;
    urlencode: any;
    pluck: any;
    unique: any;
    extend: any;
    deepExtend: any;
    flatten: any;
    groupBy: any;
    indexBy: any;
    sortBy: any;
    keysort: any;
    decimal: any;
    safeFloat: any;
    safeString: any;
    safeInteger: any;
    safeValue: any;
    capitalize: any;
    json: JSON["stringify"]
    sum: any;
    ordered: any;
    aggregate: any;
    truncate: any;
    name: string;
    // nodeVersion: string;
    fees: object;
    enableRateLimit: boolean;
    countries: string;
    // set by loadMarkets
    markets: { [symbol: string]: Market };
    marketsById: { [id: string]: Market };
    currencies: { [symbol: string]: Currency };
    ids: string[];
    symbols: string[];
    id: string;
    proxy: string;
    parse8601: typeof Date.parse
    milliseconds: typeof Date.now;
    rateLimit: number;  // milliseconds = seconds * 1000
    timeout: number; // milliseconds
    verbose: boolean;
    twofa: boolean;// two-factor authentication
    substituteCommonCurrencyCodes: boolean;
    timeframes: any;
    has: { [what: string]: any }; // https://github.com/ccxt/ccxt/pull/1984
    balance: object;
    orderbooks: object;
    orders: object;
    trades: object;
    userAgent: { 'User-Agent': string } | false;

    // methods
    getMarket (symbol: string): Market;
    describe (): any;
    defaults (): any;
    nonce (): number;
    encodeURIComponent (...args: any[]): string;
    checkRequiredCredentials (): void;
    initRestRateLimiter (): void;
    handleResponse (url: string, method: string, headers?: any, body?: any): any;
    defineRestApi (api: any, methodName: any, options?: { [x: string]: any }): void;
    fetch (url: string, method?: string, headers?: any, body?: any): Promise<any>;
    fetch2 (path: any, api?: string, method?: string, params?: { [x: string]: any }, headers?: any, body?: any): Promise<any>;
    setMarkets (markets: Market[], currencies?: Currency[]): { [symbol: string]: Market };
    loadMarkets (reload?: boolean): Promise<{ [symbol: string]: Market }>;
    fetchTicker (symbol: string, params?: { [x: string]: any }): Promise<Ticker>;
    fetchTickers (symbols?: string[], params?: { [x: string]: any }): Promise<{ [x: string]: Ticker }>;
    fetchMarkets (): Promise<Market[]>;
    fetchOrderStatus (id: string, market: string): Promise<string>;
    encode (str: string): string;
    decode (str: string): string;
    account (): Balance;
    commonCurrencyCode (currency: string): string;
    market (symbol: string): Market;
    marketId (symbol: string): string;
    marketIds (symbols: string[]): string[];
    symbol (symbol: string): string;
    extractParams (str: string): string[];
    createOrder (symbol: string, type: string, side: string, amount: number, price?: number, params?: {}): Promise<any>;
    fetchBalance (params?: any): Promise<Balances>;
    fetchTotalBalance (params?: any): Promise<PartialBalances>;
    fetchUsedBalance (params?: any): Promise<PartialBalances>;
    fetchFreeBalance (params?: any): Promise<PartialBalances>;
    fetchOrderBook (symbol: string, limit?: number, params?: any): Promise<OrderBook>;
    fetchTicker (symbol: string): Promise<Ticker>;
    fetchTickers (symbols?: string[]): Promise<Tickers>;
    fetchTrades (symbol: string, since?: number, limit?: number, params?: {}): Promise<Trade[]>;
    fetchOHLCV? (symbol: string, timeframe?: string, since?: number, limit?: number, params?: {}): Promise<OHLCV[]>;
    fetchOrders (symbol?: string, since?: number, limit?: number, params?: {}): Promise<Order[]>;
    fetchOpenOrders (symbol?: string, since?: number, limit?: number, params?: {}): Promise<Order[]>;
    fetchCurrencies (params?: any): Promise<any>;
    fetchTransactions (currency?: string, since?: number, limit?: number, params?: {}): Promise<Transaction[]>;
    fetchDeposits (currency?: string, since?: number, limit?: number, params?: {}): Promise<Transaction[]>;
    fetchWithdrawals (currency?: string, since?: number, limit?: number, params?: {}): Promise<Transaction[]>;
    cancelOrder (id: string, symbol?: string, params?: {}): Promise<any>;
    createDepositAddress (currency: string, params?: {}): Promise<DepositAddressResponse>;
    fetchDepositAddress (currency: string, params?: {}): Promise<DepositAddressResponse>;
    withdraw (currency: string, amount: number, address: string, tag?: string, params?: {}): Promise<WithdrawalResponse>;
    request (path: string, api?: string, method?: string, params?: any, headers?: any, body?: any): Promise<any>;
    YmdHMS (timestamp: string, infix: string) : string;
    iso8601 (timestamp: string): string;
    seconds (): number;
    microseconds (): number;
}
{
    'id':   'exchange'                  // lowercase string exchange id
    'name': 'Exchange'                  // human-readable string
    'countries': [ 'US', 'CN', 'EU' ],  // array of ISO country codes
    'urls': {
        'api': 'https://api.example.com/data',  // string or dictionary of base API URLs
        'www': 'https://www.example.com'        // string website URL
        'doc': 'https://docs.example.com/api',  // string URL or array of URLs
    },
    'version':         'v1',            // string ending with digits
    'api':             { ... },         // dictionary of api endpoints
    'has': {                            // exchange capabilities
        'CORS': false,
        'publicAPI': true,
        'privateAPI': true,
        'cancelOrder': true,
        'createDepositAddress': false,
        'createOrder': true,
        'deposit': false,
        'fetchBalance': true,
        'fetchClosedOrders': false,
        'fetchCurrencies': false,
        'fetchDepositAddress': false,
        'fetchMarkets': true,
        'fetchMyTrades': false,
        'fetchOHLCV': false,
        'fetchOpenOrders': false,
        'fetchOrder': false,
        'fetchOrderBook': true,
        'fetchOrders': false,
        'fetchStatus': 'emulated',
        'fetchTicker': true,
        'fetchTickers': false,
        'fetchBidsAsks': false,
        'fetchTrades': true,
        'withdraw': false,
    },
    'timeframes': {                     // empty if the exchange !has.fetchOHLCV
        '1m': '1minute',
        '1h': '1hour',
        '1d': '1day',
        '1M': '1month',
        '1y': '1year',
    },
    'timeout':          10000,          // number in milliseconds
    'rateLimit':        2000,           // number in milliseconds
    'userAgent':       'ccxt/1.1.1 ...' // string, HTTP User-Agent header
    'verbose':          false,          // boolean, output error details
    'markets':         { ... }          // dictionary of markets/pairs by symbol
    'symbols':         [ ... ]          // sorted list of string symbols (traded pairs)
    'currencies':      { ... }          // dictionary of currencies by currency code
    'markets_by_id':   { ... },         // dictionary of dictionaries (markets) by id
    'proxy': 'https://crossorigin.me/', // string URL
    'apiKey':   '92560ffae9b8a0421...', // string public apiKey (ASCII, hex, Base64, ...)
    'secret':   '9aHjPmW+EtRRKN/Oi...'  // string private secret key
    'password': '6kszf4aci8r',          // string password
    'uid':      '123456',               // string user id
}

About

ccxt是最强大的交易所交易api的工具。

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published