发布于 2025-01-06 18:59:19 · 阅读量: 63175
欧易(OKX)是全球领先的加密货币交易所之一,提供丰富的API接口供开发者、交易者和程序化交易员使用。无论你是需要进行自动化交易,还是集成实时市场数据,欧易API接口都能提供强大的支持。本文将详细介绍如何使用欧易API接口,助你快速上手。
在你能使用欧易API之前,需要先创建一个账户,并在账户中生成API密钥。以下是获取API密钥的步骤:
欧易提供了详细的API文档,可以帮助你理解每个接口的功能和使用方式。API文档涵盖了如下内容:
你可以在欧易的API文档页面查看所有接口的详细说明。
想要获取欧易的市场行情数据,API提供了GET /api/v5/market/tickers
接口。下面是一个Python请求的示例:
import requests
url = "https://www.okx.com/api/v5/market/tickers" params = { "instId": "BTC-USDT" # 查询BTC/USDT的市场数据 }
response = requests.get(url, params=params) data = response.json() print(data)
查询账户余额可以使用GET /api/v5/account/balance
接口,以下是获取账户余额的Python示例:
import hmac import hashlib import time import requests
api_key = "your_api_key" secret_key = "your_secret_key" passphrase = "your_passphrase" url = "https://www.okx.com/api/v5/account/balance"
timestamp = str(time.time()) body = '' signature = hmac.new(secret_key.encode(), f"{timestamp}GET/api/v5/account/balance{body}".encode(), hashlib.sha256).hexdigest()
headers = { "OK-API-KEY": api_key, "OK-API-SIGN": signature, "OK-API-TIMESTAMP": timestamp, "OK-API-PASSPHRASE": passphrase }
response = requests.get(url, headers=headers) data = response.json() print(data)
这个代码会查询账户的余额信息,返回结果是一个包含各个币种余额的JSON格式数据。
欧易API提供了创建订单的接口。以POST /api/v5/trade/order
接口为例,以下是一个下单的示例:
import hmac import hashlib import time import requests import json
api_key = "your_api_key" secret_key = "your_secret_key" passphrase = "your_passphrase" url = "https://www.okx.com/api/v5/trade/order"
timestamp = str(time.time()) order_data = { "instId": "BTC-USDT", # 交易对 "tdMode": "cash", # 现货模式 "side": "buy", # 买入 "ordType": "limit", # 限价单 "px": "30000", # 价格 "sz": "0.01" # 数量 }
body = json.dumps(order_data) signature = hmac.new(secret_key.encode(), f"{timestamp}POST/api/v5/trade/order{body}".encode(), hashlib.sha256).hexdigest()
headers = { "OK-API-KEY": api_key, "OK-API-SIGN": signature, "OK-API-TIMESTAMP": timestamp, "OK-API-PASSPHRASE": passphrase, "Content-Type": "application/json" }
response = requests.post(url, headers=headers, data=body) data = response.json() print(data)
这个代码会向欧易下达一个限价买单,价格为30000 USDT,数量为0.01 BTC。
在进行API请求时,可能会遇到各种错误。常见的错误包括:
欧易API接口会返回详细的错误信息,帮助你定位问题所在。你可以通过响应中的msg
字段查看错误提示。
WebSocket接口提供了实时的市场数据推送,包括行情、深度数据、K线等。使用WebSocket可以实现低延迟的实时数据流,非常适合用于高频交易或数据监控。
例如,订阅BTC/USDT的实时行情数据:
import websocket import json
def on_message(ws, message): print("Received message:", message)
def on_error(ws, error): print("Error:", error)
def on_close(ws): print("Closed connection")
def on_open(ws): subscription = { "op": "subscribe", "args": [{"channel": "spot/ticker", "instId": "BTC-USDT"}] } ws.send(json.dumps(subscription))
ws = websocket.WebSocketApp("wss://ws.okx.com:8443/ws/v5/public", on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
通过以上步骤,你应该能够熟练使用欧易的API接口来进行自动化交易和数据获取。希望这篇指南能够帮助你在加密货币交易的道路上更加顺利!