Skip to content
First Access Exchange

Placing and cancelling orders

The examples here use dYdX's own clients, pointed at this chain:

# TypeScript (Node 20 or later), in a CommonJS project
npm install @dydxprotocol/v4-client-js@3.6.0 long@5.3.2 tsx@4.21.0
# Python 3.10 or later
pip install dydx-v4-client==1.1.6

Each example is a complete program. It reads the market's perpetual, book and oracle price from the REST API, so it works for any chain market by ticker (FA_TICKER, default TESTCOPERP-USD). MNEMONIC is a funded testnet key (quickstart). The site's tests run every example against a local node built like the testnet and check what the chain did.

Look up the market

Orders name a clob pair id, prices are in subticks and sizes in quantums (units):

# The perpetual: id, oracle market id, chain_market (kind, price cap, band)
curl -s https://api.testnet.firstaccess.exchange/dydxprotocol/perpetuals/perpetual/0
# The book: id, perpetual_clob_metadata.perpetual_id, subticks_per_tick, status
curl -s https://api.testnet.firstaccess.exchange/dydxprotocol/clob/clob_pair/0
# The oracle price (I for the perpetual), same units as subticks
curl -s https://api.testnet.firstaccess.exchange/dydxprotocol/prices/market/0

A long-term limit order, then a cancel

Deposits $100 into the market's subaccount, rests a post-only bid for one contract 1% under the index, then cancels it.

// Deposits test USDC into a subaccount, rests a long-term post-only bid for
// one contract of TESTCOPERP-USD 1% under the index, then cancels it.
// Run: MNEMONIC="word1 ... word24" npx tsx place-order.ts
import Long from 'long';
import {
  BECH32_PREFIX,
  LocalWallet,
  OrderFlags,
  Order_Side,
  Order_TimeInForce,
  SubaccountInfo,
  ValidatorClient,
  ValidatorConfig,
} from '@dydxprotocol/v4-client-js';
 
const RPC = process.env.FA_RPC ?? 'https://rpc.testnet.firstaccess.exchange';
const REST = process.env.FA_REST ?? 'https://api.testnet.firstaccess.exchange';
const TICKER = process.env.FA_TICKER ?? 'TESTCOPERP-USD';
 
const get = async (path: string) => {
  const r = await fetch(REST + path);
  if (!r.ok) throw new Error(`${path}: ${r.status}`);
  return r.json();
};
 
async function main() {
  // USDC is asset 0; its denom is read from the chain.
  const { asset } = await get('/dydxprotocol/assets/asset/0');
  const client = await ValidatorClient.connect(
    new ValidatorConfig(RPC, 'firstaccess-testnet-1', {
      USDC_DENOM: asset.denom,
      USDC_DECIMALS: 6,
      CHAINTOKEN_DENOM: 'adv4tnt',
      CHAINTOKEN_DECIMALS: 18,
    }),
  );
  const wallet = await LocalWallet.fromMnemonic(process.env.MNEMONIC!, BECH32_PREFIX);
 
  // The market: its perpetual, its order book (clob pair) and its oracle price.
  const { perpetual } = await get('/dydxprotocol/perpetuals/perpetual?pagination.limit=1000');
  const perp = perpetual.find((p: any) => p.params.ticker === TICKER);
  const { clob_pair } = await get('/dydxprotocol/clob/clob_pair?pagination.limit=1000');
  const book = clob_pair.find((c: any) => c.perpetual_clob_metadata.perpetual_id === perp.params.id);
  const { market_price } = await get(`/dydxprotocol/prices/market/${perp.params.market_id}`);
 
  // Chain markets: one quantum is one contract; subticks are micro-dollars a
  // contract; the tick is the book's subticks_per_tick: 10,000 ($0.01), or
  // 1,000 ($0.001) on a binary's book.
  const tick = BigInt(book.subticks_per_tick);
  const index = BigInt(market_price.price);
  const bid = ((index * 99n) / 100n / tick) * tick;
 
  // One subaccount per chain market (they are isolated). The trading app uses
  // perpetual id + 1, so it shows this order too.
  const subaccount = SubaccountInfo.forLocalWallet(wallet, perp.params.id + 1);
 
  // $100 of USDC (asset 0, in quote quantums: micro-USDC) from the wallet
  // into the subaccount. Transfers pay a gas fee. The deposit is broadcast
  // synchronously, so wait for its block: the long-term order after it
  // reads the account's sequence.
  const sequence = async () =>
    Number((await get(`/cosmos/auth/v1beta1/accounts/${wallet.address}`)).account.sequence);
  const before = await sequence();
  await client.post.deposit(subaccount, 0, Long.fromNumber(100_000_000));
  while ((await sequence()) === before) await new Promise((r) => setTimeout(r, 500));
 
  const clientId = Math.floor(Math.random() * 2 ** 32);
  const goodTilBlockTime = Math.floor(Date.now() / 1000) + 24 * 3600;
  await client.post.placeOrder(
    subaccount,
    clientId,
    book.id,
    Order_Side.SIDE_BUY,
    Long.fromNumber(1), // quantums: contracts
    Long.fromString(bid.toString()), // subticks
    Order_TimeInForce.TIME_IN_FORCE_POST_ONLY,
    OrderFlags.LONG_TERM,
    false, // reduce-only: short-term IOC orders only
    undefined, // good-til-block: short-term orders only
    goodTilBlockTime,
  );
  console.log('placed', clientId, 'at', Number(bid) / 1e6);
 
  await client.post.cancelOrder(
    subaccount,
    clientId,
    OrderFlags.LONG_TERM,
    book.id,
    undefined,
    goodTilBlockTime,
  );
  console.log('cancelled');
}
 
