This commit is contained in:
zihao.jiang 2023-06-16 16:24:23 +08:00
parent fcd7f52dae
commit ceadad7210
68 changed files with 1352 additions and 452 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -2,37 +2,29 @@
"cells": [ "cells": [
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"# Get Started\n", "# Get Started\n",
"## Install python package\n", "## Install python package\n",
"You can install `python-okx` from PyPi server." "You can install `python-okx` from PyPi server."
] ],
"metadata": {
"collapsed": false
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"! pip install python-okx --upgrade" "! pip install python-okx --upgrade"
] ],
"metadata": {
"collapsed": false
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Sign up as an OKX user\n", "## Sign up as an OKX user\n",
"Please refer to [Create account](https://www.okx.com/account/register)" "Please refer to [Create account](https://www.okx.com/account/register)"
@ -40,11 +32,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Create API Key\n", "## Create API Key\n",
"Please refer to [Create API Key](https://www.okx.com/account/my-api)" "Please refer to [Create API Key](https://www.okx.com/account/my-api)"
@ -52,11 +40,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Import API modules\n", "## Import API modules\n",
"The following modules are available\n", "The following modules are available\n",
@ -80,7 +64,7 @@
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"pycharm": { "pycharm": {
"name": "#%%\n" "is_executing": true
} }
}, },
"outputs": [], "outputs": [],
@ -90,11 +74,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Fill in your API key details" "## Fill in your API key details"
] ]
@ -102,11 +82,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"api_key = \"xxxxx\"\n", "api_key = \"xxxxx\"\n",
@ -116,11 +92,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Get available funds" "## Get available funds"
] ]
@ -130,7 +102,7 @@
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"pycharm": { "pycharm": {
"name": "#%%\n" "is_executing": true
} }
}, },
"outputs": [], "outputs": [],
@ -147,11 +119,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Get market data" "## Get market data"
] ]
@ -161,7 +129,7 @@
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"pycharm": { "pycharm": {
"name": "#%%\n" "is_executing": true
} }
}, },
"outputs": [], "outputs": [],
@ -178,22 +146,14 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Handle errors" "## Handle errors"
] ]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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", "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." "Please refer to [error code](https://www.okx.com/docs-v5/en/#error-code) for addtional information."
@ -203,10 +163,10 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"scrolled": true,
"pycharm": { "pycharm": {
"name": "#%%\n" "is_executing": true
}, }
"scrolled": true
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
@ -222,11 +182,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"# Prepare for trading\n", "# 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", "- 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", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Get account balance. Please refer to [Get balance](https://www.okx.com/docs-v5/en/#rest-api-account-get-balance)." "## 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"pycharm": {
"name": "#%%\n"
},
"scrolled": true "scrolled": true
}, },
"outputs": [], "outputs": [],
@ -266,11 +215,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## Get available trading pairs from [Get instruments](https://www.okx.com/docs-v5/en/#rest-api-public-data-get-instruments)." "## 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"pycharm": {
"name": "#%%\n"
},
"scrolled": true "scrolled": true
}, },
"outputs": [], "outputs": [],
@ -300,11 +242,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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)" "## 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"import okx.Account as Account\n", "import okx.Account as Account\n",
@ -335,11 +269,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"import okx.Account as Account\n", "import okx.Account as Account\n",
@ -357,22 +287,14 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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-统一交易账户介绍)" "## 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", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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)." "## 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"import okx.Account as Account\n", "import okx.Account as Account\n",
@ -409,22 +327,14 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"# Start Spot Trading" "# Start Spot Trading"
] ]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### Spot trading under simple/single-currency margin mode" "### Spot trading under simple/single-currency margin mode"
] ]
@ -432,11 +342,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"import okx.Trade as Trade\n", "import okx.Trade as Trade\n",
@ -448,11 +354,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"#### place a limit order" "#### place a limit order"
] ]
@ -460,11 +362,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# limit order\n", "# limit order\n",
@ -486,11 +384,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"#### place a market order" "#### place a market order"
] ]
@ -498,11 +392,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# market order\n", "# market order\n",
@ -518,11 +408,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"#### place an order with tgtCcy=quote_ccy (only applicable to spot)" "#### place an order with tgtCcy=quote_ccy (only applicable to spot)"
] ]
@ -530,11 +416,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# market order\n", "# market order\n",
@ -551,11 +433,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"#### place an order with your own clOrdId" "#### place an order with your own clOrdId"
] ]
@ -563,11 +441,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# market order\n", "# market order\n",
@ -584,11 +458,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### Spot trading under multi-currency/porfolio margin mode" "### Spot trading under multi-currency/porfolio margin mode"
] ]
@ -596,11 +466,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# cross-margin spot trading\n", "# cross-margin spot trading\n",
@ -622,11 +488,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### For additional information on the place order endpointplease refer to [Place order](https://www.okx.com/docs-v5/en/#rest-api-trade-place-order)\n", "### For additional information on the place order endpointplease refer to [Place order](https://www.okx.com/docs-v5/en/#rest-api-trade-place-order)\n",
"\n", "\n",
@ -636,11 +498,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"place_orders = [\n", "place_orders = [\n",
@ -654,11 +512,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### To amend pending ordersplease refer to [Amend order](https://www.okx.com/docs-v5/en/#rest-api-trade-amend-order)" "### To amend pending ordersplease refer to [Amend order](https://www.okx.com/docs-v5/en/#rest-api-trade-amend-order)"
] ]
@ -666,11 +520,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.amend_order(\n", "result = tradeAPI.amend_order(\n",
@ -683,11 +533,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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)" "### 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"amend_orders = [\n", "amend_orders = [\n",
@ -713,11 +555,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### To cancel pending ordersplease refer to [Cancel order](https://www.okx.com/docs-v5/en/#rest-api-trade-cancel-order)" "### To cancel pending ordersplease refer to [Cancel order](https://www.okx.com/docs-v5/en/#rest-api-trade-cancel-order)"
] ]
@ -725,11 +563,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.cancel_order(instId=\"BTC-USDT\", ordId = \"489093931993509888\")\n", "result = tradeAPI.cancel_order(instId=\"BTC-USDT\", ordId = \"489093931993509888\")\n",
@ -738,11 +572,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### To cancel orders in a batchplease refer to [Cancel multiple orders](https://www.okx.com/docs-v5/zh/#rest-api-trade-cancel-multiple-orders)" "### To cancel orders in a batchplease 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"cancel_orders = [\n", "cancel_orders = [\n",
@ -768,11 +594,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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)" "## 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.get_order(instId=\"BTC-USDT\", clOrdId=\"002\")\n", "result = tradeAPI.get_order(instId=\"BTC-USDT\", clOrdId=\"002\")\n",
@ -794,11 +612,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.get_order(instId=\"BTC-USDT\", ordId=\"497819823594909696\")\n", "result = tradeAPI.get_order(instId=\"BTC-USDT\", ordId=\"497819823594909696\")\n",
@ -807,11 +621,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## To get the list of open ordersplease refer to [Get order List](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-list)" "## To get the list of open ordersplease 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.get_order_list()\n", "result = tradeAPI.get_order_list()\n",
@ -832,11 +638,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### To get past ordersplease 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)" "### To get past ordersplease 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.get_orders_history(\n", "result = tradeAPI.get_orders_history(\n",
@ -860,11 +658,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.get_orders_history_archive(\n", "result = tradeAPI.get_orders_history_archive(\n",
@ -875,11 +669,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### To get past tradesplease 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)" "### To get past tradesplease 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.get_fills(\n", "result = tradeAPI.get_fills(\n",
@ -903,11 +689,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.get_fills_history(\n", "result = tradeAPI.get_fills_history(\n",
@ -918,11 +700,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### If you wish to place orders when the price reaches a certain level, you can place an algo order" "### 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.place_algo_order(\n", "result = tradeAPI.place_algo_order(\n",
@ -952,11 +726,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"## You can also use Stop Loss or Take Profit order to sell the currencies in your account" "## You can also use Stop Loss or Take Profit order to sell the currencies in your account"
] ]
@ -964,11 +734,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.place_algo_order(\n", "result = tradeAPI.place_algo_order(\n",
@ -986,22 +752,14 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### For additional information, please refer to [Place algo order](https://www.okx.com/docs-v5/en/#rest-api-trade-place-algo-order)" "### 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", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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)" "### 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"algo_orders = [\n", "algo_orders = [\n",
@ -1026,11 +780,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "source": [
"### To get list of currently pending algo ordersplease refer to [Get algo order list](https://www.okx.com/docs-v5/en/#rest-api-trade-get-algo-order-list)" "### To get list of currently pending algo ordersplease 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.order_algos_list(\n", "result = tradeAPI.order_algos_list(\n",
@ -1053,11 +799,7 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"pycharm": {
"name": "#%% md\n"
}
},
"source": [ "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)" "### 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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"result = tradeAPI.order_algos_history(\n", "result = tradeAPI.order_algos_history(\n",

BIN
okx/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -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): 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) Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, flag, domain,debug)
# Get Positions # Get Positions
def get_position_risk(self, instType=''): def get_position_risk(self, instType=''):
params = {} params = {}
@ -61,8 +60,9 @@ class AccountAPI(Client):
return self._request_with_params(GET, MAX_TRADE_SIZE, params) return self._request_with_params(GET, MAX_TRADE_SIZE, params)
# Get Maximum Available Tradable Amount # Get Maximum Available Tradable Amount
def get_max_avail_size(self, instId, tdMode, ccy='', reduceOnly=''): def get_max_avail_size(self, instId, tdMode, ccy='', reduceOnly='', unSpotOffset='', quickMgnType=''):
params = {'instId': instId, 'tdMode': tdMode, 'ccy': ccy, 'reduceOnly': reduceOnly} params = {'instId': instId, 'tdMode': tdMode, 'ccy': ccy, 'reduceOnly': reduceOnly,
'unSpotOffset': unSpotOffset, 'quickMgnType': quickMgnType}
return self._request_with_params(GET, MAX_AVAIL_SIZE, params) return self._request_with_params(GET, MAX_AVAIL_SIZE, params)
# Increase / Decrease margin # Increase / Decrease margin
@ -111,8 +111,8 @@ class AccountAPI(Client):
return self._request_with_params(GET, MAX_WITHDRAWAL, params) return self._request_with_params(GET, MAX_WITHDRAWAL, params)
# Get borrow repay # Get borrow repay
def borrow_repay(self, ccy='', side='', amt=''): def borrow_repay(self, ccy='', side='', amt='', ordId=''):
params = {'ccy': ccy, 'side': side, 'amt': amt} params = {'ccy': ccy, 'side': side, 'amt': amt, 'ordId': ordId}
return self._request_with_params(POST, BORROW_REPAY, params) return self._request_with_params(POST, BORROW_REPAY, params)
# Get borrow repay history # Get borrow repay history
@ -126,8 +126,8 @@ class AccountAPI(Client):
return self._request_with_params(GET, INTEREST_LIMITS, params) return self._request_with_params(GET, INTEREST_LIMITS, params)
# Get Simulated Margin # Get Simulated Margin
def get_simulated_margin(self, instType ='',inclRealPos=True,instId='',pos=''): def get_simulated_margin(self, instType='', inclRealPos=True, spotOffsetType='', simPos=[]):
params = {'instType': instType, 'inclRealPos': inclRealPos,'instId': instId,'pos': pos,} params = {'instType': instType, 'inclRealPos': inclRealPos, 'spotOffsetType': spotOffsetType, 'simPos': simPos}
return self._request_with_params(POST, SIMULATED_MARGIN, params) return self._request_with_params(POST, SIMULATED_MARGIN, params)
# Get Greeks # Get Greeks
@ -162,5 +162,38 @@ class AccountAPI(Client):
} }
return self._request_with_params(GET,GET_PM_LIMIT,params) 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)

View File

@ -10,8 +10,10 @@ class BlockTradingAPI(Client):
params = {} params = {}
return self._request_with_params(GET, COUNTERPARTIES, params) return self._request_with_params(GET, COUNTERPARTIES, params)
def create_rfq(self, counterparties=[], anonymous='false', clRfqId='', legs = []): def create_rfq(self, counterparties=[], anonymous='false', clRfqId='', tag='', allowPartialExecution='false',
params = {'counterparties': counterparties, 'anonymous': anonymous, 'clRfqId': clRfqId, 'legs': legs} legs=[]):
params = {'counterparties': counterparties, 'anonymous': anonymous, 'clRfqId': clRfqId, 'tag': tag,
'allowPartialExecution': allowPartialExecution, 'legs': legs}
return self._request_with_params(POST, CREATE_RFQ, params) return self._request_with_params(POST, CREATE_RFQ, params)
def cancel_rfq(self, rfqId = '', clRfqId = ''): def cancel_rfq(self, rfqId = '', clRfqId = ''):
@ -26,13 +28,13 @@ class BlockTradingAPI(Client):
params = {} params = {}
return self._request_with_params(POST, CANCEL_ALL_RSQS, params) return self._request_with_params(POST, CANCEL_ALL_RSQS, params)
def execute_quote(self, rfqId='', quoteId=''): def execute_quote(self, rfqId='', quoteId='', legs=[]):
params = {'rfqId': rfqId, 'quoteId': quoteId} params = {'rfqId': rfqId, 'quoteId': quoteId, 'legs': legs}
return self._request_with_params(POST, EXECUTE_QUOTE, params) return self._request_with_params(POST, EXECUTE_QUOTE, params)
def create_quote(self, rfqId='', clQuoteId='', quoteSide = '', legs = [],anonymous=False,expiresIn=''): def create_quote(self, rfqId='', clQuoteId='', tag='', quoteSide='', legs=[], anonymous=False, expiresIn=''):
params = {'rfqId': rfqId, 'clQuoteId': clQuoteId, 'quoteSide': quoteSide, 'legs': legs, params = {'rfqId': rfqId, 'clQuoteId': clQuoteId, 'tag': tag, 'quoteSide': quoteSide, 'legs': legs,
'anonymous':anonymous,'expiresIn':expiresIn} 'anonymous': anonymous, 'expiresIn': expiresIn}
return self._request_with_params(POST, CREATE_QUOTE, params) return self._request_with_params(POST, CREATE_QUOTE, params)
def cancel_quote(self, quoteId = '', clQuoteId = ''): 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} 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) return self._request_with_params(GET, GET_QUOTES, params)
def get_trades(self, rfqId = '', clRfqId = '', quoteId = '', clQuoteId = '', state = '', beginId = '', endId = '', limit = ''): def get_trades(self, rfqId='', clRfqId='', quoteId='', clQuoteId='', state='', beginId='', endId='', beginTs='',
params = {'rfqId': rfqId, 'clRfqId': clRfqId, 'quoteId':quoteId,'clQuoteId':clQuoteId, 'state': state, 'beginId': beginId, 'endId': endId, 'limit':limit} 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) return self._request_with_params(GET, GET_RFQ_TRADES, params)
def get_public_trades(self, beginId = '', endId = '', limit = ''): def get_public_trades(self, beginId = '', endId = '', limit = ''):
@ -68,4 +72,8 @@ class BlockTradingAPI(Client):
def set_marker_instrument(self,params = []): def set_marker_instrument(self,params = []):
return self._request_with_params(POST, MARKER_INSTRUMENT_SETTING, params) 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)

