跳转到主要内容

Coinbase Pro API的非官方Python客户端

项目描述

coinbasepro-python

Build Status

Coinbase Pro API (以前称为GDAX) 的Python客户端

由Daniel Paquin提供MIT许可证。

注意:此库可能存在细微的错误或不稳定。代码在MIT许可证下发布 - 请认真对待以下信息

软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、针对特定目的的适用性和非侵权性。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任负责,无论这些责任是基于合同、侵权或其他方式,无论这些责任是否与软件或其使用或其他方式有关。

优势

  • 这是一个简单的Python包装器,用于公共和认证端点。
  • 大约10分钟内,你就可以在世界上最大的比特币交易所之一进行程序化交易了!
  • 无需担心处理API的细微差别,每个API端点都提供了易于使用的接口。
  • 通过深入了解CB Pro,了解每个tick的背后是什么和谁,在市场中获得优势。

开发中

  • 测试脚本
  • 实时订单簿的附加功能
  • FIX API客户端 寻求帮助

入门指南

本README是关于本存储库中展示的Python客户端语法的文档。请参阅函数文档字符串以获取完整的语法细节。
此API试图提供一个干净的接口来展示CB Pro,但为了充分利用它,您必须熟悉官方CB Pro文档。

pip install cbpro
#or
pip install git+git://github.com/danpaquin/coinbasepro-python.git

公共客户端

API中的一些端点对所有人开放。公共端点可以通过使用PublicClient来访问。

import cbpro
public_client = cbpro.PublicClient()

PublicClient方法

public_client.get_products()
# Get the order book at the default level.
public_client.get_product_order_book('BTC-USD')
# Get the order book at a specific level.
public_client.get_product_order_book('BTC-USD', level=1)
# Get the product ticker for a specific product.
public_client.get_product_ticker(product_id='ETH-USD')
# Get the product trades for a specific product.
# Returns a generator
public_client.get_product_trades(product_id='ETH-USD')
public_client.get_product_historic_rates('ETH-USD')
# To include other parameters, see function docstring:
public_client.get_product_historic_rates('ETH-USD', granularity=3000)
public_client.get_product_24hr_stats('ETH-USD')
public_client.get_currencies()
public_client.get_time()

认证客户端

并非所有API端点都对所有人开放。需要用户认证的端点可以通过使用AuthenticatedClient来访问。您必须在您的账户设置中设置API访问。由于AuthenticatedClientPublicClient类继承所有方法,所以如果您打算将两者集成到脚本中,您只需初始化一个即可。

import cbpro
auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)
# Use the sandbox API (requires a different set of API access credentials)
auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase,
                                  api_url="https://api-public.sandbox.pro.coinbase.com")

分页

一些调用是分页的,这意味着必须进行多次调用才能接收完整的数据集。CB Pro Python API提供了一种分页端点的抽象形式,即生成器,它为迭代提供了一种干净的接口,但可能在幕后进行多个HTTP请求。如果需要,可以提供关键字参数beforeafterlimit,但对于典型用例而言,这不是必需的。

fills_gen = auth_client.get_fills()
# Get all fills (will possibly make multiple HTTP requests)
all_fills = list(fills_gen)

值得指出的一种分页参数的使用场景是仅检索自上次请求以来的新数据。对于get_fills()的情况,trade_id是用于索引的参数。通过传递before=some_trade_id,只有比该trade_id更近的填充将被返回。请注意,当使用before时,将返回最多100个条目 - 这是CB Pro的限制。

from itertools import islice
# Get 5 most recent fills
recent_fills = islice(auth_client.get_fills(), 5)
# Only fetch new fills since last call by utilizing `before` parameter.
new_fills = auth_client.get_fills(before=recent_fills[0]['trade_id'])

AuthenticatedClient方法

auth_client.get_accounts()
auth_client.get_account("7d0f7d8e-dd34-4d9c-a846-06f431c381ba")
# Returns generator:
auth_client.get_account_history("7d0f7d8e-dd34-4d9c-a846-06f431c381ba")
# Returns generator:
auth_client.get_account_holds("7d0f7d8e-dd34-4d9c-a846-06f431c381ba")
# Buy 0.01 BTC @ 100 USD
auth_client.buy(price='100.00', #USD
               size='0.01', #BTC
               order_type='limit',
               product_id='BTC-USD')
# Sell 0.01 BTC @ 200 USD
auth_client.sell(price='200.00', #USD
                size='0.01', #BTC
                order_type='limit',
                product_id='BTC-USD')
# Limit order-specific method
auth_client.place_limit_order(product_id='BTC-USD', 
                              side='buy', 
                              price='200.00', 
                              size='0.01')
# Place a market order by specifying amount of USD to use. 
# Alternatively, `size` could be used to specify quantity in BTC amount.
auth_client.place_market_order(product_id='BTC-USD', 
                               side='buy', 
                               funds='100.00')
# Stop order. `funds` can be used instead of `size` here.
auth_client.place_stop_order(product_id='BTC-USD', 
                              side='buy', 
                              price='200.00', 
                              size='0.01')
