Skip to content

Trading

Describes @stxapp/stx-typescript 0.12.1, the current release.

Placing and cancelling need a read_write key. The examples run on the US demo exchange with 1-cent buy orders that will not fill. How orders behave on the exchange is covered in Order types and Risk controls; this page shows the SDK calls.

The examples use a market that is open, accepting orders (trading is true), and whose event has not started:

import { STX } from "@stxapp/stx-typescript";
const client = new STX();
let market;
for await (const m of client.iterMarkets({ status: "open", trading: true, sortBy: "event_start", sortDirection: "desc" })) {
if (m.event_status === "scheduled") {
market = m;
break;
}
}
if (!market?.market_id) throw new Error("no tradeable market");
const marketId = market.market_id; // "e00651a3-10cb-4bc1-9e1f-c5ea1796c83b"
const order = await client.placeOrder(marketId, "buy", "limit", {
price: "0.01",
quantity: "1",
clientOrderId: "my-first-order",
});
console.log(order.id, order.status);
// 8f023ead-6f2d-4cf5-9931-cd217e44a2ee accepted
await client.cancelOrder(order.id!);

placeOrder(marketId, action, orderType, options) takes action "buy" or "sell" and orderType "limit" or "market". Options:

Option Type
price Dollar string, e.g. "0.58". Required for "limit", omitted for "market"
quantity Contract string, e.g. "100"
clientOrderId Your own id, echoed back and filterable
expiration, expirationTime See Expiration
cancelOnDisconnect See Cancel-on-disconnect
deviceId Optional label
fillMode "normal" (the default), "post_only" or "fill_or_kill", for limit orders. See Post-only and fill-or-kill

If the exchange refuses the order, the call throws with the exchange’s message:

import { STXRejectedException, STXValidationException } from "@stxapp/stx-typescript";
try {
await client.placeOrder(marketId, "buy", "limit", { price: "0.01", quantity: "1.5" });
} catch (err) {
if (err instanceof STXRejectedException || err instanceof STXValidationException) {
console.error(err.statusCode, err.message);
// 422 Invalid order fields: quantity - Fractional quantity is not allowed.
} else {
throw err;
}
}

A market order leaves out price:

await client.placeOrder(marketId, "buy", "market", { quantity: "1" });
const results = await client.placeOrders([
{ marketId, action: "buy", orderType: "limit", price: "0.01", quantity: "1" },
{ marketId, action: "buy", orderType: "limit", price: "0.02", quantity: "1" },
]);
for (const r of results) {
console.log(r.ok ? r.order!.id : r.errors); // the new order's id, or why it was refused
}

Each result holds either order or errors, in the order you sent them. One rejection does not stop the rest.

console.log(await client.cancelOrder(orderId)); // one
// { order_id: "8f023ead-6f2d-4cf5-9931-cd217e44a2ee", status: "cancelled" }
console.log(await client.cancelOrders([idA, idB])); // several
// [
// { order_id: "8f023ead-6f2d-4cf5-9931-cd217e44a2ee", status: "cancelled" },
// { order_id: "09b3c058-f9c0-4b0d-a6e9-f1295b7f0b33", status: "Order not found" },
// ]
console.log(await client.cancelAllOrders()); // everything on the account
// [{ order_id: "4702e9b6-211a-4805-a605-0eb0817ee9b3", status: "partially_cancelled" }]

Each returns cancellations with order_id and status: the order’s status after cancelling (partially_cancelled when part of it had already filled), or the reason it was not cancelled. An order can still fill while a cancel is in flight, so reconcile against fills.

for await (const o of client.iterOrders({ status: ["created", "requested", "accepted", "delayed", "open"] })) {
console.log(o.id, o.price, o.filled, "/", o.quantity);
}
// 4702e9b6-211a-4805-a605-0eb0817ee9b3 0.5800 40.00 / 100.00
const one = await client.order(orderId);
console.log(one.client_order_id, one.status, one.avg_price); // my-order-001 open 0.5800

orders() filters on orderIds, clientOrderIds, marketIds and status. The five statuses above are every order still working: an order on a pre_open market waits at accepted, so "open" alone misses it. See order statuses.