71
okx/CopyTrading.py Normal file
View File

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

View File

@ -14,15 +14,17 @@ class EarningAPI(Client):
} }
return self._request_with_params(GET,STACK_DEFI_OFFERS,params) return self._request_with_params(GET,STACK_DEFI_OFFERS,params)
def purchase(self,productId = '',investData = [],term = ''): def purchase(self, productId='', investData=[], term='', tag=''):
params = { params = {
'productId':productId, 'productId': productId,
'investData':investData 'investData': investData
} }
if term != '': if term != '':
params['term'] = 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 = ''): def redeem(self,ordId = '',protocolType = '',allowEarlyRedeem = ''):
params = { params = {
@ -59,6 +61,55 @@ class EarningAPI(Client):
} }
return self._request_with_params(GET,STACK_DEFI_ORDERS_HISTORY,params) 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)

View File

@ -30,13 +30,15 @@ class FundingAPI(Client):
return self._request_with_params(POST, FUNDS_TRANSFER, params) return self._request_with_params(POST, FUNDS_TRANSFER, params)
# Withdrawal # Withdrawal
def withdrawal(self, ccy, amt, dest, toAddr, fee,chain = '', 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,'clientId':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) return self._request_with_params(POST, WITHDRAWAL_COIN, params)
# Get Deposit History # Get Deposit History
def get_deposit_history(self, ccy='', state='', after='', before='', limit='',txId='',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} 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) return self._request_with_params(GET, DEPOSIT_HISTORIY, params)
# Get Withdrawal History # Get Withdrawal History
@ -72,25 +74,21 @@ class FundingAPI(Client):
params = {'ccy':ccy, 'invoice':invoice, 'memo':memo} params = {'ccy':ccy, 'invoice':invoice, 'memo':memo}
return self._request_with_params(POST, WITHDRAWAL_LIGHTNING, params) return self._request_with_params(POST, WITHDRAWAL_LIGHTNING, params)
# POST SET LENDING RATE # POST SET LENDING RATE
def set_lending_rate(self, ccy, rate): def set_lending_rate(self, ccy, rate):
params = {'ccy': ccy, 'rate': rate} params = {'ccy': ccy, 'rate': rate}
return self._request_with_params(POST, SET_LENDING_RATE, params) return self._request_with_params(POST, SET_LENDING_RATE, params)
# GET LENDING HISTORY # GET LENDING HISTORY
def get_lending_history(self, ccy='', before='', after='', limit='' ): def get_lending_history(self, ccy='', before='', after='', limit='' ):
params = {'ccy': ccy, 'after': after, 'before': before, 'limit': limit } params = {'ccy': ccy, 'after': after, 'before': before, 'limit': limit }
return self._request_with_params(GET, LENDING_HISTORY, params) return self._request_with_params(GET, LENDING_HISTORY, params)
# GET LENDING RATE HISTORY # GET LENDING RATE HISTORY
def get_lending_rate_history(self, ccy='',after = '',before = '',limit = '' ): def get_lending_rate_history(self, ccy='',after = '',before = '',limit = '' ):
params = {'ccy': ccy,'after':after,'before':before,'limit':limit} params = {'ccy': ccy,'after':after,'before':before,'limit':limit}
return self._request_with_params(GET, LENDING_RATE_HISTORY, params) return self._request_with_params(GET, LENDING_RATE_HISTORY, params)
# GET LENDING RATE SUMMARY # GET LENDING RATE SUMMARY
def get_lending_rate_summary(self, ccy=''): def get_lending_rate_summary(self, ccy=''):
params = {'ccy': ccy} params = {'ccy': ccy}
@ -124,3 +122,21 @@ class FundingAPI(Client):
'ccy':ccy 'ccy':ccy
} }
return self._request_with_params(GET, GET_SAVING_BALANCE, params) 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)

