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.6Each 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/0A 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);
});# 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" python place_order.py
import asyncio
import os
import random
import time
import httpx
from dydx_v4_client import OrderFlags
from dydx_v4_client.key_pair import KeyPair
from dydx_v4_client.network import NodeConfig, secure_channel
from dydx_v4_client.node.client import NodeClient
from dydx_v4_client.node.message import order, order_id, subaccount
from dydx_v4_client.wallet import Wallet
from v4_proto.dydxprotocol.clob.order_pb2 import Order
GRPC = os.environ.get("FA_GRPC", "grpc.testnet.firstaccess.exchange:443")
REST = os.environ.get("FA_REST", "https://api.testnet.firstaccess.exchange")
TICKER = os.environ.get("FA_TICKER", "TESTCOPERP-USD")
def accepted(response):
# A synchronous broadcast returns CheckTx's answer: code 0 is accepted.
if response.tx_response.code != 0:
raise RuntimeError(response.tx_response.raw_log)
return response.tx_response.txhash
async def in_block(node, address, sequence):
# Waits until the transaction sent at `sequence` is in a block: the
# client reads the account's sequence for the next one.
while (await node.get_account(address)).sequence == sequence:
await asyncio.sleep(0.5)
def get(path):
r = httpx.get(REST + path)
r.raise_for_status()
return r.json()
async def main():
# USDC is asset 0; its denom is read from the chain.
usdc_denom = get("/dydxprotocol/assets/asset/0")["asset"]["denom"]
node = await NodeClient.connect(
NodeConfig(
"firstaccess-testnet-1",
chaintoken_denom="adv4tnt",
usdc_denom=usdc_denom,
channel=secure_channel(GRPC),
)
)
# dydx_v4_client prices gas only in dYdX's own USDC denom or the chain
# token, so fees are paid in the chain token (adv4tnt).
node.builder.denomination = "adv4tnt"
mnemonic = os.environ["MNEMONIC"]
address = Wallet(KeyPair.from_mnemonic(mnemonic), 0, 0).address
wallet = await Wallet.from_mnemonic(node, mnemonic, address)
# The market: its perpetual, its order book (clob pair), its oracle price.
perps = get("/dydxprotocol/perpetuals/perpetual?pagination.limit=1000")["perpetual"]
perp = next(p["params"] for p in perps if p["params"]["ticker"] == TICKER)
books = get("/dydxprotocol/clob/clob_pair?pagination.limit=1000")["clob_pair"]
book = next(c for c in books if c["perpetual_clob_metadata"]["perpetual_id"] == perp["id"])
index = int(get(f"/dydxprotocol/prices/market/{perp['market_id']}")["market_price"]["price"])
# 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.
tick = int(book["subticks_per_tick"])
bid = index * 99 // 100 // tick * tick
# One subaccount per chain market; the trading app uses perpetual id + 1.
number = perp["id"] + 1
# $100 of USDC (asset 0, in quote quantums: micro-USDC) into the
# subaccount. Transfers pay a gas fee, here in the chain token.
sequence = (await node.get_account(address)).sequence
accepted(await node.deposit(wallet, address, subaccount(address, number), 0, 100_000_000))
await in_block(node, address, sequence)
oid = order_id(address, number, random.randint(0, 2**32 - 1), book["id"], OrderFlags.LONG_TERM)
good_til_block_time = int(time.time()) + 24 * 3600
placed = await node.place_order(
wallet,
order(
oid,
Order.Side.SIDE_BUY,
quantums=1,
subticks=bid,
time_in_force=Order.TimeInForce.TIME_IN_FORCE_POST_ONLY,
reduce_only=False,
builder_code_parameters=None,
twap_parameters=None,
order_router_address=None,
good_til_block_time=good_til_block_time,
),
)
print("placed", oid.client_id, "at", bid / 1e6, accepted(placed))
await in_block(node, address, sequence + 1)
cancelled = await node.cancel_order(wallet, oid, good_til_block_time=good_til_block_time)
print("cancelled", accepted(cancelled))
asyncio.run(main())# Long-term orders from the chain's CLI, in dollars and contracts on chain-market books
# (or raw quantums and subticks): good-til-block-time is unix seconds.
dydxprotocold tx clob place-long-term-order dydx1... 1 42 0 buy 1763337600 \
--price 49.50 --size 1 --post-only \
--from KEY --chain-id firstaccess-testnet-1 --node https://rpc.testnet.firstaccess.exchange:443
dydxprotocold tx clob cancel-long-term-order dydx1... 1 42 0 1763337600 \
--from KEY --chain-id firstaccess-testnet-1 --node https://rpc.testnet.firstaccess.exchange:443What matters:
order_flags64 and agood_til_block_timeat most 95 days ahead;TIME_IN_FORCE_POST_ONLYrests 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_timeat 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);
});# 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.py).
# Run: MNEMONIC="word1 ... word24" python market_order.py
import asyncio
import os
import random
import httpx
from dydx_v4_client import OrderFlags
from dydx_v4_client.key_pair import KeyPair
from dydx_v4_client.network import NodeConfig, secure_channel
from dydx_v4_client.node.client import NodeClient
from dydx_v4_client.node.message import order, order_id
from dydx_v4_client.wallet import Wallet
from v4_proto.dydxprotocol.clob.order_pb2 import Order
GRPC = os.environ.get("FA_GRPC", "grpc.testnet.firstaccess.exchange:443")
REST = os.environ.get("FA_REST", "https://api.testnet.firstaccess.exchange")
TICKER = os.environ.get("FA_TICKER", "TESTCOPERP-USD")
def accepted(response):
# A synchronous broadcast returns CheckTx's answer: code 0 is accepted.
if response.tx_response.code != 0:
raise RuntimeError(response.tx_response.raw_log)
return response.tx_response.txhash
def get(path):
r = httpx.get(REST + path)
r.raise_for_status()
return r.json()
async def main():
# USDC is asset 0; its denom is read from the chain.
usdc_denom = get("/dydxprotocol/assets/asset/0")["asset"]["denom"]
node = await NodeClient.connect(
NodeConfig(
"firstaccess-testnet-1",
chaintoken_denom="adv4tnt",
usdc_denom=usdc_denom,
channel=secure_channel(GRPC),
)
)
# dydx_v4_client prices gas only in dYdX's own USDC denom or the chain
# token, so fees are paid in the chain token (adv4tnt).
node.builder.denomination = "adv4tnt"
mnemonic = os.environ["MNEMONIC"]
address = Wallet(KeyPair.from_mnemonic(mnemonic), 0, 0).address
wallet = await Wallet.from_mnemonic(node, mnemonic, address)
perps = get("/dydxprotocol/perpetuals/perpetual?pagination.limit=1000")["perpetual"]
perp = next(p["params"] for p in perps if p["params"]["ticker"] == TICKER)
books = get("/dydxprotocol/clob/clob_pair?pagination.limit=1000")["clob_pair"]
book = next(c for c in books if c["perpetual_clob_metadata"]["perpetual_id"] == perp["id"])
index = int(get(f"/dydxprotocol/prices/market/{perp['market_id']}")["market_price"]["price"])
# 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.
tick = int(book["subticks_per_tick"])
band_ppm = perp["chain_market"].get("price_band_ppm") or 20_000
half_width = max(-(-index * band_ppm // 1_000_000), tick)
worst_price = (index + half_width) // tick * tick
height = await node.latest_block_height()
oid = order_id(address, perp["id"] + 1, random.randint(0, 2**32 - 1), book["id"], OrderFlags.SHORT_TERM)
sent = await node.place_order(
wallet,
order(
oid,
Order.Side.SIDE_BUY,
quantums=1,
subticks=worst_price,
time_in_force=Order.TimeInForce.TIME_IN_FORCE_IOC,
reduce_only=False,
builder_code_parameters=None,
twap_parameters=None,
order_router_address=None,
good_til_block=height + 10, # at most 40 blocks ahead
),
)
print("sent", oid.client_id, "worst price", worst_price / 1e6, accepted(sent))
asyncio.run(main())# place-order owner subaccount client-id clob-pair-id side(1 buy, 2 sell) quantums subticks good-til-block
# (a CLI short-term order has no time in force flag: it is a limit order good until the block)
dydxprotocold tx clob place-order dydx1... 1 43 0 1 1 55000000 123456 \
--from KEY --chain-id firstaccess-testnet-1 --node https://rpc.testnet.firstaccess.exchange:443What matters:
order_flags0 and agood_til_blockafter 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(CLIdydxprotocold 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/fillsand thev4_subaccountschannel (indexer API).