main().catch((e) => {
  console.error(e);
  process.exit(1);
});

What matters:

  • order_flags 64 and a good_til_block_time at most 95 days ahead;
  • TIME_IN_FORCE_POST_ONLY rests the order or cancels it, never takes; a long-term order can't be IOC;
  • the subaccount is perpetual id + 1, one subaccount per chain market, as the trading app uses, so the app shows the order too;
  • the cancel names the same order id (subaccount, client id, flags, book) and a good_til_block_time at least the order's;
  • the order is in chain state from its block, and the index and S read it from the next.

A market order

A short-term IOC buy of one contract at a worst price: the top of the perpetual's price band.

// A market buy of one contract of TESTCOPERP-USD: a short-term
// immediate-or-cancel order at a worst price, here the top of the
// perpetual's price band (the index plus price_band_ppm, rounded down to the
// tick). What doesn't fill at once is cancelled. The subaccount must hold
// the margin already (see place-order.ts).
// Run: MNEMONIC="word1 ... word24" npx tsx market-order.ts
import Long from 'long';
import {
  BECH32_PREFIX,
  LocalWallet,
  OrderFlags,
  Order_Side,
  Order_TimeInForce,
  SubaccountInfo,
  ValidatorClient,
  ValidatorConfig,
} from '@dydxprotocol/v4-client-js';
 
const RPC = process.env.FA_RPC ?? 'https://rpc.testnet.firstaccess.exchange';
const REST = process.env.FA_REST ?? 'https://api.testnet.firstaccess.exchange';
const TICKER = process.env.FA_TICKER ?? 'TESTCOPERP-USD';
 
const get = async (path: string) => {
  const r = await fetch(REST + path);
  if (!r.ok) throw new Error(`${path}: ${r.status}`);
  return r.json();
};
 
async function main() {
  // USDC is asset 0; its denom is read from the chain.
  const { asset } = await get('/dydxprotocol/assets/asset/0');
  const client = await ValidatorClient.connect(
    new ValidatorConfig(RPC, 'firstaccess-testnet-1', {
      USDC_DENOM: asset.denom,
      USDC_DECIMALS: 6,
      CHAINTOKEN_DENOM: 'adv4tnt',
      CHAINTOKEN_DECIMALS: 18,
    }),
  );
  const wallet = await LocalWallet.fromMnemonic(process.env.MNEMONIC!, BECH32_PREFIX);
 
  const { perpetual } = await get('/dydxprotocol/perpetuals/perpetual?pagination.limit=1000');
  const perp = perpetual.find((p: any) => p.params.ticker === TICKER);
  const { clob_pair } = await get('/dydxprotocol/clob/clob_pair?pagination.limit=1000');
  const book = clob_pair.find((c: any) => c.perpetual_clob_metadata.perpetual_id === perp.params.id);
  const { market_price } = await get(`/dydxprotocol/prices/market/${perp.params.market_id}`);
 
  // The band the chain prices orders and fills in: I +/- price_band_ppm of I
  // (at least a tick). A buy priced above it is refused.
  const tick = BigInt(book.subticks_per_tick);
  const index = BigInt(market_price.price);
  const bandPpm = BigInt(perp.params.chain_market.price_band_ppm || 20_000);
  let halfWidth = (index * bandPpm + 999_999n) / 1_000_000n;
  if (halfWidth < tick) halfWidth = tick;
  const worstPrice = ((index + halfWidth) / tick) * tick;
 
  const height = await client.get.latestBlockHeight();
  const subaccount = SubaccountInfo.forLocalWallet(wallet, perp.params.id + 1);
  const clientId = Math.floor(Math.random() * 2 ** 32);
  await client.post.placeOrder(
    subaccount,
    clientId,
    book.id,
    Order_Side.SIDE_BUY,
    Long.fromNumber(1),
    Long.fromString(worstPrice.toString()),
    Order_TimeInForce.TIME_IN_FORCE_IOC,
    OrderFlags.SHORT_TERM,
    false,
    height + 10, // good-til-block: at most 40 blocks ahead
  );
  console.log('sent', clientId, 'worst price', Number(worstPrice) / 1e6);
}
 
main().catch((e) => {
  console.error(e);
  process.exit(1);
});

What matters:

  • order_flags 0 and a good_til_block after the current height and at most 40 blocks ahead;
  • TIME_IN_FORCE_IOC: what doesn't fill at once is cancelled;
  • the transaction is never in a block; its fills are. Check the subaccount's position, or the indexer's fills, a block or two later.

With a builder code

The same market order, paying a builder 500 ppm of each fill's notional: builder codes.

Stop orders

A conditional order (order_flags 32): stop orders.

Following your orders

  • Long-term orders in state: dydxprotocol.clob.Query/StatefulOrder (CLI dydxprotocold q clob stateful-order OWNER SUBACCOUNT CLIENT_ID CLOB_PAIR_ID 64).
  • Positions and USDC: /dydxprotocol/subaccounts/subaccount/{owner}/{number}.
  • Everything, short-term orders and fills included, with their statuses: the indexer's /v4/orders, /v4/fills and the v4_subaccounts channel (indexer API).