View File

@ -76,3 +76,57 @@ class GridAPI(Client):
'duration':duration 'duration':duration
} }
return self._request_with_params(GET, GRID_AI_PARAM, params) 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)

View File

@ -115,6 +115,20 @@ class MarketAPI(Client):
} }
return self._request_with_params(GET, BLOCK_TRADES, params) 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)

View File

@ -56,13 +56,6 @@ class PublicAPI(Client):
def get_system_time(self): def get_system_time(self):
return self._request_without_params(GET, SYSTEM_TIME) 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 # Get Mark Price
def get_mark_price(self, instType, uly='', instId='',instFamily = ''): def get_mark_price(self, instType, uly='', instId='',instFamily = ''):
params = {'instType': instType, 'uly': uly, 'instId': instId,'instFamily':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) 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)

View File

@ -59,5 +59,25 @@ class SubAccountAPI(Client):
} }
return self._request_with_params(GET, GET_ASSET_SUBACCOUNT_BALANCE, params) 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)

View File

@ -9,10 +9,13 @@ class TradeAPI(Client):
# Place Order # Place Order
def place_order(self, instId, tdMode, side, ordType, sz, ccy='', clOrdId='', tag='', posSide='', px='', 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, params = {'instId': instId, 'tdMode': tdMode, 'side': side, 'ordType': ordType, 'sz': sz, 'ccy': ccy,
'clOrdId': clOrdId, 'tag': tag, 'posSide': posSide, 'px': px, 'reduceOnly': reduceOnly, '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) return self._request_with_params(POST, PLACR_ORDER, params)
# Place Multiple Orders # Place Multiple Orders
@ -29,10 +32,12 @@ class TradeAPI(Client):
return self._request_with_params(POST, CANAEL_BATCH_ORDERS, orders_data) return self._request_with_params(POST, CANAEL_BATCH_ORDERS, orders_data)
# Amend Order # 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, params = {'instId': instId, 'cxlOnFailc': cxlOnFail, 'ordId': ordId, 'clOrdId': clOrdId, 'reqId': reqId,
'newSz': newSz, 'newSz': newSz, 'newPx': newPx, 'newTpTriggerPx': newTpTriggerPx, 'newTpOrdPx': newTpOrdPx,
'newPx': newPx} 'newSlTriggerPx': newSlTriggerPx, 'newSlOrdPx': newSlOrdPx, 'newTpTriggerPxType': newTpTriggerPxType,
'newSlTriggerPxType': newSlTriggerPxType}
return self._request_with_params(POST, AMEND_ORDER, params) return self._request_with_params(POST, AMEND_ORDER, params)
# Amend Multiple Orders # Amend Multiple Orders
@ -40,8 +45,9 @@ class TradeAPI(Client):
return self._request_with_params(POST, AMEND_BATCH_ORDER, orders_data) return self._request_with_params(POST, AMEND_BATCH_ORDER, orders_data)
# Close Positions # Close Positions
def close_positions(self, instId, mgnMode, posSide='', ccy='',autoCxl=''): def close_positions(self, instId, mgnMode, posSide='', ccy='', autoCxl='', clOrdId='', tag=''):
params = {'instId': instId, 'mgnMode': mgnMode, 'posSide': posSide, 'ccy': ccy,'autoCxl':autoCxl} params = {'instId': instId, 'mgnMode': mgnMode, 'posSide': posSide, 'ccy': ccy, 'autoCxl': autoCxl,
'clOrdId': clOrdId, 'tag': tag}
return self._request_with_params(POST, CLOSE_POSITION, params) return self._request_with_params(POST, CLOSE_POSITION, params)
# Get Order Details # Get Order Details
@ -56,15 +62,19 @@ class TradeAPI(Client):
return self._request_with_params(GET, ORDERS_PENDING, params) return self._request_with_params(GET, ORDERS_PENDING, params)
# Get Order History (last 7 days # 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, 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) return self._request_with_params(GET, ORDERS_HISTORY, params)
# Get Order History (last 3 months) # 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, 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) return self._request_with_params(GET, ORDERS_HISTORY_ARCHIVE, params)
# Get Transaction Details # Get Transaction Details
@ -80,7 +90,8 @@ class TradeAPI(Client):
triggerPx='', orderPx='', tgtCcy='', pxVar='', triggerPx='', orderPx='', tgtCcy='', pxVar='',
pxSpread='', pxSpread='',
szLimit='', pxLimit='', timeInterval='', tpTriggerPxType='', slTriggerPxType='', 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, params = {'instId': instId, 'tdMode': tdMode, 'side': side, 'ordType': ordType, 'sz': sz, 'ccy': ccy,
'posSide': posSide, 'reduceOnly': reduceOnly, 'tpTriggerPx': tpTriggerPx, 'tpOrdPx': tpOrdPx, 'posSide': posSide, 'reduceOnly': reduceOnly, 'tpTriggerPx': tpTriggerPx, 'tpOrdPx': tpOrdPx,
'slTriggerPx': slTriggerPx, 'slOrdPx': slOrdPx, 'triggerPx': triggerPx, 'orderPx': orderPx, 'slTriggerPx': slTriggerPx, 'slOrdPx': slOrdPx, 'triggerPx': triggerPx, 'orderPx': orderPx,
@ -88,11 +99,9 @@ class TradeAPI(Client):
'timeInterval': timeInterval, 'timeInterval': timeInterval,
'pxSpread': pxSpread, 'tpTriggerPxType': tpTriggerPxType, 'slTriggerPxType': slTriggerPxType, 'pxSpread': pxSpread, 'tpTriggerPxType': tpTriggerPxType, 'slTriggerPxType': slTriggerPxType,
'callbackRatio' : callbackRatio, 'callbackSpread':callbackSpread,'activePx':activePx, '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) return self._request_with_params(POST, PLACE_ALGO_ORDER, params)
# Cancel Algo Order # Cancel Algo Order
def cancel_algo_order(self, params): def cancel_algo_order(self, params):
return self._request_with_params(POST, CANCEL_ALGOS, 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) return self._request_with_params(POST, Cancel_Advance_Algos, params)
# Get Algo Order List # 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, 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) return self._request_with_params(GET, ORDERS_ALGO_OENDING, params)
# Get Algo Order History # Get Algo Order History
@ -157,3 +166,18 @@ class TradeAPI(Client):
'limit':limit 'limit':limit
} }
return self._request_with_params(GET,ONE_CLICK_REPAY_HISTORY,params) 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)

