欧易(okex)API V5接口实现指南

下载源文件

from lib import RestAccount, RestAsset, RestMarket, RestOrder, RestPublic

##################################################################################
#
# 交易
#
##################################################################################

test_order = RestOrder()

# 下单
order_args = {
    'instId': 'BTC-USDT',
    'tdMode': 'cash',
    'side': 'buy',
    'ordType': 'limit',
    'sz': '1',
    'px': '5000.0'
}
test_order.order(args=order_args)

# 查订单信息
orders = test_order.get_order_information(inst_id='XPO-USDT', order_id='387591526083358720')
for order in orders:
    print(order)

# 获取最近7天的已经完结状态的订单数据
orders = test_order.get_orders_history()
for order in orders:
    print(order)

# 获取最近3个月的已经完结状态的订单数据
orders = test_order.get_orders_history_archive()
for order in orders:
    print(order)

# 获取近3天的订单成交明细信息
trades = test_order.get_trade_fills(inst_type='SPOT')
for trade in trades:
    print(trade)

# 获取近3个月订单成交明细信息
trades = test_order.get_trade_fills_history(inst_type='SPOT')
for trade in trades:
    print(trade)

del test_order

##################################################################################
#
# 资金
#
##################################################################################

test_asset = RestAsset()

# 获取资金账户所有资产列表,查询各币种的余额、冻结和可用等信息
balances = test_asset.get_asset_balances()
for balance in balances:
    print(balance)

# 查询资金账户账单流水,可查询最近一个月的数据
bills = test_asset.get_asset_bills()
for bill in bills:
    print(bill)

# 获取平台所有币种列表。并非所有币种都可被用于交易
currencies = test_asset.get_asset_currencies()
for currency in currencies:
    print(currency)

# 获取各个币种的充值地址,包括曾使用过的老地址
addresses = test_asset.get_asset_deposit_address(parameters={'ccy': 'BTC'})
for address in addresses:
    print(address)

# 根据币种,充值状态,时间范围获取充值记录
histories = test_asset.get_asset_deposit_history(parameters={'ccy': 'BTC'})
for history in histories:
    print(history)

# 根据币种,提币状态,时间范围获取提币记录
histories = test_asset.get_asset_withdrawal_history(parameters={'ccy': 'BTC'})
for history in histories:
    print(history)

del test_asset

##################################################################################
#
# 账户
#
##################################################################################

test_account = RestAccount()

# 获取账户中资金余额信息。
balances = test_account.get_account_balance()
for balance in balances:
    print(balance)

# 账单流水查询(近七天)
bills = test_account.get_account_bills(inst_type='SPOT')
for bill in bills:
    print(bill)

# 账单流水查询(近三月)
bills = test_account.get_account_bills_archive(inst_type='SPOT')
for bill in bills:
    print(bill)

# 查看当前账户的配置信息
configs = test_account.get_account_config()
for config in configs:
    print(config)

# 查看账户持仓风险
risks = test_account.get_account_position_risk(inst_type='MARGIN')
for risk in risks:
    print(risk)

# 获取该账户下拥有实际持仓的信息
positions = test_account.get_account_positions(inst_type='MARGIN')
for position in positions:
    print(position)

del test_account

##################################################################################
#
# 市场
#
##################################################################################

test_market = RestMarket()

# 获取产品深度列表
books = test_market.get_market_books(inst_id='BTC-USDT')
for book in books:
    print(book)

# 获取K线数据
candles = test_market.get_market_candles(
    inst_id='BTC-USDT',
    after='1575561600000',
    before='1569945600000',
    bar='1D'
)
for candle in candles:
    print(candle)

# 获取交易产品历史K线数据(仅主流币)
candles = test_market.get_market_history_candles(
    inst_id='BTC-USDT',
    after='1575561600000',
    before='1569945600000',
    bar='1D'
)
for candle in candles:
    print(candle)

# 指数K线数据每个粒度最多可获取最近1440条
candles = test_market.get_market_index_candles(
    inst_id='BTC-USDT',
    after='1575561600000',
    before='1569945600000',
    bar='1D'
)
for candle in candles:
    print(candle)

# 获取指数行情数据
tickers = test_market.get_market_index_tickers(inst_id='BTC-USDT')
for ticker in tickers:
    print(ticker)

