Stop orders
A stop order is dYdX's conditional order: a stateful order that waits, untriggered, until its market's trigger price crosses its trigger price, then enters the book as an ordinary order. Every chain market takes them: company perpetuals, binaries that are part of an IPO event, calls and puts.
On the wire
A conditional order is an ordinary MsgPlaceOrder with:
| Field | Value |
|---|---|
order_id.order_flags | 32 (conditional) |
condition_type | CONDITION_TYPE_STOP_LOSS (1) or CONDITION_TYPE_TAKE_PROFIT (2) |
conditional_order_trigger_subticks | The trigger price in subticks, a multiple of the book's tick ($0.01, or $0.001 on a binary), above 0 |
good_til_block_time | Unix seconds, at most 95 days ahead, as a long-term order |
subticks | The limit price the triggered order is placed at |
time_in_force | TIME_IN_FORCE_IOC: a stop market or take-profit market; TIME_IN_FORCE_UNSPECIFIED or POST_ONLY: a stop limit or take-profit limit |
reduce_only | Allowed with IOC |
A conditional order is cancelled like a long-term one: MsgCancelOrder with the order id and a
good_til_block_time at least the order's.
When it triggers
The chain compares the market's trigger price with the order's trigger:
| Order | Triggers when the trigger price is |
|---|---|
| Stop-loss sell | at or below the trigger |
| Stop-loss buy | at or above the trigger |
| Take-profit sell | at or above the trigger |
| Take-profit buy | at or below the trigger |
So a long protects itself with a stop-loss sell under the price and a take-profit sell above it; a short with a stop-loss buy above and a take-profit buy below.
The chain writes every chain-market price at the end of each block. Stops trigger at the very
end of that block (the last step of x/binary's EndBlock, after every price is written and
every halt in the block has removed its books' orders), on the prices just written. An order
triggered in block N goes on the book before block N + 1 and trades in it, at its limit price,
with the time priority of its trigger. It can be triggered in the block it was placed in.
Unlike dYdX, the block's trade prices never trigger a stop on a chain market: only the trigger price does.
Which price
| Market | Trigger price |
|---|---|
| Market | Trigger price |
| --- | --- |
| Company perpetual | The company index I, its oracle price (the company index) |
| Binary | Its event's slow binary price reference (binary_price_reference in /dydxprotocol/binary/implied_price/{event}), held within 0.1¢ and 99.9¢ |
| Call, put | Its own book average: the time-averaged mid of its covered long-term quotes, held at most at the price cap |
The slow reference follows the binary's price p by 1/binary_price_reference_blocks of the
gap a block (1/600 by default), and p follows only the binary's valid long-term quote average
(the implied market cap).
An option's book average is the one S and a quoted call's mark read, sampled each block by the
same rules: orders placed before the block, each account's counted only if its collateral
covers all of them, at least min_depth contracts from at least min_quoters (2) accounts a
side within the depth band, and valid with min_valid_samples valid samples in the event's
window_blocks (40 of 60 by default). While an option's book has no valid average, its stops
don't trigger: they wait until it has one, and then trigger at once if the average is already
past their trigger. A model value (an unquoted call's mark, a put's value from p and S) can sit
far from where the option trades, so it never triggers a stop. An option nobody quotes takes
stops that never trigger.
So no trade, of any size, triggers a stop on a binary, a call or a put; moving their trigger prices takes covered two-sided quotes held for most of the window, and a stop there triggers late, by design, when the market moves fast. Their oracle prices (a binary's and a put's last trade, a call's mark) stay what they are for everything else (display, margin, settlement).
A stop on the perpetual fires on the index the position is margined and liquidated against, not on the perpetual's own trades.
The trigger price now
The chain's StopTrigger query gives what a market's stops trigger on now:
curl -s https://api.testnet.firstaccess.exchange/dydxprotocol/binary/stop_trigger/{perpetual_id}
# or: dydxprotocold q binary show-stop-trigger <perpetual id>| Field | Meaning |
|---|---|
source | index, binary_price_reference or book_average (above) |
valid | Whether its stops can trigger now |
price | The trigger price in micro-dollars a contract while valid, else 0 |
reason | While not valid: no_book_average (an option's book has no valid average yet: stops wait), no_event (a standalone binary: it takes no stops) or no_implied_price |
The trading app shows it on the stop ticket and on a market's page, and says so when an option's stops can't trigger now.
Placing
- No collateral until it triggers (dYdX's rule). A builder code's fee is backed at placement on every book, as for any order (builder codes).
- Unreachable triggers are refused with
ErrUnreachableStopTrigger(x/clob error 20110, "stop order's trigger price can never be reached on this market"): a trigger above the market's price cap, or on a binary outside 0.1¢ to 99.9¢ (the ends themselves are allowed). - A standalone binary (listed alone by
MsgCreateBinaryMarket, not part of an event) has no slow reference and takes no stops:ErrStopNeedsSlowPrice(20111, "stop orders on a binary need its event's slow price reference: a standalone binary takes none"). - The limit price must be at most the market's price cap. It isn't held to a call's or the perpetual's price band when it is placed: the band applies to its fills.
- At most 20 untriggered stops a subaccount, on all chain-market books together: a 21st is
refused with
ErrTooManyChainStops(x/clob error 20112, "subaccount has the most untriggered stop orders allowed on chain-market books"). A stop stops counting once it triggers, is cancelled or expires. Governance sets the number (MsgUpdateChainStopLimits; query/dydxprotocol/clob/chain_stop_limits). There is no limit per book, so no account can fill a book and lock others out. - Stops also count toward the stateful order rate limit and the equity tier limit like long-term orders (limits). As on dYdX, the equity tier is checked only when a stop is placed: collateral moved out afterwards cancels no stop. An untriggered stop is never sampled for S, the call marks or the index, and doesn't count toward the one-book rule or the covered-orders check on long-term quotes.
- TWAP orders stay refused on chain markets.
Once triggered
A triggered stop is an ordinary order:
- each fill is margined (fully backed on binaries and puts, writer margin on calls, 2× on the company perpetual) and capped by the market's open interest cap; a stop its subaccount can't margin, or that would raise open interest past the cap, is cancelled;
- on a call's or the company perpetual's book, each fill is priced within the band. A triggered
taker that meets the book only outside the band is removed after its fills in the band, with
ORDER_REMOVAL_REASON_OUTSIDE_CALL_PRICE_BAND; one that meets nothing rests, like an order the band has moved away from. So a market-style stop-loss on the perpetual sells only into bids within the band, at most 10% below I (2% while the index isn't blended); - a reduce-only stop only closes the position;
- the isolation rules apply: an order that would open a second market in its subaccount is removed.
Removals
- Halts: halting a market (an IPO halt, an event halt, a governance settlement) cancels
every stop on its book, untriggered or triggered, with the other orders
(
ORDER_REMOVAL_REASON_FINAL_SETTLEMENT). Nothing triggers on a halted book, so the settlement prices trigger nothing. - A lowered price cap cancels the stops whose limit is above the new cap, and the
untriggered stop-loss buys and take-profit sells whose trigger is above it: the trigger price
never goes above the cap, so they could never trigger (
ORDER_REMOVAL_REASON_INTERNAL_ERROR, the reason the chain gives a protocol cancel on a parameter change). An untriggered stop-loss sell or take-profit buy whose trigger is above the new cap stays: the trigger price is already at or below its trigger, so it triggers at the end of that block (on an option, once its book has a valid average). - Expiry: a stop still untriggered at its
good_til_block_timeexpires (ORDER_REMOVAL_REASON_EXPIRED).
In the indexer
The indexer reports stops as dYdX's does. An untriggered stop is an order with status
UNTRIGGERED and its triggerPrice; its type is STOP_LIMIT or STOP_MARKET (stop-loss,
limit or IOC) or TAKE_PROFIT or TAKE_PROFIT_MARKET (take-profit). Once triggered it becomes
OPEN, then FILLED or CANCELED with its removal reason, like any order
(indexer API).
curl -s 'https://indexer.testnet.firstaccess.exchange/v4/orders?address=dydx1...&subaccountNumber=1&status=UNTRIGGERED'Example
A stop-loss for a long position in the perpetual: trigger at 90% of the index, then sell one contract IOC, reduce-only, no lower than 2% under the trigger.
// A stop-loss for a long position in TESTCOPERP-USD: a conditional order
// (order flags 32) that triggers once the perpetual's trigger price (its
// oracle price, the index I; never a trade) is at or below 90% of where it
// is now, then sells one contract immediate-or-cancel, reduce-only, no lower
// than 2% under the trigger. On a binary the trigger price is the event's
// slow binary price reference instead, and on a put its model value at it.
// Run: MNEMONIC="word1 ... word24" npx tsx stop-order.ts
import Long from 'long';
import {
BECH32_PREFIX,
LocalWallet,
OrderFlags,
Order_ConditionType,
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}`);
const tick = BigInt(book.subticks_per_tick);
const index = BigInt(market_price.price);
const trigger = ((index * 90n) / 100n / tick) * tick;
const worstPrice = ((trigger * 98n) / 100n / tick) * tick;
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_SELL,
Long.fromNumber(1),
Long.fromString(worstPrice.toString()),
Order_TimeInForce.TIME_IN_FORCE_IOC, // a stop market; TIME_IN_FORCE_UNSPECIFIED rests: a stop limit
OrderFlags.CONDITIONAL,
true, // reduce-only: allowed because the order is IOC
undefined,
Math.floor(Date.now() / 1000) + 28 * 24 * 3600, // good-til-block-time, at most 95 days
undefined,
Order_ConditionType.CONDITION_TYPE_STOP_LOSS,
Long.fromString(trigger.toString()), // trigger, in subticks
);
console.log('stop placed', clientId, 'trigger', Number(trigger) / 1e6);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});# A stop-loss for a long position in TESTCOPERP-USD: a conditional order
# (order flags 32) that triggers once the perpetual's trigger price (its
# oracle price, the index I; never a trade) is at or below 90% of where it
# is now, then sells one contract immediate-or-cancel, reduce-only, no lower
# than 2% under the trigger. On a binary the trigger price is the event's
# slow binary price reference instead, and on a put its model value at it.
# Run: MNEMONIC="word1 ... word24" python stop_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
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"])
tick = int(book["subticks_per_tick"])
trigger = index * 90 // 100 // tick * tick
worst_price = trigger * 98 // 100 // tick * tick
oid = order_id(address, perp["id"] + 1, random.randint(0, 2**32 - 1), book["id"], OrderFlags.CONDITIONAL)
placed = await node.place_order(
wallet,
order(
oid,
Order.Side.SIDE_SELL,
quantums=1,
subticks=worst_price,
# A stop market; TIME_IN_FORCE_UNSPECIFIED rests: a stop limit.
time_in_force=Order.TimeInForce.TIME_IN_FORCE_IOC,
reduce_only=True, # allowed because the order is IOC
builder_code_parameters=None,
twap_parameters=None,
order_router_address=None,
good_til_block_time=int(time.time()) + 28 * 24 * 3600, # at most 95 days
condition_type=Order.ConditionType.CONDITION_TYPE_STOP_LOSS,
conditional_order_trigger_subticks=trigger,
),
)
print("stop placed", oid.client_id, "trigger", trigger / 1e6, accepted(placed))
asyncio.run(main())dYdX's clients build the same order from their order types: STOP_LIMIT and STOP_MARKET are
CONDITION_TYPE_STOP_LOSS; TAKE_PROFIT and TAKE_PROFIT_MARKET are
CONDITION_TYPE_TAKE_PROFIT; the market variants are IOC.