View File

@ -2,4 +2,4 @@
Python SDK for the OKX API v5 Python SDK for the OKX API v5
""" """
__version__="0.1.9" __version__="0.2.0"

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -37,8 +37,6 @@ class Client(object):
response = self.client.get(request_path, headers=header) response = self.client.get(request_path, headers=header)
elif method == c.POST: elif method == c.POST:
response = self.client.post(request_path, data=body, headers=header) 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() return response.json()
def _request_without_params(self, method, request_path): def _request_without_params(self, method, request_path):

View File

@ -46,6 +46,13 @@ SIMULATED_MARGIN = '/api/v5/account/simulated_margin'
GREEKS = '/api/v5/account/greeks' GREEKS = '/api/v5/account/greeks'
POSITIONS_HISTORY = '/api/v5/account/positions-history' #need add POSITIONS_HISTORY = '/api/v5/account/positions-history' #need add
GET_PM_LIMIT = '/api/v5/account/position-tiers' #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 # funding-complete-testcomplete
DEPOSIT_ADDRESS = '/api/v5/asset/deposit-address' 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_HISTORY = '/api/v5/asset/lending-rate-history'
LENDING_RATE_SUMMARY = '/api/v5/asset/lending-rate-summary' LENDING_RATE_SUMMARY = '/api/v5/asset/lending-rate-summary'
GET_SAVING_BALANCE = '/api/v5/asset/saving-balance' #need to add 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 # 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_TICKERS = '/api/v5/market/block-tickers' #need to add
BLOCK_TICKER = '/api/v5/market/block-ticker'#need to add BLOCK_TICKER = '/api/v5/market/block-ticker'#need to add
BLOCK_TRADES = '/api/v5/market/block-trades'#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 # Public Data-Complete-testComplete
INSTRUMENT_INFO = '/api/v5/public/instruments' 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 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 INSURANCE_FUND = '/api/v5/public/insurance-fund'#need to add
CONVERT_CONTRACT_COIN = '/api/v5/public/convert-contract-coin' #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 # TRADING DATA-COMPLETE
SUPPORT_COIN = '/api/v5/rubik/stat/trading-data/support-coin' 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' Cancel_Advance_Algos = '/api/v5/trade/cancel-advance-algos'
ORDERS_ALGO_OENDING = '/api/v5/trade/orders-algo-pending' ORDERS_ALGO_OENDING = '/api/v5/trade/orders-algo-pending'
ORDERS_ALGO_HISTORY = '/api/v5/trade/orders-algo-history' 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_CURRENCY_LIST = '/api/v5/trade/easy-convert-currency-list'
EASY_CONVERT = '/api/v5/trade/easy-convert' 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 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 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_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-all need to implmented-completed
BROKER_INFO = '/api/v5/broker/nd/info' 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_COMPUTE_MARIGIN_BALANCE = '/api/v5/tradingBot/grid/compute-margin-balance'
GRID_MARGIN_BALANCE = '/api/v5/tradingBot/grid/margin-balance' GRID_MARGIN_BALANCE = '/api/v5/tradingBot/grid/margin-balance'
GRID_AI_PARAM = '/api/v5/tradingBot/grid/ai-param' 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 #stacking - all need to implement-testcomplete
STACK_DEFI_OFFERS = '/api/v5/finance/staking-defi/offers' 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_CANCEL = '/api/v5/finance/staking-defi/cancel'
STACK_DEFI_ORDERS_ACTIVITY = '/api/v5/finance/staking-defi/orders-active' STACK_DEFI_ORDERS_ACTIVITY = '/api/v5/finance/staking-defi/orders-active'
STACK_DEFI_ORDERS_HISTORY = '/api/v5/finance/staking-defi/orders-history' 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-complete
STATUS = '/api/v5/system/status' 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'

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
test/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -1,12 +1,12 @@
import unittest import unittest
from ..okx import Account from okx import Account
class AccountTest(unittest.TestCase): class AccountTest(unittest.TestCase):
def setUp(self): def setUp(self):
api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' api_key = 'e2ea07df-15ca-405c-9e23-addb4aca8a42'
api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' api_secret_key = 'DE69BED90FF154085B56020A88B2638A'
passphrase = 'Beijing123' passphrase = '12345678aA.'
self.AccountAPI = Account.AccountAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') 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 POSITIONS_HISTORY = '/api/v5/account/positions-history' #need add
@ -73,8 +73,36 @@ class AccountTest(unittest.TestCase):
def test_get_greeks(self): def test_get_greeks(self):
print(self.AccountAPI.get_greeks()) print(self.AccountAPI.get_greeks())
''' '''
def test_simulated_margin(self): # def test_simulated_margin(self):
print(self.AccountAPI.get_simulated_margin()) # 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__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,12 +1,12 @@
import unittest import unittest
from ..okx import BlockTrading from okx import BlockTrading
class BlockTradingTest(unittest.TestCase): class BlockTradingTest(unittest.TestCase):
def setUp(self): def setUp(self):
api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' api_key = 'a6f1e378-1c03-472d-ada0-710f4d51eebf'
api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' api_secret_key = '74A6E1E03700D5EFCC2BBB7782170189'
passphrase = 'Beijing123' passphrase = 'Qa131415!'
self.BlockTradingAPI = BlockTrading.BlockTradingAPI(use_server_time=False, flag='1') self.BlockTradingAPI = BlockTrading.BlockTradingAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1')
""" """
def test_get_counter_parties(self): def test_get_counter_parties(self):
@ -42,7 +42,46 @@ class BlockTradingTest(unittest.TestCase):
""" """
def test_get_public_trades(self): # def test_get_public_trades(self):
print(self.BlockTradingAPI.get_public_trades()) # 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__': if __name__ == '__main__':
unittest.main() unittest.main()