The client never resends a POST after a server error or a dropped connection, because the order may already be on the book. Send a clientOrderId and look it up before trying again:

import { randomUUID } from "node:crypto";
import { STXServerException, STXTransportException } from "@stxapp/stx-typescript";
const clientOrderId = randomUUID();
let order;
try {
order = await client.placeOrder(marketId, "buy", "limit", { price: "0.01", quantity: "1", clientOrderId });
} catch (err) {
if (!(err instanceof STXServerException || err instanceof STXTransportException)) throw err;
order = (await client.orders({ clientOrderIds: [clientOrderId] })).items[0];
}

fillMode: "post_only" places a limit order that only ever rests on the book as a maker. If it would match on arrival, the exchange does not place it and the call throws STXPostOnlyWouldMatchException: reason is "auto_matching" (the exchange cancelled it; err.order is the cancelled order) or "match_with_self" (the first order it would match is your own).

fillMode: "fill_or_kill" fills in full at your price or better, or not at all. The call returns the order accepted (or delayed in play); it then becomes filled, or cancelled with cancellation_reason "auto_matching" and nothing filled. Follow it on the orders channel or with client.order(id). How both behave on the exchange is in Order types.

import { STXNotAvailableException, STXPostOnlyWouldMatchException } from "@stxapp/stx-typescript";
try {
const order = await client.placeOrder(marketId, "buy", "limit", { price: "0.01", quantity: "1", fillMode: "post_only" });
console.log(order.id, order.status, order.fill_mode);
// 2b65805b-3584-4f29-adbe-0284c99f982b accepted post_only
await client.cancelOrder(order.id!);
} catch (err) {
if (err instanceof STXPostOnlyWouldMatchException) {
console.log("would have taken liquidity:", err.reason);
} else if (err instanceof STXNotAvailableException) {
console.log(err.message);
// Post-only orders are not available on stxapp.io yet.
} else {
throw err;
}
}

The exchange decides whether it takes either mode; which exchanges offer them is in Order types. Where a mode is not enabled, the exchange rejects the order and the call throws STXNotAvailableException with feature "orders.post_only" or "orders.fill_or_kill". A combination market accepts only normal orders: a fill mode there throws STXFillModeNotAllowedException, which carries fillMode. placeOrders() takes fillMode on each order and maps a rejection the same way; there a post-only order that would have matched comes back cancelled in its result.

The two expiration modes are described in Risk controls. In the SDK:

await client.placeOrder(marketId, "buy", "limit", { price: "0.01", quantity: "1", expiration: "good_till_start" });
await client.placeOrder(marketId, "buy", "limit", {
price: "0.01",
quantity: "1",
expiration: "good_till_time",
expirationTime: (Date.now() + 10 * 60_000) * 1000, // microseconds
});

How cancel-on-disconnect works is described in Risk controls. In the SDK, arm it on the orders channel and opt each order in. The client then keeps pinging the channel for you while the socket is up, at a third of the granted timeout, so two pings can be lost before the exchange cancels your orders.

const ws = await client.websocket().connect();
const orders = await ws.orders({ cancelOnDisconnect: true, pingTimeout: 5000 });
console.log("granted timeout (ms):", orders.reply.ping_timeout); // granted timeout (ms): 5000
await client.placeOrder(marketId, "buy", "limit", { price: "0.01", quantity: "1", cancelOnDisconnect: true });

STX is operated by XV Exchange, LLC, a Designated Contract Market regulated by the U.S. Commodity Futures Trading Commission (CFTC). Contracts traded on STX are cleared by XV Clearing, LLC, a CFTC-registered Derivatives Clearing Organization. Trading involves substantial risk of loss and may not be appropriate for everyone. Members risk losing the cost to enter any transaction, including fees. Consider whether trading is appropriate for you in light of your experience and financial resources. Nothing on this site is investment advice or a recommendation to trade. Past performance is not indicative of future results.

© 2026 STX. All rights reserved.llms.txtllms-full.txtView as Markdown
Docs version v1.10.5