diff --git a/.DS_Store b/.DS_Store index d3c415a..aedefaf 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/example/get_started_en.ipynb b/example/get_started_en.ipynb index 706e409..d75dcb6 100644 --- a/example/get_started_en.ipynb +++ b/example/get_started_en.ipynb @@ -2,37 +2,29 @@ "cells": [ { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, "source": [ "# Get Started\n", "## Install python package\n", "You can install `python-okx` from PyPi server." - ] + ], + "metadata": { + "collapsed": false + } }, { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, "outputs": [], "source": [ "! pip install python-okx --upgrade" - ] + ], + "metadata": { + "collapsed": false + } }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Sign up as an OKX user\n", "Please refer to [Create account](https://www.okx.com/account/register)" @@ -40,11 +32,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Create API Key\n", "Please refer to [Create API Key](https://www.okx.com/account/my-api)" @@ -52,11 +40,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Import API modules\n", "The following modules are available\n", @@ -80,7 +64,7 @@ "execution_count": null, "metadata": { "pycharm": { - "name": "#%%\n" + "is_executing": true } }, "outputs": [], @@ -90,11 +74,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Fill in your API key details" ] @@ -102,11 +82,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "api_key = \"xxxxx\"\n", @@ -116,11 +92,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Get available funds" ] @@ -130,7 +102,7 @@ "execution_count": null, "metadata": { "pycharm": { - "name": "#%%\n" + "is_executing": true } }, "outputs": [], @@ -147,11 +119,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Get market data" ] @@ -161,7 +129,7 @@ "execution_count": null, "metadata": { "pycharm": { - "name": "#%%\n" + "is_executing": true } }, "outputs": [], @@ -178,22 +146,14 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Handle errors" ] }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "You will the error code `51000` when. you run the following code. More details about the error code can be found in `msg`.\n", "Please refer to [error code](https://www.okx.com/docs-v5/en/#error-code) for addtional information." @@ -203,10 +163,10 @@ "cell_type": "code", "execution_count": null, "metadata": { + "scrolled": true, "pycharm": { - "name": "#%%\n" - }, - "scrolled": true + "is_executing": true + } }, "outputs": [], "source": [ @@ -222,11 +182,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "# Prepare for trading\n", "- Make sure you understand the basic trading rules. Please refer to [Basic Trading Rules](https://www.okx.com/support/hc/en-us/sections/360011507312)\n", @@ -235,11 +191,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Get account balance. Please refer to [Get balance](https://www.okx.com/docs-v5/en/#rest-api-account-get-balance)." ] @@ -248,9 +200,6 @@ "cell_type": "code", "execution_count": null, "metadata": { - "pycharm": { - "name": "#%%\n" - }, "scrolled": true }, "outputs": [], @@ -266,11 +215,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Get available trading pairs from [Get instruments](https://www.okx.com/docs-v5/en/#rest-api-public-data-get-instruments)." ] @@ -279,9 +224,6 @@ "cell_type": "code", "execution_count": null, "metadata": { - "pycharm": { - "name": "#%%\n" - }, "scrolled": true }, "outputs": [], @@ -300,11 +242,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Make sure you have enough funds to trade a certain pair. Please refer to [Get maximum tradable amount](https://www.okx.com/docs-v5/en/#rest-api-account-get-maximum-available-tradable-amount)" ] @@ -312,11 +250,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "import okx.Account as Account\n", @@ -335,11 +269,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "import okx.Account as Account\n", @@ -357,22 +287,14 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## In unified account, you can trade Spot under simple, single currency, multi currency and portfolio margin account mode. Please refer to [Introduction on Unified Account](https://www.okx.com/support/hc/en-us/articles/360054690791-1-统一交易账户介绍)" ] }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Get the current account configuration from the `acctLv` parameter in [Get account configuration](https://www.okx.com/docs-v5/en/#rest-api-account-get-account-configuration)." ] @@ -380,11 +302,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "import okx.Account as Account\n", @@ -409,22 +327,14 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "# Start Spot Trading" ] }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### Spot trading under simple/single-currency margin mode" ] @@ -432,11 +342,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "import okx.Trade as Trade\n", @@ -448,11 +354,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "#### place a limit order" ] @@ -460,11 +362,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "# limit order\n", @@ -486,11 +384,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "#### place a market order" ] @@ -498,11 +392,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "# market order\n", @@ -518,11 +408,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "#### place an order with tgtCcy=quote_ccy (only applicable to spot)" ] @@ -530,11 +416,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "# market order\n", @@ -551,11 +433,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "#### place an order with your own clOrdId" ] @@ -563,11 +441,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "# market order\n", @@ -584,11 +458,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### Spot trading under multi-currency/porfolio margin mode" ] @@ -596,11 +466,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "# cross-margin spot trading\n", @@ -622,11 +488,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### For additional information on the place order endpoint,please refer to [Place order](https://www.okx.com/docs-v5/en/#rest-api-trade-place-order)\n", "\n", @@ -636,11 +498,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "place_orders = [\n", @@ -654,11 +512,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To amend pending orders,please refer to [Amend order](https://www.okx.com/docs-v5/en/#rest-api-trade-amend-order)" ] @@ -666,11 +520,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.amend_order(\n", @@ -683,11 +533,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To amend orders in a batch, please refer to [Amend multiple orders](https://www.okx.com/docs-v5/en/#rest-api-trade-amend-multiple-orders)" ] @@ -695,11 +541,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "amend_orders = [\n", @@ -713,11 +555,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To cancel pending orders,please refer to [Cancel order](https://www.okx.com/docs-v5/en/#rest-api-trade-cancel-order)" ] @@ -725,11 +563,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.cancel_order(instId=\"BTC-USDT\", ordId = \"489093931993509888\")\n", @@ -738,11 +572,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To cancel orders in a batch,please refer to [Cancel multiple orders](https://www.okx.com/docs-v5/zh/#rest-api-trade-cancel-multiple-orders)" ] @@ -750,11 +580,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "cancel_orders = [\n", @@ -768,11 +594,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## Get details of a certain order, please refer to [Get order details](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-details)" ] @@ -780,11 +602,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.get_order(instId=\"BTC-USDT\", clOrdId=\"002\")\n", @@ -794,11 +612,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.get_order(instId=\"BTC-USDT\", ordId=\"497819823594909696\")\n", @@ -807,11 +621,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## To get the list of open orders,please refer to [Get order List](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-list)" ] @@ -819,11 +629,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.get_order_list()\n", @@ -832,11 +638,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To get past orders,please refer to [Get order history (last 7 days)](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-history-last-7-days) and [Get order history (last 3 months)](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-history-last-3-months)" ] @@ -844,11 +646,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.get_orders_history(\n", @@ -860,11 +658,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.get_orders_history_archive(\n", @@ -875,11 +669,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To get past trades,please refer to [Get transaction details (last 3 days)](https://www.okx.com/docs-v5/en/#rest-api-trade-get-transaction-details-last-3-days) and [Get transaction details (last 3 months) ](https://www.okx.com/docs-v5/en/#rest-api-trade-get-transaction-details-last-3-months)" ] @@ -887,11 +677,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.get_fills(\n", @@ -903,11 +689,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.get_fills_history(\n", @@ -918,11 +700,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### If you wish to place orders when the price reaches a certain level, you can place an algo order" ] @@ -930,11 +708,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.place_algo_order(\n", @@ -952,11 +726,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "## You can also use Stop Loss or Take Profit order to sell the currencies in your account" ] @@ -964,11 +734,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.place_algo_order(\n", @@ -986,22 +752,14 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### For additional information, please refer to [Place algo order](https://www.okx.com/docs-v5/en/#rest-api-trade-place-algo-order)" ] }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### Cancel pending algo orders (not including Iceberg order, TWAP order, Trailing Stop order),please refer to [Cancel algo order](https://www.okx.com/docs-v5/en/#rest-api-trade-cancel-algo-order)" ] @@ -1009,11 +767,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "algo_orders = [\n", @@ -1026,11 +780,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To get list of currently pending algo orders,please refer to [Get algo order list](https://www.okx.com/docs-v5/en/#rest-api-trade-get-algo-order-list)" ] @@ -1038,11 +788,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.order_algos_list(\n", @@ -1053,11 +799,7 @@ }, { "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%% md\n" - } - }, + "metadata": {}, "source": [ "### To get the past algo orders (last three months),please refer to [Get algo order history](https://www.okx.com/docs-v5/en/#rest-api-trade-get-algo-order-history)" ] @@ -1065,11 +807,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, + "metadata": {}, "outputs": [], "source": [ "result = tradeAPI.order_algos_history(\n", diff --git a/okx/.DS_Store b/okx/.DS_Store new file mode 100644 index 0000000..38734ca Binary files /dev/null and b/okx/.DS_Store differ diff --git a/okx/Account.py b/okx/Account.py index 2a087c8..e0a6d27 100644 --- a/okx/Account.py +++ b/okx/Account.py @@ -7,7 +7,6 @@ class AccountAPI(Client): def __init__(self, api_key='-1', api_secret_key='-1', passphrase='-1', use_server_time=False, flag='1', domain = 'https://www.okx.com',debug = True): Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, flag, domain,debug) - # Get Positions def get_position_risk(self, instType=''): params = {} @@ -61,8 +60,9 @@ class AccountAPI(Client): return self._request_with_params(GET, MAX_TRADE_SIZE, params) # Get Maximum Available Tradable Amount - def get_max_avail_size(self, instId, tdMode, ccy='', reduceOnly=''): - params = {'instId': instId, 'tdMode': tdMode, 'ccy': ccy, 'reduceOnly': reduceOnly} + def get_max_avail_size(self, instId, tdMode, ccy='', reduceOnly='', unSpotOffset='', quickMgnType=''): + params = {'instId': instId, 'tdMode': tdMode, 'ccy': ccy, 'reduceOnly': reduceOnly, + 'unSpotOffset': unSpotOffset, 'quickMgnType': quickMgnType} return self._request_with_params(GET, MAX_AVAIL_SIZE, params) # Increase / Decrease margin @@ -111,8 +111,8 @@ class AccountAPI(Client): return self._request_with_params(GET, MAX_WITHDRAWAL, params) # Get borrow repay - def borrow_repay(self, ccy='', side='', amt=''): - params = {'ccy': ccy, 'side': side, 'amt': amt} + def borrow_repay(self, ccy='', side='', amt='', ordId=''): + params = {'ccy': ccy, 'side': side, 'amt': amt, 'ordId': ordId} return self._request_with_params(POST, BORROW_REPAY, params) # Get borrow repay history @@ -126,8 +126,8 @@ class AccountAPI(Client): return self._request_with_params(GET, INTEREST_LIMITS, params) # Get Simulated Margin - def get_simulated_margin(self, instType ='',inclRealPos=True,instId='',pos=''): - params = {'instType': instType, 'inclRealPos': inclRealPos,'instId': instId,'pos': pos,} + def get_simulated_margin(self, instType='', inclRealPos=True, spotOffsetType='', simPos=[]): + params = {'instType': instType, 'inclRealPos': inclRealPos, 'spotOffsetType': spotOffsetType, 'simPos': simPos} return self._request_with_params(POST, SIMULATED_MARGIN, params) # Get Greeks @@ -162,5 +162,38 @@ class AccountAPI(Client): } return self._request_with_params(GET,GET_PM_LIMIT,params) + #- Get VIP interest accrued data + def get_VIP_interest_accrued_data(self, ccy='', ordId='', after='', before='', limit=''): + params = {'ccy': ccy, 'ordId': ordId, 'after': after, 'before': before, 'limit': limit} + return self._request_with_params(GET, GET_VIP_INTEREST_ACCRUED_DATA, params) + #- Get VIP interest deducted data + def get_VIP_interest_deducted_data(self, ccy='', ordId='', after='', before='', limit=''): + params = {'ccy': ccy, 'ordId': ordId, 'after': after, 'before': before, 'limit': limit} + return self._request_with_params(GET, GET_VIP_INTEREST_DEDUCTED_DATA, params) + # - Get VIP loan order list + def get_VIP_loan_order_list(self, ordId='',state='', ccy='', after='', before='', limit=''): + params = {'ordId': ordId, 'state': state, 'ccy': ccy,'after': after, 'before': before, 'limit': limit} + return self._request_with_params(GET, GET_VIP_LOAN_ORDER_LIST, params) + + #- Get VIP loan order detail + def get_VIP_loan_order_detail(self, ccy='', ordId='', after='', before='', limit=''): + params = {'ccy': ccy, 'ordId': ordId, 'after': after, 'before': before, 'limit': limit} + return self._request_with_params(GET, GET_VIP_LOAN_ORDER_DETAIL, params) + + #- Set risk offset type + def set_risk_offset_typel(self, type=''): + params = {'type': type} + return self._request_with_params(POST, SET_RISK_OFFSET_TYPE,params) + + # - Set auto loan + def set_auto_loan(self, autoLoan=''): + params = { + 'autoLoan': autoLoan + } + return self._request_with_params(POST, SET_AUTO_LOAN, params) + + #- Activate option + def activate_option(self): + return self._request_without_params(POST, ACTIVSTE_OPTION) diff --git a/okx/BlockTrading.py b/okx/BlockTrading.py index 0275555..4ff22a1 100644 --- a/okx/BlockTrading.py +++ b/okx/BlockTrading.py @@ -10,8 +10,10 @@ class BlockTradingAPI(Client): params = {} return self._request_with_params(GET, COUNTERPARTIES, params) - def create_rfq(self, counterparties=[], anonymous='false', clRfqId='', legs = []): - params = {'counterparties': counterparties, 'anonymous': anonymous, 'clRfqId': clRfqId, 'legs': legs} + def create_rfq(self, counterparties=[], anonymous='false', clRfqId='', tag='', allowPartialExecution='false', + legs=[]): + params = {'counterparties': counterparties, 'anonymous': anonymous, 'clRfqId': clRfqId, 'tag': tag, + 'allowPartialExecution': allowPartialExecution, 'legs': legs} return self._request_with_params(POST, CREATE_RFQ, params) def cancel_rfq(self, rfqId = '', clRfqId = ''): @@ -26,13 +28,13 @@ class BlockTradingAPI(Client): params = {} return self._request_with_params(POST, CANCEL_ALL_RSQS, params) - def execute_quote(self, rfqId='', quoteId=''): - params = {'rfqId': rfqId, 'quoteId': quoteId} + def execute_quote(self, rfqId='', quoteId='', legs=[]): + params = {'rfqId': rfqId, 'quoteId': quoteId, 'legs': legs} return self._request_with_params(POST, EXECUTE_QUOTE, params) - def create_quote(self, rfqId='', clQuoteId='', quoteSide = '', legs = [],anonymous=False,expiresIn=''): - params = {'rfqId': rfqId, 'clQuoteId': clQuoteId, 'quoteSide': quoteSide, 'legs': legs, - 'anonymous':anonymous,'expiresIn':expiresIn} + def create_quote(self, rfqId='', clQuoteId='', tag='', quoteSide='', legs=[], anonymous=False, expiresIn=''): + params = {'rfqId': rfqId, 'clQuoteId': clQuoteId, 'tag': tag, 'quoteSide': quoteSide, 'legs': legs, + 'anonymous': anonymous, 'expiresIn': expiresIn} return self._request_with_params(POST, CREATE_QUOTE, params) def cancel_quote(self, quoteId = '', clQuoteId = ''): @@ -55,8 +57,10 @@ class BlockTradingAPI(Client): params = {'rfqId': rfqId, 'clRfqId': clRfqId, 'quoteId':quoteId,'clQuoteId':clQuoteId, 'state': state, 'beginId': beginId, 'endId': endId, 'limit':limit} return self._request_with_params(GET, GET_QUOTES, params) - def get_trades(self, rfqId = '', clRfqId = '', quoteId = '', clQuoteId = '', state = '', beginId = '', endId = '', limit = ''): - params = {'rfqId': rfqId, 'clRfqId': clRfqId, 'quoteId':quoteId,'clQuoteId':clQuoteId, 'state': state, 'beginId': beginId, 'endId': endId, 'limit':limit} + def get_trades(self, rfqId='', clRfqId='', quoteId='', clQuoteId='', state='', beginId='', endId='', beginTs='', + endTs='', limit=''): + params = {'rfqId': rfqId, 'clRfqId': clRfqId, 'quoteId': quoteId, 'clQuoteId': clQuoteId, 'state': state, + 'beginId': beginId, 'endId': endId, 'beginTs': beginTs, 'endTs': endTs, 'limit': limit} return self._request_with_params(GET, GET_RFQ_TRADES, params) def get_public_trades(self, beginId = '', endId = '', limit = ''): @@ -68,4 +72,8 @@ class BlockTradingAPI(Client): def set_marker_instrument(self,params = []): - return self._request_with_params(POST, MARKER_INSTRUMENT_SETTING, params) \ No newline at end of file + return self._request_with_params(POST, MARKER_INSTRUMENT_SETTING, params) + + #Get Quote products + def get_quote_products(self): + return self._request_without_params(GET, MARKER_INSTRUMENT_SETTING) diff --git a/okx/CopyTrading.py b/okx/CopyTrading.py new file mode 100644 index 0000000..0f41254 --- /dev/null +++ b/okx/CopyTrading.py @@ -0,0 +1,71 @@ +from .client import Client +from .consts import * + + +class CopyTradingAPI(Client): + def __init__(self, api_key='-1', api_secret_key='-1', passphrase='-1', use_server_time=False, flag='1', + domain='https://www.okx.com', debug=True): + Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, flag, domain, debug) + + # Get existing leading positions + def get_existing_leading_positions(self, instId=''): + params = { + 'instId': instId + } + return self._request_with_params(GET, GET_EXISTING_LEADING_POSITIONS, params) + + # Get leading position history + def get_leading_position_history(self, instId='', after='', before='', limit=''): + params = { + 'instId': instId, + 'after': after, + 'before': before, + 'limit': limit + } + return self._request_with_params(GET, GET_LEADING_POSITIONS_HISTORY, params) + + # Place leading stop order + def place_leading_stop_order(self, subPosId='', tpTriggerPx='', slTriggerPx='', tpTriggerPxType='', slTriggerPxType=''): + params = { + 'subPosId': subPosId, + 'tpTriggerPx': tpTriggerPx, + 'slTriggerPx': slTriggerPx, + 'tpTriggerPxType': tpTriggerPxType, + 'slTriggerPxType': slTriggerPxType + } + return self._request_with_params(POST, PLACE_LEADING_STOP_ORDER, params) + + # Close leading position + def close_leading_position(self, subPosId=''): + params = { + 'subPosId': subPosId + } + return self._request_with_params(POST, CLOSE_LEADING_POSITIONS, params) + + # Get leading instruments + def get_leading_instruments(self): + return self._request_without_params(GET, GET_LEADING_POSITIONS) + + # Amend leading instruments + def amend_leading_instruments(self, instId=''): + params = { + 'instId': instId + } + return self._request_with_params(POST, AMEND_EXISTING_LEADING_POSITIONS, params) + + # Get profit sharing details + def get_profit_sharing_details(self, after='', before='', limit=''): + params = { + 'after': after, + 'before': before, + 'limit': limit + } + return self._request_with_params(GET, GET_PROFIT_SHARING_DETAILS, params) + + # Get total profit sharing + def get_total_profit_sharing(self): + return self._request_without_params(GET, GET_TOTAL_PROFIT_SHARING) + + # Get unrealized profit sharing details + def get_unrealized_profit_sharing_details(self): + return self._request_without_params(GET, GET_UNREALIZED_PROFIT_SHARING_DETAILS) diff --git a/okx/Earning.py b/okx/Earning.py index 0ecb256..44e3363 100644 --- a/okx/Earning.py +++ b/okx/Earning.py @@ -14,15 +14,17 @@ class EarningAPI(Client): } return self._request_with_params(GET,STACK_DEFI_OFFERS,params) - def purchase(self,productId = '',investData = [],term = ''): + def purchase(self, productId='', investData=[], term='', tag=''): params = { - 'productId':productId, - 'investData':investData + 'productId': productId, + 'investData': investData } if term != '': params['term'] = term - return self._request_with_params(POST,STACK_DEFI_PURCHASE,params) + if tag != '': + params['tag'] = tag + return self._request_with_params(POST, STACK_DEFI_PURCHASE, params) def redeem(self,ordId = '',protocolType = '',allowEarlyRedeem = ''): params = { @@ -59,6 +61,55 @@ class EarningAPI(Client): } return self._request_with_params(GET,STACK_DEFI_ORDERS_HISTORY,params) + # - Get saving balance + def get_saving_balance(self, ccy=''): + params = { + 'ccy': ccy + } + return self._request_with_params(GET, GET_SAVING_BALANCE, params) + # - Savings purchase/redemption + def savings_purchase_redemption(self, ccy='', amt='', side='', rate=''): + params = { + 'ccy': ccy, + 'amt': amt, + 'side': side, + 'rate': rate + } + return self._request_with_params(POST, SAVING_PURCHASE_REDEMPTION, params) + # - Set lending rate + def set_lending_rate(self, ccy='', rate=''): + params = { + 'ccy': ccy, + 'rate': rate + } + return self._request_with_params(POST, SET_LENDING_RATE, params) + + # - Get lending history + def get_lending_history(self, ccy='', after='', before='', limit=''): + params = { + 'ccy': ccy, + 'after': after, + 'before': before, + 'limit': limit + } + return self._request_with_params(GET, GET_LENDING_HISTORY, params) + + # - Get public borrow info (public) + def get_public_borrow_info(self, ccy=''): + params = { + 'ccy': ccy + } + return self._request_with_params(GET, GET_PUBLIC_BORROW_INFO, params) + + # - Get public borrow history (public) + def get_public_borrow_history(self, ccy='', after='', before='', limit=''): + params = { + 'ccy': ccy, + 'after': after, + 'before': before, + 'limit': limit + } + return self._request_with_params(GET, GET_PUBLIC_BORROW_HISTORY, params) diff --git a/okx/Funding.py b/okx/Funding.py index 56b4a76..31cd36d 100644 --- a/okx/Funding.py +++ b/okx/Funding.py @@ -30,13 +30,15 @@ class FundingAPI(Client): return self._request_with_params(POST, FUNDS_TRANSFER, params) # Withdrawal - def withdrawal(self, ccy, amt, dest, toAddr, fee,chain = '', clientId = ''): - params = {'ccy': ccy, 'amt': amt, 'dest': dest, 'toAddr': toAddr, 'fee': fee,'chain':chain,'clientId':clientId} + def withdrawal(self, ccy, amt, dest, toAddr, fee, chain='', areaCode='', clientId=''): + params = {'ccy': ccy, 'amt': amt, 'dest': dest, 'toAddr': toAddr, 'fee': fee, 'chain': chain, + 'areaCode': areaCode, 'clientId': clientId} return self._request_with_params(POST, WITHDRAWAL_COIN, params) # Get Deposit History - def get_deposit_history(self, ccy='', state='', after='', before='', limit='',txId='',depId=''): - params = {'ccy': ccy, 'state': state, 'after': after, 'before': before, 'limit': limit,'txId':txId,'depId':depId} + def get_deposit_history(self, ccy='', state='', after='', before='', limit='', txId='', depId='', fromWdId=''): + params = {'ccy': ccy, 'state': state, 'after': after, 'before': before, 'limit': limit, 'txId': txId, + 'depId': depId, 'fromWdId': fromWdId} return self._request_with_params(GET, DEPOSIT_HISTORIY, params) # Get Withdrawal History @@ -72,25 +74,21 @@ class FundingAPI(Client): params = {'ccy':ccy, 'invoice':invoice, 'memo':memo} return self._request_with_params(POST, WITHDRAWAL_LIGHTNING, params) - # POST SET LENDING RATE def set_lending_rate(self, ccy, rate): params = {'ccy': ccy, 'rate': rate} return self._request_with_params(POST, SET_LENDING_RATE, params) - # GET LENDING HISTORY def get_lending_history(self, ccy='', before='', after='', limit='' ): params = {'ccy': ccy, 'after': after, 'before': before, 'limit': limit } return self._request_with_params(GET, LENDING_HISTORY, params) - # GET LENDING RATE HISTORY def get_lending_rate_history(self, ccy='',after = '',before = '',limit = '' ): params = {'ccy': ccy,'after':after,'before':before,'limit':limit} return self._request_with_params(GET, LENDING_RATE_HISTORY, params) - # GET LENDING RATE SUMMARY def get_lending_rate_summary(self, ccy=''): params = {'ccy': ccy} @@ -124,3 +122,21 @@ class FundingAPI(Client): 'ccy':ccy } return self._request_with_params(GET, GET_SAVING_BALANCE, params) + + #Get non-tradable assets + def get_non_tradable_assets(self, ccy=''): + params = { + 'ccy': ccy + } + return self._request_with_params(GET, GET_NON_TRADABLE_ASSETS, params) + + #Get deposit withdraw status + def get_deposit_withdraw_status(self, wdId='', txId='', ccy='', to='', chain=''): + params = {'wdId': wdId, 'txId': txId, 'ccy': ccy, 'to': to, 'chain': chain} + return self._request_with_params(GET, GET_DEPOSIT_WITHDrAW_STATUS, params) + + #Get withdrawal history + def get_withdrawal_history(self, ccy='', wdId='', clientId='', txId='', type='', state='', after='', before ='', limit=''): + params = {'ccy': ccy, 'wdId': wdId, 'clientId': clientId, 'txId': txId, 'type': type, 'state': state, 'after': after, 'before': before, 'limit': limit} + return self._request_with_params(GET, GET_WITHDRAWAL_HISTORY, params) + diff --git a/okx/Grid.py b/okx/Grid.py index 6cf4991..0e4ea9d 100644 --- a/okx/Grid.py +++ b/okx/Grid.py @@ -76,3 +76,57 @@ class GridAPI(Client): 'duration':duration } return self._request_with_params(GET, GRID_AI_PARAM, params) + + # - Place recurring buy order + def place_recurring_buy_order(self, stgyName='', recurringList=[], period='', recurringDay='', recurringTime='', + timeZone='', amt='', investmentCcy='', tdMode='', algoClOrdId='', tag=''): + params = {'stgyName': stgyName, 'recurringList': recurringList, 'period': period, 'recurringDay': recurringDay, + 'recurringTime': recurringTime, + 'timeZone': timeZone, 'amt': amt, 'investmentCcy': investmentCcy, 'tdMode': tdMode, + 'algoClOrdId': algoClOrdId, 'tag': tag} + return self._request_with_params(POST, PLACE_RECURRING_BUY_ORDER, params) + + # - Amend recurring buy order + def amend_recurring_buy_order(self, algoId='', stgyName=''): + params = {'algoId': algoId, 'stgyName': stgyName} + return self._request_with_params(POST, AMEND_RECURRING_BUY_ORDER, params) + + # - Stop recurring buy order + def stop_recurring_buy_order(self, orders_data): + return self._request_with_params(POST, STOP_RECURRING_BUY_ORDER, orders_data) + + # - Get recurring buy order list + def get_recurring_buy_order_list(self, algoId='', after='', before='', limit=''): + params = { + 'algoId': algoId, + 'after': after, + 'before': before, + 'limit': limit + } + return self._request_with_params(GET, GET_RECURRING_BUY_ORDER_LIST, params) + + # - Get recurring buy order history + def get_recurring_buy_order_history(self, algoId='', after='', before='', limit=''): + params = { + 'algoId': algoId, + 'after': after, + 'before': before, + 'limit': limit + } + return self._request_with_params(GET, GET_RECURRING_BUY_ORDER_HISTORY, params) + + # - Get recurring buy order details + def get_recurring_buy_order_details(self, algoId=''): + params = {'algoId': algoId} + return self._request_with_params(GET, GET_RECURRING_BUY_ORDER_DETAILS, params) + + # - Get recurring buy sub orders + def get_recurring_buy_sub_orders(self, algoId='', ordId='', after='', before='', limit=''): + params = { + 'algoId': algoId, + 'ordId': ordId, + 'after': after, + 'before': before, + 'limit': limit + } + return self._request_with_params(GET, GET_RECURRING_BUY_SUB_ORDERS, params) diff --git a/okx/MarketData.py b/okx/MarketData.py index 1dc2bdf..da4691b 100644 --- a/okx/MarketData.py +++ b/okx/MarketData.py @@ -115,6 +115,20 @@ class MarketAPI(Client): } return self._request_with_params(GET, BLOCK_TRADES, params) + #- Get order lite book + def get_order_lite_book(self,instId = ''): + params = { + 'instId':instId + } + return self._request_with_params(GET, GET_ORDER_LITE_BOOK, params) + + #- Get option trades + def get_option_trades(self,instFamily = ''): + params = { + 'instFamily':instFamily + } + return self._request_with_params(GET, GET_OPTION_TRADES, params) + diff --git a/okx/PublicData.py b/okx/PublicData.py index 10438eb..8f915c0 100644 --- a/okx/PublicData.py +++ b/okx/PublicData.py @@ -56,13 +56,6 @@ class PublicAPI(Client): def get_system_time(self): return self._request_without_params(GET, SYSTEM_TIME) - # Get Liquidation Orders - def get_liquidation_orders(self, instType, mgnMode='', instId='', ccy='', uly='', alias='', state='', before='', - after='', limit='',instFamily =''): - params = {'instType': instType, 'mgnMode': mgnMode, 'instId': instId, 'ccy': ccy, 'uly': uly, - 'alias': alias, 'state': state, 'before': before, 'after': after, 'limit': limit,'instFamily':instFamily} - return self._request_with_params(GET, LIQUIDATION_ORDERS, params) - # Get Mark Price def get_mark_price(self, instType, uly='', instId='',instFamily = ''): params = {'instType': instType, 'uly': uly, 'instId': instId,'instFamily':instFamily} @@ -113,5 +106,19 @@ class PublicAPI(Client): } return self._request_with_params(GET, CONVERT_CONTRACT_COIN, params) + # Get option tickBands + def get_option_tickBands(self, instType='', instFamily=''): + params = { + 'instType': instType, + 'instFamily': instFamily + } + return self._request_with_params(GET, GET_OPTION_TICKBANDS, params) - + # Get option trades + def get_option_trades(self, instId='', instFamily='', optType=''): + params = { + 'instId': instId, + 'instFamily': instFamily, + 'optType': optType + } + return self._request_with_params(GET, GET_OPTION_TRADES, params) diff --git a/okx/SubAccount.py b/okx/SubAccount.py index ea0428b..09fce2f 100644 --- a/okx/SubAccount.py +++ b/okx/SubAccount.py @@ -59,5 +59,25 @@ class SubAccountAPI(Client): } return self._request_with_params(GET, GET_ASSET_SUBACCOUNT_BALANCE, params) + # - Get the user's affiliate rebate information + def get_the_user_affiliate_rebate_information(self, apiKey=''): + params = { + 'apiKey': apiKey + } + return self._request_with_params(GET, GET_THE_USER_AFFILIATE_REBATE, params) + # - Set sub_accounts VIP loan% + def set_sub_accounts_VIP_loan(self, enable='', alloc=[]): + params = { + 'enable': enable, + 'alloc': alloc + } + return self._request_with_params(POST, SET_SUB_ACCOUNTS_VIP_LOAN, params) + # - Get sub_account borrow interest and limit + def get_sub_account_borrow_interest_and_limit(self, subAcct='', ccy=''): + params = { + 'subAcct': subAcct, + 'ccy': ccy + } + return self._request_with_params(GET, GET_SUB_ACCOUNT_BORROW_INTEREST_AND_LIMIT, params) diff --git a/okx/Trade.py b/okx/Trade.py index 2db2e83..3df71fc 100644 --- a/okx/Trade.py +++ b/okx/Trade.py @@ -9,10 +9,13 @@ class TradeAPI(Client): # Place Order def place_order(self, instId, tdMode, side, ordType, sz, ccy='', clOrdId='', tag='', posSide='', px='', - reduceOnly='', tgtCcy=''): + reduceOnly='', tgtCcy='', tpTriggerPx='', tpOrdPx='', slTriggerPx='', slOrdPx='', + tpTriggerPxType='', slTriggerPxType='', quickMgnType='', stpId='', stpMode=''): params = {'instId': instId, 'tdMode': tdMode, 'side': side, 'ordType': ordType, 'sz': sz, 'ccy': ccy, 'clOrdId': clOrdId, 'tag': tag, 'posSide': posSide, 'px': px, 'reduceOnly': reduceOnly, - 'tgtCcy': tgtCcy} + 'tgtCcy': tgtCcy, 'tpTriggerPx': tpTriggerPx, 'tpOrdPx': tpOrdPx, 'slTriggerPx': slTriggerPx, + 'slOrdPx': slOrdPx, 'tpTriggerPxType': tpTriggerPxType, 'slTriggerPxType': slTriggerPxType, + 'quickMgnType': quickMgnType, 'stpId': stpId, 'stpMode': stpMode} return self._request_with_params(POST, PLACR_ORDER, params) # Place Multiple Orders @@ -29,10 +32,12 @@ class TradeAPI(Client): return self._request_with_params(POST, CANAEL_BATCH_ORDERS, orders_data) # Amend Order - def amend_order(self, instId, cxlOnFail='', ordId='', clOrdId='', reqId='', newSz='', newPx=''): + def amend_order(self, instId, cxlOnFail='', ordId='', clOrdId='', reqId='', newSz='', newPx='', newTpTriggerPx='', + newTpOrdPx='', newSlTriggerPx='', newSlOrdPx='', newTpTriggerPxType='', newSlTriggerPxType=''): params = {'instId': instId, 'cxlOnFailc': cxlOnFail, 'ordId': ordId, 'clOrdId': clOrdId, 'reqId': reqId, - 'newSz': newSz, - 'newPx': newPx} + 'newSz': newSz, 'newPx': newPx, 'newTpTriggerPx': newTpTriggerPx, 'newTpOrdPx': newTpOrdPx, + 'newSlTriggerPx': newSlTriggerPx, 'newSlOrdPx': newSlOrdPx, 'newTpTriggerPxType': newTpTriggerPxType, + 'newSlTriggerPxType': newSlTriggerPxType} return self._request_with_params(POST, AMEND_ORDER, params) # Amend Multiple Orders @@ -40,8 +45,9 @@ class TradeAPI(Client): return self._request_with_params(POST, AMEND_BATCH_ORDER, orders_data) # Close Positions - def close_positions(self, instId, mgnMode, posSide='', ccy='',autoCxl=''): - params = {'instId': instId, 'mgnMode': mgnMode, 'posSide': posSide, 'ccy': ccy,'autoCxl':autoCxl} + def close_positions(self, instId, mgnMode, posSide='', ccy='', autoCxl='', clOrdId='', tag=''): + params = {'instId': instId, 'mgnMode': mgnMode, 'posSide': posSide, 'ccy': ccy, 'autoCxl': autoCxl, + 'clOrdId': clOrdId, 'tag': tag} return self._request_with_params(POST, CLOSE_POSITION, params) # Get Order Details @@ -56,15 +62,19 @@ class TradeAPI(Client): return self._request_with_params(GET, ORDERS_PENDING, params) # Get Order History (last 7 days) - def get_orders_history(self, instType, uly='', instId='', ordType='', state='', after='', before='', limit='',instFamily = ''): + def get_orders_history(self, instType, uly='', instId='', ordType='', state='', after='', before='', begin='', + end='', limit='', instFamily=''): params = {'instType': instType, 'uly': uly, 'instId': instId, 'ordType': ordType, 'state': state, - 'after': after, 'before': before, 'limit': limit,'instFamily':instFamily} + 'after': after, 'before': before, 'begin': begin, 'end': end, 'limit': limit, + 'instFamily': instFamily} return self._request_with_params(GET, ORDERS_HISTORY, params) # Get Order History (last 3 months) - def get_orders_history_archive(self, instType, uly='', instId='', ordType='', state='', after='', before='', limit='',instFamily = ''): + def get_orders_history_archive(self, instType, uly='', instId='', ordType='', state='', after='', before='', + begin='', end='', limit='', instFamily=''): params = {'instType': instType, 'uly': uly, 'instId': instId, 'ordType': ordType, 'state': state, - 'after': after, 'before': before, 'limit': limit,'instFamily':instFamily} + 'after': after, 'before': before, 'begin': begin, 'end': end, 'limit': limit, + 'instFamily': instFamily} return self._request_with_params(GET, ORDERS_HISTORY_ARCHIVE, params) # Get Transaction Details @@ -80,7 +90,8 @@ class TradeAPI(Client): triggerPx='', orderPx='', tgtCcy='', pxVar='', pxSpread='', szLimit='', pxLimit='', timeInterval='', tpTriggerPxType='', slTriggerPxType='', - callbackRatio='',callbackSpread='',activePx='',tag='',triggerPxType=''): + callbackRatio='',callbackSpread='',activePx='',tag='',triggerPxType='',closeFraction='' + ,quickMgnType='',algoClOrdId=''): params = {'instId': instId, 'tdMode': tdMode, 'side': side, 'ordType': ordType, 'sz': sz, 'ccy': ccy, 'posSide': posSide, 'reduceOnly': reduceOnly, 'tpTriggerPx': tpTriggerPx, 'tpOrdPx': tpOrdPx, 'slTriggerPx': slTriggerPx, 'slOrdPx': slOrdPx, 'triggerPx': triggerPx, 'orderPx': orderPx, @@ -88,11 +99,9 @@ class TradeAPI(Client): 'timeInterval': timeInterval, 'pxSpread': pxSpread, 'tpTriggerPxType': tpTriggerPxType, 'slTriggerPxType': slTriggerPxType, 'callbackRatio' : callbackRatio, 'callbackSpread':callbackSpread,'activePx':activePx, - 'tag':tag,'triggerPxType':triggerPxType,} + 'tag':tag,'triggerPxType':triggerPxType,'closeFraction':closeFraction,'quickMgnType':quickMgnType,'algoClOrdId':algoClOrdId} return self._request_with_params(POST, PLACE_ALGO_ORDER, params) - - # Cancel Algo Order def cancel_algo_order(self, params): return self._request_with_params(POST, CANCEL_ALGOS, params) @@ -102,9 +111,9 @@ class TradeAPI(Client): return self._request_with_params(POST, Cancel_Advance_Algos, params) # Get Algo Order List - def order_algos_list(self, ordType ='', algoId='', instType='', instId='', after='', before='', limit=''): + def order_algos_list(self, ordType='', algoId='', instType='', instId='', after='', before='', limit='',algoClOrdId=''): params = {'ordType': ordType, 'algoId': algoId, 'instType': instType, 'instId': instId, 'after': after, - 'before': before, 'limit': limit} + 'before': before, 'limit': limit, 'algoClOrdId': algoClOrdId} return self._request_with_params(GET, ORDERS_ALGO_OENDING, params) # Get Algo Order History @@ -157,3 +166,18 @@ class TradeAPI(Client): 'limit':limit } return self._request_with_params(GET,ONE_CLICK_REPAY_HISTORY,params) + + # Get algo order details + def get_algo_order_details(self, algoId='', algoClOrdId=''): + params = {'algoId': algoId, 'algoClOrdId': algoClOrdId} + return self._request_with_params(GET, GET_ALGO_ORDER_DETAILS, params) + + # Amend algo order + def amend_algo_order(self, instId='', algoId='', algoClOrdId='', cxlOnFail='', reqId='', newSz='', + newTpTriggerPx='', newTpOrdPx='', newSlTriggerPx='', newSlOrdPx='', newTpTriggerPxType='', + newSlTriggerPxType=''): + params = {'instId': instId, 'algoId': algoId, 'algoClOrdId': algoClOrdId, 'cxlOnFail': cxlOnFail, + 'reqId': reqId, 'newSz': newSz, 'newTpTriggerPx': newTpTriggerPx, 'newTpOrdPx': newTpOrdPx, + 'newSlTriggerPx': newSlTriggerPx, 'newSlOrdPx': newSlOrdPx, + 'newTpTriggerPxType': newTpTriggerPxType, 'newSlTriggerPxType': newSlTriggerPxType} + return self._request_with_params(POST, AMEND_ALGO_ORDER, params) diff --git a/okx/__init__.py b/okx/__init__.py index 8dd9460..6d04186 100644 --- a/okx/__init__.py +++ b/okx/__init__.py @@ -2,4 +2,4 @@ Python SDK for the OKX API v5 """ -__version__="0.1.9" \ No newline at end of file +__version__="0.2.0" \ No newline at end of file diff --git a/okx/__pycache__/Account.cpython-310.pyc b/okx/__pycache__/Account.cpython-310.pyc new file mode 100644 index 0000000..a2e117d Binary files /dev/null and b/okx/__pycache__/Account.cpython-310.pyc differ diff --git a/okx/__pycache__/BlockTrading.cpython-310.pyc b/okx/__pycache__/BlockTrading.cpython-310.pyc new file mode 100644 index 0000000..386d74b Binary files /dev/null and b/okx/__pycache__/BlockTrading.cpython-310.pyc differ diff --git a/okx/__pycache__/CopyTrading.cpython-310.pyc b/okx/__pycache__/CopyTrading.cpython-310.pyc new file mode 100644 index 0000000..e4880b2 Binary files /dev/null and b/okx/__pycache__/CopyTrading.cpython-310.pyc differ diff --git a/okx/__pycache__/Earning.cpython-310.pyc b/okx/__pycache__/Earning.cpython-310.pyc new file mode 100644 index 0000000..f961a09 Binary files /dev/null and b/okx/__pycache__/Earning.cpython-310.pyc differ diff --git a/okx/__pycache__/Funding.cpython-310.pyc b/okx/__pycache__/Funding.cpython-310.pyc new file mode 100644 index 0000000..88fd90d Binary files /dev/null and b/okx/__pycache__/Funding.cpython-310.pyc differ diff --git a/okx/__pycache__/Grid.cpython-310.pyc b/okx/__pycache__/Grid.cpython-310.pyc new file mode 100644 index 0000000..15693f1 Binary files /dev/null and b/okx/__pycache__/Grid.cpython-310.pyc differ diff --git a/okx/__pycache__/MarketData.cpython-310.pyc b/okx/__pycache__/MarketData.cpython-310.pyc new file mode 100644 index 0000000..fa48a46 Binary files /dev/null and b/okx/__pycache__/MarketData.cpython-310.pyc differ diff --git a/okx/__pycache__/NDBroker.cpython-310.pyc b/okx/__pycache__/NDBroker.cpython-310.pyc new file mode 100644 index 0000000..c897f43 Binary files /dev/null and b/okx/__pycache__/NDBroker.cpython-310.pyc differ diff --git a/okx/__pycache__/PublicData.cpython-310.pyc b/okx/__pycache__/PublicData.cpython-310.pyc new file mode 100644 index 0000000..1171ce5 Binary files /dev/null and b/okx/__pycache__/PublicData.cpython-310.pyc differ diff --git a/okx/__pycache__/Status.cpython-310.pyc b/okx/__pycache__/Status.cpython-310.pyc new file mode 100644 index 0000000..f8f1b72 Binary files /dev/null and b/okx/__pycache__/Status.cpython-310.pyc differ diff --git a/okx/__pycache__/SubAccount.cpython-310.pyc b/okx/__pycache__/SubAccount.cpython-310.pyc new file mode 100644 index 0000000..06dd8ac Binary files /dev/null and b/okx/__pycache__/SubAccount.cpython-310.pyc differ diff --git a/okx/__pycache__/Trade.cpython-310.pyc b/okx/__pycache__/Trade.cpython-310.pyc new file mode 100644 index 0000000..da50df4 Binary files /dev/null and b/okx/__pycache__/Trade.cpython-310.pyc differ diff --git a/okx/__pycache__/__init__.cpython-310.pyc b/okx/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..9f23e77 Binary files /dev/null and b/okx/__pycache__/__init__.cpython-310.pyc differ diff --git a/okx/__pycache__/client.cpython-310.pyc b/okx/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000..75c94a9 Binary files /dev/null and b/okx/__pycache__/client.cpython-310.pyc differ diff --git a/okx/__pycache__/consts.cpython-310.pyc b/okx/__pycache__/consts.cpython-310.pyc new file mode 100644 index 0000000..897d7b6 Binary files /dev/null and b/okx/__pycache__/consts.cpython-310.pyc differ diff --git a/okx/__pycache__/exceptions.cpython-310.pyc b/okx/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000..22ea9dc Binary files /dev/null and b/okx/__pycache__/exceptions.cpython-310.pyc differ diff --git a/okx/__pycache__/utils.cpython-310.pyc b/okx/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000..e0e8fc0 Binary files /dev/null and b/okx/__pycache__/utils.cpython-310.pyc differ diff --git a/okx/client.py b/okx/client.py index 25c8a3d..fc9acd3 100644 --- a/okx/client.py +++ b/okx/client.py @@ -37,8 +37,6 @@ class Client(object): response = self.client.get(request_path, headers=header) elif method == c.POST: response = self.client.post(request_path, data=body, headers=header) - if not str(response.status_code).startswith('2'): - raise exceptions.OkxAPIException(response) return response.json() def _request_without_params(self, method, request_path): diff --git a/okx/consts.py b/okx/consts.py index 649e843..aec0f09 100644 --- a/okx/consts.py +++ b/okx/consts.py @@ -46,6 +46,13 @@ SIMULATED_MARGIN = '/api/v5/account/simulated_margin' GREEKS = '/api/v5/account/greeks' POSITIONS_HISTORY = '/api/v5/account/positions-history' #need add GET_PM_LIMIT = '/api/v5/account/position-tiers' #need add +GET_VIP_INTEREST_ACCRUED_DATA = '/api/v5/account/vip-interest-accrued' +GET_VIP_INTEREST_DEDUCTED_DATA = '/api/v5/account/vip-interest-deducted' +GET_VIP_LOAN_ORDER_LIST= '/api/v5/account/vip-loan-order-list' +GET_VIP_LOAN_ORDER_DETAIL= '/api/v5/account/vip-loan-order-detail' +SET_RISK_OFFSET_TYPE = '/api/v5/account/set-riskOffset-type' +SET_AUTO_LOAN = '/api/v5/account/set-auto-loan' +ACTIVSTE_OPTION = '/api/v5/account/activate-option' # funding-complete-testcomplete DEPOSIT_ADDRESS = '/api/v5/asset/deposit-address' @@ -68,6 +75,9 @@ LENDING_HISTORY = '/api/v5/asset/lending-history' LENDING_RATE_HISTORY = '/api/v5/asset/lending-rate-history' LENDING_RATE_SUMMARY = '/api/v5/asset/lending-rate-summary' GET_SAVING_BALANCE = '/api/v5/asset/saving-balance' #need to add +GET_WITHDRAWAL_HISTORY = '/api/v5/asset/withdrawal-history' +GET_NON_TRADABLE_ASSETS = '/api/v5/asset/non-tradable-assets' +GET_DEPOSIT_WITHDrAW_STATUS = '/api/v5/asset/deposit-withdraw-status' # Market Data-Complete-testComplete @@ -88,6 +98,8 @@ HISTORY_TRADES = '/api/v5/market/history-trades' #need to add BLOCK_TICKERS = '/api/v5/market/block-tickers' #need to add BLOCK_TICKER = '/api/v5/market/block-ticker'#need to add BLOCK_TRADES = '/api/v5/market/block-trades'#need to add +GET_ORDER_LITE_BOOK = '/api/v5/market/books-lite' +GET_OPTION_TRADES = '/api/v5/market/option/instrument-family-trades' # Public Data-Complete-testComplete INSTRUMENT_INFO = '/api/v5/public/instruments' @@ -108,6 +120,8 @@ UNDERLYING = '/api/v5/public/underlying' #need to add VIP_INTEREST_RATE_LOAN_QUOTA = '/api/v5/public/vip-interest-rate-loan-quota' #need to add INSURANCE_FUND = '/api/v5/public/insurance-fund'#need to add CONVERT_CONTRACT_COIN = '/api/v5/public/convert-contract-coin' #need to add +GET_OPTION_TICKBANDS = '/api/v5/public/instrument-tick-bands' +GET_OPTION_TRADES = '/api/v5/public/option-trades' # TRADING DATA-COMPLETE SUPPORT_COIN = '/api/v5/rubik/stat/trading-data/support-coin' @@ -140,6 +154,8 @@ CANCEL_ALGOS = '/api/v5/trade/cancel-algos' Cancel_Advance_Algos = '/api/v5/trade/cancel-advance-algos' ORDERS_ALGO_OENDING = '/api/v5/trade/orders-algo-pending' ORDERS_ALGO_HISTORY = '/api/v5/trade/orders-algo-history' +GET_ALGO_ORDER_DETAILS = '/api/v5/trade/order-algo' +AMEND_ALGO_ORDER = '/api/v5/trade/amend-algos' EASY_CONVERT_CURRENCY_LIST = '/api/v5/trade/easy-convert-currency-list' EASY_CONVERT = '/api/v5/trade/easy-convert' @@ -158,6 +174,9 @@ SUBACCOUNT_TRANSFER = '/api/v5/asset/subaccount/transfer' ENTRUST_SUBACCOUNT_LIST = '/api/v5/users/entrust-subaccount-list' #need to add SET_TRSNSFER_OUT = '/api/v5/users/subaccount/set-transfer-out' #need to add GET_ASSET_SUBACCOUNT_BALANCE = '/api/v5/asset/subaccount/balances' #need to add +GET_THE_USER_AFFILIATE_REBATE = '/api/v5/users/partner/if-rebate' +SET_SUB_ACCOUNTS_VIP_LOAN = '/api/v5/account/subaccount/set-loan-allocation' +GET_SUB_ACCOUNT_BORROW_INTEREST_AND_LIMIT = '/api/v5/account/subaccount/interest-limits' # Broker-all need to implmented-completed BROKER_INFO = '/api/v5/broker/nd/info' @@ -222,6 +241,13 @@ GRID_WITHDRAW_INCOME = '/api/v5/tradingBot/grid/withdraw-income' GRID_COMPUTE_MARIGIN_BALANCE = '/api/v5/tradingBot/grid/compute-margin-balance' GRID_MARGIN_BALANCE = '/api/v5/tradingBot/grid/margin-balance' GRID_AI_PARAM = '/api/v5/tradingBot/grid/ai-param' +PLACE_RECURRING_BUY_ORDER = '/api/v5/tradingBot/recurring/order-algo' +AMEND_RECURRING_BUY_ORDER = '/api/v5/tradingBot/recurring/amend-order-algo' +STOP_RECURRING_BUY_ORDER = '/api/v5/tradingBot/recurring/stop-order-algo' +GET_RECURRING_BUY_ORDER_LIST = '/api/v5/tradingBot/recurring/orders-algo-pending' +GET_RECURRING_BUY_ORDER_HISTORY = '/api/v5/tradingBot/recurring/orders-algo-history' +GET_RECURRING_BUY_ORDER_DETAILS = '/api/v5/tradingBot/recurring/orders-algo-details' +GET_RECURRING_BUY_SUB_ORDERS = '/api/v5/tradingBot/recurring/sub-orders' #stacking - all need to implement-testcomplete STACK_DEFI_OFFERS = '/api/v5/finance/staking-defi/offers' @@ -230,6 +256,24 @@ STACK_DEFI_REDEEM = '/api/v5/finance/staking-defi/redeem' STACK_DEFI_CANCEL = '/api/v5/finance/staking-defi/cancel' STACK_DEFI_ORDERS_ACTIVITY = '/api/v5/finance/staking-defi/orders-active' STACK_DEFI_ORDERS_HISTORY = '/api/v5/finance/staking-defi/orders-history' +GET_SAVING_BALANCE = '/api/v5/finance/savings/balance' +SAVING_PURCHASE_REDEMPTION = '/api/v5/finance/savings/purchase-redempt' +SET_LENDING_RATE = '/api/v5/finance/savings/set-lending-rate' +GET_LENDING_HISTORY = '/api/v5/finance/savings/lending-history' +GET_PUBLIC_BORROW_INFO = '/api/v5/finance/savings/lending-rate-summary' +GET_PUBLIC_BORROW_HISTORY = '/api/v5/finance/savings/lending-rate-history' # status-complete STATUS = '/api/v5/system/status' + +#Copy Trading +GET_EXISTING_LEADING_POSITIONS = '/api/v5/copytrading/current-subpositions' +GET_LEADING_POSITIONS_HISTORY = '/api/v5/copytrading/subpositions-history' +PLACE_LEADING_STOP_ORDER = '/api/v5/copytrading/algo-order' +CLOSE_LEADING_POSITIONS = '/api/v5/copytrading/close-subposition' +GET_LEADING_POSITIONS = '/api/v5/copytrading/instruments' +AMEND_EXISTING_LEADING_POSITIONS = '/api/v5/copytrading/set-instruments' +GET_PROFIT_SHARING_DETAILS = '/api/v5/copytrading/profit-sharing-details' +GET_TOTAL_PROFIT_SHARING = '/api/v5/copytrading/total-profit-sharing' +GET_UNREALIZED_PROFIT_SHARING_DETAILS = '/api/v5/copytrading/unrealized-profit-sharing-details' + diff --git a/okx/websocket/__pycache__/WsClientFactory.cpython-310.pyc b/okx/websocket/__pycache__/WsClientFactory.cpython-310.pyc new file mode 100644 index 0000000..721c2e6 Binary files /dev/null and b/okx/websocket/__pycache__/WsClientFactory.cpython-310.pyc differ diff --git a/okx/websocket/__pycache__/WsClientProtocol.cpython-310.pyc b/okx/websocket/__pycache__/WsClientProtocol.cpython-310.pyc new file mode 100644 index 0000000..5931c70 Binary files /dev/null and b/okx/websocket/__pycache__/WsClientProtocol.cpython-310.pyc differ diff --git a/okx/websocket/__pycache__/WsConnectManager.cpython-310.pyc b/okx/websocket/__pycache__/WsConnectManager.cpython-310.pyc new file mode 100644 index 0000000..6286ff1 Binary files /dev/null and b/okx/websocket/__pycache__/WsConnectManager.cpython-310.pyc differ diff --git a/okx/websocket/__pycache__/WsPrivate.cpython-310.pyc b/okx/websocket/__pycache__/WsPrivate.cpython-310.pyc new file mode 100644 index 0000000..c3638fc Binary files /dev/null and b/okx/websocket/__pycache__/WsPrivate.cpython-310.pyc differ diff --git a/okx/websocket/__pycache__/WsPublic.cpython-310.pyc b/okx/websocket/__pycache__/WsPublic.cpython-310.pyc new file mode 100644 index 0000000..9c2b204 Binary files /dev/null and b/okx/websocket/__pycache__/WsPublic.cpython-310.pyc differ diff --git a/okx/websocket/__pycache__/WsUtils.cpython-310.pyc b/okx/websocket/__pycache__/WsUtils.cpython-310.pyc new file mode 100644 index 0000000..dc33cf7 Binary files /dev/null and b/okx/websocket/__pycache__/WsUtils.cpython-310.pyc differ diff --git a/okx/websocket/__pycache__/__init__.cpython-310.pyc b/okx/websocket/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..c2eb84a Binary files /dev/null and b/okx/websocket/__pycache__/__init__.cpython-310.pyc differ diff --git a/test/.DS_Store b/test/.DS_Store new file mode 100644 index 0000000..38734ca Binary files /dev/null and b/test/.DS_Store differ diff --git a/test/AccountTest.py b/test/AccountTest.py index 2d08848..0a4c922 100644 --- a/test/AccountTest.py +++ b/test/AccountTest.py @@ -1,12 +1,12 @@ import unittest -from ..okx import Account +from okx import Account class AccountTest(unittest.TestCase): def setUp(self): - api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' - api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' - passphrase = 'Beijing123' + api_key = 'e2ea07df-15ca-405c-9e23-addb4aca8a42' + api_secret_key = 'DE69BED90FF154085B56020A88B2638A' + passphrase = '12345678aA.' self.AccountAPI = Account.AccountAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') ''' POSITIONS_HISTORY = '/api/v5/account/positions-history' #need add @@ -73,8 +73,36 @@ class AccountTest(unittest.TestCase): def test_get_greeks(self): print(self.AccountAPI.get_greeks()) ''' - def test_simulated_margin(self): - print(self.AccountAPI.get_simulated_margin()) + # def test_simulated_margin(self): + # print(self.AccountAPI.get_simulated_margin()) + # def test_get_VIP_interest_accrued_data(self): + # print(self.AccountAPI.get_VIP_interest_accrued_data()) + + # def test_get_VIP_interest_deducted_data(self): + # print(self.AccountAPI.get_VIP_interest_deducted_data()) + + # def test_get_VIP_loan_order_list(self): + # print(self.AccountAPI.get_VIP_loan_order_list()) + + # def test_get_VIP_loan_order_detail(self): + # print(self.AccountAPI.get_VIP_loan_order_detail(ordId='1')) + + # def test_set_risk_offset_typel(self): + # print(self.AccountAPI.set_risk_offset_typel(type='1')) + # + # def test_set_auto_loan(self): + # print(self.AccountAPI.set_auto_loan()) + # + # def test_activate_option(self): + # print(self.AccountAPI.activate_option()) + + # def test_get_max_avaliable_size(self): + # print(self.AccountAPI.get_max_avail_size(instId="BTC-USDT",tdMode="cash",quickMgnType='manual')) + # def test_borrow_repay(self): + # print(self.AccountAPI.borrow_repay("BTC", "borrow", "1.0")) + + def test_simulated_margin(self): + print(self.AccountAPI.get_simulated_margin(spotOffsetType='3')) if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/test/BlockTradingTest.py b/test/BlockTradingTest.py index 8d86974..4d062a9 100644 --- a/test/BlockTradingTest.py +++ b/test/BlockTradingTest.py @@ -1,12 +1,12 @@ import unittest -from ..okx import BlockTrading +from okx import BlockTrading class BlockTradingTest(unittest.TestCase): def setUp(self): - api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' - api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' - passphrase = 'Beijing123' - self.BlockTradingAPI = BlockTrading.BlockTradingAPI(use_server_time=False, flag='1') + api_key = 'a6f1e378-1c03-472d-ada0-710f4d51eebf' + api_secret_key = '74A6E1E03700D5EFCC2BBB7782170189' + passphrase = 'Qa131415!' + self.BlockTradingAPI = BlockTrading.BlockTradingAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') """ def test_get_counter_parties(self): @@ -42,7 +42,46 @@ class BlockTradingTest(unittest.TestCase): """ - def test_get_public_trades(self): - print(self.BlockTradingAPI.get_public_trades()) + # def test_get_public_trades(self): + # print(self.BlockTradingAPI.get_public_trades()) + + # def test_get_quote_products(self): + # print(self.BlockTradingAPI.get_quote_products()) + + def test_create_rfqs(self): + counterparties=['8924'] + legs =[{ + 'instId':"BTC-USDT", + 'sz':'25', + 'side':'buy', + 'posSide':'net', + 'tdMode':'cross', + 'ccy':'USDT' + }] + print(self.BlockTradingAPI.create_rfq(counterparties,allowPartialExecution='true',tag='1234',legs = legs)) + + # def test_execute_quotes(self): + # legs = [{ + # 'instId':"BTC-USDT", + # 'sz':'0.0001', + # }] + # print(self.BlockTradingAPI.execute_quote("3IR9E68","3IR9E80",legs)) + + # def test_create_quotes(self): + # legs = [{ + # 'instId': "BTC-USDT", + # 'sz': '25', + # 'side': 'buy', + # 'posSide': 'net', + # 'tdMode': 'cross', + # 'ccy': 'USDT' + # }] + # print(self.BlockTradingAPI.create_quote(rfqId='3IR9BT8',quoteSide='buy',legs=legs)) + + # def test_get_trade(self): + # print(self.BlockTradingAPI.get_trades()) + + + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/test/CopyTradingTest.py b/test/CopyTradingTest.py new file mode 100644 index 0000000..dd76a43 --- /dev/null +++ b/test/CopyTradingTest.py @@ -0,0 +1,40 @@ +import unittest +from okx import CopyTrading + +class CopyTradingTest(unittest.TestCase): + def setUp(self): + api_key = 'd4ee8839-1142-41c0-add5-e2e82a91efd2' + api_secret_key = '57E5BEFAB7BD024A91647819E9BCA285' + passphrase = '123456aA.' + self.StackingAPI = CopyTrading.CopyTradingAPI(api_key, api_secret_key, passphrase, use_server_time=False, + flag='0') + + # def test_get_existing_leading_positions(self): + # print(self.StackingAPI.get_existing_leading_positions(instId='DOGE-USDT-SWAP')) + + # def test_get_leading_position_history(self): + # print(self.StackingAPI.get_leading_position_history()) + + # def test_place_leading_stop_order(self): + # print(self.StackingAPI.place_leading_stop_order(subPosId='581247467976732672',tpTriggerPx='1')) + # + # def test_close_leading_position(self): + # print(self.StackingAPI.close_leading_position(subPosId='581247467976732672')) + + # def test_get_leading_instruments(self): + # print(self.StackingAPI.get_leading_instruments()) + + # def test_amend_leading_instruments(self): + # print(self.StackingAPI.amend_leading_instruments(instId='AAVE-USDT-SWAP')) + # + # def test_get_profit_sharing_details(self): + # print(self.StackingAPI.get_profit_sharing_details()) + # + # def test_get_total_profit_sharing(self): + # print(self.StackingAPI.get_total_profit_sharing()) + # + def test_get_unrealized_profit_sharing_details(self): + print(self.StackingAPI.get_unrealized_profit_sharing_details()) + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/test/EarningTest.py b/test/EarningTest.py new file mode 100644 index 0000000..f81dd76 --- /dev/null +++ b/test/EarningTest.py @@ -0,0 +1,45 @@ +import unittest +from okx import Earning + +class EarningTest(unittest.TestCase): + def setUp(self): + api_key = 'cfa1017d-940a-445f-af52-b340cbd6b0e0' + api_secret_key = '6C50A4E980230A4BBE7046411DED0276' + passphrase = '123456aA.' + self.StackingAPI = Earning.EarningAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='0') + + + def test_get_saving_balance(self): + print(self.StackingAPI.get_saving_balance(ccy='USDT')) + + # def test_savings_purchase_redemption(self): + # print(self.StackingAPI.savings_purchase_redemption(ccy='USDT',amt="0.1",side="redempt",rate="1")) + + # def test_set_lending_rate(self): + # print(self.StackingAPI.set_lending_rate(ccy='USDT',rate="1")) + + # def test_get_lending_history(self): + # print(self.StackingAPI.get_lending_history(ccy='USDT')) + + + # def test_get_public_borrow_info(self): + # print(self.StackingAPI.get_public_borrow_info(ccy='USDT')) + + # def test_get_public_borrow_history(self): + # print(self.StackingAPI.get_public_borrow_history(ccy='USDT')) + + + # def setUp(self): + # api_key = 'da097c9c-2f77-4dea-be18-2bfa77d0e394' + # api_secret_key = '56CC6C72D6B8A46EC993D48C83142A25' + # passphrase = '123456aA.' + # self.StackingAPI = Earning.EarningAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') + # def test_purcase(self): + # investData = [{ + # 'ccy': 'USDT', + # 'amt': '50' + # }] + # print(self.StackingAPI.purchase(productId='1456', investData=investData,term='100',tag='dfg')) + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/test/FundingTest.py b/test/FundingTest.py index 2cce1e1..ea8e872 100644 --- a/test/FundingTest.py +++ b/test/FundingTest.py @@ -1,13 +1,13 @@ import unittest -from ..okx import Funding +from okx import Funding class FundingTest(unittest.TestCase): def setUp(self): - api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' - api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' - passphrase = 'Beijing123' - self.FundingAPI = Funding.FundingAPI(use_server_time=False, flag='0') + api_key = 'cfa1017d-940a-445f-af52-b340cbd6b0e0' + api_secret_key = '6C50A4E980230A4BBE7046411DED0276' + passphrase = '123456aA.' + self.FundingAPI = Funding.FundingAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='0') """ CANCEL_WITHDRAWAL = '/api/v5/asset/cancel-withdrawal' #need add CONVERT_DUST_ASSETS = '/api/v5/asset/convert-dust-assets' #need add @@ -58,9 +58,25 @@ class FundingTest(unittest.TestCase): print(self.FundingAPI.get_lending_rate_summary('BTC')) """ - def test_get_lending_summary(self): - print(self.FundingAPI.get_lending_rate_summary('BTC')) - def test_get_lending_rate_history(self): - print(self.FundingAPI.get_lending_rate_history()) + # def test_get_lending_summary(self): + # print(self.FundingAPI.get_lending_rate_summary('BTC')) + # def test_get_lending_rate_history(self): + # print(self.FundingAPI.get_lending_rate_history()) + + # def test_get_non_tradable_assets(self): + # print(self.FundingAPI.get_non_tradable_assets()) + + def test_get_deposit_withdraw_status(self): + print(self.FundingAPI.get_deposit_withdraw_status(wdId='84804812')) + + # def test_get_withdrawal_history(self): + # print(self.FundingAPI.get_withdrawal_history()) + + # def test_get_deposit_history(self): + # print(self.FundingAPI.get_deposit_history()) + + # def test_withdrawal(self): + # print(self.FundingAPI.withdrawal(ccy='USDT',amt='1',dest='3',toAddr='18740405107',fee='0',areaCode='86')) + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/test/GridTest.py b/test/GridTest.py index 072e67c..5efb68a 100644 --- a/test/GridTest.py +++ b/test/GridTest.py @@ -1,12 +1,12 @@ import unittest -from ..okx import Grid +from okx import Grid class GridTest(unittest.TestCase): def setUp(self): - api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' - api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' - passphrase = 'Beijing123' + api_key = 'da097c9c-2f77-4dea-be18-2bfa77d0e394' + api_secret_key = '56CC6C72D6B8A46EC993D48C83142A25' + passphrase = '123456aA.' self.GridAPI = Grid.GridAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1', debug=False) """ GRID_COMPUTE_MARIGIN_BALANCE = '/api/v5/tradingBot/grid/compute-margin-balance' @@ -49,7 +49,37 @@ class GridTest(unittest.TestCase): """ - def test_order_algo(self): - print(self.GridAPI.grid_order_algo("BTC-USDT","grid","45000","20000","100","1",quoteSz="50")) + # def test_order_algo(self): + # print(self.GridAPI.grid_order_algo("BTC-USDT","grid","45000","20000","100","1",quoteSz="50")) + + # def test_place_recurring_buy_order(self): + # print(self.GridAPI.place_recurring_buy_order(stgyName="jzhtest",recurringList=[{ + # 'ccy':"ETH", + # 'ratio':'1' + # }],period="daily",recurringDay='1',recurringTime='0',timeZone='8',amt='100',investmentCcy='USDT',tdMode='cross')) + + # def test_amend_recurring_buy_order(self): + # print(self.GridAPI.amend_recurring_buy_order(algoId="581185292170952704",stgyName="changtest")) + + # def test_stop_recurring_buy_order(self): + # orderData = [{ + # "algoId": "581190894481838080" + # }] + # print(self.GridAPI.stop_recurring_buy_order(orderData)) + + # def test_get_recurring_buy_order_list(self): + # print(self.GridAPI.get_recurring_buy_order_list()) + + # def test_get_recurring_buy_order_history(self): + # print(self.GridAPI.get_recurring_buy_order_history()) + + # def test_get_recurring_buy_order_details(self): + # print(self.GridAPI.get_recurring_buy_order_details(algoId="581191143417970688")) + + # def test_get_recurring_buy_sub_orders(self): + # print(self.GridAPI.get_recurring_buy_sub_orders(algoId="581191143417970688")) + + #581191143417970688 + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/test/MarketTest.py b/test/MarketTest.py index fdf8df7..7ce0bec 100644 --- a/test/MarketTest.py +++ b/test/MarketTest.py @@ -1,6 +1,6 @@ import unittest -from ..okx import MarketData +from okx import MarketData ''' ORACLE = '/api/v5/market/open-oracle' #need to update? if it is open oracle @@ -58,7 +58,11 @@ class MarketAPITest(unittest.TestCase): print(self.MarketApi.get_volume()) ''' + # def test_get_order_lite_book(self): + # print(self.MarketApi.get_order_lite_book(instId='BTC-USDT')) + def test_get_option_trades(self): + print(self.MarketApi.get_option_trades(instFamily='BTC-USD')) if __name__ == "__main__": diff --git a/test/PublicDataTest.py b/test/PublicDataTest.py index f0b5138..f723425 100644 --- a/test/PublicDataTest.py +++ b/test/PublicDataTest.py @@ -1,10 +1,10 @@ import unittest -from ..okx import PublicData +from okx import PublicData class publicDataTest(unittest.TestCase): def setUp(self): - api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' - api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' - passphrase = 'Beijing123' + api_key = 'da097c9c-2f77-4dea-be18-2bfa77d0e394' + api_secret_key = '56CC6C72D6B8A46EC993D48C83142A25' + passphrase = '123456aA.' self.publicDataApi = PublicData.PublicAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') ''' TestCase For: @@ -50,8 +50,14 @@ class publicDataTest(unittest.TestCase): print(self.publicDataApi.get_mark_price('SWAP')) ''' - def test_position_tier(self): - print(self.publicDataApi.get_position_tiers('SWAP','cross',uly='ETH-USD')) + # def test_position_tier(self): + # print(self.publicDataApi.get_position_tiers('SWAP','cross',uly='ETH-USD')) + + # def test_get_option_tickBands(self): + # print(self.publicDataApi.get_option_tick_bands(instType='OPTION')) + + def test_get_option_trades(self): + print(self.publicDataApi.get_option_trades(instFamily='BTC-USD')) if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/test/StackingTest.py b/test/StackingTest.py index 1d6a875..feff55b 100644 --- a/test/StackingTest.py +++ b/test/StackingTest.py @@ -1,5 +1,5 @@ import unittest -from ..okx import Status +from okx import Status class StackingTest(unittest.TestCase): def setUp(self): @@ -22,15 +22,6 @@ class StackingTest(unittest.TestCase): def test_purcase(self): print(self.StackingAPI.purchase(1456,"USDT","100","0")) - def test_redeem(self): - print(self.StackingAPI.redeem()) - def test_cencel(self): - print(self.StackingAPI.cancel()) - def test_order_activity(self): - print(self.StackingAPI.get_activity_orders()) - def test_order_history(self): - print(self.StackingAPI.stack_get_order_history()) - if __name__ == "__main__": unittest.main() \ No newline at end of file diff --git a/test/SubAccountTest.py b/test/SubAccountTest.py index c251c0b..69491d9 100644 --- a/test/SubAccountTest.py +++ b/test/SubAccountTest.py @@ -1,11 +1,11 @@ import unittest -from ..okx import SubAccount +from okx import SubAccount class SubAccountTest(unittest.TestCase): def setUp(self): - api_key = '52c37310-a8b0-454a-8191-3250acff2626' - api_secret_key = 'EC37534156E6B8C32E78FE8D8C1D506B' - passphrase = 'Hanhao0.0' + api_key = 'e2ea07df-15ca-405c-9e23-addb4aca8a42' + api_secret_key = 'DE69BED90FF154085B56020A88B2638A' + passphrase = '12345678aA.' self.SubAccountApi = SubAccount.SubAccountAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') ''' ENTRUST_SUBACCOUNT_LIST = '/api/v5/users/entrust-subaccount-list' #need to add @@ -36,5 +36,15 @@ class SubAccountTest(unittest.TestCase): ''' + # def test_get_the_user_affiliate_rebate_information(self): + # print(self.SubAccountApi.get_the_user_affiliate_rebate_information(apiKey='3af380a7-72af-4cc6-80d1-4b5a34ea69ad')) + + # def test_set_sub_accounts_VIP_loan(self): + # print(self.SubAccountApi.set_sub_accounts_VIP_loan(enable='true',alloc=[{'subAcct':'coretrading7', + # 'loanAlloc':'1'}])) + + def test_get_sub_account_borrow_interest_and_limit(self): + print(self.SubAccountApi.get_sub_account_borrow_interest_and_limit(subAcct='coretrading7')) + if __name__ == "__main__": unittest.main() \ No newline at end of file diff --git a/test/TradeTest.py b/test/TradeTest.py index d963787..0434564 100644 --- a/test/TradeTest.py +++ b/test/TradeTest.py @@ -1,10 +1,10 @@ import unittest -from ..okx import Trade +from okx import Trade class TradeTest(unittest.TestCase): def setUp(self): - api_key = '35d8f27e-63cc-45bc-a578-45d76363d47f' - api_secret_key = '0B7C968025BC2D4D71CF74771EA0E15C' - passphrase = '123456' + api_key = 'da097c9c-2f77-4dea-be18-2bfa77d0e394' + api_secret_key = '56CC6C72D6B8A46EC993D48C83142A25' + passphrase = '123456aA.' self.tradeApi = Trade.TradeAPI(api_key, api_secret_key, passphrase, False, '1') """ def test_place_order(self): @@ -112,10 +112,80 @@ class TradeTest(unittest.TestCase): """ #485903392536264704 #485936482235191296 - def test_oneclick_repay_history(self): - print(self.tradeApi.oneclick_repay_history()) + # def test_oneclick_repay_history(self): + # print(self.tradeApi.oneclick_repay_history()) + # def test_order_algo(self): + # print(self.tradeApi.place_algo_order(instId='BTC-USDT-SWAP', tdMode='cross', side='buy', ordType='conditional', \ + # tpTriggerPx='15', tpOrdPx='18',sz='2')) + # 581628185981308928 + # def test_get_algo_order_details(self): + # print(self.tradeApi.get_algo_order_details(algoId='581628185981308928')) + #581628185981308928 + # def test_amend_algo_order(self): + # print(self.tradeApi.amend_algo_order(instId='BTC-USDT-SWAP', algoId='581628185981308928',newSz='3')) + # def test_get_order_history(self): + # print(self.tradeApi.get_orders_history(instType="SPOT",begin='1684857629313',end='1684857629313')) + + # def test_get_order_histry_archive(self): + # print(self.tradeApi.get_orders_history_archive(instType="SPOT",begin='1684857629313',end='1684857629313')) + # def test_place_order(self): + # print(self.tradeApi.place_order("BTC-USDT", tdMode="cross", clOrdId="asCai1", side="buy", ordType="limit", + # sz="0.01", px="18000")) + # def test_batch_order(self): + # orderData = [{ + # "instId": "ETH-USDT", + # "tdMode": "cross", + # "clOrdId": "b151121", + # "side": "buy", + # "ordType": "limit", + # "px": "2.15", + # "sz": "2" + # }, + # { + # "instId": "BTC-USDT", + # "tdMode": "cross", + # "clOrdId": "b152233", + # "side": "buy", + # "ordType": "limit", + # "px": "2.15", + # "sz": "2" + # }] + # print(self.tradeApi.place_multiple_orders(orderData)) + + #581616258865516544 + #581616258865516545 + # def test_amend_order(self): + # print(self.tradeApi.amend_order("BTC-USDT", ordId="581616258865516544", newSz="0.03")) + # def test_amend_order_batch(self): + # orderData = [ + # { + # 'instId': 'ETH-USDT', + # 'ordId': '581616258865516544', + # 'newSz': '0.02' + # }, + # { + # 'instId': 'BTC-USDT', + # 'ordId': '581616258865516545', + # 'newPx': '3.0' + # } + # ] + # print(self.tradeApi.amend_multiple_orders(orderData)) + + # def test_order_algo(self): + # + # print(self.tradeApi.place_algo_order(instId='BTC-USDT-SWAP', tdMode='cross', side='buy', ordType='conditional', \ + # tpTriggerPx='15', tpOrdPx='18', sz='2',algoClOrdId='7678687',quickMgnType='manual')) + + def test_order_algos_list(self): + print(self.tradeApi.order_algos_list(ordType='conditional')) + + # def test_order_algo(self): + # print(self.tradeApi.place_order(instId='BTC-USDT-SWAP', tdMode='cross', side='buy',px='121',sz='2', + # clOrdId='234234565535',ordType='market')) + # def test_close_all_positions(self): + # print(self.tradeApi.close_positions(instId="BTC-USDT-SWAP", mgnMode="cross",clOrdId='1213124')) if __name__=='__main__': unittest.main() diff --git a/test/WsPublicTest.py b/test/WsPublicTest.py index e0fbec5..957f234 100644 --- a/test/WsPublicTest.py +++ b/test/WsPublicTest.py @@ -8,7 +8,8 @@ def publicCallback(message): if __name__ == '__main__': - url = "wss://ws.okx.com:8443/ws/v5/public" + #url = "wss://wspri.coinall.ltd:8443/ws/v5/ipublic?brokerId=9999" + url = "wss://wspap.okx.com:8443/ws/v5/public" ws = WsPublic(url=url) ws.start() args = [] diff --git a/test/__pycache__/AccountTest.cpython-310.pyc b/test/__pycache__/AccountTest.cpython-310.pyc new file mode 100644 index 0000000..695099c Binary files /dev/null and b/test/__pycache__/AccountTest.cpython-310.pyc differ diff --git a/test/__pycache__/BlockTradingTest.cpython-310.pyc b/test/__pycache__/BlockTradingTest.cpython-310.pyc new file mode 100644 index 0000000..1c78dbf Binary files /dev/null and b/test/__pycache__/BlockTradingTest.cpython-310.pyc differ diff --git a/test/__pycache__/BrokerTest.cpython-310.pyc b/test/__pycache__/BrokerTest.cpython-310.pyc new file mode 100644 index 0000000..122df9d Binary files /dev/null and b/test/__pycache__/BrokerTest.cpython-310.pyc differ diff --git a/test/__pycache__/ConvertTest.cpython-310.pyc b/test/__pycache__/ConvertTest.cpython-310.pyc new file mode 100644 index 0000000..178dd55 Binary files /dev/null and b/test/__pycache__/ConvertTest.cpython-310.pyc differ diff --git a/test/__pycache__/CopyTradingTest.cpython-310.pyc b/test/__pycache__/CopyTradingTest.cpython-310.pyc new file mode 100644 index 0000000..9375323 Binary files /dev/null and b/test/__pycache__/CopyTradingTest.cpython-310.pyc differ diff --git a/test/__pycache__/EarningTest.cpython-310.pyc b/test/__pycache__/EarningTest.cpython-310.pyc new file mode 100644 index 0000000..45c80bb Binary files /dev/null and b/test/__pycache__/EarningTest.cpython-310.pyc differ diff --git a/test/__pycache__/FundingTest.cpython-310.pyc b/test/__pycache__/FundingTest.cpython-310.pyc new file mode 100644 index 0000000..5bfe0a7 Binary files /dev/null and b/test/__pycache__/FundingTest.cpython-310.pyc differ diff --git a/test/__pycache__/GridTest.cpython-310.pyc b/test/__pycache__/GridTest.cpython-310.pyc new file mode 100644 index 0000000..2e7abd9 Binary files /dev/null and b/test/__pycache__/GridTest.cpython-310.pyc differ diff --git a/test/__pycache__/MarketTest.cpython-310.pyc b/test/__pycache__/MarketTest.cpython-310.pyc new file mode 100644 index 0000000..5100ae0 Binary files /dev/null and b/test/__pycache__/MarketTest.cpython-310.pyc differ diff --git a/test/__pycache__/PublicDataTest.cpython-310.pyc b/test/__pycache__/PublicDataTest.cpython-310.pyc new file mode 100644 index 0000000..49c2efb Binary files /dev/null and b/test/__pycache__/PublicDataTest.cpython-310.pyc differ diff --git a/test/__pycache__/StackingTest.cpython-310.pyc b/test/__pycache__/StackingTest.cpython-310.pyc new file mode 100644 index 0000000..6bad039 Binary files /dev/null and b/test/__pycache__/StackingTest.cpython-310.pyc differ diff --git a/test/__pycache__/SubAccountTest.cpython-310.pyc b/test/__pycache__/SubAccountTest.cpython-310.pyc new file mode 100644 index 0000000..0f4bcab Binary files /dev/null and b/test/__pycache__/SubAccountTest.cpython-310.pyc differ diff --git a/test/__pycache__/TradeTest.cpython-310.pyc b/test/__pycache__/TradeTest.cpython-310.pyc new file mode 100644 index 0000000..50bc818 Binary files /dev/null and b/test/__pycache__/TradeTest.cpython-310.pyc differ diff --git a/test/__pycache__/TradingDataTest.cpython-310.pyc b/test/__pycache__/TradingDataTest.cpython-310.pyc new file mode 100644 index 0000000..c7b30b7 Binary files /dev/null and b/test/__pycache__/TradingDataTest.cpython-310.pyc differ diff --git a/test/ws_org.py b/test/ws_org.py new file mode 100644 index 0000000..c429cfb --- /dev/null +++ b/test/ws_org.py @@ -0,0 +1,542 @@ +import asyncio +import base64 +import datetime +import hmac +import json +import time +import zlib + +import requests +import websockets + + +def get_timestamp(): + now = datetime.datetime.now() + t = now.isoformat("T", "milliseconds") + return t + "Z" + + +def get_server_time(): + url = "https://www.okx.com/api/v5/public/time" + response = requests.get(url) + if response.status_code == 200: + return response.json()['data'][0]['ts'] + else: + return "" + + +def get_local_timestamp(): + return int(time.time()) + + +def login_params(timestamp, api_key, passphrase, secret_key): + message = timestamp + 'GET' + '/users/self/verify' + + mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256') + d = mac.digest() + sign = base64.b64encode(d) + + login_param = {"op": "login", "args": [{"apiKey": api_key, + "passphrase": passphrase, + "timestamp": timestamp, + "sign": sign.decode("utf-8")}]} + login_str = json.dumps(login_param) + return login_str + + +def partial(res): + data_obj = res['data'][0] + bids = data_obj['bids'] + asks = data_obj['asks'] + instrument_id = res['arg']['instId'] + # print('全量数据bids为:' + str(bids)) + # print('档数为:' + str(len(bids))) + # print('全量数据asks为:' + str(asks)) + # print('档数为:' + str(len(asks))) + return bids, asks, instrument_id + + +def update_bids(res, bids_p): + # 获取增量bids数据 + bids_u = res['data'][0]['bids'] + # print('增量数据bids为:' + str(bids_u)) + # print('档数为:' + str(len(bids_u))) + # bids合并 + for i in bids_u: + bid_price = i[0] + for j in bids_p: + if bid_price == j[0]: + if i[1] == '0': + bids_p.remove(j) + break + else: + del j[1] + j.insert(1, i[1]) + break + else: + if i[1] != "0": + bids_p.append(i) + else: + bids_p.sort(key=lambda price: sort_num(price[0]), reverse=True) + # print('合并后的bids为:' + str(bids_p) + ',档数为:' + str(len(bids_p))) + return bids_p + + +def update_asks(res, asks_p): + # 获取增量asks数据 + asks_u = res['data'][0]['asks'] + # print('增量数据asks为:' + str(asks_u)) + # print('档数为:' + str(len(asks_u))) + # asks合并 + for i in asks_u: + ask_price = i[0] + for j in asks_p: + if ask_price == j[0]: + if i[1] == '0': + asks_p.remove(j) + break + else: + del j[1] + j.insert(1, i[1]) + break + else: + if i[1] != "0": + asks_p.append(i) + else: + asks_p.sort(key=lambda price: sort_num(price[0])) + # print('合并后的asks为:' + str(asks_p) + ',档数为:' + str(len(asks_p))) + return asks_p + + +def sort_num(n): + if n.isdigit(): + return int(n) + else: + return float(n) + + +def check(bids, asks): + # 获取bid档str + bids_l = [] + bid_l = [] + count_bid = 1 + while count_bid <= 25: + if count_bid > len(bids): + break + bids_l.append(bids[count_bid - 1]) + count_bid += 1 + for j in bids_l: + str_bid = ':'.join(j[0: 2]) + bid_l.append(str_bid) + # 获取ask档str + asks_l = [] + ask_l = [] + count_ask = 1 + while count_ask <= 25: + if count_ask > len(asks): + break + asks_l.append(asks[count_ask - 1]) + count_ask += 1 + for k in asks_l: + str_ask = ':'.join(k[0: 2]) + ask_l.append(str_ask) + # 拼接str + num = '' + if len(bid_l) == len(ask_l): + for m in range(len(bid_l)): + num += bid_l[m] + ':' + ask_l[m] + ':' + elif len(bid_l) > len(ask_l): + # bid档比ask档多 + for n in range(len(ask_l)): + num += bid_l[n] + ':' + ask_l[n] + ':' + for l in range(len(ask_l), len(bid_l)): + num += bid_l[l] + ':' + elif len(bid_l) < len(ask_l): + # ask档比bid档多 + for n in range(len(bid_l)): + num += bid_l[n] + ':' + ask_l[n] + ':' + for l in range(len(bid_l), len(ask_l)): + num += ask_l[l] + ':' + + new_num = num[:-1] + int_checksum = zlib.crc32(new_num.encode()) + fina = change(int_checksum) + return fina + + +def change(num_old): + num = pow(2, 31) - 1 + if num_old > num: + out = num_old - num * 2 - 2 + else: + out = num_old + return out + + +# subscribe channels un_need login +async def subscribe_without_login(url, channels): + l = [] + while True: + try: + async with websockets.connect(url) as ws: + sub_param = {"op": "subscribe", "args": channels} + sub_str = json.dumps(sub_param) + await ws.send(sub_str) + print(f"send: {sub_str}") + + while True: + try: + res = await asyncio.wait_for(ws.recv(), timeout=25) + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e: + try: + await ws.send('ping') + res = await ws.recv() + print(res) + continue + except Exception as e: + print("连接关闭,正在重连……") + break + + print(get_timestamp() + res) + res = eval(res) + if 'event' in res: + continue + for i in res['arg']: + if 'books' in res['arg'][i] and 'books5' not in res['arg'][i]: + # 订阅频道是深度频道 + if res['action'] == 'snapshot': + for m in l: + if res['arg']['instId'] == m['instrument_id']: + l.remove(m) + # 获取首次全量深度数据 + bids_p, asks_p, instrument_id = partial(res) + d = {} + d['instrument_id'] = instrument_id + d['bids_p'] = bids_p + d['asks_p'] = asks_p + l.append(d) + + # 校验checksum + checksum = res['data'][0]['checksum'] + # print('推送数据的checksum为:' + str(checksum)) + check_num = check(bids_p, asks_p) + # print('校验后的checksum为:' + str(check_num)) + if check_num == checksum: + print("校验结果为:True") + else: + print("校验结果为:False,正在重新订阅……") + + # 取消订阅 + await unsubscribe_without_login(url, channels) + # 发送订阅 + async with websockets.connect(url) as ws: + sub_param = {"op": "subscribe", "args": channels} + sub_str = json.dumps(sub_param) + await ws.send(sub_str) + print(f"send: {sub_str}") + + elif res['action'] == 'update': + for j in l: + if res['arg']['instId'] == j['instrument_id']: + # 获取全量数据 + bids_p = j['bids_p'] + asks_p = j['asks_p'] + # 获取合并后数据 + bids_p = update_bids(res, bids_p) + asks_p = update_asks(res, asks_p) + + # 校验checksum + checksum = res['data'][0]['checksum'] + # print('推送数据的checksum为:' + str(checksum)) + check_num = check(bids_p, asks_p) + # print('校验后的checksum为:' + str(check_num)) + if check_num == checksum: + print("校验结果为:True") + else: + print("校验结果为:False,正在重新订阅……") + + # 取消订阅 + await unsubscribe_without_login(url, channels) + # 发送订阅 + async with websockets.connect(url) as ws: + sub_param = {"op": "subscribe", "args": channels} + sub_str = json.dumps(sub_param) + await ws.send(sub_str) + print(f"send: {sub_str}") + except Exception as e: + print(e) + print("连接断开,正在重连……") + continue + + +# subscribe channels need login +async def subscribe(url, api_key, passphrase, secret_key, channels): + while True: + try: + async with websockets.connect(url) as ws: + # login + timestamp = str(get_local_timestamp()) + login_str = login_params(timestamp, api_key, passphrase, secret_key) + await ws.send(login_str) + # print(f"send: {login_str}") + res = await ws.recv() + print(res) + + # subscribe + sub_param = {"op": "subscribe", "args": channels} + sub_str = json.dumps(sub_param) + await ws.send(sub_str) + print(f"send: {sub_str}") + + while True: + try: + res = await asyncio.wait_for(ws.recv(), timeout=25) + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e: + try: + await ws.send('ping') + res = await ws.recv() + print(res) + continue + except Exception as e: + print("连接关闭,正在重连……") + break + + print(get_timestamp() + res) + + except Exception as e: + print("连接断开,正在重连……") + continue + + +# trade +async def trade(url, api_key, passphrase, secret_key, trade_param): + while True: + try: + async with websockets.connect(url) as ws: + # login + timestamp = str(get_local_timestamp()) + login_str = login_params(timestamp, api_key, passphrase, secret_key) + await ws.send(login_str) + # print(f"send: {login_str}") + res = await ws.recv() + print(res) + + # trade + sub_str = json.dumps(trade_param) + await ws.send(sub_str) + print(f"send: {sub_str}") + + while True: + try: + res = await asyncio.wait_for(ws.recv(), timeout=25) + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e: + try: + await ws.send('ping') + res = await ws.recv() + print(res) + continue + except Exception as e: + print("连接关闭,正在重连……") + break + + print(get_timestamp() + res) + + except Exception as e: + print("连接断开,正在重连……") + continue + + +# unsubscribe channels +async def unsubscribe(url, api_key, passphrase, secret_key, channels): + async with websockets.connect(url) as ws: + # login + timestamp = str(get_local_timestamp()) + login_str = login_params(timestamp, api_key, passphrase, secret_key) + await ws.send(login_str) + # print(f"send: {login_str}") + + res = await ws.recv() + print(f"recv: {res}") + + # unsubscribe + sub_param = {"op": "unsubscribe", "args": channels} + sub_str = json.dumps(sub_param) + await ws.send(sub_str) + print(f"send: {sub_str}") + + res = await ws.recv() + print(f"recv: {res}") + + +# unsubscribe channels +async def unsubscribe_without_login(url, channels): + async with websockets.connect(url) as ws: + # unsubscribe + sub_param = {"op": "unsubscribe", "args": channels} + sub_str = json.dumps(sub_param) + await ws.send(sub_str) + print(f"send: {sub_str}") + + res = await ws.recv() + print(f"recv: {res}") + + +api_key = "4497a4fa-062e-41f3-a991-b46814a9f104" +secret_key = "2CD859E62F9A8E1D25702A093C3EED58" +passphrase = "123456aA." + + +# WebSocket公共频道 public channels +# 实盘 real trading +# url = "wss://ws.okx.com:8443/ws/v5/public" +# 模拟盘 demo trading +url = "wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999" +# url = "wss://ws.okx.com:8443/ws/v5/public?brokerId=9999" +# WebSocket私有频道 private channels +# 实盘 real trading +# url = "wss://ws.okx.com:8443/ws/v5/private" +# 模拟盘 demo trading +# url = "wss://wspap.okx.com:8443/ws/v5/private" +# 充值信息/提币信息频道、定投策略订单频道(实盘) +# url = "wss://ws.okx.com:8443/ws/v5/business" +# 充值信息/提币信息频道、提币信息频道、定投策略订单频道(模拟盘) +# url = "wss://ws.okx.com:8443/ws/v5/business?brokerId=9999" + +''' +公共频道 public channel +:param channel: 频道名 +:param instType: 产品类型 +:param instId: 产品ID +:param uly: 合约标的指数 + +''' + +# 产品频道 Instruments Channel +# channels = [{"channel": "instruments", "instType": "FUTURES"}] +# 行情频道 tickers channel +channels = [{"channel": "tickers", "instId": "BTC-USDT"}, {"channel": "tickers", "instId": "ETH-USDT"}] +# 持仓总量频道 Open interest Channel +# channels = [{"channel": "open-interest", "instId": "BTC-USD-210326"}] +# K线频道 Candlesticks Channel +# channels = [{"channel": "candle1m", "instId": "BTC-USD-210326"}] +# 交易频道 Trades Channel +# channels = [{"channel": "trades", "instId": "BTC-USD-201225"}] +# 预估交割/行权价格频道 Estimated delivery/exercise Price Channel +# channels = [{"channel": "estimated-price", "instType": "FUTURES", "uly": "BTC-USD"}] +# 标记价格频道 Mark Price Channel +# channels = [{"channel": "mark-price", "instId": "BTC-USDT-210326"}] +# 标记价格K线频道 Mark Price Candlesticks Channel +# channels = [{"channel": "mark-price-candle1D", "instId": "BTC-USD-201225"}] +# 限价频道 Price Limit Channel +# channels = [{"channel": "price-limit", "instId": "BTC-USD-201225"}] +# 深度频道 Order Book Channel +# channels = [{"channel": "books", "instId": "BTC-USD-SWAP"}] +# 期权定价频道 OPTION Summary Channel +# channels = [{"channel": "opt-summary", "uly": "BTC-USD"}] +# 资金费率频道 Funding Rate Channel +# channels = [{"channel": "funding-rate", "instId": "BTC-USD-SWAP"}] +# 指数K线频道 Index Candlesticks Channel +# channels = [{"channel": "index-candle1m", "instId": "BTC-USDT"}] +# 指数行情频道 Index Tickers Channel +# channels = [{"channel": "index-tickers", "instId": "BTC-USDT"}] +# status频道 Status Channel +# channels = [{"channel": "status"}] +# 平台公共爆仓单频道 +# channels = [{"channel": "liquidation-orders", "instType":"SWAP"}] +# 期权公共成交频道 +# channels = [{"channel": "option-trades", "instType":"OPTION","instFamily":"BTC-USD"}] +# 公共大宗交易频道 Public block trading channel +# channels = [{"channel": "public-struc-block-trades"}] +# 大宗交易行情频道 Block trading market channel +# channels = [{"channel": "block-tickers", "instId":"BTC-USDT-SWAP"}] +# 公共大宗交易单腿交易频道 +# channels = [{"channel": "public-block-trades", "instId":"BTC-USDT-SWAP"}] + +''' +私有频道 private channel +:param channel: 频道名 +:param ccy: 币种 +:param instType: 产品类型 +:param uly: 合约标的指数 +:param instId: 产品ID + +''' + +# 账户频道 Account Channel +# channels = [{"channel": "account", "ccy": "BTC"}] +# 持仓频道 Positions Channel +# channels = [{"channel": "positions", "instType": "FUTURES", "uly": "BTC-USDT", "instId": "BTC-USDT-210326"}] +# 余额和持仓频道 Balance and Position Channel +# channels = [{"channel": "balance_and_position"}] +# 订单频道 Order Channel +# channels = [{"channel": "orders", "instType": "FUTURES", "uly": "BTC-USD", "instId": "BTC-USD-201225"}] +# 策略委托订单频道 Algo Orders Channel +# channels = [{"channel": "orders-algo", "instType": "FUTURES", "uly": "BTC-USD", "instId": "BTC-USD-201225"}] +# 高级策略委托订单频道 Cancel Advance Algos +# channels = [{"channel": "algo-advance", "instType": "SPOT","instId": "BTC-USD-201225","algoId":"12345678"}] +# 爆仓风险预警推送频道 +# channels = [{"channel": "liquidation-warning", "instType": "SWAP","instType": "","uly":"","instId":""}] +# 账户greeks频道 +# channels = [{"channel": "account-greeks", "ccy": "BTC"}] +# 询价频道 Inquiry channel +# channels = [{"channel": "rfqs"}] +# 报价频道 Quote channel +# channels = [{"channel": "quotes"}] +# 大宗交易频道 Block trading channel +# channels = [{"channel": "struc-block-trades"}] +# 现货网格策略委托订单频道 Consignment order channel of spot grid strategy +# channels = [{"channel": "grid-orders-spot", "instType": "ANY"}] +# 合约网格策略委托订单频道 Spot grid policy delegated order channel contract grid policy delegated order channel +# channels = [{"channel": "grid-orders-contract", "instType": "ANY"}] +# 合约网格持仓频道 Contract grid position channel +# channels = [{"channel": "grid-positions", "algoId": ""}] +# 网格策略子订单频道 Grid policy suborder channel +# channels = [{"channel": "grid-sub-orders", "algoId": ""}] +# 充值信息频道 +# channels = [{"channel": "deposit-info", "ccy":"BTC"}] +# 提币信息频道 +# channels = [{"channel": "withdrawal-info", "ccy":"BTC"}] +# 定投策略委托订单频道 +# channels = [{"channel": "algo-recurring-buy", "instType":"SPOT"}] +''' +交易 trade +''' + +# 下单 Place Order +# trade_param = {"id": "1512", "op": "order", "args": [{"side": "buy", "instId": "BTC-USDT", "tdMode": "isolated", "ordType": "limit", "px": "19777", "sz": "1"}]} +# 批量下单 Place Multiple Orders +# trade_param = {"id": "1512", "op": "batch-orders", "args": [ +# {"side": "buy", "instId": "BTC-USDT", "tdMode": "isolated", "ordType": "limit", "px": "19666", "sz": "1"}, +# {"side": "buy", "instId": "BTC-USDT", "tdMode": "isolated", "ordType": "limit", "px": "19633", "sz": "1"} +# ]} +# 撤单 Cancel Order +# trade_param = {"id": "1512", "op": "cancel-order", "args": [{"instId": "BTC-USDT", "ordId": "259424589042823169"}]} +# 批量撤单 Cancel Multiple Orders +# trade_param = {"id": "1512", "op": "batch-cancel-orders", "args": [ +# {"instId": "BTC-USDT", "ordId": ""}, +# {"instId": "BTC-USDT", "ordId": ""} +# ]} +# 改单 Amend Order +# trade_param = {"id": "1512", "op": "amend-order", "args": [{"instId": "BTC-USDT", "ordId": "259432767558135808", "newSz": "2"}]} +# 批量改单 Amend Multiple Orders +# trade_param = {"id": "1512", "op": "batch-amend-orders", "args": [ +# {"instId": "BTC-USDT", "ordId": "", "newSz": "2"}, +# {"instId": "BTC-USDT", "ordId": "", "newSz": "3"} +# ]} + + +loop = asyncio.get_event_loop() + +# 公共频道 不需要登录(行情,持仓总量,K线,标记价格,深度,资金费率等)subscribe public channel +loop.run_until_complete(subscribe_without_login(url, channels)) + +# 私有频道 需要登录(账户,持仓,订单等)subscribe private channel +# loop.run_until_complete(subscribe(url, api_key, passphrase, secret_key, channels)) + +# 交易(下单,撤单,改单等)trade +# loop.run_until_complete(trade(url, api_key, passphrase, secret_key, trade_param)) + +loop.close() + +if __name__ == '__main__': + subscribe(url,api_key,passphrase,secret_key,channels) \ No newline at end of file