auth_client.cancel_order("d50ec984-77a8-460a-b958-66f114b0de9b")
auth_client.cancel_all(product_id='BTC-USD')
# Returns generator:
auth_client.get_orders()
auth_client.get_order("d50ec984-77a8-460a-b958-66f114b0de9b")
# All return generators
auth_client.get_fills()
# Get fills for a specific order
auth_client.get_fills(order_id="d50ec984-77a8-460a-b958-66f114b0de9b")
# Get fills for a specific product
auth_client.get_fills(product_id="ETH-BTC")
depositParams = {
        'amount': '25.00', # Currency determined by account specified
        'coinbase_account_id': '60680c98bfe96c2601f27e9c'
}
auth_client.deposit(depositParams)
# Withdraw from CB Pro into Coinbase Wallet
withdrawParams = {
        'amount': '1.00', # Currency determined by account specified
        'coinbase_account_id': '536a541fa9393bb3c7000023'
}
auth_client.withdraw(withdrawParams)

WebsocketClient

如果您想接收实时市场更新,您必须订阅websocket feed

订阅单个产品

import cbpro
# Paramters are optional
wsClient = cbpro.WebsocketClient(url="wss://ws-feed.pro.coinbase.com", products="BTC-USD")
# Do other stuff...
wsClient.close()

订阅多个产品

import cbpro
# Paramaters are optional
wsClient = cbpro.WebsocketClient(url="wss://ws-feed.pro.coinbase.com",
                                products=["BTC-USD", "ETH-USD"])
# Do other stuff...
wsClient.close()

WebsocketClient + MongoDB

现在WebsocketClient支持通过MongoDB收集数据。给定一个MongoDB集合,WebsocketClient将直接将结果流式传输到数据库集合。

# import PyMongo and connect to a local, running Mongo instance
from pymongo import MongoClient
import cbpro
mongo_client = MongoClient('mongodb://localhost:27017/')

# specify the database and collection
db = mongo_client.cryptocurrency_database
BTC_collection = db.BTC_collection

# instantiate a WebsocketClient instance, with a Mongo collection as a parameter
wsClient = cbpro.WebsocketClient(url="wss://ws-feed.pro.coinbase.com", products="BTC-USD",
    mongo_collection=BTC_collection, should_print=False)
wsClient.start()

WebsocketClient方法

WebsocketClient在初始化时在单独的线程中订阅。有三个方法可以在初始化之前覆盖,以便它能够对传入的数据流做出反应。当前的客户端仅用于说明目的。

  • onOpen - 仅调用一次,在建立socket连接之前立即调用,这是添加初始参数的地方。
  • onMessage - 每收到一条消息就调用一次,接受一个包含字典类型消息的参数。
  • on_close - 在websocket关闭后调用一次。
  • close - 调用此方法来关闭websocket连接(不要重写)。
import cbpro, time
class myWebsocketClient(cbpro.WebsocketClient):
    def on_open(self):
        self.url = "wss://ws-feed.pro.coinbase.com/"
        self.products = ["LTC-USD"]
        self.message_count = 0
        print("Lets count the messages!")
    def on_message(self, msg):
        self.message_count += 1
        if 'price' in msg and 'type' in msg:
            print ("Message type:", msg["type"],
                   "\t@ {:.3f}".format(float(msg["price"])))
    def on_close(self):
        print("-- Goodbye! --")

wsClient = myWebsocketClient()
wsClient.start()
print(wsClient.url, wsClient.products)
while (wsClient.message_count < 500):
    print ("\nmessage_count =", "{} \n".format(wsClient.message_count))
    time.sleep(1)
wsClient.close()

测试

正在开发测试套件。需要一组沙盒API凭证来测试认证客户端。为了提供这些凭证,将测试文件夹中的api_config.json.example重命名为api_config.json并相应地编辑文件。要运行测试,请在项目目录中启动并运行

python -m pytest

实时订单簿

OrderBook订阅了一个websocket,并实时记录输入product_id的订单簿。请提供您的反馈以供未来改进。

import cbpro, time
order_book = cbpro.OrderBook(product_id='BTC-USD')
order_book.start()
time.sleep(10)
order_book.close()

测试

正在使用pytest框架开发单元测试。欢迎贡献力量!

要运行完整的测试套件,在项目目录中运行

python -m pytest

变更日志

1.1.2 当前PyPI版本

  • 重构项目以适应Coinbase Pro
  • 对分页处理方式进行了重大改进

1.0

  • 这是第一个不向后兼容的版本
  • 重构以遵循PEP 8标准
  • 改进了文档

0.3

  • 添加了加密货币和LTC的存取款(未记录)。
  • 添加了对保证金交易的支持(未记录)。
  • 增强了WebsocketClient的功能。
  • 软发布订单簿(未记录)。
  • 修复了少量错误和语法改进。

0.2.2

  • 添加了额外的API功能,如cancelAll()和ETH提款。

0.2.1

  • 允许WebsocketClient以直观的方式操作并重构了示例工作流程。

0.2.0

  • 将项目重命名为GDAX-Python
  • 合并websocket更新以处理错误和重连。

0.1.2

  • 更新了JSON处理,以增加某些用户的兼容性。
  • 添加了对支付方式、报告和Coinbase用户账户的支持。
  • 其他兼容性更新。

0.1.1b2

  • 原始PyPI发布。

项目详情


下载文件

下载适用于您平台的应用程序。如果您不确定选择哪个,请了解更多关于安装软件包的信息。

源分布

cbpro-next-1.1.5.tar.gz (32.1 kB 查看哈希值)

上传时间

支持者: