MeowQuant is an independent third-party information site, not OKX official. The sign-up button carries invite code OK30001, and we may earn a promotion fee from it. Full disclosure →

OKX · API Hands-On

OKX API for Quant Beginners: From API Key to Your First Order Script (Tested)

You probably got here the same way most people do: you saw a few profit screenshots from quant influencers, got tempted, opened your OKX dashboard ready to start—and hit a wall at step one. You click into "API Management" and there's a pile of options: apiKey, Secret, Passphrase, Read, Trade, Withdraw, IP whitelist. You recognize every word, but strung together you have no idea what to fill in. So you close the tab and tell yourself "maybe later."

This piece is here to get you past that wall. We (the MeowQuant desk) break the whole journey—from zero to a working first order script in Python—into a few steps, and we've done each one ourselves, including the gotchas the official docs won't mention but you'll almost certainly hit. By the end you should be able to create a safe API Key in the OKX dashboard, confirm it works with a dozen lines of code, then place and cancel your first order on the demo account. You don't need to be a programmer—just follow along and copy.

First, ask yourself: do you actually need the API?

This is the question most tutorials skip and the one you should settle first. Opening an API and writing scripts has a cost—you have to set up the environment, debug the code, and guard against your own fat-finger mistakes. If your needs are actually simple, there's a good chance you never have to touch the API at all.

OKX's built-in "Trading Bots" section has ready-made grid bots, DCA, and futures arbitrage tools. You set the parameters with a few clicks on the web or app, and it runs for you—no code required. For most people who are just starting out and only want a program to handle their buy and sell orders, the built-in bots are plenty, and when something goes wrong you have an interface to watch and stop it directly.

So when is the API worth it? Here's how we'd call it—roughly these situations:

  • You want strategy logic the built-in bots can't do, like dynamically rebalancing based on some indicator, or coordinating across multiple coins.
  • You want to backtest, which means pulling historical candles in bulk and simulating fills.
  • You want to run several strategies at once and manage them all through a script instead of by hand.
  • You simply want to learn quant trading, using the exchange as a sandbox to practice in.

If any of those is you, read on. But if you realize you just want to "set up a grid and let it earn off the chop while I sleep," you might as well open a built-in grid in the dashboard first; once you actually hit the ceiling of the built-in tools, it's not too late to come back and open the API. We have a whole separate piece on how to set grid bot parameters, which suits you if you take that road.

Three things to understand before you create a Key

Before you actually create a Key, there are three things you need to get straight. Click "Create" without understanding them and you'll most likely either fail to connect or quietly bury a security hole for yourself.

① You'll get three credentials, not two

A lot of people assume an API is just "one account, one password." On OKX you'll do a double-take—it hands you three things:

  • apiKey: the public identifier for this Key, like a "username."
  • secret (Secret Key): the key used to sign requests, like a "password"—shown only once, at creation.
  • Passphrase: a string you set yourself at creation, unique to OKX.

That third one, the Passphrase, is where beginners crash hardest. It's not your OKX login password—it's a separate string you set up when creating this particular Key. What makes it worse: in Python's ccxt library, this field isn't called passphrase, it's called password. So countless people take it at face value and enter their login password, then scratch their heads at the "authentication failed" error. Remember one line and you're fine: the password in ccxt = the Passphrase you set when creating the Key.

② Tick only "Trade"—never "Withdraw"

When you create the Key, OKX asks what this Key is allowed to do. There are three main levels:

  • Read: check prices, balances, orders. Lowest risk.
  • Trade: place, cancel, and amend orders. Required to run a strategy.
  • Withdraw: move coins out of the account.

Here's a security line with almost no exceptions: for a quant Key, tick only "Read" and "Trade"—never tick "Withdraw." The logic is direct: even if your three credentials leak someday, as long as the Key has no withdrawal permission, whoever gets them can at most place wild orders in your account (bad enough), but can't run off with your money. The moment you tick withdrawal, a leak is like handing over the keys to your safe. Automated trading never needs to withdraw anything, so this permission gives you only downside, no upside.

Bottom line: we've seen people tick every permission to save themselves the trouble, only to have credentials hard-coded in a script get pushed to a public repo—and the account drained within half an hour. Withdrawal permission is zero-necessary for a quant script; ticking it is asking for trouble.

③ Whether to set an IP whitelist

OKX lets you bind an IP whitelist to a Key—only requests from the specified IPs are accepted. It's a well-worth-it extra layer of insurance.

