OKX Trading Bot in Python¶
This guide shows how to build a OKX trading bot in Python with LumiBot, for both AI agent trading and algorithmic trading. LumiBot connects to OKX through CCXT, the open source library that talks to more than 100 crypto exchanges. You will create a OKX account and API key, connect it, and run two examples: a simple algorithmic trading bot and an agentic trading bot where an AI agent makes the calls.
What BotSpot MCP adds
Use Claude, ChatGPT, Codex, Cursor, VS Code or another MCP-compatible assistant? Connect the free BotSpot MCP for:
Skills: build LumiBot strategies.
Free data: news, economics and SEC filings.
Backtests: run tests and read charts.
Cloud hosting: low-cost scheduled bots.
Community: share bots and discuss trades.
Marketplace: discover and publish strategies.
Broker linking: connect accounts through BotSpot.
OKX at a glance¶
CCXT exchange id |
|
Markets |
Spot, Margin, Perpetual swaps, Dated futures, Options |
Testnet (sandbox) |
Yes |
Credentials |
API key, API passphrase (CCXT calls it |
Live data streams |
prices, order book, trades, candles, your orders, your balance, your positions |
CCXT request spacing |
about 110 ms between requests |
Official site |
|
API docs |
|
Fees |
What is OKX?¶
OKX is a large crypto exchange where you can buy and sell more than 300 coins. It also offers futures, options and other derivatives, plus trading bots and a crypto wallet.
Sign up for OKX¶
Create an OKX account on the website or app.
Finish identity verification and turn on two-factor authentication.
For practice, open Trade, then Demo Trading. Demo trading uses its own API keys, made inside demo mode.
Create a OKX API key¶
Log in, open your Profile and go to API (API and connections). Click Create API key.
Enter a name for the key and pick the account (main account or a sub-account) it should use.
Add your bot’s IP address to the IP allowlist. Each key can hold up to 20 addresses.
Pick the permissions (see below).
Make up a passphrase and type it in. OKX cannot show or recover it later, so save it.
Confirm with your two-factor code, then copy the API key and Secret key.
Which permissions to turn on: Turn on Read and Trade. Leave Withdraw off. OKX says Trade covers placing and canceling orders, and it tells users never to turn on withdrawal for a trading tool.
Warning
Never turn on withdrawals for a OKX trading bot key. Bind the key to your server’s IP address when OKX lets you, keep the secret out of your code and out of Git, and delete the key if it ever leaks.
Connect OKX to LumiBot¶
The simplest way: put these lines in a .env file next to your strategy. LumiBot loads the file, sees TRADING_BROKER=okx and connects to OKX for you, so your strategy needs no broker code.
TRADING_BROKER=okx
OKX_API_KEY=your_apiKey
OKX_API_PASSPHRASE=your_password
OKX_API_SECRET=your_secret
OKX_SANDBOX=true # testnet; remove this line for your live account
LumiBot reads exactly the fields CCXT needs for OKX (apiKey, password, secret). If one is missing, LumiBot stops at start-up and names the variable you still need.
You can also build the broker in code. This is handy when one script talks to more than one exchange, or when you need extra CCXT options. The keys in the config are CCXT’s own credential names for OKX:
import os
OKX_CONFIG = {
"exchange_id": "okx",
"apiKey": os.environ.get("OKX_API_KEY"),
"password": os.environ.get("OKX_API_PASSPHRASE"),
"secret": os.environ.get("OKX_API_SECRET"),
"sandbox": True, # testnet first; set False for your live account
}
from lumibot.brokers import Ccxt
broker = Ccxt(OKX_CONFIG)
# then: MyStrategy(broker=broker, ...)
Either way, LumiBot turns on CCXT’s built-in rate limiting for you.
Practice on the OKX testnet¶
OKX does not have a separate testnet website. It has Demo Trading inside the normal OKX site. Make a demo key at Trade, then Demo Trading, then Personal Center, then Demo Trading API. Set OKX_SANDBOX=true (or "sandbox": True in a code config) and use that demo key. Real keys do not work in demo mode, and demo keys do not work for real trading.
CCXT sends sandbox requests to: https://www.okx.com. Testnet and live accounts use different keys.
Algorithmic trading example: a simple OKX bot¶
This bot buys about 50 USDT of BTC on OKX once and then holds it. It is a starting point to check that your keys, balances and orders work. If the exchange’s minimum order is larger, raise the amount. OKX accepts only limit orders through CCXT, so the example places a limit order just above the last price.
from lumibot.entities import Asset
from lumibot.strategies import Strategy
class OkxBuyOnce(Strategy):
"""Buy a small amount of BTC once, then hold it."""
def initialize(self):
self.sleeptime = "1H"
self.set_market("24/7") # crypto trades all day, every day
def on_trading_iteration(self):
coin = Asset("BTC", asset_type=Asset.AssetType.CRYPTO)
if self.get_position(coin) is not None:
return # already holding BTC
price = self.get_last_price(coin, quote=self.quote_asset)
if price:
quantity = round(50 / price, 6) # about 50 USDT worth
# This exchange takes only limit orders through CCXT.
order = self.create_order(coin, quantity, "buy", limit_price=price * 1.002, quote=self.quote_asset)
self.submit_order(order)
if __name__ == "__main__":
# LumiBot reads TRADING_BROKER and the keys from your .env file.
strategy = OkxBuyOnce(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
strategy.run_live()
Agentic trading example: an AI agent that trades on OKX¶
Agentic trading means an AI agent reads the market and decides what to do. In this example one LumiBot agent looks at prices and your OKX account, then places the orders itself. There is no Python logic in between: you set the rules in plain English in the prompt, such as what it may trade and how big each order can be. This follows the same pattern as LumiBot’s AI trading team examples.
from lumibot.entities import Asset
from lumibot.strategies import Strategy
class OkxAITrader(Strategy):
"""One AI agent researches the market and places the trades itself."""
def initialize(self):
self.sleeptime = "4H"
self.set_market("24/7")
self.agents.create(
name="trader",
model="openai/gpt-6-luna",
reasoning_effort="high",
allow_trading=True,
system_prompt=(
"You manage a small crypto account on OKX. "
"You may trade BTC and ETH against USDT (asset_type 'crypto', quote_symbol 'USDT'), or hold cash. "
"Before every order, call account_portfolio, account_positions and "
"market_last_price for that exact symbol in the same run. "
"Keep each order under 10% of the account value. "
"Explain each decision in one short paragraph."
),
)
def on_trading_iteration(self):
self.agents["trader"].run(
task_prompt="Review recent BTC/USDT and ETH/USDT prices and your current holdings, then decide whether to buy, sell or hold.",
context={"exchange": "OKX", "quote": "USDT", "date": self.get_datetime().isoformat()},
)
if __name__ == "__main__":
# LumiBot reads TRADING_BROKER and the keys from your .env file.
strategy = OkxAITrader(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
strategy.run_live()
The agent needs a model key such as OPENAI_API_KEY in your environment. See the AI agents quickstart for models, tools and memory.
What you can trade on OKX¶
Market |
Listed by CCXT |
|---|---|
Spot |
Yes |
Margin |
Yes |
Perpetual swaps |
Yes |
Dated futures |
Yes |
Options |
Yes |
CCXT lists these order features for OKX: stop orders, stop-loss orders, take-profit orders, reduce-only orders, editing open orders, canceling orders.
For perpetual contracts, use the full CCXT symbol so the settlement currency is clear, for example BTC/USDT:USDT. See the CCXT guide for contract quantities, position modes and leverage.
Perpetual futures example on OKX¶
OKX also lists perpetual swaps. This bot opens one small long position in BTC/USDT:USDT worth about 50 USDT and then holds it. LumiBot treats a perpetual as asset_type="crypto_future" and sizes it in contracts, the same model as LumiBot’s Bitunix futures broker. Contract symbols can differ by exchange, so check the symbol in self.broker.api.markets before going live. In hedge mode, add position_side="long" to create_order. OKX accepts only limit orders through CCXT, so the example places a limit order just above the last price.
from lumibot.entities import Asset
from lumibot.strategies import Strategy
class OkxOpenOneLong(Strategy):
"""Open one small long BTC perpetual position, then hold it."""
def initialize(self):
self.sleeptime = "1H"
self.set_market("24/7") # crypto trades all day, every day
def on_trading_iteration(self):
# The full CCXT symbol keeps the settlement currency clear.
contract = self.broker.get_asset("BTC/USDT:USDT")
if self.get_position(contract) is not None:
return # already holding the position
price = self.get_last_price(contract)
if price:
# Each contract covers contract.multiplier BTC; size the order to about 50 USDT.
quantity = round(50 / (price * contract.multiplier), 6)
# This exchange takes only limit orders through CCXT.
order = self.create_order(contract, quantity, "buy", limit_price=price * 1.002)
self.submit_order(order)
if __name__ == "__main__":
# LumiBot reads TRADING_BROKER and the keys from your .env file.
strategy = OkxOpenOneLong(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
strategy.run_live()
Fees and partner IDs on OKX¶
You pay OKX’s normal trading fees. CCXT, the library underneath, normally tags OKX orders with its own partner ID. LumiBot removes that tag. LumiBot may attach its own exchange partner ID instead. That costs you nothing extra. LumiBot never adds an extra builder fee unless one is turned on, and it logs a warning when one is.
OKX tips¶
OKX keys have three parts: API key, Secret key and passphrase. Put the passphrase in
OKX_API_PASSPHRASE(or"password"in a code config).Always bind an IP address. OKX deletes a key that has Trade or Withdraw permission and no IP binding after 14 days without use.
OKX uses different API hosts for some sites. Accounts registered on app.okx.com use
us.okx.com, and accounts registered on my.okx.com useeea.okx.com. CCXT has the idsokxusandmyokxfor those sites. Useokxfor accounts on www.okx.com.Make the key inside the sub-account you want the bot to use. OKX says not to mix the main account’s and a sub-account’s key, secret or passphrase.
Frequently asked questions¶
Can I build a OKX trading bot in Python?
Yes. Install LumiBot (pip install lumibot), set your OKX keys and use the okx CCXT exchange id as shown above.
Does OKX have a testnet?
Yes. Set OKX_SANDBOX=true and use keys from the OKX testnet.
Which API permissions does a OKX bot need?
Turn on Read and Trade. Leave Withdraw off. OKX says Trade covers placing and canceling orders, and it tells users never to turn on withdrawal for a trading tool.
Can an AI agent trade on OKX by itself?
Yes. The agentic example above gives one agent permission to trade. You control what it may trade and how much through its prompt.
Can I trade OKX perpetual futures with LumiBot?
CCXT lists perpetual swaps for this exchange. Use the full contract symbol, such as BTC/USDT:USDT.
Is LumiBot free?
Yes. LumiBot is open source on GitHub at https://github.com/Lumiwealth/lumibot. You pay only your exchange’s trading fees and, for AI agents, your model provider.
Run it in the cloud with BotSpot¶
Do not want to keep a computer running for your OKX bot? BotSpot is the hosted home for LumiBot strategies and AI trading agents: build with AI, backtest, connect a broker, and watch every trade with logs and alerts.
Sources¶
OKX Help: API FAQ (read 2026-10-23)
OKX API v5 docs: overview, API key creation, demo trading and API domains (read 2026-10-23)
OKX Help: How do I connect a third-party trading terminal or bot to my OKX account? (read 2026-10-23)
OKX home page (read 2026-10-23)
Exchange id, URLs, markets, credentials and stream support: CCXT 4.5.91 metadata, generated 2026-11-01