How can I do spot trading with the Jupyter Notebook?

發佈於 2023年9月29日更新於 2024年4月24日閱讀時長 8 分鐘128

Learn how you can do simple Spot trading by calling the functions in the python-okx library on a Jupyter Notebook.

1. How can I run Python code snippets on a Jupyter Notebook?

CT-web-spottrading-howtoapi-1

The Jupyter Notebook is an incredibly powerful and easy-to-use tool for Python development and data analysis. You can run a Jupyter Notebook server on Windows, Mac OS or Linux. This tutorial provides a pretty comprehensive guide on how to get a Jupyter Notebook up and running.

2. How can I install the python-okx package?

Once you start running a Jupyter Notebook, you can install the python-okx package by simply running the pip install python-okx in the notebook or in a terminal (or via command prompt for Windows):

CT-web-spottrading-howtoapi-2

3. How can I create API keys?

1. After signing in OKX, go to Trade > Demo trading to create API keys for testing purposes

CT-web-trade-demo trading

Open Demo trading page


2. Go to Account -> API to create API keys

CT-web-profile-API

Open API to create API keys

3. Create API keys for the different master/sub accounts you might've

CT-web-API-create

Select Create API key

4. Select Trade in the Permissions to trade with the API key

CT-web-API-trade

Select Trade in Permissions

5. Now you have access to your API key, your Secret key, and your passphrase. Keep them in a safe place!

6. Instantiate python variables to save your API details in the notebook for later usage


1 api_key = "xxxxx"
2 secret_key = "xxxxx"
3 passphrase = "xxxxxx"

```
api_key = "xxxxx"
secret_key = "xxxxx"
passphrase = "xxxxxx"
```

4. How can I import OKX modules?

In python-okx, there are several modules based on our REST API modules. Read our guide to learn how to import OKX modules.

  • Trade

  • BlockTrading

  • Funding

  • Account

  • Convert

  • Earning

  • SubAccount

  • MarketData

  • PublicData

  • TradingData

  • Status

  • NDBroker

  • FDBroker

To import the Trade module, you can run:

1 import okx.Trade as Trade

```
import okx.Trade as Trade
```

Now you are ready to use the comprehensive features available in python-okx!

5. How can I access our market data?

Learn more on how to access our market data and refer to the code below.

1 import okx.MarketData as MarketData
2 flag = "1" # live trading: 0, demo trading: 1
3 marketDataAPI = MarketData.MarketAPI(flag=flag)
4 result = marketDataAPI.get_tickers(instType="SPOT")print(result)

```
import okx.MarketData as MarketData
flag = "1" # live trading: 0, demo trading: 1
marketDataAPI = MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_tickers(instType="SPOT"
)
print(result)
```

6. How can I read the available trading pairs?

Learn more on how to read our available trading pairs and refer to the code below.

```
import okx.PublicData as PublicData

flag = "1" # live trading: 0, demo trading: 1

PublicDataAPI = PublicData.PublicAPI(flag=flag)

result = PublicDataAPI.get_instruments(
instType="SPOT"
)
print(result)
```

7. How can I read my account balance?

For more information on how to read your account balance, please read our dedicated guide.

Note: For spot trading under "cash" tdMode, you mainly need to check the cashBal, frozenBal parameters for each ccy under details, and the totalEq parameter.

```
import okx.Account as Account
flag = "1" # live trading: 0, demo trading: 1

accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)

result = accountAPI.get_account_balance()
print(result)
```

8. How can I access the four different account modes?

In our unified account system, there are four account modes:

  • Simple account

  • Single-currency margin account

  • Multi-currency margin account

  • Portfolio margin account

To understand the difference between different account modes and how to set up the account mode via the web UI, please read our dedicated guide. In margin mode or trade mode, the parameter tdMode determines how your position is going to be margined, which you need to set every time you place a new order. For spot trading under simple or single-currency margin account mode, please set tdMode='cash'. For spot trading under multi-currency margin or portfolio margin account mode, please set tdMode = 'cross'. You'll find below a quick explanation of how to figure out what mode your current account is configured as.

9. How can I figure out what mode my current account configured as?

