OKX rejects an order with 51121 (“Order quantity must be a multiple of the lot size.”) or 51020 (“Your order should meet or exceed the minimum order amount.”) when the size you send doesn’t match the instrument’s trading rules. Both are fixed the same way: read the rules from getInstruments(), round the size down to lotSz, check it against minSz, and remember that SWAP sizes are counted in contracts, not coins.
The examples use okx-api 3.2.10. Read the current instrument settings before submitting an order.
OKX codes for order size and price
| sCode | OKX message | Usual cause |
|---|---|---|
51121 | Order quantity must be a multiple of the lot size. | sz has more precision than lotSz allows, often from float maths or a coin amount sent to a SWAP. |
51020 | Your order should meet or exceed the minimum order amount. | sz is below minSz. |
51120 | Order amount is less than {param0}, please try again. | The order is below a minimum amount OKX names in the message. |
51007 | Order failed. Please place orders of at least 1 contract or more. | A contract size below what the instrument accepts. |
51006 | Order price is not within the price limit (max buy price: {param0}, min sell price: {param1}) | The limit price is outside the current price band. Rounding to tickSz won’t fix this one; move the price. |
For a single order, OKX returns an outer code plus a per-order sCode and sMsg inside data. The order-specific reason is always in sCode.
Where the rules live: getInstruments()
getInstruments() is public, so no API key is needed. The fields that matter for order sizing are:
lotSz: the size step. For SPOT and MARGIN it is in the base currency; for SWAP, FUTURES and OPTION it is in contracts.minSz: the smallest size, in the same unit aslotSz.tickSz: the price step.ctValandctValCcy: what one contract is worth (derivatives only).maxLmtSzandmaxMktSz: the largest limit and market order sizes.state: onlyliveinstruments accept normal orders.
| instId | tickSz | lotSz | minSz | ctVal | maxMktSz |
|---|---|---|---|---|---|
| BTC-USDT | 0.1 | 0.00000001 | 0.00001 | (spot) | 1000000 |
| DOGE-USDT | 0.00001 | 0.000001 | 10 | (spot) | 1000000 |
| BTC-USDT-SWAP | 0.1 | 0.01 | 0.01 | 0.01 BTC | 35000 |
| ETH-USDT-SWAP | 0.01 | 0.01 | 0.01 | 0.1 ETH | 90000 |
| DOGE-USDT-SWAP | 0.00001 | 0.01 | 0.01 | 1000 DOGE | 24000 |
Two things stand out. DOGE-USDT spot needs at least 10 DOGE, so a 9.5 DOGE order fails with 51020 however you round it. And on BTC-USDT-SWAP, sz: '0.05' means 0.05 contracts (0.0005 BTC), not 0.05 BTC.
npm install okx-api
import { RestClient } from 'okx-api';
const client = new RestClient({
apiKey: process.env.OKX_API_KEY,
apiSecret: process.env.OKX_API_SECRET,
apiPass: process.env.OKX_API_PASSPHRASE,
demoTrading: process.env.OKX_DEMO === 'true',
});
const rules = new Map();
async function loadRules(instType) {
const instruments = await client.getInstruments({ instType });
for (const inst of instruments) {
rules.set(inst.instId, inst);
}
}
await loadRules('SPOT');
await loadRules('SWAP');
console.log(rules.get('BTC-USDT-SWAP'));
Set demoTrading: true only with keys created in OKX demo trading. Demo and live keys are not interchangeable.
Round sizes and prices without floating-point errors
The classic cause of 51121 is building sz with JavaScript numbers. 0.1 + 0.2 is 0.30000000000000004, and Math.floor(x / step) * step produces values like 0.30000000000000004 again. OKX sends the rules as strings, so keep them as strings and do the arithmetic on scaled integers:
function decimals(step) {
const i = step.indexOf('.');
return i === -1 ? 0 : step.length - i - 1;
}
function toUnits(value, scale) {
const [whole, frac = ''] = value.split('.');
return BigInt(whole + frac.padEnd(scale, '0').slice(0, scale));
}
function fromUnits(units, scale) {
if (scale === 0) return units.toString();
const s = units.toString().padStart(scale + 1, '0');
return `${s.slice(0, -scale)}.${s.slice(-scale)}`.replace(/\.?0+$/, '');
}
// Round DOWN to a multiple of step, using strings only
function floorToStep(value, step) {
const scale = Math.max(decimals(value), decimals(step));
const v = toUnits(value, scale);
const s = toUnits(step, scale);
return fromUnits((v / s) * s, scale);
}
function isAtLeast(value, min) {
const scale = Math.max(decimals(value), decimals(min));
return toUnits(value, scale) >= toUnits(min, scale);
}
console.log(floorToStep('0.123456789', '0.00000001')); // 0.12345678
console.log(floorToStep('0.30000000000000004', '0.1')); // 0.3
Rounding down is deliberate. Rounding a size up can push an order past your balance or position limit, which swaps a 51121 for a balance error.
Check the order before sending it
function prepareLimitOrder(instId, rawSz, rawPx) {
const inst = rules.get(instId);
if (!inst) throw new Error(`No rules loaded for ${instId}`);
if (inst.state !== 'live') throw new Error(`${instId} is ${inst.state}, not live`);
const sz = floorToStep(rawSz, inst.lotSz);
const px = floorToStep(rawPx, inst.tickSz);
if (!isAtLeast(sz, inst.minSz)) {
throw new Error(`${instId}: size ${sz} is below minSz ${inst.minSz}`);
}
if (!isAtLeast(inst.maxLmtSz, sz)) {
throw new Error(`${instId}: size ${sz} is above maxLmtSz ${inst.maxLmtSz}`);
}
return { sz, px };
}
console.log(prepareLimitOrder('BTC-USDT', '0.0000123456', '87654.32'));
// { sz: '0.00001234', px: '87654.3' }
prepareLimitOrder('DOGE-USDT', '9.5', '0.15');
// Error: DOGE-USDT: size 9.5 is below minSz 10
For a buy, rounding the price down to tickSz keeps it at or below your intended price. For a sell you may prefer to round up; either way the result must be a multiple of tickSz.
SWAP orders: convert coins to contracts first
On SWAP and FUTURES, sz is a number of contracts. Divide the coin amount by ctVal, then round to lotSz:
function baseToContracts(instId, baseQty) {
const inst = rules.get(instId);
if (!inst || inst.instType !== 'SWAP') throw new Error(`${instId} is not a loaded SWAP`);
const scale = Math.max(decimals(baseQty), decimals(inst.ctVal), decimals(inst.lotSz)) + 8;
const raw = (toUnits(baseQty, scale) * 10n ** BigInt(scale)) / toUnits(inst.ctVal, scale);
return floorToStep(fromUnits(raw, scale), inst.lotSz);
}
console.log(baseToContracts('BTC-USDT-SWAP', '0.0567')); // 5.67 contracts
console.log(baseToContracts('ETH-USDT-SWAP', '1.234')); // 12.34 contracts
console.log(baseToContracts('DOGE-USDT-SWAP', '2500')); // 2.5 contracts
Spot market orders have their own unit rule: OKX’s tgtCcy defaults to quote_ccy for market buys and base_ccy for market sells. A market buy with sz: '50' on BTC-USDT spends 50 USDT unless you set tgtCcy: 'base_ccy'.
Submit the order and read sCode on rejection
When OKX returns a non-zero code, okx-api rejects the promise with the response body, so the per-order reason is at error.data[0].sCode. Authentication failures have no data entries; with dummy keys the body is {"msg":"Invalid OK-ACCESS-KEY","code":"50111"}.
async function placeLimit(instId, side, rawSz, rawPx) {
const { sz, px } = prepareLimitOrder(instId, rawSz, rawPx);
try {
const [result] = await client.submitOrder({
instId,
tdMode: instId.endsWith('-SWAP') ? 'cross' : 'cash',
side,
ordType: 'limit',
sz,
px,
clOrdId: `lot${Date.now()}`,
});
return result;
} catch (e) {
const sCode = e?.data?.[0]?.sCode;
if (sCode === '51121' || sCode === '51020') {
// The rules may have changed since start-up: reload before any retry
await loadRules(instId.endsWith('-SWAP') ? 'SWAP' : 'SPOT');
}
throw new Error(
`OKX rejected ${instId}: code=${e?.code} sCode=${sCode} ${e?.data?.[0]?.sMsg ?? e?.msg ?? ''}`,
);
}
}
Use tdMode: 'cash' for spot without margin. For SWAP, use the margin mode your account runs, and if the account is in long/short position mode you also need posSide; that is the OKX 51000 posSide error.
Keep the rules fresh
OKX changes lot sizes and tick sizes from time to time. Load the rules at start-up, reload them when an order fails with 51121 or 51020, and optionally subscribe to the public instruments channel, which pushes only the instruments that changed:
import { WebsocketClient } from 'okx-api';
const ws = new WebsocketClient({});
ws.on('update', (msg) => {
if (msg?.arg?.channel !== 'instruments') return;
for (const inst of msg.data) {
rules.set(inst.instId, inst); // pushes can be partial: merge by instId
}
});
ws.subscribe([
{ channel: 'instruments', instType: 'SPOT' },
{ channel: 'instruments', instType: 'SWAP' },
]);
In a 10-second test the subscription was confirmed but no pushes arrived, because nothing changed. Keep the REST load at start-up as your baseline.
Use a trade-only key with an IP allowlist. See the API key security guide.