40
test/CopyTradingTest.py Normal file
View File

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

45
test/EarningTest.py Normal file
View File

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

View File

@ -1,13 +1,13 @@
import unittest import unittest
from ..okx import Funding from okx import Funding
class FundingTest(unittest.TestCase): class FundingTest(unittest.TestCase):
def setUp(self): def setUp(self):
api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' api_key = 'cfa1017d-940a-445f-af52-b340cbd6b0e0'
api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' api_secret_key = '6C50A4E980230A4BBE7046411DED0276'
passphrase = 'Beijing123' passphrase = '123456aA.'
self.FundingAPI = Funding.FundingAPI(use_server_time=False, flag='0') 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 CANCEL_WITHDRAWAL = '/api/v5/asset/cancel-withdrawal' #need add
CONVERT_DUST_ASSETS = '/api/v5/asset/convert-dust-assets' #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')) print(self.FundingAPI.get_lending_rate_summary('BTC'))
""" """
def test_get_lending_summary(self): # def test_get_lending_summary(self):
print(self.FundingAPI.get_lending_rate_summary('BTC')) # print(self.FundingAPI.get_lending_rate_summary('BTC'))
def test_get_lending_rate_history(self): # def test_get_lending_rate_history(self):
print(self.FundingAPI.get_lending_rate_history()) # 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__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,12 +1,12 @@
import unittest import unittest
from ..okx import Grid from okx import Grid
class GridTest(unittest.TestCase): class GridTest(unittest.TestCase):
def setUp(self): def setUp(self):
api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' api_key = 'da097c9c-2f77-4dea-be18-2bfa77d0e394'
api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' api_secret_key = '56CC6C72D6B8A46EC993D48C83142A25'
passphrase = 'Beijing123' passphrase = '123456aA.'
self.GridAPI = Grid.GridAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1', debug=False) 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' GRID_COMPUTE_MARIGIN_BALANCE = '/api/v5/tradingBot/grid/compute-margin-balance'
@ -49,7 +49,37 @@ class GridTest(unittest.TestCase):
""" """
def test_order_algo(self): # def test_order_algo(self):
print(self.GridAPI.grid_order_algo("BTC-USDT","grid","45000","20000","100","1",quoteSz="50")) # 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__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,6 +1,6 @@
import unittest import unittest
from ..okx import MarketData from okx import MarketData
''' '''
ORACLE = '/api/v5/market/open-oracle' #need to update? if it is open oracle 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()) 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__": if __name__ == "__main__":

