发布于 2025-02-07 09:40:13 · 阅读量: 178263
CoinEx 是一个全球化的加密货币交易所,支持丰富的交易对,并且提供了一套完善的 API(应用程序接口)。如果你想要用代码自动化交易,或者抓取市场数据,那 API 绝对是你的得力助手。CoinEx 的 API 主要有 RESTful API 和 WebSocket API 两种,前者适合请求式交互(比如获取账户信息、下单、查询订单等),后者则适合实时推送(比如市场深度、成交数据)。
在开始使用 API 之前,你得先申请一个 API Key,相当于你的数字身份卡。操作步骤如下:
CoinEx API 主要通过 HTTP 请求 进行交互,我们以 Python 为例,使用 requests
库进行访问。
bash pip install requests
import requests
url = "https://api.coinex.com/v1/market/ticker" params = {"market": "BTCUSDT"}
response = requests.get(url, params=params) print(response.json())
这段代码会返回 BTC/USDT 的最新行情数据,包括最新成交价、买一价、卖一价等。
想要执行账户相关的操作(比如下单、撤单、查询余额),就必须进行 API 认证。CoinEx 采用 HMAC-SHA256 签名方式,具体操作如下:
import hashlib import hmac import time
API_KEY = "你的APIKey" SECRET_KEY = "你的SecretKey"
def get_signature(params, secret_key): sorted_params = "&".join(f"{key}={value}" for key, value in sorted(params.items())) return hmac.new(secret_key.encode(), sorted_params.encode(), hashlib.sha256).hexdigest()
def place_order(): url = "https://api.coinex.com/v1/order/limit" params = { "access_id": API_KEY, "market": "BTCUSDT", "type": "buy", "amount": "0.01", "price": "30000", "tonce": int(time.time() * 1000), } params["signature"] = get_signature(params, SECRET_KEY)
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=params, headers=headers)
return response.json()
print(place_order())
如果你想要实时监听交易所的市场数据,CoinEx 的 WebSocket API 是更好的选择。以下是一个 Python 示例,监听 BTC/USDT 最新成交价格。
import websocket import json
def on_message(ws, message): data = json.loads(message) print("最新成交价:", data.get("params", [None, None])[1])
def on_open(ws): sub_msg = { "method": "state.subscribe", "params": ["BTCUSDT"], "id": 1 } ws.send(json.dumps(sub_msg))
ws = websocket.WebSocketApp("wss://socket.coinex.com/", on_message=on_message) ws.run_forever()
signature error
?signature
计算正确,参数顺序要按照字母排序再签名。 tonce
需要是最新的时间戳(毫秒)。 asyncio
和 aiohttp
进行异步请求,提高并发能力。 pandas
处理数据,存入数据库进行分析。