The decision is simple. If your script runs on a machine with a fixed IP (a cloud server, or home broadband with a static public IP), add that IP to the whitelist and your security goes up a notch immediately. If you run it on your own computer and your home IP changes often, a whitelist will get you rejected constantly as the IP shifts, which is a hassle. In that case you can leave it off for now—but you must keep your credentials well guarded. When you eventually move the script to a fixed-IP server for the long haul, add the whitelist then.

Creating the API Key in the OKX dashboard

With those three things understood, go create the Key. Here's the real path, per the current OKX dashboard (the UI gets tweaked occasionally, but the logic stays the same):

  1. Log in to OKX, hover over your avatar in the top right, find "API" or "API Management" in the dropdown, and click in.
  2. On the API management page, click "Create API Key." If it asks about the purpose, choose the personal-trading type—don't choose third-party access.
  3. Give the Key a name (note), like meow-grid-bot, so you can tell at a glance what it's for later.
  4. Set the Passphrase. Here you define a string yourself—commit it to memory, because ccxt will need it later, it's bound to this Key only, and if you lose it you can only delete and recreate.
  5. Tick the permissions: tick "Read" and "Trade," do not tick "Withdraw." (Per the previous section's bottom line.)
  6. If you run on a fixed-IP machine, fill in the IP whitelist; if unsure, leave it blank for now.
  7. Click confirm and pass two-factor verification (phone / email / authenticator app).
  8. The page will show the apiKey and Secret Key. The Secret is shown only this once—copy and save it somewhere safe right away. Close the page and you'll never see it again; lose it and you can only delete the Key and recreate.

At this point you should have three things in hand: the apiKey, the Secret, and the Passphrase you set yourself. Store them in a local file that won't be synced or uploaded—don't screenshot and send it over chat, don't paste it into any online notes app. Next we'll use these three credentials to connect.

Don't have an OKX account yet, or don't want to use your existing one to practice on? Then open a fresh account just for scripts. Register with our invite code OK30001 for a fee discount that applies to API orders too. Sign up for OKX and open the API here →

Connecting with Python + ccxt and confirming it works

Credentials in hand, the next step is verifying they actually work. We use ccxt—a library that wraps hundreds of exchanges' APIs behind a single unified interface, so you don't have to wade through OKX's raw signing details and can check balances and place orders in a few lines.

Install it first. Open a terminal (command line) and type:

pip install ccxt

Once installed, create a file okx_check.py, copy in the block below, and replace the three placeholders in quotes with your own credentials:

import ccxt

# Three credentials: apiKey, secret, password (= Passphrase)
okx = ccxt.okx({
    'apiKey':   'YOUR_apiKey',
    'secret':   'YOUR_secret',
    'password': 'YOUR_Passphrase',   # OKX-specific, the one beginners most often miss
})

# Pull the account balance to confirm auth works
balance = okx.fetch_balance()
print('USDT free:', balance['USDT']['free'])
print('USDT total:', balance['USDT']['total'])

Save it and run python okx_check.py in the terminal. If it prints your USDT balance (even if it's 0), congratulations—auth works and the API is connected. If it errors, don't panic—nine times out of ten one of the three credentials is wrong or missing. Jump to the "gotchas beginners hit most" section of this article and cross-check; it lists the cause behind each error.

One more word on storing credentials: above, to keep things clear, we wrote the credentials straight into the code, but that's only fine for a one-off local test. Once a script is going to run long-term, let alone on a server, don't hard-code the credentials—switch to environment variables or a separate config file, and make sure that file isn't synced or committed to a code repo. This is the key habit that keeps the odds of your account being stolen as low as possible.

Your first order script: placing and cancelling

Being able to check the balance means your read permission works; now test the trade permission—place an order, then cancel it. Here we use a limit order rather than a market order, because with a limit order you set the price yourself: set it far from the market price and it won't fill right away, which lets you practice placing and cancelling without actually spending money.

Before placing an order, two small things to understand:

How to write the symbol (trading pair). In ccxt, spot pairs are written uniformly as base/quote, so Bitcoin against USDT is BTC/USDT and Ethereum against USDT is ETH/USDT. Note it's a forward slash, uppercase. Getting the format wrong is another common source of errors.

Order parameters. ccxt's order method is create_order(symbol, type, side, amount, price), with the five arguments being: trading pair, order type (limit / market), side (buy / sell), amount, and price.

The block below places a deliberately-won't-fill low-price limit buy, then cancels it the moment it has the order ID. Run it on the demo account first (the next section covers how to connect to the demo):

import ccxt, time

okx = ccxt.okx({
    'apiKey':   'YOUR_apiKey',
    'secret':   'YOUR_secret',
    'password': 'YOUR_Passphrase',
})

symbol = 'BTC/USDT'

# A limit buy designed not to fill: price far below market
order = okx.create_order(
    symbol=symbol,
    type='limit',
    side='buy',
    amount=0.0001,     # tiny amount, go by the minimum order size
    price=20000,       # far below current BTC price, sits unfilled
)
order_id = order['id']
print('Order placed, id:', order_id)

time.sleep(2)

# Cancel the order we just placed
canceled = okx.cancel_order(order_id, symbol)
print('Cancelled:', canceled['id'])

Once it runs you'll see two lines of output: first the order ID, then two seconds later the cancellation confirmation. That means your script can already do a full "place–cancel," the two most basic moves in quant trading. Everything else—grids, DCA, hedging—is essentially these two moves with some decision logic and loops bolted on.

On amount: every trading pair has a minimum order size and a precision limit, and too small a value gets rejected by the exchange. If you get a "size doesn't meet rules" error, use okx.load_markets() to check this pair's limits and precision, and fill in the minimum it requires.

Demo first: run it with play money

For all the code above, we strongly recommend you run it on the demo account first, confirm everything works, then switch to real money. The demo uses virtual funds, so wrong orders and buggy logic won't actually lose you money—this is the cheapest step in your beginner phase, with almost no reason to skip it.

OKX's demo is called Demo Trading, and you can switch into it on both the app and the web. The nice part: it shares the same API Key as your live account, so you don't need to create a separate Key for the demo. To make ccxt send requests to the demo instead of live, just flip the sandbox toggle after initialization:

import ccxt

okx = ccxt.okx({
    'apiKey':   'YOUR_apiKey',
    'secret':   'YOUR_secret',
    'password': 'YOUR_Passphrase',
})

# The key line: switch to the demo account (Demo Trading)
okx.set_sandbox_mode(True)

# After this, all requests go to the demo and use virtual funds
balance = okx.fetch_balance()
print('Demo USDT free:', balance['USDT']['free'])

Some versions also support writing 'options': {'sandboxMode': True} in the config, with the same effect—pick whichever one runs for you. Once you're on the demo, you can run that place–cancel script over and over without worry: even if you fat-finger the price near the market and it actually fills, what you spend is virtual USDT.

Our habit is: any new strategy, any changed code, gets run on the demo continuously for a while first, confirming order callbacks, cancellations, and balance changes all match expectations, before we remove that set_sandbox_mode(True) line and switch to live—and the first live run uses only a tiny amount. This order has saved us several times: a few logic bugs surfaced during the demo stage, and had we gone straight to real money the cost would have been more than just cash.

📋 Desk test · 2026-06-07
At 14:22 we used the ccxt script above on OKX Demo Trading to place a BTC/USDT limit buy: amount 0.0001, price hard-coded at 20,000 (the market was in the sixty-thousands at the time, so it sat unfilled). create_order returned an order ID immediately, with about a 0.4-second delay; after sleep(2) we called cancel_order, which returned the same order ID with status canceled. We then changed the price to above market to make it fill on purpose, and confirmed that the demo BTC balance in fetch_balance rose accordingly and the callback fields lined up. The whole "place → check callback → cancel" loop ran in under 3 seconds, and the logic checked out. This step uses nothing but play money, but once the flow runs smoothly you feel a lot steadier when the real money goes in.

The gotchas beginners hit most

This is the section of this article most worth bookmarking. Each item below is an error we've hit ourselves, or seen come up again and again in the community. Cross-checking against it can save you hours.

Passphrase missing / wrong (most common)

The error is usually an auth one (something like "Invalid sign" or "passphrase incorrect"). Check that the password field in ccxt holds the Passphrase you set when creating the Key—not your login password, and not the secret. This one accounts for more than half of beginners' auth failures.

Timestamp error / request expired

OKX has a tolerance for request timestamps; if your computer's or server's system time is off (more than a few dozen seconds), the signature gets rejected as an expired timestamp. The fix is to sync your system time to accurate network time (turn on NTP auto-sync). Cloud servers usually have it on by default; local machines occasionally drift.

Permission denied

If you can check the balance but not place orders, it's basically that you only ticked "Read" and not "Trade" when creating the Key. Go back to API management and add the Trade permission to this Key—no need to recreate.

Hitting the rate limit

If you hammer price queries or place/cancel orders in a loop, you'll hit the endpoint rate limit and get something like "Too Many Requests." The easiest fix is to turn on ccxt's rate limiter at init: ccxt.okx({..., 'enableRateLimit': True}), which automatically inserts gaps between requests. Don't use a while True with no delay to hammer the endpoint.

Wrong symbol

Writing BTC/USDT as BTCUSDT, btc/usdt, or using a futures format for a spot order all throw "instrument does not exist." Remember spot is UPPER/UPPER with a slash; if unsure, run print(okx.load_markets().keys()) first to see what the available pairs actually look like.

IP not on the whitelist

If you set a whitelist, changing networks (turning on a proxy, or your broadband IP changing) gets you rejected. Confirm your current outbound IP is still on that Key's whitelist; if not, go update the list in the dashboard.

Risk and mindset: quant doesn't mean guaranteed profit

Now that you can run a script, we owe you a splash of cold water. Handing trading to a program won't make you money automatically—it only executes your decisions faster and with less emotion. If your strategy itself loses money, automating it just makes you lose faster and more consistently.

And API automation has its own particular risk: a program never hesitates like a human. A miswritten loop, a flipped buy/sell direction, an amount missing a decimal point—things you might catch before hitting confirm by hand—a script will faithfully and continuously execute dozens of times. We've watched our own loop, in the demo stage, fire off a string of orders that should never have been placed within seconds, all because one condition was written backwards. On live, that would have been real money.

So a few practical pieces of advice for when you're just starting out:

  • Start small. For your first live run, use an amount you wouldn't mind losing entirely. Treat it as tuition, not capital.
  • Set position caps. Hard-code limits on single-order and total position size in the script, so the program never gets a chance to bet all your funds.
  • Keep a stop-loss. However good the strategy looks, give it an explicit stop-loss or maximum-drawdown line that halts on trigger.
  • Be cautious with futures and leverage. This whole article is about spot. Leveraged futures can zero out your capital in a very short time, so at the beginner stage we strongly suggest sticking to spot until your flow and mindset are steady.
  • Watch it run for a while. In the first few days of a new strategy going live, don't actually walk away—watch it, and confirm its behavior matches what you saw on the demo.
Risk note: crypto asset prices swing violently, and your capital can shrink sharply or even go to zero. API automation amplifies execution speed, so once a strategy or its code is flawed, losses get amplified in step; futures and leveraged trading can lead to 100% loss of capital. This article is a record of operations and information, and is not investment advice of any kind. Use only spare money you can afford to lose entirely, and take responsibility for your own account security and trading decisions.

FAQ

If I enable the API, is my money safe?

As long as you don't tick the Withdraw permission when you create the Key, anyone who gets hold of your apiKey, secret and Passphrase still can't move your coins out—the most they can do is place orders in your account. Add an IP whitelist and the risk drops further. The real danger is storing the three credentials in plain text somewhere that gets uploaded, or enabling withdrawal.

Can I use the API if I can't code?

Writing your own scripts means knowing a little Python, but you can run quant strategies without code—OKX has built-in grid and DCA bots you can use without touching a single line. The API suits people who want custom logic, backtesting, or to run several strategies at once. Figure out which camp you're in before you decide to open an API.

Does the demo-account API Key work for live trading too?

Your live OKX API Key can also connect to the demo account (Demo Trading); the difference is whether the request carries the demo flag. In ccxt you switch with the sandbox toggle, the code logic barely changes, and one line takes you from play money to real money. Always run your script on the demo account first, confirm orders, cancellations and callbacks all work, then switch to live.

How are fees calculated when I place orders via the API?

API orders use the same fee schedule as web and app orders, split by your tier and maker/taker, with exact rates per whatever OKX currently publishes. Accounts registered with an invite code get a fee discount, and orders placed via the API get it too. High-frequency place/cancel loops in a script aren't necessarily free, so read the rules for your tier first.

What do I put in the ccxt password field?

Put in the Passphrase you set when you created the API Key—not your login password, and not the secret. This is OKX's distinctive third credential, and the one beginners most often miss. ccxt names this field password, which leads a lot of people to enter their login password by mistake and get stuck on authentication errors.

My order script says permission denied—what now?

Most likely you only ticked Read and not Trade when you created the Key. Checking your balance is a read permission; placing orders is a trade permission, and they're granted separately. Go back to API management on OKX, check this Key's permissions, and add Trade. If you set an IP whitelist, also confirm your current outbound IP is on the list.

Once you've cleared the API wall, you'll probably want a concrete strategy to practice on. We suggest starting with the easiest one to grasp, the grid bot, or first using a small tool to work out the parameters and fees before you act. Whichever road you take, remember the order from today's piece: demo first, then small-size live, survive first, talk returns later.

Ready to open the API and run your first order?

Get your account and API ready first, then come back and pick a strategy. A new account registered with the invite code gets a fee discount, and orders you place via the API get it too—this is the closest step to actually starting.

OK30001 Sign up for OKX with OK30001 →

Crypto asset prices swing violently, and futures and leverage can lead to a total loss of capital. Quant and automated trading don't guarantee profit—use only funds you can afford to lose.