You send a post-only limit order to Bybit, get retCode: 0 and an orderId back, and your bot records a new resting order. A moment later the order is not on the book. Nothing failed, as far as your code can tell.
What happened is usually simple: the price would have crossed the spread, so Bybit cancelled the order instead of letting it take liquidity. This post shows how to detect that in Node.js and TypeScript with bybit-api (v4.8.6 at the time of writing), reprice safely, and recover after a reconnect.
Why retCode 0 is not “order is live”
Bybit’s Place Order docs say the acknowledgement only means the request was accepted. The request is asynchronous, and Bybit tells you to confirm the order status on the WebSocket. For timeInForce: 'PostOnly', the same page says that if the order would be filled immediately when submitted, it will be cancelled.
So a post-only order that crosses the book can come back with retCode: 0 and then be cancelled straight away. The reason is in rejectReason on the order. Bybit’s enum list describes EC_PostOnlyWillTakeLiquidity as “your post only order would have executed as a taker, and so was rejected”.
const res = await rest.submitOrder({
category: 'linear',
symbol: 'BTCUSDT',
side: 'Buy',
orderType: 'Limit',
qty: '0.001',
price: '95000',
timeInForce: 'PostOnly',
orderLinkId: 'mk-1764150000000-a1b2c3',
});
// retCode 0 here means "request accepted", nothing more.
console.log(res.retCode, res.result.orderId);
Other exchanges report the same situation differently. In hummingbot issue #8469, maker-only orders on Kalshi perpetual and Binance spot came back as HTTP 400 on the place-order call. Hummingbot logged those expected rejections as NETWORK errors with full tracebacks, and on Binance also suggested checking the API key and network connection. PR #8596, merged on 26 November 2026, improves those messages across several connectors. The general point applies to any bot: a maker-only rejection is a normal outcome, and it should be handled as one, not as a connection problem. On Bybit you just find out later, on the order stream.
What to look for
| Where | What you see |
|---|---|
submitOrder() response |
retCode: 0, an orderId, and your orderLinkId |
order stream, or an order lookup |
A final orderStatus with rejectReason: 'EC_PostOnlyWillTakeLiquidity' |
The docs say the order is cancelled. Check rejectReason rather than one specific orderStatus value. The code below treats any final status (Cancelled, Rejected and the others in the SDK’s OrderStatusV5 type) with that reason as a post-only rejection.
Detect it, reprice, and recover
The approach:
- Give every order your own
orderLinkIdand track it before you send it. The order stream may answer beforesubmitOrder()resolves. - Subscribe to the private
ordertopic and wait for the subscription to be confirmed before trading. - On
EC_PostOnlyWillTakeLiquidity, read the book again and send a new order at a fresh maker price, with a neworderLinkId. Do not resend the same price. It was rejected because it crosses, and resending it straight away will usually get the same result. - Cap the attempts, so a fast market cannot turn this into a loop.
- After a reconnect, and after a submit that timed out, look up each pending order by
orderLinkId.
import {
isTopicSubscriptionSuccess,
isWsAccountOrderEventV5,
OrderRejectReasonV5,
OrderSideV5,
OrderStatusV5,
RestClientV5,
WebsocketClient,
WS_KEY_MAP,
} from 'bybit-api';
const key = process.env.BYBIT_API_KEY;
const secret = process.env.BYBIT_API_SECRET;
const rest = new RestClientV5({ key, secret });
const ws = new WebsocketClient({ key, secret });
const symbol = 'BTCUSDT';
const qty = '0.001';
const maxAttempts = 3;
interface Quote {
side: OrderSideV5;
price: string;
attempt: number;
}
// Fields shared by the WebSocket and REST order shapes.
interface OrderView {
orderLinkId: string;
orderStatus: OrderStatusV5;
rejectReason?: OrderRejectReasonV5;
}
// Maker orders sent, with no final state seen yet. Key: orderLinkId.
const pending = new Map<string, Quote>();
const finalStatuses: OrderStatusV5[] = [
'Filled',
'Cancelled',
'Rejected',
'PartiallyFilledCanceled',
'Deactivated',
];
function newLinkId(): string {
// Max 36 characters: letters, numbers, dashes and underscores.
const rand = Math.random().toString(36).slice(2, 8);
return `mk-${Date.now()}-${rand}`;
}
async function placeMaker(
side: OrderSideV5,
price: string,
attempt = 1,
) {
const orderLinkId = newLinkId();
pending.set(orderLinkId, { side, price, attempt });
let res;
try {
res = await rest.submitOrder({
category: 'linear',
symbol,
side,
orderType: 'Limit',
qty,
price,
timeInForce: 'PostOnly',
orderLinkId,
});
} catch (e) {
// A timeout or network error does not mean "not placed".
// Keep it pending and look it up by orderLinkId.
console.error('submitOrder threw, checking', orderLinkId, e);
setTimeout(() => void resync([orderLinkId]), 2000);
return;
}
if (res.retCode !== 0) {
// Rejected up front (params, balance...). Nothing was created.
pending.delete(orderLinkId);
console.error('submitOrder failed', res.retCode, res.retMsg);
return;
}
// retCode 0 only means Bybit accepted the request.
// Whether it rests on the book arrives on the order stream.
console.log('accepted', orderLinkId, side, price);
}
function wouldHaveTaken(order: OrderView): boolean {
return order.rejectReason === 'EC_PostOnlyWillTakeLiquidity';
}
// A fresh maker price: join the best price on our own side of the book.
async function makerPrice(side: OrderSideV5): Promise<string> {
const res = await rest.getTickers({ category: 'linear', symbol });
const ticker = res.result.list[0];
if (res.retCode !== 0 || !ticker) {
throw new Error(`getTickers failed: ${res.retMsg}`);
}
return side === 'Buy' ? ticker.bid1Price : ticker.ask1Price;
}
async function onOrder(order: OrderView) {
const quote = pending.get(order.orderLinkId);
if (!quote || !finalStatuses.includes(order.orderStatus)) return;
pending.delete(order.orderLinkId);
if (!wouldHaveTaken(order)) {
console.log('final', order.orderLinkId, order.orderStatus);
return;
}
console.warn('post-only rejected, price', quote.price, 'would take');
if (quote.attempt >= maxAttempts) {
console.warn('giving up after', quote.attempt, 'attempts');
return;
}
// Do not resend the same price. Read the book again first.
const price = await makerPrice(quote.side);
await placeMaker(quote.side, price, quote.attempt + 1);
}
ws.on('update', (event) => {
if (!isWsAccountOrderEventV5(event)) return;
for (const order of event.data) {
if (order.category !== 'linear') continue;
onOrder(order).catch((e) => console.error('onOrder failed', e));
}
});
// Look up one order by orderLinkId after a gap in the stream.
async function lookUp(
orderLinkId: string,
): Promise<OrderView | undefined> {
const params = { category: 'linear' as const, orderLinkId };
// Open orders, plus recent closed ones (when Bybit still has them).
const active = await rest.getActiveOrders(params);
const fromActive = active.result?.list?.[0];
if (fromActive) return fromActive;
// Cancelled and rejected orders: only the last 24 hours.
const history = await rest.getHistoricOrders(params);
return history.result?.list?.[0];
}
async function resync(linkIds = [...pending.keys()]) {
for (const orderLinkId of linkIds) {
try {
const order = await lookUp(orderLinkId);
if (order) await onOrder(order);
else console.warn('not found yet', orderLinkId);
} catch (e) {
console.error('lookup failed', orderLinkId, e);
}
}
}
let orderStreamReady: () => void = () => {};
const ready = new Promise<void>((r) => (orderStreamReady = r));
// Fires after the first subscribe, and after the SDK
// resubscribes on a reconnected private connection.
ws.on('response', (res) => {
if (res.wsKey !== WS_KEY_MAP.v5Private) return;
if (!isTopicSubscriptionSuccess(res)) return;
orderStreamReady();
void resync();
});
ws.on('reconnected', ({ wsKey }) => {
if (wsKey === WS_KEY_MAP.v5Private) {
console.warn('private stream reconnected, resyncing');
}
});
ws.on('exception', (e) => console.error('ws exception', e));
async function start() {
ws.subscribeV5('order', 'linear');
await ready; // don't trade before the order stream is live
const price = await makerPrice('Buy');
await placeMaker('Buy', price);
}
start().catch((e) => console.error('start failed', e));
How it works
- Tracking.
pendingholds every maker order without a final state yet, keyed byorderLinkId. Bybit allows up to 36 characters for it: letters, numbers, dashes and underscores. - Submit errors. A non-zero
retCodemeans Bybit refused the request, and nothing was created. A thrown error, such as a timeout, means you do not know. The order is kept as pending and looked up byorderLinkId. - The order stream.
subscribeV5('order', 'linear')subscribes on the SDK’s single private connection,v5Private. Theordertopic covers all categories, so the handler skips anything that is notlinear.isWsAccountOrderEventV5()narrows the event type. - Repricing.
makerPrice()readsbid1Priceorask1PricefromgetTickers()and joins the best price on your own side. That price can still go stale before the order arrives, which is why there is an attempt cap. - Waiting for the stream. The
responsehandler usesisTopicSubscriptionSuccess(). The SDK resubscribes for you after a reconnect, so this handler also runs after each resubscribe onv5Private, which is when it resyncs.
Looking an order up after a gap
Neither REST endpoint covers every case on its own, so the lookup uses both:
getActiveOrders()(GET /v5/order/realtime) returns open orders. Queried byorderLinkId, it can also return a recent closed one, because Bybit keeps up to the last 500 closed orders per account and category there. After a server release or restart, Bybit says closed orders of Unified accounts should only be queried through order history.getHistoricOrders()(GET /v5/order/history) covers closed orders. Cancelled and rejected orders without fills can only be queried there for the last 24 hours. Bybit also notes this endpoint can lag, because order creation and cancellation are asynchronous.
So check open orders first, then history. If neither has the order yet, keep it pending and check again a little later instead of assuming it was never placed.
Checklist
| Symptom | Likely cause | Fix |
|---|---|---|
retCode: 0, then the order is gone |
Post-only price would have crossed the spread | Watch the order stream for rejectReason: 'EC_PostOnlyWillTakeLiquidity' |
| Bot keeps sending orders that disappear | Resending the same crossing price | Reprice from a fresh book read, use a new orderLinkId, and cap attempts |
| Bot thinks an order is resting after a reconnect | The cancel arrived while the stream was down | Look up by orderLinkId: getActiveOrders(), then getHistoricOrders() |
| Duplicate orders after a timeout | Treating a thrown submit as “not placed” | Look up the orderLinkId before you send again |
| Order lookup returns nothing | History can lag, and cancelled orders only stay 24 hours | Check again shortly. Reconcile well within 24 hours |
- Treat
retCode: 0as “accepted”, not “resting”. - Track orders by your own
orderLinkId. - Treat a maker-only rejection as a normal outcome, not a network error.
- Never retry a rejected post-only order at the same price.
Further reading
- Bybit JavaScript SDK: install, clients and examples
- Bybit API JavaScript tutorial: REST and WebSocket clients in more detail
- bybit-api docs
- SDK example: ws-private-v5.ts, in the bybit-api repository
- Bybit API docs: Place Order, Order stream and Enums
- Related: WebSocket reconnects and backfill
- REST API vs WebSockets vs WebSocket API: why order state belongs on the stream