For more information on how to figure out what mode your current account is configured as, please read our dedicated guide and enter the acctLv parameter.

```
import okx.Account as Account

flag = "1" # live trading: 0, demo trading: 1

accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
result = accountAPI.get_account_config()
print(result)

if result['code'] == "0":
acctLv = result["data"][0]["acctLv"]
if acctLv == "1":
print("Simple mode")
elif acctLv == "2":
print("Single-currency margin mode")
elif acctLv == "3":
print("Multi-currency margin mode")
elif acctLv == "4":
print("Portfolio margin mode")
```

10. How can I place spot orders under Simple / Single-currency margin mode?

10.1 How can I place a limit order?

For more information on how to place a limit order under a Simple or Single-currency margin account mode, please read our dedicated guide.

Here's an example of buying 0.01 BTC at the price of 19000 USDT.

```
# limit order
result = tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="limit",
px="19000",
sz="0.01"
)
print(result)

if result["code"] == "0":
print("Successful order request,order_id = ",result["data"][0]["ordId"])
else:
print("Unsuccessful order request,error_code = ",result["data"][0]["sCode"], ", Error_message = ", result["data"][0]["sMsg"])
```

10.2 How can I place a market order?

For more information on how to place a market order under a Simple or Single-currency margin account mode, please read our dedicated guide.

Here's an example of buying BTC that is worth 100 USD at the current market price.

```
# market order
result = tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
)
print(result)
```

10.3 How can I use the target currency parameter tgtCcy while spot trading?

In spot trading, the parameter tgtCcy determines the unit of the size parameter sz, which can be either the base currency or the quote currency of the trading pair. For example, in the pair BTC-USDT, the base currency is BTC and the quote currency is USDT.

By default, tgtCcy = quote_ccy for buy orders, which means the sz you specified is in terms of the quote currency. Meanwhile, the default value of tgtCcy for sell orders is base_ccy, which means the sz you specified is in terms of the base currency.

In the example below, you are about to place a market order to buy BTC that is worth 100 USD.

```
# market order
result = tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
tgtCcy="quote_ccy" # this determines the unit of the sz parameter.
)
print(result)
```

10.4 How can I use the client order ID parameter clOrdId?

When you place an order, you can specify your own client order ID by specifying the parameter clOrdId, which can later be used as an identifier in place of ordId when calling an order cancellation, amendment or retrieval endpoint.

```
# market order
result = tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
clOrdId="003" # you can define your own client defined order ID
)
print(result)
```

11. How can I get details about a certain order?

For more information on how to get details about a certain order, please read our dedicated guide.

Using ordId

```
result = tradeAPI.get_order(instId="BTC-USDT", ordId="497819823594909696")
print(result)
```

Using clOrdId

```
result = tradeAPI.get_order(instId="BTC-USDT", clOrdId="002")
print(result)
```

12. How can I cancel an order?

For more information on how to cancel an order, please read our dedicated guide.

You can also use clOrdId instead of ordId.

```
result = tradeAPI.cancel_order(instId="BTC-USDT", ordId = "489093931993509888")
print(result)
```

13. How can I amend an order?

For more information on how to amend an order, please read our dedicated guide.

You can also use clOrdId instead of ordId.

```
result = tradeAPI.amend_order(
instId="BTC-USDT",
ordId="489103565508685824",
newSz="0.012"
)
print(result)
```

14. How can I access the list of open orders?

For more information on how to access the list of open orders, please read our dedicated guide.

```
result = tradeAPI.get_order_list()
print(result)
```

15. How can I access order history?

15.1 For the last 7 days

For more information on how to access the order history for the last 7 days, please read our dedicated guide.

```
result = tradeAPI.get_orders_history(
instType="SPOT"
)
print(result)
```

15.2 For the last 3 months

For more information on how to access the order history for the last 3 months, please read our dedicated guide.

```
result = tradeAPI.get_orders_history_archive(
instType="SPOT"
)
print(result)
```

16. How can I go further with the OKX API with a Jupyter Notebook?

For more examples, download the full Jupyter Notebook here. Any questions about our APIs, you may raise them in the OKX API support Telegram channel.