欧易API调用教程:如何使用OKEx API进行自动化交易与数据查询

发布于 2025-01-09 02:40:51 · 阅读量: 84118

欧易API调用教程

欧易(OKEx)是一个全球知名的加密货币交易所,提供了丰富的API接口,方便开发者和交易者进行自动化交易、获取市场数据、管理账户等操作。通过调用欧易API,你可以实现自定义交易策略、获取实时行情、查询余额、下单等操作。本篇教程将带你了解如何使用欧易API,帮助你快速上手。

准备工作

在开始调用API之前,你需要做一些准备工作:

  1. 注册并登录欧易账户
    如果你还没有注册账户,首先到欧易官网注册一个账号,并登录。

  2. 生成API密钥
    登录后,进入“API管理”页面,点击“创建API密钥”按钮,生成你的API密钥。你会得到一个API KeySecret KeyPassphrase,这些信息对于调用API至关重要。务必保管好这些密钥,不要轻易泄露。

  3. API Key:用于标识API请求的身份

  4. Secret Key:用于签名请求
  5. Passphrase:用于验证你的API访问权限

  6. 确认权限设置
    创建API密钥时,你可以设置API的权限,如“读取账户信息”、“下单权限”等。根据你的需求,选择相应的权限。一般来说,默认的权限设置已经足够大多数用途。

使用Python调用欧易API

我们将以Python为例,演示如何调用欧易API进行常见操作。首先,确保你安装了requests库,可以通过以下命令进行安装:

bash pip install requests

1. 获取行情数据

获取欧易市场行情数据是API最常用的功能之一。下面的代码示例演示了如何通过API获取指定交易对的最新市场数据。

import requests

设置API endpoint

url = "https://www.okx.com/api/v5/market/tickers"

发送请求

response = requests.get(url) data = response.json()

打印返回的行情数据

if data['code'] == '0': for ticker in data['data']: print(f"交易对: {ticker['instId']}, 最新价格: {ticker['last']}") else: print("获取行情失败:", data)

2. 查询账户余额

使用API查询账户余额可以帮助你监控资金状况。以下是查询账户余额的示例代码:

import requests import time import hashlib import hmac

API Key, Secret Key, Passphrase

api_key = 'your_api_key' secret_key = 'your_secret_key' passphrase = 'your_passphrase'

构建请求头

def generate_signature(timestamp, method, request_path, body): body_str = body if body else '' prehash = timestamp + method + request_path + body_str return hmac.new(secret_key.encode(), prehash.encode(), hashlib.sha256).hexdigest()

设置API endpoint

url = "https://www.okx.com/api/v5/account/balances" method = "GET" request_path = "/api/v5/account/balances" body = ""

获取时间戳

timestamp = str(time.time())

生成签名

signature = generate_signature(timestamp, method, request_path, body)

构建请求头

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()

打印余额信息

if data['code'] == '0': for balance in data['data']: print(f"币种: {balance['currency']}, 可用余额: {balance['availBal']}") else: print("获取余额失败:", data)

3. 下单操作

下单是加密货币交易所API最重要的功能之一。以下代码演示了如何使用欧易API下达限价单。

import requests import time import hashlib import hmac import json

API Key, Secret Key, Passphrase

api_key = 'your_api_key' secret_key = 'your_secret_key' passphrase = 'your_passphrase'

构建请求头

def generate_signature(timestamp, method, request_path, body): body_str = body if body else '' prehash = timestamp + method + request_path + body_str return hmac.new(secret_key.encode(), prehash.encode(), hashlib.sha256).hexdigest()

设置API endpoint

url = "https://www.okx.com/api/v5/trade/order" method = "POST" request_path = "/api/v5/trade/order"

设置订单参数

order_data = { "instId": "BTC-USDT", # 交易对 "tdMode": "cash", # 交易模式:现货 "side": "buy", # 买入 "ordType": "limit", # 限价单 "px": "30000", # 限价 "sz": "0.001" # 数量 }

转换订单数据为JSON格式

body = json.dumps(order_data)

获取时间戳

timestamp = str(time.time())

生成签名

signature = generate_signature(timestamp, method, request_path, body)

构建请求头

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()

打印返回的订单信息

if data['code'] == '0': print(f"订单已成功创建, 订单ID: {data['data'][0]['ordId']}") else: print("下单失败:", data)

4. 查询订单状态

查询订单状态可以帮助你确认订单是否被成功执行。以下代码展示了如何查询订单状态。

import requests import time import hashlib import hmac

API Key, Secret Key, Passphrase

api_key = 'your_api_key' secret_key = 'your_secret_key' passphrase = 'your_passphrase'

构建请求头

def generate_signature(timestamp, method, request_path, body): body_str = body if body else '' prehash = timestamp + method + request_path + body_str return hmac.new(secret_key.encode(), prehash.encode(), hashlib.sha256).hexdigest()

设置API endpoint

url = "https://www.okx.com/api/v5/trade/order" method = "GET" request_path = "/api/v5/trade/order" order_id = "your_order_id"

设置订单查询参数

params = { "ordId": order_id }

获取时间戳

timestamp = str(time.time())

生成签名

signature = generate_signature(timestamp, method, request_path, "")

构建请求头

headers = { 'OK-API-KEY': api_key, 'OK-API-SIGN': signature, 'OK-API-TIMESTAMP': timestamp, 'OK-API-PASSPHRASE': passphrase, }

发送请求

response = requests.get(url, headers=headers, params=params) data = response.json()

打印订单状态

if data['code'] == '0': print(f"订单状态: {data['data'][0]['state']}") else: print("查询订单失败:", data)

错误处理与调试

在调用API时,可能会遇到各种错误。欧易API的返回数据中通常会包括一个code字段来标识请求是否成功。code0表示成功,其他值表示失败。你可以根据返回的错误代码进行调试。

常见的错误包括:

  • 400 Bad Request:请求格式不正确
  • 401 Unauthorized:API密钥错误或权限不足
  • 404 Not Found:API路径错误
  • 500 Internal Server Error:服务器故障

你可以通过查看错误信息并检查请求参数,密钥配置等来解决问题。

常用API接口

  • 获取市场行情/api/v5/market/tickers
  • 查询账户余额/api/v5/account/balances
  • 下单/api/v5/trade/order
  • 查询订单/api/v5/trade/order

你可以根据自己的需求,参考官方文档来进一步了解更多API接口。

其他文章

Gate.io Logo 加入 Gate.io,注册赢取最高$6666迎新任务奖励!