# 标记价格K线数据每个粒度最多可获取最近1440条
candles = test_market.get_market_mark_price_candles(inst_id='BTC-USDT')
for candle in candles:
    print(candle)

# 获取单个产品行情信息
tickers = test_market.get_market_ticker(inst_id='BTC-USDT')
for ticker in tickers:
    print(ticker)

# 获取产品行情信息
tickers = test_market.get_market_tickers(inst_type='SPOT')
for ticker in tickers:
    print(ticker)

# 查询市场上的成交信息数据
trades = test_market.get_market_trades(inst_id='BTC-USDT')
for trade in trades:
    print(trade)

del test_market

##################################################################################
#
# 公共
#
##################################################################################

test_public = RestPublic()

# 获取所有可交易产品的信息列表
instruments = test_public.get_public_instruments(inst_type='SPOT')
for instrument in instruments:
    print(instrument)

### Python欧易交易所API对接实现量化交易平台搭建 #### 了解欧易交易所API接口 为了能够通过Python操作欧易交易所,开发者需要先注册成为该平台用户并获取API密钥。API提供了多种功能调用方式,包括市场数据查询、账户信息读取以及下单等功能[^1]。 #### 安装必要的库文件 在开始编写代码之前,需安装一些第三方库来简化HTTP请求处理过程和JSON解析工作。可以利用`pip install requests`命令完成对requests库的安装;另外还需要引入pandas用于数据分析处理[^2]。 ```bash pip install requests pandas ``` #### 获取行情数据 下面展示了一段简单的Python脚本用来获取最新价格: ```python import requests def get_latest_price(symbol='BTCUSDT'): url = f"https://api.okex.com/api/v5/market/ticker?instId={symbol}" response = requests.get(url).json() if 'data' not in response or len(response['data']) == 0: raise Exception('Failed to fetch latest price') ticker_data = response['data'][0] last_trade_price = float(ticker_data['last']) return last_trade_price ``` 这段程序定义了一个名为`get_latest_price()` 的函数,它接受一个参数`symbols`(默认为比特币/美元),并通过发送GET请求到指定URL地址获得最新的成交价[^3]。 #### 下单交易指令 当准备执行买卖动作时,则要构建更复杂的POST请求向服务器提交订单详情。这里给出一个简单例子说明如何创建限价买单: ```python import hashlib, hmac, time from urllib.parse import urlencode class OkexClient(object): def __init__(self, api_key=None, secret_key=None, passphrase=None): self.base_url = "https://www.okex.com" self.api_key = api_key self.secret_key = secret_key self.passphrase = passphrase def _sign(self, method, path, query_params=None, body=None): timestamp = str(time.time()).split('.')[0]+'.'+str(int(round(time.time()*1000)))[-3:] message = timestamp + method.upper() + path + (f"?{urlencode(query_params)}" if query_params else "") + (body if body else "") signature = base64.b64encode(hmac.new(bytes(self.secret_key,'utf8'), bytes(message,'utf8'), digestmod=hashlib.sha256).digest()) headers = { "OK-ACCESS-KEY": self.api_key, "OK-ACCESS-SIGN": signature.decode(), "OK-ACCESS-TIMESTAMP": timestamp, "OK-ACCESS-PASSPHRASE": self.passphrase, "Content-Type": "application/json", } return headers def place_order(self, side="buy", instrument_id="BTC-USDT", size=1, order_type="limit", price=None): endpoint = "/api/spot/v3/orders" params = {"side": side,"instrument_id": instrument_id,"type":order_type} if order_type=="limit": params["price"]=str(price) params["size"]=str(size) header=self._sign("POST",endpoint,params,json.dumps(params)) resp=requests.post(f"{self.base_url}{endpoint}",headers=header,data=json.dumps(params)).json() try: result={"status":"success","message":"","order_id":""} result.update(resp) return result except KeyError as e: error_msg=f"Error placing order: {e}. Response was:\n{resp}" logging.error(error_msg) return {"status":"failure","message":error_msg} client = OkexClient(api_key='your_apikey',secret_key='your_secretkey',passphrase='your_passphrase') print(client.place_order(side="buy", instrument_id="ETH-USDT", size=.01, order_type="market")) ``` 上述类实现了签名算法,并封装了下单逻辑。注意替换掉示例中的API Key等相关字段为自己实际申请得到的信息[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

marc2719

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值