View File

@ -1,10 +1,10 @@
import unittest import unittest
from ..okx import PublicData from okx import PublicData
class publicDataTest(unittest.TestCase): class publicDataTest(unittest.TestCase):
def setUp(self): def setUp(self):
api_key = 'ef06bf27-6a01-4797-b801-e3897031e45d' api_key = 'da097c9c-2f77-4dea-be18-2bfa77d0e394'
api_secret_key = 'D3620B2660203350EEE80FDF5BE0C960' api_secret_key = '56CC6C72D6B8A46EC993D48C83142A25'
passphrase = 'Beijing123' passphrase = '123456aA.'
self.publicDataApi = PublicData.PublicAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') self.publicDataApi = PublicData.PublicAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1')
''' '''
TestCase For: TestCase For:
@ -50,8 +50,14 @@ class publicDataTest(unittest.TestCase):
print(self.publicDataApi.get_mark_price('SWAP')) print(self.publicDataApi.get_mark_price('SWAP'))
''' '''
def test_position_tier(self): # def test_position_tier(self):
print(self.publicDataApi.get_position_tiers('SWAP','cross',uly='ETH-USD')) # 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__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,5 +1,5 @@
import unittest import unittest
from ..okx import Status from okx import Status
class StackingTest(unittest.TestCase): class StackingTest(unittest.TestCase):
def setUp(self): def setUp(self):
@ -22,15 +22,6 @@ class StackingTest(unittest.TestCase):
def test_purcase(self): def test_purcase(self):
print(self.StackingAPI.purchase(1456,"USDT","100","0")) 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__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -1,11 +1,11 @@
import unittest import unittest
from ..okx import SubAccount from okx import SubAccount
class SubAccountTest(unittest.TestCase): class SubAccountTest(unittest.TestCase):
def setUp(self): def setUp(self):
api_key = '52c37310-a8b0-454a-8191-3250acff2626' api_key = 'e2ea07df-15ca-405c-9e23-addb4aca8a42'
api_secret_key = 'EC37534156E6B8C32E78FE8D8C1D506B' api_secret_key = 'DE69BED90FF154085B56020A88B2638A'
passphrase = 'Hanhao0.0' passphrase = '12345678aA.'
self.SubAccountApi = SubAccount.SubAccountAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag='1') 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 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__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -1,10 +1,10 @@
import unittest import unittest
from ..okx import Trade from okx import Trade
class TradeTest(unittest.TestCase): class TradeTest(unittest.TestCase):
def setUp(self): def setUp(self):
api_key = '35d8f27e-63cc-45bc-a578-45d76363d47f' api_key = 'da097c9c-2f77-4dea-be18-2bfa77d0e394'
api_secret_key = '0B7C968025BC2D4D71CF74771EA0E15C' api_secret_key = '56CC6C72D6B8A46EC993D48C83142A25'
passphrase = '123456' passphrase = '123456aA.'
self.tradeApi = Trade.TradeAPI(api_key, api_secret_key, passphrase, False, '1') self.tradeApi = Trade.TradeAPI(api_key, api_secret_key, passphrase, False, '1')
""" """
def test_place_order(self): def test_place_order(self):
@ -112,10 +112,80 @@ class TradeTest(unittest.TestCase):
""" """
#485903392536264704 #485903392536264704
#485936482235191296 #485936482235191296
def test_oneclick_repay_history(self): # def test_oneclick_repay_history(self):
print(self.tradeApi.oneclick_repay_history()) # 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__': if __name__=='__main__':
unittest.main() unittest.main()

View File

@ -8,7 +8,8 @@ def publicCallback(message):
if __name__ == '__main__': 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 = WsPublic(url=url)
ws.start() ws.start()
args = [] args = []

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

542
test/ws_org.py Normal file
View File

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