# Rubin Documentation
> Rubin (rubin.trade) is a decentralized perpetual futures exchange on Rubin Chain, a sovereign proof-of-stake chain with EVM support. Trading and account operations for AI agents go through the MCP server at https://mcp.testnet.rubin.trade/mcp (mainnet: https://mcp.mainnet.rubin.trade/mcp).
## Contacts
Questions, integration requests, listings, bug reports — reach the team
through either channel:
| Channel | Contact |
| -------- | -------------------------------------------- |
| Email | [team@rubin.trade](mailto\:team@rubin.trade) |
| Telegram | [@RubinTeamBot](https://t.me/RubinTeamBot) |
The Telegram bot is the fastest way to get a response.
import { HomePage } from 'vocs/components'
Rubin DocumentationThis website contains all the required documentation for Rubin protocol to start trading.Get startedGitHub
## TODO
## Bridge Contracts
Rubin accepts USDC collateral deposited through native bridges on **Ethereum** and **Arbitrum**. On each source chain the deposited USDC is held by the Rubin bridge contract; validators observe the deposit, wait for finality, and credit your Rubin main account.
For the end-to-end deposit and withdrawal flows, see [Deposits & Withdrawals](/interaction/deposits-withdrawals/overview). USDC can also arrive over IBC — see [IBC Transfers](/bridge/ibc).
:::warning
Always confirm a bridge address against an official Rubin channel before sending funds. Verify the contract on the block explorer, and send a small test deposit the first time you use a new address or chain.
:::
### Ethereum
| Contract | Address | Explorer |
| -------- | -------------------------------------------- | ------------------------------------------------------------------------------------ |
| Bridge | `0x26206BFdEE32128739f08Aa12f57505A3a4CcaaF` | [Etherscan](https://etherscan.io/address/0x26206BFdEE32128739f08Aa12f57505A3a4CcaaF) |
| USDC | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | [Etherscan](https://etherscan.io/token/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) |
### Arbitrum
| Contract | Address | Explorer |
| -------- | -------------------------------------------- | ---------------------------------------------------------------------------------- |
| Bridge | `0x26206BFdEE32128739f08Aa12f57505A3a4CcaaF` | [Arbiscan](https://arbiscan.io/address/0x26206BFdEE32128739f08Aa12f57505A3a4CcaaF) |
| USDC | `0xaf88d065e77c8cC2239327C5EDb3A432268e5831` | [Arbiscan](https://arbiscan.io/token/0xaf88d065e77c8cC2239327C5EDb3A432268e5831) |
:::note
The bridge contract holds the deposited USDC collateral on each chain — the same address is used on both Ethereum and Arbitrum. USDC addresses are the canonical Circle deployments; verify them on the linked explorer before depositing.
:::
### Verifying an address
* Cross-check every bridge address against an official Rubin channel — never trust an address from a link, DM, or search result alone.
* On the block explorer, confirm the contract is verified and matches the expected deployer and deployment history.
* Send a small test deposit the first time you use a new address or source chain.
### Chain explorer
The Rubin chain itself is a Cosmos chain. Track credited deposits, withdrawals, and governance on [Explorer](https://explorer.rubin.trade/ritbit-mainnet).
## IBC Transfers
Besides the Ethereum and Arbitrum [bridge contracts](/bridge/contracts), Rubin is connected to the Cosmos ecosystem over IBC. USDC arrives from [Noble](https://www.noble.xyz/) across a standard ICS-20 transfer channel.
### The channel
| | Noble | Rubin |
| ---------- | ------------------- | ----------------- |
| chain id | `noble-1` | `ritbit-mainnet` |
| client | `07-tendermint-228` | `07-tendermint-0` |
| connection | `connection-212` | `connection-0` |
| channel | `channel-607` | `channel-0` |
Both ends are open and name each other as counterparty. Check the Rubin side at any time:
```bash
curl -s https://rest.mainnet.rubin.trade/ibc/core/channel/v1/channels \
| jq -r '.channels[] | "\(.channel_id) \(.state) counterparty=\(.counterparty.channel_id)"'
```
### What arrives in the account
A plain ICS-20 transfer credits the receiver with a voucher denom of the form `ibc/`, derived from the transfer path. Rubin does not stop there.
An incoming packet that matches a governance-configured rule is **wrapped**: the voucher is moved to the `x/wrap` module account as collateral, and the receiver is credited a local denom one-for-one. For USDC sent from Noble over `channel-0` the receiver therefore ends up holding native **`uusdc`** — the same denom the exchange uses for collateral, margin and subaccounts — and not `ibc/8E27BA2D…`.
Integrators need to do nothing for this to happen. There is no extra message to send, no approval, and no manual conversion step. The only thing to get right is expecting the native denom in the resulting balance instead of deriving the voucher hash from the channel path.
The ratio is exactly one-to-one because both sides carry six decimals: `uusdc` on Noble and `uusdc` here.
### Wrapping rules
A rule is keyed by the triple `(port_id, channel_id, source_denom)`. The channel is part of the key on purpose — it is a trust boundary, not a convenience. A voucher hash is computed from the path, so without binding the rule to a specific channel anyone could launch a chain, mint a coin named `uusdc` on it, send it over, and be credited real exchange collateral. The channel is what ties the voucher to its actual issuer.
The rule currently in force was set by [governance](https://explorer.rubin.trade/ritbit-mainnet/gov):
```json
{
"port_id": "transfer",
"channel_id": "channel-0",
"source_denom": "uusdc",
"local_denom": "uusdc"
}
```
There is no global on/off switch. The rule set is the only source of truth: a packet that matches a rule is wrapped, a packet that matches nothing passes through untouched and lands as an ordinary `ibc/` voucher.
:::warning
Channel numbers change if a channel is ever recreated, and a stale rule simply stops matching — silently, without an error. Deposits would then arrive as raw vouchers instead of exchange collateral. Any channel change has to be followed by a governance update to the rule.
:::
### Sending assets back out
The `x/wrap` module offers two ways to go the other direction. Both burn the local denom; they differ in what happens to the voucher that backed it.
`MsgWithdraw` burns the local denom and sends the equivalent back over IBC in one step. It carries the sender, the amount in the smallest unit of the local denom, the receiver on the source chain, a timeout in seconds, and the voucher denom to leave by. The receiver is not validated as a bech32 address of this chain, because its prefix belongs to the destination — `noble1…` for Noble.
`MsgRedeem` burns the local denom and hands the voucher itself to the sender on this chain, without sending any IBC packet. There is no receiver field: crediting somebody else would be a transfer, and a transfer belongs in `MsgSend` where it is visible as one. What the sender then does with the voucher — send it home with an ordinary `MsgTransfer`, pass it on, or hold it — is up to them.
:::note
`MsgRedeem` exists for external routers such as Skip. They know how to build a route starting from an `ibc/` voucher, but they do not know about this chain's local denom or about `MsgWithdraw`. `Redeem` gives them an entry point in the terms they already understand, so an integrator does not have to reimplement route selection.
:::
Both messages require the voucher denom explicitly. One local denom can be backed by several vouchers at once — the same asset that arrived by different routes — and picking one automatically would risk sending funds along a route the user did not intend, or one whose backing is insufficient. The `Backing` query returns the available vouchers with the amount issued and the remaining balance for each.
## Indexer API
The Indexer is a high-availability system designed to provide structured data. It serves both over its [HTTP/REST API](/indexer-client/http) for spontaneous requests and over its [WebSockets API](/indexer-client/websockets) for continuous data streaming.
See the [guide](/interaction/endpoints#indexer-client) on how to use the available Indexer client to learn how to connect to it.
## AI Agents & MCP
Rubin ships an official [MCP (Model Context Protocol)](https://modelcontextprotocol.io) server so that AI agents can trade and read account data without hand-rolling REST calls. The MCP server signs transactions with a scoped on-chain trading key, verifies fills, and enforces safety limits that raw REST cannot.
| Network | MCP endpoint (Streamable HTTP) | Web app |
| ----------- | ------------------------------------- | ---------------------------------------------------------- |
| **testnet** | `https://mcp.testnet.rubin.trade/mcp` | [https://testnet.rubin.trade](https://testnet.rubin.trade) |
| **mainnet** | `https://mcp.mainnet.rubin.trade/mcp` | [https://rubin.trade](https://rubin.trade) |
The network is pinned per deployment — it is not part of the credential.
### Connecting
#### claude.ai, Claude Desktop, ChatGPT (OAuth)
Hosts that support MCP OAuth discover it automatically (`/.well-known/oauth-protected-resource`, `/.well-known/oauth-authorization-server`, dynamic client registration):
1. Add the MCP URL above as a custom connector / remote MCP server.
2. The consent page redirects to the Rubin web app's authorize page.
3. Connect a wallet and approve — the web app issues a **scoped trading key** for that account and completes the flow. The private key travels in a POST body, never in a URL, and never enters the model context.
#### Claude Code
```bash
claude mcp add --transport http rubin https://mcp.testnet.rubin.trade/mcp
```
Then run `/mcp` to authenticate (same OAuth flow as above).
#### Headless: static Bearer credential
For hosts without OAuth support (API integrations, Cursor, `mcp-remote`), the web app's `More → API Trading Keys` dialog issues a credential — `base64(JSON)` of:
```json
{ "tradingPrivateKey": "", "masterAddress": "rit1…" }
```
Send it as `Authorization: Bearer ` on MCP initialize:
* Anthropic Messages API: `mcp_servers: [{ url, authorization_token }]`;
* Cursor / VS Code `mcp.json`: `"headers": { "Authorization": "Bearer " }`;
* Any stdio host: `npx mcp-remote https://mcp.testnet.rubin.trade/mcp --header "Authorization: Bearer "`.
Omit `tradingPrivateKey` for a read-only session (market data and account reads only).
### What the trading key can and cannot do
The trading key is a [Permissioned Key](/interaction/permissioned-keys) registered on-chain as an `x/accountplus` authenticator with the scope:
* **can**: place order, cancel order, batch cancel — on **subaccount 0** only;
* **cannot**: withdraw or transfer funds, or touch any other subaccount.
This boundary is enforced by the chain, not by the MCP server. One authorization is bound to one account; to trade from another wallet, authorize the connector again from that wallet.
Accounts have two address forms — the same 20 bytes as `0x…` and `rit1…`. Trading keys can be authorized directly by an EVM wallet signature (EIP-712). See [Addresses: EVM & Native](/concepts/addresses).
### Agent skill
A ready-made skill teaches agents the Rubin workflow (connection, order flow, safety rules). Source: [https://github.com/rubin-trade/skills](https://github.com/rubin-trade/skills)
```bash
npx skills add rubin-trade/skills
```
### Testnet funds
The testnet faucet is available in the web app's deposit flow, or via REST:
```bash
curl -X POST https://faucet.testnet.rubin.trade/faucet/tokens \
-H "Content-Type: application/json" \
-d '{"address": "rit1…"}'
```
Send the `rit1` form. If you hold the address as `0x`, convert it first — see
[Addresses: EVM & Native](/concepts/addresses).
:::note
For machine-readable discovery, this site serves an [agent-skills manifest](https://docs.rubin.trade/.well-known/agent-skills/index.json), plus a generated page index at [/llms.txt](https://docs.rubin.trade/llms.txt) and the full page text at [/llms-full.txt](https://docs.rubin.trade/llms-full.txt).
:::
## Connecting to Rubin
Rubin provides two networks for trading: a **mainnet**, and a **testnet**:
* **mainnet**: The core network where real financial transactions occur;
* **testnet**: A separate, risk-free, network. Served mainly for the purposes of testing and experimenting before transitioning to the **mainnet**.
For the purposes of this guide, we'll assume that the **mainnet** is being used. Nevertheless, the API is exactly the same for both the **mainnet** and the **testnet**, so any code working in the **mainnet** should work in the **testnet**. Choosing between the **mainnet** and the **testnet** is simply a matter of changing the used endpoints.
:::note
It is advisable that for the purposes of learning and trying out the Rubin ecosystem that the **testnet** is used and preferred over the **mainnet**.
:::
### Available clients
Interacting with the Rubin network API is made through several sets of methods grouped with structures referred to as clients. Each of these clients essentially connects to a different server with its own functionality and purpose.
#### Node client
The Node client (also known as the Validator client) is the main client for interacting with the Rubin network. It provides the [Node API](/node-client/index) allowing the user to do operations that require authentication (e.g., issue trading orders) through the [Private API](/node-client/private/index).
You'll need an endpoint to setup the Node client. Grab an RPC endpoint from [here](#node). Additionally for the Python client, you'all also need a HTTP and WebSockets endpoints.
:::code-group
```python [Python]
from ritbit_v4_client.network import make_mainnet
from ritbit_v4_client.node.client import NodeClient
config = make_mainnet( # [!code focus]
node_url="rpc.mainnet.rubin.trade", # [!code focus]
rest_indexer="https://indexer.mainnet.rubin.trade", # [!code focus]
websocket_indexer="wss://indexer.mainnet.rubin.trade/v4/ws", # [!code focus]
).node # [!code focus]
# Call make_testnet() to use the testnet instead. # [!code focus]
# Connect to the network. # [!code focus]
node = await NodeClient.connect(config) # [!code focus]
```
```typescript [TypeScript]
import { ValidatorClient, Network } from '@ritbit/v4-client-js';
// Using a pre-configured endpoint. // [!code focus]
const config = Network.mainnet().validatorConfig; // [!code focus]
// Or use `Network.testnet()` for the testnet. [!code focus]
// You can modify the endpoint doing `config.restEndpoint = "...";`
// Connect to the network. // [!code focus]
const node = await ValidatorClient.connect(config); // [!code focus]
```
```rust [Rust]
use ritbit::{config::ClientConfig, node::NodeClient};
// The configuration file should have the endpoint. Use an RPC endpoint. // [!code focus]
let config = ClientConfig::from_file("config.toml").await?; // [!code focus]
// Connect to the network. // [!code focus]
let node = NodeClient::connect(config.node).await?; // [!code focus]
```
:::
While the Node client can also query data through the [Public API](/node-client/public/index), the Indexer client should be preferred.
#### Indexer client
The Indexer is a high-availability system designed to provide structured data and offload computational burden from the core full nodes. The Indexer client provides methods from the [Indexer API](/indexer-client/index). It serves both as a spontaneuous source of data retrieval through its REST endpoint, or a continuous feed of trading data through its WebSockets endpoint.
Given that the Indexer client can use these two different protocols, you'll need two endpoints to setup it up. Grab these from [here](#indexer).
:::code-group
```python [Python]
from ritbit_v4_client.network import make_mainnet
from ritbit_v4_client.indexer.rest.indexer_client import IndexerClient
from ritbit_v4_client.indexer.socket.websocket import IndexerSocket
config = make_mainnet( # [!code focus]
node_url="your-custom-grpc-node.com", # [!code focus]
rest_indexer="https://your-custom-rest-indexer.com", # [!code focus]
websocket_indexer="wss://your-custom-websocket-indexer.com" # [!code focus]
).node # [!code focus]
# Instantiate the HTTP sub-client. # [!code focus]
indexer = IndexerClient(config.rest_indexer) # [!code focus]
# Instatiate the WebSockets sub-client, connecting to the network. # [!code focus]
socket = await IndexerSocket(network.websocket_indexer).connect() # [!code focus]
```
```typescript [TypeScript]
import { IndexerClient, Network, SocketClient } from '@ritbit/v4-client-js';
const apiTimeout = 1000;
// Using a pre-configured endpoint. // [!code focus]
const config = Network.mainnet().indexerConfig; // [!code focus]
// You can modify the HTTP endpoint doing `config.restEndpoint = "...";` [!code focus]
// You can modify the WebSockets endpoint doing `config.websocketEndpoint = "...";` [!code focus]
// Instantiate the HTTP client. // [!code focus]
const indexer = new IndexerClient(config, apiTimeout); // [!code focus]
// Instantiate the WebSockets client, connecting to the network. // [!code focus]
const socket = new SocketClient( // [!code focus]
config.indexerConfig, // [!code focus]
() => {}, // onOpenCallback
() => {}, // onCloseCallback
() => {}, // onMessageCallback
() => {} // onErrorCallback
); // [!code focus]
socket.connect(); // [!code focus]
```
```rust [Rust]
use ritbit::{config::ClientConfig, indexer::IndexerClient};
// The configuration file should have the endpoint. // [!code focus]
let config = ClientConfig::from_file("config.toml").await?; // [!code focus]
// Instantiate the client. // [!code focus]
// Both HTTP and WebSockets methods are provided with the `indexer`. // [!code focus]
let indexer = IndexerClient::new(config.indexer); // [!code focus]
```
:::
#### Composite client (TypeScript only)
The Composite client groups commonly used methods into a single structure. It is essentially composed by both the Node and Indexer clients.
```typescript [TypeScript]
import { CompositeClient, Network } from '@ritbit/v4-client-js';
const network = Network.mainnet();
const client = await CompositeClient.connect(network); // [!code focus]
```
:::info
The Python and Rust APIs do not have a Composite client. The explicit Node and Indexer clients should be used instead.
:::
### Endpoints
Some known endpoints are provided below. Use these to connect to the Rubin networks.
#### Node
Connections to the trading client to the full nodes are established using the RPC protocol.
##### mainnet
##### RPC
| Team | URI |
| --------- | ------------------------- |
| Tyranodex | `rpc.mainnet.rubin.trade` |
##### REST
| Team | URI |
| --------- | ---------------------------------- |
| Tyranodex | `https://rest.mainnet.rubin.trade` |
##### testnet
##### RPC
| Team | URI |
| --------- | ------------------------- |
| Tyranodex | `rpc.testnet.rubin.trade` |
##### REST
| Team | URI |
| --------- | ---------------------------------- |
| Tyranodex | `https://rest.testnet.rubin.trade` |
#### Indexer
Connections with the Indexer are established either using HTTP (for spontaneuous data retrieval) or WebSockets (for data streaming).
##### mainnet
| Type | URI |
| ---- | ------------------------------------- |
| HTTP | `https://indexer.mainnet.rubin.trade` |
| WS | `wss://indexer.mainnet.rubin.trade` |
##### testnet
| Type | URI |
| ---- | ------------------------------------- |
| HTTP | `https://indexer.testnet.rubin.trade` |
| WS | `wss://indexer.testnet.rubin.trade` |
## Guide
import Details from '../../components/Details';
## Wallet Setup
To manage your accounts, issue orders, and perform other operations that are required to be signed, a Wallet is required. To instantiate a Wallet, you must first have your associated **mnemonic**.
* The Python client requires the use of an address to setup the Wallet. However, the address can only be fetched using a Wallet. The address is derived from the mnemonic (address \< public key \< private key \< mnemonic).
* Wallet, accounts, subaccounts are all handled differently among the clients. Probably the Rust client handles this best, giving the user more control:
1. There is a `Wallet`;
2. The `Wallet` is used to derive an `Account` by index (each `Account` is associated with a keypair);
3. An `Account` is used to derive a `Subaccount` by index. A `Subaccount` is employed to create orders.
::::steps
### Getting the mnemonic
A Wallet is setup using your secret **mnemonic** phrase. A **mnemonic** is a set of 24 words to back up and access your account.
You can fetch your **mnemonic** from the [Rubin Frontend](https://rubin.trade). After logging in, follow the instructions in "Export secret phrase", accessed by clicking your address in the upper right corner.
For the purpose of this guide, lets copy and store the **mnemonic** in a `mnemonic.txt` file.
:::warning
Handle your **mnemonic** in a secure manner. **Do not share** it with other parties. Do not commit your **mnemonic** to a public VCS like GitHub. Access to your **mnemonic** provides access to your account and funds.
:::
### Read the mnemonic
Lets start coding. Load the mnemonic into a string variable. This assumes the mnemonic is stored in a text file.
:::code-group
```python [Python]
mnemonic = open('mnemonic.txt').read().strip()
```
```typescript [TypeScript]
const mnemonic = require('fs').readFileSync('mnemonic.txt', 'utf8').trim();
```
```rust [Rust]
let mnemonic = std::fs::read_to_string("mnemonic.txt").unwrap().trim().to_string();
```
:::
### Create the Wallet
Use the **mnemonic** to create a Wallet instance capable of signing transactions.
:::code-group
```python [Python]
from ritbit_v4_client.key_pair import KeyPair
from ritbit_v4_client.wallet import Wallet
# Define your address.
address = Wallet(KeyPair.from_mnemonic(mnemonic), 0, 0).address()
# Create a Wallet with updated parameters required for trading
wallet = await Wallet.from_mnemonic(node, mnemonic, address)
```
```typescript [TypeScript]
import { BECH32_PREFIX, LocalWallet } from '@ritbit/v4-client-js';
const wallet = await LocalWallet.fromMnemonic(mnemonic, BECH32_PREFIX);
```
```rust [Rust]
use ritbit::node::Wallet;
let wallet = Wallet::from_mnemonic(&mnemonic)?;
```
:::
:::note
Please check the list of [available endpoints here](/interaction/endpoints#endpoints).
:::
### Instantiate a Subaccount
:::note
This step is not required in the Python client.
:::
When issuing orders, the relevant Subaccount must be chosen to place the order under. A Subaccount is associated with an Account, and is meant to provide trade isolation against your other Subaccounts and enhance funds management.
See more about [Accounts and Subaccounts](/concepts/trading/accounts).
:::code-group
```python [Python]
# Not required. The `wallet` instance created above already contains the necessary information.
# The Subaccount to be used is defined using an integer when creating an order.
```
```typescript [TypeScript]
import { SubaccountInfo } from '@ritbit/v4-client-js';
const subaccount = new SubaccountInfo(wallet, 0);
```
```rust [Rust]
// Create an `Account` instance for the account index 0. This `Account` has updated parameters required for trading.
let account = wallet.account(0, &mut node).await?;
// Create a `Subaccount` instance for the subaccount index 0.
let subaccount = account.subaccount(0)?;
```
:::
:::info
By default, both Python and TypeScript client Wallets will derive and use the Account indexed at 0.
:::
::::
## Addresses: EVM & Native
Every Rubin account has exactly one address — the same 20 bytes — shown in two encodings:
* **EVM form**: hex with a `0x` prefix, e.g. `0x1234…abcd`;
* **Native form**: bech32 with the `rit1` prefix, e.g. `rit1…`.
These are not two accounts and not a mapping stored anywhere: the conversion is purely mechanical (bech32 decode/encode of the same bytes), works offline in both directions, and involves no signature or on-chain action.
### Which form to use where
| Context | Form |
| ----------------------------------------------------------------------------------- | ------ |
| EVM wallets (MetaMask etc.), EVM explorers | `0x` |
| EVM JSON-RPC (`https://evm-rpc.rubin.trade`, `https://evm-rpc.testnet.rubin.trade`) | `0x` |
| Chain tooling: CLI, node REST/gRPC, IBC, governance | `rit1` |
| Indexer API address parameters | `rit1` |
| Testnet faucet (`POST https://faucet.testnet.rubin.trade/faucet/tokens`) | `rit1` |
:::note
AI agents and integrations should always display **both** forms to the user — wallets show the `0x` form while chain explorers and tooling show `rit1`, and users may not know they are the same account.
:::
### Converting between forms
The conversion needs only a bech32 library. With [`@cosmjs/encoding`](https://www.npmjs.com/package/@cosmjs/encoding):
```ts
import { fromBech32, fromHex, toBech32, toHex } from '@cosmjs/encoding'
const hexToBech32 = (hex: string): string =>
toBech32('rit', fromHex(hex.replace(/^0x/, '')))
const bech32ToHex = (address: string): string =>
`0x${toHex(fromBech32(address).data)}`
```
### EVM signatures (EIP-712)
The chain accepts EVM-style signatures, so an EVM wallet can act on its account without any chain-native tooling. In particular, [Permissioned Keys](/interaction/permissioned-keys) (agent keys / permissioned trading keys) can be authorized by signing an EIP-712 typed message — `RubinTransaction:ApproveAgent` — in the web app; the chain then registers an `EthAddressSignatureVerification` authenticator for the key. This is how MetaMask-style wallets authorize the [MCP trading key](/interaction/ai-agents).
## Node API
Nodes are the servers that manage and maintain the Rubin network. Trading transactions are broadcast to these, which then are evaluated and eventually comitted into state by the underlying consensus mechanim. It serves both a [Private API](/node-client/private), which receives transactions signed by the user, and a [Public API](/node-client/public), available for different data queries. The [Permissioned Keys API](/node-client/authenticators) is also available.
See the [guide](/interaction/endpoints#node-client) on how to use the available Node client to learn how to connect to it.
:::tip
Consider using the [Indexer API](/indexer-client) over the Node Public API for data queries.
:::
## Network Constants
### Chain ID
**mainnet**: `ritbit-mainnet`
**testnet**: `ritbit-testnet`
### Native Token Denom
**mainnet**: `urit`
**testnet**: `urit`
The denom is 18-decimal: `1 RIT = 10^18 urit`.
### Address Prefix
**account**: `rit`
**validator operator**: `ritvaloper`
### Fee Denoms
Both networks accept fees in either the native token or USDC:
| Denom | Minimum gas price |
| ------- | ----------------- |
| `urit` | `25000000000` |
| `uusdc` | `0.025` |
To confirm the current values against a live node:
```bash
curl -s https://rest.mainnet.rubin.trade/cosmos/base/node/v1beta1/config | jq -r '.minimum_gas_price'
```
### USDC over IBC
In addition to the native `uusdc`, USDC bridged from Noble over IBC is
available on mainnet as:
```
ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5
```
This is the hash of `transfer/channel-0/uusdc`, where `channel-0` is the
transfer channel to Noble (`noble-1`).
### EVM
Native currency: **RIT**, 18 decimals.
| | mainnet | testnet |
| ------------ | -------------------- | -------------------- |
| EVM Chain ID | `111984` (`0x1b570`) | `202006` (`0x31516`) |
EVM RPC/WebSocket URLs are listed in [Public Endpoints](#public-endpoints)
below.
### Public Endpoints
All endpoints are served under two equivalent domains — `rubin.trade` and
`ritbit.xyz`. Use either; they point to the same infrastructure.
#### Mainnet
:::code-group
```ini [rubin.trade]
RPC https://rpc.mainnet.rubin.trade
RPC WebSocket wss://rpc.mainnet.rubin.trade/websocket
REST https://rest.mainnet.rubin.trade
gRPC (TLS) grpc.mainnet.rubin.trade:443
# EVM
EVM JSON-RPC https://evm-rpc.mainnet.rubin.trade
EVM WebSocket wss://evm-rpc.mainnet.rubin.trade
# Indexer
Indexer API https://indexer.mainnet.rubin.trade
Indexer WebSocket wss://indexer.mainnet.rubin.trade/v4/ws
```
```ini [ritbit.xyz]
RPC https://rpc.mainnet.ritbit.xyz
RPC WebSocket wss://rpc.mainnet.ritbit.xyz/websocket
REST https://rest.mainnet.ritbit.xyz
gRPC (TLS) grpc.mainnet.ritbit.xyz:443
# EVM
EVM JSON-RPC https://evm-rpc.mainnet.ritbit.xyz
EVM WebSocket wss://evm-rpc.mainnet.ritbit.xyz
# Indexer
Indexer API https://indexer.mainnet.ritbit.xyz
Indexer WebSocket wss://indexer.mainnet.ritbit.xyz/v4/ws
```
:::
#### Testnet
:::code-group
```ini [rubin.trade]
RPC https://rpc.testnet.rubin.trade
RPC WebSocket wss://rpc.testnet.rubin.trade/websocket
REST https://rest.testnet.rubin.trade
gRPC (TLS) grpc.testnet.rubin.trade:443
# EVM
EVM JSON-RPC https://evm-rpc.testnet.rubin.trade
EVM WebSocket wss://evm-rpc.testnet.rubin.trade
# Indexer
Indexer API https://indexer.testnet.rubin.trade
Indexer WebSocket wss://indexer.testnet.rubin.trade/v4/ws
```
```ini [ritbit.xyz]
RPC https://rpc.testnet.ritbit.xyz
RPC WebSocket wss://rpc.testnet.ritbit.xyz/websocket
REST https://rest.testnet.ritbit.xyz
gRPC (TLS) grpc.testnet.ritbit.xyz:443
# EVM
EVM JSON-RPC https://evm-rpc.testnet.ritbit.xyz
EVM WebSocket wss://evm-rpc.testnet.ritbit.xyz
# Indexer
Indexer API https://indexer.testnet.ritbit.xyz
Indexer WebSocket wss://indexer.testnet.ritbit.xyz/v4/ws
```
:::
### Chain Registry
**Mainnet**: [`ritbit`](https://github.com/cosmos/chain-registry/tree/master/ritbit)
The testnet is not published in the Cosmos chain registry.
## Resources
### Networks Repository
Genesis files, peer lists and per-network configuration live in the `networks`
repository:
* **Mainnet**: [`ritbit/networks/ritbit-mainnet`](https://gitlab.itrf.ru/ritbit/networks/-/tree/main/ritbit-mainnet)
* **Testnet**: [`ritbit/networks/ritbit-testnet`](https://gitlab.itrf.ru/ritbit/networks/-/tree/main/ritbit-testnet)
:::warning
This repository is being prepared and the links above are not live yet. Until it
is published, fetch the genesis file directly from a public node:
```bash
curl -s https://rpc.mainnet.rubin.trade/genesis \
| jq '.result.genesis' > genesis.json
```
:::
### Binaries
Builds are published per version, one directory per release:
* [storage.yandexcloud.net/ritbit-upgrade](https://storage.yandexcloud.net/ritbit-upgrade/)
Each version directory contains the `linux-amd64` archive and an
`upgrade-info.txt` with the SHA-256 checksum. The archive contains a single
`bin/ritbitd`.
```bash
VERSION=v27.5
curl -L -O https://storage.yandexcloud.net/ritbit-upgrade/$VERSION/ritbitd-$VERSION-linux-amd64.tar.gz
curl -s https://storage.yandexcloud.net/ritbit-upgrade/$VERSION/upgrade-info.txt
```
To find the version a network currently runs:
```bash
curl -s https://rest.mainnet.rubin.trade/cosmos/base/tendermint/v1beta1/node_info \
| jq -r '.application_version.version'
```
### Upgrades History
Heights below are the blocks at which each upgrade was applied, as reported by
the networks themselves. To verify any row:
```bash
curl -s https://rest.mainnet.rubin.trade/cosmos/upgrade/v1beta1/applied_plan/v27.5
```
:::details[mainnet]
| Version | Applied at height |
| -------- | ----------------- |
| `v26.9` | 509,260 |
| `v26.13` | 9,160,000 |
| `v26.14` | 12,380,000 |
| `v27.0` | 12,395,000 |
| `v27.1` | 12,471,130 |
| `v27.2` | 12,471,830 |
| `v27.3` | 12,842,226 |
| `v27.4` | 12,933,138 |
| `v27.5` | 12,960,191 |
:::
:::details[testnet]
| Version | Applied at height |
| -------- | ----------------- |
| `v26.12` | 776,500 |
| `v26.13` | 876,000 |
| `v26.14` | 2,550,000 |
| `v27.0` | 4,403,000 |
| `v27.1` | 4,420,500 |
| `v27.2` | 4,497,068 |
| `v27.3` | 4,845,637 |
| `v27.4` | 4,942,502 |
| `v27.5` | 5,016,944 |
:::
### Public Endpoints
All endpoints are served under two equivalent domains — `rubin.trade` and
`ritbit.xyz`. Use either; they point to the same infrastructure.
#### Mainnet
:::code-group
```ini [rubin.trade]
RPC https://rpc.mainnet.rubin.trade
RPC WebSocket wss://rpc.mainnet.rubin.trade/websocket
REST https://rest.mainnet.rubin.trade
gRPC (TLS) grpc.mainnet.rubin.trade:443
# EVM
EVM JSON-RPC https://evm-rpc.mainnet.rubin.trade
EVM WebSocket wss://evm-rpc.mainnet.rubin.trade
# Indexer
Indexer API https://indexer.mainnet.rubin.trade
Indexer WebSocket wss://indexer.mainnet.rubin.trade/v4/ws
```
```ini [ritbit.xyz]
RPC https://rpc.mainnet.ritbit.xyz
RPC WebSocket wss://rpc.mainnet.ritbit.xyz/websocket
REST https://rest.mainnet.ritbit.xyz
gRPC (TLS) grpc.mainnet.ritbit.xyz:443
# EVM
EVM JSON-RPC https://evm-rpc.mainnet.ritbit.xyz
EVM WebSocket wss://evm-rpc.mainnet.ritbit.xyz
# Indexer
Indexer API https://indexer.mainnet.ritbit.xyz
Indexer WebSocket wss://indexer.mainnet.ritbit.xyz/v4/ws
```
:::
#### Testnet
:::code-group
```ini [rubin.trade]
RPC https://rpc.testnet.rubin.trade
RPC WebSocket wss://rpc.testnet.rubin.trade/websocket
REST https://rest.testnet.rubin.trade
gRPC (TLS) grpc.testnet.rubin.trade:443
# EVM
EVM JSON-RPC https://evm-rpc.testnet.rubin.trade
EVM WebSocket wss://evm-rpc.testnet.rubin.trade
# Indexer
Indexer API https://indexer.testnet.rubin.trade
Indexer WebSocket wss://indexer.testnet.rubin.trade/v4/ws
```
```ini [ritbit.xyz]
RPC https://rpc.testnet.ritbit.xyz
RPC WebSocket wss://rpc.testnet.ritbit.xyz/websocket
REST https://rest.testnet.ritbit.xyz
gRPC (TLS) grpc.testnet.ritbit.xyz:443
# EVM
EVM JSON-RPC https://evm-rpc.testnet.ritbit.xyz
EVM WebSocket wss://evm-rpc.testnet.ritbit.xyz
# Indexer
Indexer API https://indexer.testnet.ritbit.xyz
Indexer WebSocket wss://indexer.testnet.ritbit.xyz/v4/ws
```
:::
### Peer Nodes
To seed a new node, use the public full node as a persistent peer:
```
f907537d0ea47759e369f7bac5cb2c22be5e3c93@213.165.223.41:26656
```
Additional peers can be discovered from any running node:
```bash
curl -s https://rpc.mainnet.rubin.trade/net_info \
| jq -r '.result.peers[] | "\(.node_info.id)@\(.remote_ip):26656"'
```
:::note
A curated seed list will move to the [`networks` repository](#networks-repository)
once it is published.
:::
### Snapshots
Snapshots of mainnet state are published regularly to a public bucket:
* [storage.yandexcloud.net/ritbit-mainnet-snapshot](https://storage.yandexcloud.net/ritbit-mainnet-snapshot/)
File names follow `ritbit-mainnet__block-.tar.lz4`. The
timestamp sorts lexicographically, so the last key is the newest snapshot:
```bash
BUCKET=https://storage.yandexcloud.net/ritbit-mainnet-snapshot
LATEST=$(curl -s "$BUCKET/?list-type=2" \
| grep -oE '[^<]+' | sed 's/<[^>]*>//g' | sort | tail -1)
echo "$LATEST"
curl -L -O "$BUCKET/$LATEST"
```
Archives are roughly 25 GiB compressed. See
[Set Up a Full Node](/nodes/running-node/setup) for how to restore one.
### State Sync
The public full nodes above also serve state sync snapshots over P2P, taken every
2000 blocks. State sync fetches only the current application state — no archive
download — and brings a new node online in minutes. See
[Configure Your Node's State Sync Setting](/nodes/running-node/optimize#configure-your-nodes-state-sync-setting)
for the procedure.
:::warning
A state-synced node holds no blocks below the height it synced from, so it cannot
serve historical queries. Restore from a snapshot archive instead if you need history.
:::
### Indexer Endpoints
See [Endpoints](/interaction/endpoints#indexer).
### Block Explorer
* [explorer.rubin.trade](https://explorer.rubin.trade/ritbit-mainnet)
:::note
A Mintscan listing is in progress and will be available at
`https://www.mintscan.io/rubin` once indexing is enabled.
:::
### Chain Registry
* Cosmos chain registry: [`ritbit`](https://github.com/cosmos/chain-registry/tree/master/ritbit)
The testnet is not published in the Cosmos chain registry.
## Security
### Independent Audits
The upstream open-source protocol that Rubin Chain is built on has been audited by
the [Informal Systems](https://informal.systems/) team.
### Reporting a Vulnerability
If you believe you have found a security vulnerability in the protocol, the indexer,
or the bridge contracts, please report it privately to [team@rubin.trade](mailto\:team@rubin.trade) rather
than opening a public issue or disclosing it publicly. Include enough detail to
reproduce the issue.
## Terms-of-Use & Privacy Policy
By using, recording, referencing, or downloading (i.e., any “action”) any information contained on this page or in any Rubin Lab ("Rubin") database or documentation, you hereby and thereby agree to the [v4 Terms of Use](https://rubin.trade/terms) and [Privacy Policy](https://rubin.trade/privacy) governing such information, and you agree that such action establishes a binding agreement between you and Rubin.
This documentation provides information on how to use Rubin v4 software (”Rubin Chain”). Rubin does not deploy or run v4 software for public use, or operate or control any Rubin Chain infrastructure. Rubin is not responsible for any actions taken by other third parties who use v4 software. Rubin services and products are not available to persons or entities who reside in, are located in, are incorporated in, or have registered offices in the United States or Canada, or Restricted Persons (as defined in the Rubin [Terms of Use](https://rubin.trade/terms)). The content provided herein does not constitute, and should not be construed, or relied upon as, financial advice, legal advice, tax advice, investment advice or advice of any other nature, and you agree that you are responsible to conduct independent research, perform due diligence and engage a professional advisor prior to taking any financial, tax, legal or investment action related to the foregoing content. The information contained herein, and any use of v4 software, are subject to the [v4 Terms of Use](https://rubin.trade/terms).
#### Method Name
// TODO: Add description
##### Method Declaration
:::code-group
```rust [Rust]
```
```python [Python]
```
```typescript [TypeScript]
```
```url [API]
```
:::
##### Parameters
| Parameter | Location | Type | Required | Description |
| --------- | -------- | ---- | -------- | ----------- |
| | | | | |
##### Response
| Status | Meaning | Description | Schema |
| ------ | ------- | ----------- | ------ |
| | | | |
import Accounts from './accounts/index.mdx'
import Markets from './markets/index.mdx'
import Utility from './utility/index.mdx'
import Vaults from './vaults/index.mdx'
## HTTP API
import BatchedArray from '../../../components/BatchedArray';
import Details from '../../../components/Details';
#### Block Height
Data feed of current block height. Data contains the last block height and time.
##### Method Declaration
:::code-group
```python [Python]
```
```typescript [TypeScript]
```
```rust [Rust]
// struct `Feeds`
pub async fn block_height(
&mut self,
batched: bool,
) -> Result, FeedError>
// The stream is unsubscribed when the `Feed` object is dropped
```
```url [Channel]
v4_block_height
```
:::
* Add feed to Python, TS clients.
##### Schema
The field `id` is not employed in the subscribe/unsubscribe schemas.
The field `contents` is serialized using the following schemas.
##### Messages
| Initial | Update |
| ----------------------------- | --------------------------------------------- |
| [`BlockHeightInitialMessage`] | [`BlockHeightUpdateMessage`] |
[`BlockHeightInitialMessage`]: /types/block_height_initial_message
[`BlockHeightUpdateMessage`]: /types/block_height_update_message
import BatchedArray from '../../../components/BatchedArray';
#### Candles
Data feed of the [candles](https://en.wikipedia.org/wiki/Candlestick_chart) of a market. Data contains updates for open, low, high, and close prices, trade volume, for a certain time resolution.
##### Method Declaration
:::code-group
```python [Python]
# class `Candles`
def subscribe(self, id: str, resolution: CandlesResolution, batched: bool = True) -> Self
def unsubscribe(self, id: str, resolution: CandlesResolution)
```
```typescript [TypeScript]
// class `IndexerSocket`
subscribeToCandles(market: string, resolution: CandlesResolution): void
unsubscribeFromCandles(market: string, resolution: CandlesResolution): void
```
```rust [Rust]
// struct `Feeds`
pub async fn candles(
&mut self,
ticker: &Ticker,
resolution: CandleResolution,
batched: bool,
) -> Result, FeedError>
// The stream is unsubscribed when the `Feed` object is dropped
```
```url [Channel]
v4_candles
```
:::
##### Schema
The field `id` is a string containing the market and candle resolution. It is formatted as `{market}/{resolution}`.
The field `contents` is serialized using the following schemas.
##### Messages
| Initial | Update |
| ------------------------- | ----------------------------------------- |
| [`CandlesInitialMessage`] | [`CandlesUpdateMessage`] |
[`CandlesInitialMessage`]: /types/candles_initial_message
[`CandlesUpdateMessage`]: /types/candles_update_message
import Feeds from './intro.mdx'
import Subaccounts from './subaccounts.mdx'
import Markets from './markets.mdx'
import Trades from './trades.mdx'
import Orders from './orders.mdx'
import Candles from './candles.mdx'
import ParentSubaccounts from './parent_subaccounts.mdx'
import BlockHeight from './block_height.mdx'
import Details from '../../../components/Details';
## WebSockets API
The WebSockets API provides data feeds providing the trader real-time information.
See the [guide](/interaction/data/feeds) for examples on how to use the WebSockets API.
### Common schemas
Interactions with the WebSockets endpoint is done using common base JSON schemas for all channels/feed types.
For specific feeds, see the following [subsections](#feeds).
#### Subscribe
Use the following schema to subscribe to a channel.
##### JSON Schema
| Parameter | Type | Description |
| --------- | ------ | --------------------------------------------------------------- |
| `type` | string | Message type (`subscribe`). |
| `channel` | string | Feed type identifier. |
| `id` | string | Selector for channel-specific data. Only used in some channels. |
| `batched` | bool | Reduce incoming messages by batching contents. |
```tsx
{
"type": "subscribe",
"channel": "v4_trades",
"id": "BTC-USD",
"batched": false
}
```
##### Response
| Parameter | Type | Description |
| --------------- | ------ | ------------------------------------------------- |
| `type` | string | Message type (`subscribed`). |
| `connection_id` | string | String identifying the subscription. |
| `message_id` | int | Message sequence number sent on the subscription. |
| `id` | string | Selector for channel-specific data. |
| `contents` | value | Channel-specific initial data. |
#### Unsubscribe
Use the following schema to unsubscribe from a channel.
Similar scheme to the `subscribe` schema, however with the `unsubscribe` type, and without the `batched` field.
##### JSON Schema
| Parameter | Type | Description |
| --------- | ------ | ----------------------------------- |
| `type` | string | Message type (`unsubscribe`). |
| `channel` | string | Feed type identifier. |
| `id` | string | Selector for channel-specific data. |
```tsx
{
"type": "unsubscribe",
"channel": "v4_trades",
"id": "BTC-USD"
}
```
##### Response
| Parameter | Type | Description |
| --------------- | ------ | --------------------------------------------------------------- |
| `type` | string | Message type (`unsubscribed`). |
| `connection_id` | string | String identifying the subscription. |
| `channel` | string | Feed type identifier. |
| `message_id` | int | Message sequence number sent on the subscription. |
| `id` | string | Selector for channel-specific data. Only used in some channels. |
#### Data
After subscription, the incoming messages will be serialized using the following schema.
##### JSON Schema
| Parameter | Type | Description |
| --------------- | ------ | --------------------------------------------------------------- |
| `connection_id` | string | String identifying the subscription. |
| `channel` | string | Feed type identifier. |
| `id` | string | Selector for channel-specific data. Only used in some channels. |
| `message_id` | int | Message sequence number sent on the subscription. |
| `version` | string | Protocol identifier. |
| `contents` | value | Channel-specific message data. |
### Channels
The available clients API is presented below.
For each, the subscription and unsubscription functions are shown. Internally, these functions send messages serialized in the [subscribe](#json-schema) and [unsubscribe](#json-schema-1) JSON schemas above.
For each channel/feed type the sub-schemas employed in the `contents` field of the received [Data](#json-schema-2) (after subscription) are shown.
import BatchedArray from '../../../components/BatchedArray';
#### Markets
Data feed of all Rubin markets. Data contains updates to all markets, including market parameters and oracle prices.
##### Method Declaration
:::code-group
```python [Python]
# class `Markets`
def subscribe(self, batched: bool = True) -> Self
def unsubscribe(self)
```
```typescript [TypeScript]
// class `IndexerSocket`
subscribeToMarkets(): void
unsubscribeFromMarkets(): void
```
```rust [Rust]
// struct `Feeds`
pub async fn markets(
&mut self,
batched: bool,
) -> Result, FeedError>
// The stream is unsubscribed when the `Feed` object is dropped
```
```url [Channel]
v4_markets
```
:::
##### Schema
The field `id` is not employed in the subscribe/unsubscribe schemas.
The field `contents` is serialized using the following schemas.
##### Messages
| Initial | Update |
| ------------------------- | ----------------------------------------- |
| [`MarketsInitialMessage`] | [`MarketsUpdateMessage`] |
[`MarketsInitialMessage`]: /types/markets_initial_message
[`MarketsUpdateMessage`]: /types/markets_update_message
import BatchedArray from '../../../components/BatchedArray';
#### Orders
Data feed of the orders of a market. Data contains lists of the bids and asks of the order book.
##### Method Declaration
:::code-group
```python [Python]
# class `OrderBook`
def subscribe(self, market: str, batched: bool = True) -> Self
def unsubscribe(self, market: str)
```
```typescript [TypeScript]
// class `IndexerSocket`
subscribeToOrderbook(market: string): void
unsubscribeFromOrderbook(market: string): void
```
```rust [Rust]
// struct `Feeds`
pub async fn orders(
&mut self,
ticker: &Ticker,
batched: bool,
) -> Result, FeedError>
// The stream is unsubscribed when the `Feed` object is dropped
```
```url [Channel]
v4_orderbook
```
:::
##### Schema
The field `id` is the market/ticker as a string.
The field `contents` is serialized using the following schemas.
##### Messages
| Initial | Update |
| ------------------------ | ---------------------------------------- |
| [`OrdersInitialMessage`] | [`OrdersUpdateMessage`] |
[`OrdersInitialMessage`]: /types/orders_initial_message
[`OrdersUpdateMessage`]: /types/orders_update_message
import BatchedArray from '../../../components/BatchedArray';
#### Parent Subaccounts
Data feed of a parent subaccount. This channel returns similar data to the [subaccount channel](/indexer-client/websockets/subaccounts).
A parent subaccount is a subaccount numbered between 0 and 127. Used for isolated position management by the Rubin frontend (web).
##### Method Declaration
:::code-group
```python [Python]
# Coming soon.
```
```typescript [TypeScript]
// Coming soon.
```
```rust [Rust]
// struct `Feeds`
pub async fn parent_subaccounts(
&mut self,
subaccount: ParentSubaccount,
batched: bool,
) -> Result, FeedError>
// The stream is unsubscribed when the `Feed` object is dropped
```
```url [Channel]
v4_parent_subaccounts
```
:::
##### Schema
The field `id` is a string containing the subaccount ID (address and subaccount number). It is formattted as `{address}/{subaccount-number}`.
The field `contents` is serialized using the following schemas.
##### Messages
| Initial | Update |
| ----------------------------------- | --------------------------------------------------- |
| [`ParentSubaccountsInitialMessage`] | [`ParentSubaccountsUpdateMessage`] |
[`ParentSubaccountsInitialMessage`]: /types/parent_subaccounts_initial_message
[`ParentSubaccountsUpdateMessage`]: /types/parent_subaccounts_update_message
import BatchedArray from '../../../components/BatchedArray';
#### Subaccounts
Data feed of a subaccount. Data contains updates to the subaccount such as position, orders and fills updates.
##### Method Declaration
:::code-group
```python [Python]
# class `Subaccounts`
def subscribe(self, address: str, subaccount_number: int) -> Self
def unsubscribe(self, address: str, subaccount_number: int)
```
```typescript [TypeScript]
// class `IndexerSocket`
subscribeToSubaccount(address: string, subaccountNumber: number): void
unsubscribeFromSubaccount(address: string, subaccountNumber: number): void
```
```rust [Rust]
// struct `Feeds`
pub async fn subaccounts(
&mut self,
subaccount: Subaccount,
batched: bool,
) -> Result, FeedError>
// The stream is unsubscribed when the `Feed` object is dropped
```
```url [Channel]
v4_subaccounts
```
:::
##### Schema
The field `id` is a string containing the subaccount ID (address and subaccount number). It is formattted as `{address}/{subaccount-number}`.
The field `contents` is serialized using the following schemas.
##### Messages
| Initial | Update |
| ----------------------------- | --------------------------------------------- |
| [`SubaccountsInitialMessage`] | [`SubaccountsUpdateMessage`] |
[`SubaccountsInitialMessage`]: /types/subaccounts_initial_message
[`SubaccountsUpdateMessage`]: /types/subaccounts_update_message
import BatchedArray from '../../../components/BatchedArray';
#### Trades
Data feed of the trades on a market. Data contains order fills updates, such as the order side, price and size.
##### Method Declaration
:::code-group
```python [Python]
# class `Trades`
def subscribe(self, market: str, batched: bool = True) -> Self
def unsubscribe(self, market: str)
```
```typescript [TypeScript]
// class `IndexerSocket`
subscribeToTrades(market: string): void
unsubscribeFromTrades(market: string): void
```
```rust [Rust]
// struct `Feeds`
pub async fn trades(
&mut self,
ticker: &Ticker,
batched: bool,
) -> Result, FeedError>
// The stream is unsubscribed when the `Feed` object is dropped
```
```url [Channel]
v4_orderbook
```
:::
##### Schema
The field `id` is the market/ticker as a string.
The field `contents` is serialized using the following schemas.
##### Messages
| Initial | Update |
| ------------------------ | ---------------------------------------- |
| [`TradesInitialMessage`] | [`TradesUpdateMessage`] |
[`TradesInitialMessage`]: /types/trades_initial_message
[`TradesUpdateMessage`]: /types/trades_update_message
## Account
`address`: [Address]
`subaccount_number`: [SubaccountNumber]
[Address]: /types/address
[SubaccountNumber]: /types/subaccount_number
## AccountAuthenticator
`id`: [u64]
`type`: [string]
`config`: [bytes]
[u64]: /types/u64
[string]: /types/string
[bytes]: /types/bytes
## AccountState
`address`: [string]
`timestamp_nonce_details`: [TimestampNonceDetails]
[string]: /types/string
[TimestampNonceDetails]: /types/timestamp_nonce_details
## AccountStateRequest
*No fields.*
## AccountWithParentSubaccountNumber
`address`: [Address]
`parent_subaccount_number`: [ParentSubaccountNumber]
[Address]: /types/address
[ParentSubaccountNumber]: /types/parent_subaccount_number
## AddBridgeEventsRequest
`bridge_events`: [BridgeEvent][]
`is_finalized`: [bool][]
`skipped_events`: [SkippedBridgeEvent][]
[BridgeEvent]: /types/bridge_event
[bool]: /types/bool
[SkippedBridgeEvent]: /types/skipped_bridge_event
## AddBridgeEventsResponse
*No fields.*
## AddWithdrawalSignaturesRequest
`signatures`: [WithdrawalSignatureProto][]
[WithdrawalSignatureProto]: /types/withdrawal_signature_proto
## AddWithdrawalSignaturesResponse
*No fields.*
## Address
An address of an account, represented by a string.
:::code-group
```rust [Rust]
String
```
```python [Python]
str
```
```typescript [TypeScript]
string
```
:::
## AffiliateInfoRequest
`address`: [string]
[string]: /types/string
## AffiliateInfoResponse
`is_whitelisted`: [bool]
`tier`: [u32]
`fee_share_ppm`: [u32]
`referred_volume`: [bytes]
`staked_amount`: [bytes]
`referred_volume_30d_rolling`: [bytes]
[bool]: /types/bool
[u32]: /types/u32
[bytes]: /types/bytes
## AffiliateOverrides
`addresses`: [string][]
[string]: /types/string
## AffiliateParameters
`maximum_30d_attributable_volume_per_referred_user_quote_quantums`: [u64]
`referee_minimum_fee_tier_idx`: [u32]
`maximum_30d_affiliate_revenue_per_referred_user_quote_quantums`: [u64]
[u64]: /types/u64
[u32]: /types/u32
## AffiliateTiers
`tiers`: [Tier][]
[Tier]: /types/tier
## AffiliateWhitelist
`tiers`: [Tier][]
[Tier]: /types/tier
## AggregatedWithdrawal
`withdrawal`: [Withdrawal]
`signatures`: [WithdrawalSignature][]
`signature_count`: [u64]
`required_signatures`: [u64]
`ready_for_relay`: [bool]
`ready_at_block`: [i64]
`assigned_relayer`: [string]
[Withdrawal]: /types/withdrawal
[WithdrawalSignature]: /types/withdrawal_signature
[u64]: /types/u64
[bool]: /types/bool
[i64]: /types/i64
[string]: /types/string
## AllAffiliateTiersRequest
*No fields.*
## AllDowntimeInfo
`infos`: [DowntimeInfo][]
[DowntimeInfo]: /types/downtime_info
## ApiOrderStatus
`ApiOrderStatus` is an enum consists of the following values
* `OrderStatus`
* `BestEffort`
## ApiTimeInForce
`ApiTimeInForce` is an enum consists of the following values
* `Gtt`
* `Fok`
* `Ioc`
## Asset
`id`: [u32]
`symbol`: [string]
`denom`: [string]
`denom_exponent`: [i32]
`has_market`: [bool]
`market_id`: [u32]
`atomic_resolution`: [i32]
[u32]: /types/u32
[string]: /types/string
[i32]: /types/i32
[bool]: /types/bool
## AssetChainDailyLimitConfig
`chain_id`: [u64]
`asset_id`: [u32]
`daily_limit`: [string]
[u64]: /types/u64
[u32]: /types/u32
[string]: /types/string
## AssetChainWithdrawalDailyUsage
`chain_id`: [u64]
`asset_id`: [u32]
`daily_used`: [string]
`last_reset`: [i64]
[u64]: /types/u64
[u32]: /types/u32
[string]: /types/string
[i64]: /types/i64
## AssetId
A string identifier representing a specific asset (e.g., "USDC"). Used to uniquely reference assets within the system.
:::code-group
```rust [Rust]
String
```
```python [Python]
str
```
```typescript [TypeScript]
string
```
:::
## AssetId
A `u32` integer identifier representing a specific asset (e.g., USDC, RIT token).
See more on [Perpetuals and Assets](/concepts/trading/assets).
## AssetPosition
`asset_id`: [u32]
`quantums`: [u8]
`index`: [u64]
[u32]: /types/u32
[u8]: /types/u8
[u64]: /types/u64
## AssetPositionResponseObject
`symbol`: [Symbol]
`side`: [PositionSide]
`size`: [Quantity]
`subaccountNumber`: [SubaccountNumber]
`assetId`: [AssetId]
[Symbol]: /types/symbol
[PositionSide]: /types/position_side
[Quantity]: /types/quantity
[SubaccountNumber]: /types/subaccount_number
[AssetId]: /types/asset_id
## AssetPositionSubaccountMessage
Update sub-message received on the `v4_subaccounts` channel.
`address`: [`Address`]
`subaccountNumber`: [`SubaccountNumber`]
`positionId`: string
`assetId`: [`AssetId`]
`symbol`: [`Symbol`]
`side`: [`PositionSide`]
`size`: [`Quantity`]
[`Address`]: /types/address
[`SubaccountNumber`]: /types/subaccount_number
[`PositionSide`]: /types/position_side
[`Quantity`]: /types/quantity
[`AssetId`]: /types/asset_id
[`Symbol`]: /types/symbol
## AssetPositionsMap
Key: [Ticker]
Value: [AssetPositionResponseObject]
[Ticker]: /types/ticker
[AssetPositionResponseObject]: /types/asset_position_response_object
## AssetWithdrawalConfig
`asset_id`: [u32]
`large_withdrawal_threshold`: [string]
`timelock_blocks`: [u64]
`withdrawal_fee`: [Coin][]
[u32]: /types/u32
[string]: /types/string
[u64]: /types/u64
[Coin]: /types/coin
## Authenticator
`Authenticator` is an enum represented by the following values
* `SignatureVerification`
* `MessageFilter`
* `SubaccountFilter`
* `ClobPairIdFilter`
* `AnyOf`
* `AllOf`
## AuthenticatorData
`address`: [string]
`authenticators`: [AccountAuthenticator][]
[string]: /types/string
[AccountAuthenticator]: /types/account_authenticator
## Bad Request
[https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1](https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1)
## BaseAccount
`address`: string
`pub_key`: Any
`account_number`: [u64]
`sequence`: [u64]
[u64]: /types/u64
## BigDecimal
A high-precision decimal number type used to represent values requiring exact precision, such as prices or quantities. Typically serialized as a string to avoid precision loss.
:::code-group
```rust [Rust]
big_decimal::BigDecimal
```
```python [Python]
str
```
```typescript [TypeScript]
string
```
:::
## Block
\`header: [Header]
`data`: [Data]
`evievidence`: [EvidenceList]
`last_commit`: [Commit]
[Header]: /types/header
[Data]: /types/data
[EvidenceList]: /types/evidence_list
[Commit]: /types/commit
## BlockHeightInitialMessage
Initial message received on the `v4_block_height` channel.
It is a [`HeightResponse`] object.
[`HeightResponse`]: /types/height_response
## BlockHeightMessage
`block_height`: [string]
`time`: [string]
`version`: [string]
[string]: /types/string
## BlockHeightUpdateMessage
Update message received on the `v4_block_height` channel.
`blockHeight`: [`Height`]
`time`: [`DateTime`]
[`DateTime`]: /types/date_time
[`Height`]: /types/height
## BlockId
`hash`: [u8] ⛁
`part_set_header`: [PartSetHeader]
[u8]: /types/u8
[PartSetHeader]: /types/part_set_header
## BlockInfo
`height`: [u32]
`timestamp`: [Timestamp]
[u32]: /types/u32
[Timestamp]: /types/timestamp
## BlockMessageIds
`ids`: [u32][]
[u32]: /types/u32
## BlockRateLimitConfiguration
`max_short_term_orders_per_n_blocks`: [MaxPerNBlocksRateLimit][]
`max_stateful_orders_per_n_blocks`: [MaxPerNBlocksRateLimit][]
`max_leverage_updates_per_n_blocks`: [MaxPerNBlocksRateLimit][]
[MaxPerNBlocksRateLimit]: /types/max_per_n_blocks_rate_limit
## BlockStats
`fills`: [Fill][]
[Fill]: /types/fill
## BridgeEvent
`id`: [u32]
`coin`: [Coin]
`address`: string
`eth_block_height`: [u64]
[u32]: /types/u32
[Coin]: /types/coin
[u64]: /types/u64
## BridgeEventInfo
`next_id`: [u32]
`eth_block_height`: [u64]
[u32]: /types/u32
[u64]: /types/u64
## BridgeOperation
*No fields.*
## BroadcastMode
`BroadcastMode` is an enum consists of the following values:
* BroadcastTxSync
* BroadcastTxCommit
## BuilderCodeParameters
Represents the metadata for the partner or builder of an order. This allows them to specify a fee for providing their service which will be paid out in the event of an order fill.
`builder_address`: [Address]
* The address of the builder to which the fee will be paid
`fee_ppm`: [u32]
* The fee enforced on the order in parts per million (ppm)
[Address]: /types/address
[u32]: /types/u32
## CachedStakedBaseTokens
`staked_base_tokens`: [bytes]
`cached_at`: [i64]
[bytes]: /types/bytes
[i64]: /types/i64
## CandleMessage
`contents`: [string]
`clob_pair_id`: [string]
`resolution`: [Resolution]
`version`: [string]
[string]: /types/string
[Resolution]: /types/resolution
## CandleResolution
`CandleResolution` is an enum represented by the following values
* `M1`
* `M5`
* `M15`
* `M30`
* `H1`
* `H4`
* `D1`
import Opt from '../../components/Opt';
## CandleResponseObject
`ticker`: [Ticker]
`trades`: [u64]
`startedAt`: [DateTime in UTC]
`baseTokenVolume`: [Quantity]
`open`: [Price]
`low`: [Price]
`high`: [Price]
`close`: [Price]
`resolution`: [CandleResolution]
`usdVolume`: [Quantity]
`startingOpenInterest`: [BigDecimal]
`orderBookMidPriceOpen`: [BigDecimal]
`orderBookMidPriceClose`: [BigDecimal]
[Ticker]: /types/ticker
[DateTime in UTC]: /types/date_time
[Quantity]: /types/quantity
[Price]: /types/price
[CandleResolution]: /types/candle_resolution
[BigDecimal]: /types/big_decimal
[u64]: /types/u64
import Array from '../../components/Array';
## CandlesInitialMessage
Initial message received on the `v4_candles` channel.
`candles`: [`CandleResponseObject`]
[`CandleResponseObject`]: /types/candle_response_object
import Array from '../../components/Array';
## CandlesUpdateMessage
Update message received on the `v4_candles` channel.
It is a [`CandleResponseObject`].
[`CandleResponseObject`]: /types/candle_response_object
## ChainBridgeEventInfo
`chain_id`: [u64]
`info`: [BridgeEventInfo]
[u64]: /types/u64
[BridgeEventInfo]: /types/bridge_event_info
## ChainConfig
`chain_id`: [u64]
`bridge_address`: [string]
`token_mappings`: [TokenMapping][]
[u64]: /types/u64
[string]: /types/string
[TokenMapping]: /types/token_mapping
## ChainWithdrawalConfig
`chain_id`: [u64]
`asset_configs`: [AssetWithdrawalConfig][]
[u64]: /types/u64
[AssetWithdrawalConfig]: /types/asset_withdrawal_config
## ChainWithdrawalConfirmationInfo
`chain_id`: [u64]
`info`: [WithdrawalConfirmationInfo]
[u64]: /types/u64
[WithdrawalConfirmationInfo]: /types/withdrawal_confirmation_info
## ChainWithdrawalState
`chain_id`: [u64]
`next_id`: [u64]
[u64]: /types/u64
## ClientId
`ClientId` is represented by [u32]
[u32]: /types/u32
## ClientMetadata
A wrapper around a [u32] value used to attach optional, client-defined metadata to orders or fills. Useful for tracking or categorizing actions on the client side.
[u32]: /types/u32
## ClobMatch
*No fields.*
## ClobMidPrice
`clob_pair`: [ClobPair]
`subticks`: [u64]
[ClobPair]: /types/clob_pair
[u64]: /types/u64
## ClobPair
`id`: [u32]
`metadata`: [Metadata]
`quantum_conversion_exponent`: [i32]
`step_base_quantums`: [u64]
`subticks_per_tick`: [u32]
`status`: [ClobPairStatus]
[u32]: /types/u32
[u64]: /types/u64
[i32]: /types/i32
[Metadata]: /types/metadata
[ClobPairStatus]: /types/clob_pair_status
## ClobPairId
A CLOB (Central Limit Order Book) Pair ID refers to the identifier for a specific order book (spot, perpetual, etc.). It uniquely identifies where liquidity rests, tick sizes, step sizes, and other trading configuration for that product.
`ClobPairId` is represented by [u32]
[u32]: /types/u32
## ClobPairStatus
`ClobPairStatus` is an enum consists of the following values:
* `Unspecified`
* `Active`
* `Paused`
* `CancelOnly`
* `PostOnly`
* `Initializing`
* `FinalSettlement`
## ClobStagedFinalizeBlockEvent
*No fields.*
## Coin
`denom`: string
`amount`: string
## Commission
`commission_rates`: [CommissionRates]
`update_time`: [Timestamp]
[CommissionRates]: /types/commission_rates
[Timestamp]: /types/timestamp
## CommissionRates
`rate`: string
`max_rate`: string
`max_change_rate`: string
## Commit
`height`: [i64]
`round`: [i32]
`block_id`: [BlockId]
`signatures`: [CommitSig] ⛁
[i64]: /types/i64
[i32]: /types/i32
[BlockId]: /types/block_id
[CommitSig]: /types/commit_sig
## CommitSig
`block_id_flag`: [i32]
`validator_address`: [u8] ⛁
`timestamp`: [Timestamp]
`signature`: [u8] ⛁
[i32]: /types/i32
[u8]: /types/u8
[Timestamp]: /types/timestamp
## ComplianceReason
`ComplianceReason` is an enum consists of the following values
* MANUAL
* US\_GEO
* CA\_GEO
* GB\_GEO
* SANCTIONED\_GEO
* COMPLIANCE\_PROVIDER
## ComplianceReason
`ComplianceReason` is an enum consists of the following values
* COMPLIANT
* FIRST\_STRIKE\_CLOSE\_ONLY
* FIRST\_STRIKE
* CLOSE\_ONLY
* BLOCKED
## ConditionalOrderPlacement
`order`: [Order]
`placement_index`: [TransactionOrdering]
`trigger_index`: [TransactionOrdering]
[Order]: /types/order
[TransactionOrdering]: /types/transaction_ordering
## Consensus
`block`: [u64]
`app`: [u64]
[u64]: /types/u64
## Cosmos
// TODO
This type is from cosmos SDK. The exact response will be added later.
## Data
`txs`: [u8] ⛁⛁
[u8]: /types/u8
## DateTime
A a timestamp type representing a specific date and time in Coordinated Universal Time (UTC), with nanosecond precision.
It must be represented as an ISO 8601 formatted string.
## DelayedCompleteBridgeMessages
`message`: [MessageCompleteBridge]
`block_height`: [u32]
[MessageCompleteBridge]: /types/message_complete_bridge
[u32]: /types/u32
## DelayedMessage
`id`: [u32]
`msg`: [Any]
`block_height`: [u32]
[u32]: /types/u32
[Any]: /types/any
## Delegation
`delegator_address`: string
`validator_address`: string
`shares`: string
## Denom
`Denom` is an enum consists of the following values
* `Usdc`
* `RIT`
* `NobleUsdc`
* `Custom`
## DenomCapacity
`denom`: [string]
`capacity_list`: [bytes][]
[string]: /types/string
[bytes]: /types/bytes
## DepositOperation
`event`: [BridgeEvent]
`is_finalized`: [bool]
[BridgeEvent]: /types/bridge_event
[bool]: /types/bool
## Description
`moniker`: string
`identity`: string
`website`: string
`security_contact`: string
`details`: string
## DowntimeParams
`durations`: [Duration][]
[Duration]: /types/duration
## EpochInfo
`name`: [string]
`next_tick`: [u32]
`duration`: [u32]
`current_epoch`: [u32]
`current_epoch_start_block`: [u32]
`is_initialized`: [bool]
`fast_forward_next_tick`: [bool]
[string]: /types/string
[u32]: /types/u32
[bool]: /types/bool
## EpochStats
`epoch_end_time`: [Timestamp]
`stats`: [UserWithStats][]
[Timestamp]: /types/timestamp
[UserWithStats]: /types/user_with_stats
## EquityTierLimit
`usd_tnc_required`: [u8] ⛁
`limit`: [u32]
[u8]: /types/u8
[u32]: /types/u32
## EquityTierLimitConfiguration
`short_term_order_equity_tiers`: [EquityTierLimit] ⛁
`stateful_order_equity_tiers`: [EquityTierLimit] ⛁
[EquityTierLimit]: /types/equity_tier_limit
## EventParams
`chains`: [ChainConfig][]
[ChainConfig]: /types/chain_config
## Evidence
`sum`: [EvidenceSum]
[EvidenceSum]: /types/evidence_sum
## EvidenceList
`evidence`: [Evidence] ⛁
[Evidence]: /types/evidence
## EvidenceSum
`EvidenceSum` is an enum consists of the following values:
* `DuplicateVoteEvidence`
* `LightClientAttackEvidence`
\#f64
`f64` represents 64 bit floating point number
## FillId
A wrapper around a String that uniquely identifies a specific fill event.
Used to reference and track individual trade executions.
import Opt from '../../components/Opt';
## FillResponseObject
Represents the details of a trade fill, including size, price, market information, and metadata related to the order and subaccount.
`id`: [FillId]
`side`: [OrderSide]
`liquidity`: [Liquidity]
`type`: [FillType]
`market`: [Ticker]
`market_type`: [MarketType]
`price`: [Price]
`size`: [BigDecimal]
`fee`: [BigDecimal]
`affiliate_rev_share`: [BigDecimal]
`created_at`: [DateTime]
`created_at_height`: [Height]
`order_id`: [OrderId]
`client_metadata`: [ClientMetadata]
`subaccount_number`: [SubaccountNumber]
`builder_fee`: [BigDecimal]
> **Note:** Builder fee fields will be introduced in a future version of the API (v9.0).
`builder_address`: [Address]
[FillId]: /types/fill_id
[OrderSide]: /types/order_side
[BigDecimal]: /types/big_decimal
[FillType]: /types/fill_type
[Liquidity]: /types/liquidity
[Ticker]: /types/ticker
[MarketType]: /types/market_type
[Price]: /types/price
[SubaccountNumber]: /types/subaccount_number
[Height]: /types/height
[DateTime]: /types/date_time
[ClientMetadata]: /types/client_metadata
[OrderId]: /types/order_id
[Address]: /types/address
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## FillSubaccountMessage
`id`: [`FillId`]
`subaccountId`: [`SubaccountId`]
`side`: [`OrderSide`]
`liquidity`: [`Liquidity`]
`type`: [`FillType`]
`clobPairId`: [`ClobPairId`]
`size`: [`Quantity`]
`price`: [`Price`]
`quoteAmount`: string
`eventId`: string
`transactionHash`: string
`createdAt`: [`DateTime`]
`createdAtHeight`: [`Height`]
`ticker`: [`Ticker`]
`orderId`: [`OrderId`]
`clientMetadata`: [`ClientMetadata`]
[`FillId`]: /types/fill_id
[`SubaccountId`]: /types/subaccount_id
[`OrderSide`]: /types/order_side
[`Liquidity`]: /types/liquidity
[`FillType`]: /types/fill_type
[`ClobPairId`]: /types/clob_pair_id
[`DateTime`]: /types/date_time
[`Height`]: /types/height
[`Quantity`]: /types/quantity
[`Ticker`]: /types/ticker
[`Price`]: /types/price
[`OrderId`]: /types/order_id
[`ClientMetadata`]: /types/client_metadata
## FillType
An enum representing the origin or nature of a fill. Possible string values are:
* `LIMIT` – Result of a regular limit order.
* `LIQUIDATED` – Result of liquidating another trader's position.
* `LIQUIDATION` – Result of one's own position being liquidated.
* `DELEVERAGED` – Caused by automatic deleveraging in risk management.
* `OFFSETTING` – Result of offsetting positions, often for risk reduction.
## FillablePriceConfig
`bankruptcy_adjustment_ppm`: [u32]
`spread_to_maintenance_margin_ratio_ppm`: [u32]
[u32]: /types/u32
## FinalityConfirmation
`event_id`: [u32]
`eth_chain_id`: [u64]
[u32]: /types/u32
[u64]: /types/u64
## FundingEventV1
`updates`: [FundingUpdateV1][]
`type`: [Type]
[FundingUpdateV1]: /types/funding_update_v1
[Type]: /types/type
## FundingPaymentResponseObject
Represents the details of a funding payment, including payment amount, funding rate, position information, and metadata related to the perpetual market and subaccount.
`createdAt`: [DateTime]
`createdAtHeight`: [Height]
`perpetualId`: string
`ticker`: [Ticker]
`oraclePrice`: [Price]
`size`: [BigDecimal]
`side`: [PositionSide]
`rate`: [BigDecimal]
`payment`: [BigDecimal]
`subaccountNumber`: [SubaccountNumber]
`fundingIndex`: [BigDecimal]
[DateTime]: /types/date_time
[Height]: /types/height
[Ticker]: /types/ticker
[Price]: /types/price
[BigDecimal]: /types/big_decimal
[PositionSide]: /types/position_side
[SubaccountNumber]: /types/subaccount_number
## FundingPaymentsResponseObject
Represents a paginated response containing funding payment data for a subaccount or parent subaccount.
`pageSize`: [u32]
`totalResults`: [u32]
`offset`: [u32]
`fundingPayments`: [FundingPaymentResponseObject][]
[u32]: /types/u32
[FundingPaymentResponseObject]: /types/funding_payment_response_object
## FundingUpdateV1
`perpetual_id`: [u32]
`funding_value_ppm`: [i32]
`funding_index`: [bytes]
[u32]: /types/u32
[i32]: /types/i32
[bytes]: /types/bytes
## GasInfo
`gas_wanted`: [u64]
`gas_used`: [u64]
[u64]: /types/u64
## GenesisState
`vest_entries`: [VestEntry][]
[VestEntry]: /types/vest_entry
## GenesisStateV6
`vaults`: [Vault][]
`default_quoting_params`: [QuotingParams]
[Vault]: /types/vault
[QuotingParams]: /types/quoting_params
## GlobalStats
`notional_traded`: [u64]
[u64]: /types/u64
## GoodTilOneof
`GoodTilOneof` is an enum consists of the following values
* `GoodTillBlock`
* `GoodTillBlockTime`
## Header
`version`: [Consensus]
`chain_id`: string
`height`: [i64]
`time`: [TimeStamp]
[Consensus]: /types/consensus
[i64]: /types/i64
[TimeStamp]: /types/timestamp
## Height
A block number representing a specific point in the blockchain's history.
Used to fetch historical data or to set an expiration block for an order.
## HistoricalBlockTradingReward
`trading_reward`: [BigDecimal]
`created_at_height`: [Height]
`created_at`: [DateTime]
[BigDecimal]: /types/big_decimal
[Height]: /types/height
[DateTime]: /types/date_time
## HistoricalFundingResponseObject
`ticker`: [Ticker]
`effective_at`: [DateTime in UTC]
`effective_at_height`: [Height]
`price`: [Price]
`rate`: [BigDecimal]
[Ticker]: /types/ticker
[DateTime in UTC]: /types/date_time
[Height]: /types/height
[Price]: /types/price
[BigDecimal]: /types/big_decimal
## HistoricalTradingRewardAggregation
`trading_reward`: [BigDecimal]
`started_at_height`: [Height]
`started_at`: [DateTime]
`ended_at_height`: [Height]
`ended_at`: [TradingRewardAggregationPeriod]
[BigDecimal]: /types/big_decimal
[Height]: /types/height
[DateTime]: /types/date_time
[TradingRewardAggregationPeriod]: /types/trading_reward_aggregation_period
## i32
signed integer
## i64
signed 64 bit integer
## IndexerAssetPosition
`asset_id`: [u32]
`quantums`: [bytes]
`index`: [u64]
[u32]: /types/u32
[bytes]: /types/bytes
[u64]: /types/u64
## IndexerEventsStoreValue
`events`: [IndexerTendermintEventWrapper][]
[IndexerTendermintEventWrapper]: /types/indexer_tendermint_event_wrapper
## IndexerOrder
`order_id`: [IndexerOrderId]
`side`: [Side]
`quantums`: [u64]
`subticks`: [u64]
`time_in_force`: [TimeInForce]
`reduce_only`: [bool]
`client_metadata`: [u32]
`condition_type`: [ConditionType]
`conditional_order_trigger_subticks`: [u64]
`builder_code_params`: [BuilderCodeParameters]
`order_router_address`: [string]
`twap_parameters`: [TwapParameters]
[IndexerOrderId]: /types/indexer_order_id
[Side]: /types/side
[u64]: /types/u64
[TimeInForce]: /types/time_in_force
[bool]: /types/bool
[u32]: /types/u32
[ConditionType]: /types/condition_type
[BuilderCodeParameters]: /types/builder_code_parameters
[string]: /types/string
[TwapParameters]: /types/twap_parameters
## IndexerOrderId
`subaccount_id`: [IndexerSubaccountId]
`client_id`: [u32]
`order_flags`: [u32]
`clob_pair_id`: [u32]
[IndexerSubaccountId]: /types/indexer_subaccount_id
[u32]: /types/u32
## IndexerPerpetualPosition
`perpetual_id`: [u32]
`quantums`: [bytes]
`funding_index`: [bytes]
`funding_payment`: [bytes]
[u32]: /types/u32
[bytes]: /types/bytes
## IndexerSubaccountId
`owner`: [string]
`number`: [u32]
[string]: /types/string
[u32]: /types/u32
## IndexerTendermintBlock
`height`: [u32]
`time`: [Timestamp]
`events`: [IndexerTendermintEvent][]
`tx_hashes`: [string][]
[u32]: /types/u32
[Timestamp]: /types/timestamp
[IndexerTendermintEvent]: /types/indexer_tendermint_event
[string]: /types/string
## IndexerTendermintEvent
`subtype`: [string]
`event_index`: [u32]
`version`: [u32]
`data_bytes`: [bytes]
[string]: /types/string
[u32]: /types/u32
[bytes]: /types/bytes
## IndexerTendermintEventWrapper
`event`: [IndexerTendermintEvent]
`txn_hash`: [string]
[IndexerTendermintEvent]: /types/indexer_tendermint_event
[string]: /types/string
## InternalOperation
*No fields.*
## KeyPair
`key`: string
## LeverageData
`entries`: [PerpetualLeverageEntry][]
[PerpetualLeverageEntry]: /types/perpetual_leverage_entry
## LimitParams
`denom`: [string]
`limiters`: [Limiter][]
[string]: /types/string
[Limiter]: /types/limiter
## Limiter
`period`: [Duration]
`baseline_minimum`: [bytes]
`baseline_tvl_ppm`: [u32]
[Duration]: /types/duration
[bytes]: /types/bytes
[u32]: /types/u32
## LimiterCapacity
`limiter`: [Limiter]
`capacity`: [bytes]
[Limiter]: /types/limiter
[bytes]: /types/bytes
## LiquidateSubaccountsRequest
`block_height`: [u32]
`liquidatable_subaccount_ids`: [SubaccountId][]
`negative_tnc_subaccount_ids`: [SubaccountId][]
[u32]: /types/u32
[SubaccountId]: /types/subaccount_id
## LiquidateSubaccountsResponse
*No fields.*
## LiquidationsConfig
`max_liquidation_fee_ppm`: [u32]
`position_block_limits`: [PositionBlockLimits]
`subaccount_block_limits`: [SubaccountBlockLimits]
`fillable_price_config`: [FillablePriceConfig]
[u32]: /types/u32
[PositionBlockLimits]: /types/position_block_limits
[SubaccountBlockLimits]: /types/subaccount_block_limits
[FillablePriceConfig]: /types/fillable_price_config
## Liquidity
An enum indicating the liquidity role of the fill. Possible string values are:
* `TAKER` – The order removed liquidity from the order book (matched an existing order).
* `MAKER` – The order added liquidity to the order book (rested before being matched).
## LiquidityTier
`id`: [u32]
`name`: [string]
`initial_margin_ppm`: [u32]
`maintenance_fraction_ppm`: [u32]
`base_position_notional`: [u64]
`impact_notional`: [u64]
`open_interest_lower_cap`: [u64]
`open_interest_upper_cap`: [u64]
[u32]: /types/u32
[string]: /types/string
[u64]: /types/u64
## ListLimitParamsRequest
*No fields.*
## ListingVaultDepositParams
`new_vault_deposit_amount`: [bytes]
`main_vault_deposit_amount`: [bytes]
`num_blocks_to_lock_shares`: [u32]
[bytes]: /types/bytes
[u32]: /types/u32
## LongTermOrderPlacement
`order`: [Order]
`placement_index`: [TransactionOrdering]
[Order]: /types/order
[TransactionOrdering]: /types/transaction_ordering
## MEVLiquidationMatch
`liquidated_subaccount_id`: [SubaccountId]
`insurance_fund_delta_quote_quantums`: [i64]
`maker_order_subaccount_id`: [SubaccountId]
`maker_order_subticks`: [u64]
`maker_order_is_buy`: [bool]
`maker_fee_ppm`: [i32]
`clob_pair_id`: [u32]
`fill_amount`: [u64]
[SubaccountId]: /types/subaccount_id
[i64]: /types/i64
[u64]: /types/u64
[bool]: /types/bool
[i32]: /types/i32
[u32]: /types/u32
## MEVMatch
`taker_order_subaccount_id`: [SubaccountId]
`taker_fee_ppm`: [i32]
`maker_order_subaccount_id`: [SubaccountId]
`maker_order_subticks`: [u64]
`maker_order_is_buy`: [bool]
`maker_fee_ppm`: [i32]
`clob_pair_id`: [u32]
`fill_amount`: [u64]
[SubaccountId]: /types/subaccount_id
[i32]: /types/i32
[u64]: /types/u64
[bool]: /types/bool
[u32]: /types/u32
## MakerFill
`fill_amount`: [u64]
`maker_order_id`: [OrderId]
[u64]: /types/u64
[OrderId]: /types/order_id
## MarketBaseEventV1
`pair`: [string]
`min_price_change_ppm`: [u32]
[string]: /types/string
[u32]: /types/u32
## MarketCreateEventV1
`base`: [MarketBaseEventV1]
`exponent`: [i32]
[MarketBaseEventV1]: /types/market_base_event_v1
[i32]: /types/i32
## MarketEventV1
`market_id`: [u32]
[u32]: /types/u32
## MarketMapperRevShareDetails
`expiration_ts`: int
## MarketMapperRevenueShareParams
`address`: [string]
`revenue_share_ppm`: [u32]
`valid_days`: [u32]
[string]: /types/string
[u32]: /types/u32
## MarketMessage
`contents`: [string]
`version`: [string]
[string]: /types/string
## MarketModifyEventV1
*No fields.*
## MarketParam
`id`: [u32]
`pair`: [string]
`exponent`: [i32]
`min_exchanges`: [u32]
`min_price_change_ppm`: [u32]
`exchange_config_json`: [string]
[u32]: /types/u32
[string]: /types/string
[i32]: /types/i32
## MarketPremiums
`perpetual_id`: [u32]
`premiums`: [i32][]
[u32]: /types/u32
[i32]: /types/i32
## MarketPrice
`id`: [u32]
`exponent`: [i32]
`price`: [u64]
[u32]: /types/u32
[i32]: /types/i32
[u64]: /types/u64
## MarketPriceUpdateEventV1
`price_with_exponent`: [u64]
[u64]: /types/u64
## Market Type
An enum indicating the type of market, with possible case-insensitive string values:
* `PERPETUAL`
* `SPOT`
## MarketsInitialMessage
Initial message received on the `v4_markets` channel.
`markets`: Map\[[`Ticker`], [`PerpetualMarket`]]
[`Ticker`]: /types/ticker
[`PerpetualMarket`]: /types/perpetual_market
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## MarketsUpdateMessage
Update message received on the `v4_markets` channel.
`trading`: Map\[[`Ticker`], [`TradingPerpetualMarket`]]
`oraclePrices`: Map\[[`Ticker`], [`OraclePriceMarket`]]
[`Ticker`]: /types/ticker
[`TradingPerpetualMarket`]: /types/trading_perpetual_market
[`OraclePriceMarket`]: /types/oracle_price_market
## MatchOrders
`taker_order_id`: [OrderId]
`fills`: [MakerFill][]
[OrderId]: /types/order_id
[MakerFill]: /types/maker_fill
## MatchPerpetualDeleveraging
`liquidated`: [SubaccountId]
`perpetual_id`: [u32]
`fills`: [Fill][]
`is_final_settlement`: [bool]
[SubaccountId]: /types/subaccount_id
[u32]: /types/u32
[Fill]: /types/fill
[bool]: /types/bool
## MatchPerpetualLiquidation
`liquidated`: [SubaccountId]
`clob_pair_id`: [u32]
`perpetual_id`: [u32]
`total_size`: [u64]
`is_buy`: [bool]
`fills`: [MakerFill][]
[SubaccountId]: /types/subaccount_id
[u32]: /types/u32
[u64]: /types/u64
[bool]: /types/bool
[MakerFill]: /types/maker_fill
## MaxPerNBlocksRateLimit
`num_blocks`: [u32]
`limit`: [u32]
[u32]: /types/u32
## MessageCompleteBridge
`authority`: string
`event`: [BridgeEvent]
[BridgeEvent]: /types/bridge_event
## Metadata
`Metadata` is an enum consists of the following values
* [PerpetualClobMetadata]
* [SpotClobMetadata]
[PerpetualClobMetadata]: /types/perpetual_clob_metadata
[SpotClobMetadata]: /types/spot_clob_metadata
## MevNodeToNodeMetrics
`validator_mev_matches`: [ValidatorMevMatches]
`clob_mid_prices`: [ClobMidPrice][]
`bp_mev_matches`: [ValidatorMevMatches]
`proposal_receive_time`: [u64]
[ValidatorMevMatches]: /types/validator_mev_matches
[ClobMidPrice]: /types/clob_mid_price
[u64]: /types/u64
## Module
`path`: string
`version`: string
`sum`: string
## MsgAcknowledgeBridges
`operations`: [BridgeOperation][]
`confirmations`: [FinalityConfirmation][]
[BridgeOperation]: /types/bridge_operation
[FinalityConfirmation]: /types/finality_confirmation
## MsgAcknowledgeBridgesResponse
*No fields.*
## MsgAddAuthenticator
`sender`: [string]
`authenticator_type`: [string]
`data`: [bytes]
[string]: /types/string
[bytes]: /types/bytes
## MsgAddAuthenticatorResponse
*No fields.*
## MsgCreateAsset
`authority`: [string]
`asset`: [Asset]
[string]: /types/string
[Asset]: /types/asset
## MsgCreateAssetResponse
*No fields.*
## MsgCreateClobPair
`authority`: [string]
`clob_pair`: [ClobPair]
[string]: /types/string
[ClobPair]: /types/clob_pair
## MsgCreateClobPairResponse
*No fields.*
## MsgCreateOracleMarket
`authority`: [string]
`params`: [MarketParam]
[string]: /types/string
[MarketParam]: /types/market_param
## MsgCreateOracleMarketResponse
*No fields.*
## MsgCreatePerpetual
`authority`: [string]
`params`: [PerpetualParams]
[string]: /types/string
[PerpetualParams]: /types/perpetual_params
## MsgCreatePerpetualResponse
*No fields.*
## MsgCreateTransfer
*No fields.*
## MsgDelayMessage
`authority`: [string]
`msg`: [Any]
`delay_blocks`: [u32]
[string]: /types/string
[Any]: /types/any
[u32]: /types/u32
## MsgDelayMessageResponse
`id`: [u64]
[u64]: /types/u64
## MsgDeleteVestEntry
`authority`: [string]
`vester_account`: [string]
[string]: /types/string
## MsgDeleteVestEntryResponse
*No fields.*
## MsgDepositToMegavault
`subaccount_id`: [SubaccountId]
`quote_quantums`: [bytes]
[SubaccountId]: /types/subaccount_id
[bytes]: /types/bytes
## MsgDepositToMegavaultResponse
`minted_shares`: [NumShares]
[NumShares]: /types/num_shares
## MsgDepositToSubaccount
`sender`: [string]
`recipient`: [SubaccountId]
`asset_id`: [u32]
`quantums`: [u64]
[string]: /types/string
[SubaccountId]: /types/subaccount_id
[u32]: /types/u32
[u64]: /types/u64
## MsgRegisterAffiliate
`referee`: [string]
`affiliate`: [string]
[string]: /types/string
## MsgRegisterAffiliateResponse
*No fields.*
## MsgSendFromModuleToAccount
`authority`: [string]
`sender_module_name`: [string]
`recipient`: [string]
`coin`: [Coin]
[string]: /types/string
[Coin]: /types/coin
## MsgSetLimitParams
`authority`: [string]
`limit_params`: [LimitParams]
[string]: /types/string
[LimitParams]: /types/limit_params
## MsgSetLimitParamsResponse
*No fields.*
## MsgSetMarketMapperRevenueShare
`authority`: [string]
`params`: [MarketMapperRevenueShareParams]
[string]: /types/string
[MarketMapperRevenueShareParams]: /types/market_mapper_revenue_share_params
## MsgSetMarketMapperRevenueShareResponse
*No fields.*
## MsgSetMarketsHardCap
`authority`: [string]
`hard_cap_for_markets`: [u32]
[string]: /types/string
[u32]: /types/u32
## MsgSetMarketsHardCapResponse
*No fields.*
## MsgSlashValidator
`authority`: [string]
`validator_address`: [string]
`infraction_height`: [u32]
`tokens_at_infraction_height`: [bytes]
`slash_factor`: [string]
[string]: /types/string
[u32]: /types/u32
[bytes]: /types/bytes
## MsgSlashValidatorResponse
*No fields.*
## MsgTransfer
`sender`: [SubaccountId]
`recipient`: [SubaccountId]
`asset_id`: [u32]
`amount`: [u64]
[SubaccountId]: /types/subaccount_id
[u32]: /types/u32
[u64]: /types/u64
## MsgUpdateDefaultQuotingParams
`authority`: [string]
`default_quoting_params`: [QuotingParams]
[string]: /types/string
[QuotingParams]: /types/quoting_params
## MsgUpdateDefaultQuotingParamsResponse
*No fields.*
## MsgUpdateDowntimeParams
`authority`: [string]
`params`: [DowntimeParams]
[string]: /types/string
[DowntimeParams]: /types/downtime_params
## MsgUpdateDowntimeParamsResponse
*No fields.*
## MsgUpdateParams
`authority`: [string]
`params`: [Params]
[string]: /types/string
[Params]: /types/params
## MsgUpdateParamsResponse
*No fields.*
## MsgUpdatePerpetualFeeParams
`authority`: [string]
`params`: [PerpetualFeeParams]
[string]: /types/string
[PerpetualFeeParams]: /types/perpetual_fee_params
## MsgUpdatePerpetualFeeParamsResponse
*No fields.*
## MsgWithdrawFromMegavault
`subaccount_id`: [SubaccountId]
`shares`: [NumShares]
`min_quote_quantums`: [bytes]
[SubaccountId]: /types/subaccount_id
[NumShares]: /types/num_shares
[bytes]: /types/bytes
## MsgWithdrawFromMegavaultResponse
`quote_quantums`: [bytes]
[bytes]: /types/bytes
## MsgWithdrawFromSubaccount
`sender`: [SubaccountId]
`recipient`: [string]
`asset_id`: [u32]
`quantums`: [u64]
[SubaccountId]: /types/subaccount_id
[string]: /types/string
[u32]: /types/u32
[u64]: /types/u64
## Not Found
[https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4](https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4)
## NumShares
`num_shares`: [u8] ⛁
[u8]: /types/u8
## OffChainUpdateV1
*No fields.*
## OK
[https://datatracker.ietf.org/doc/html/rfc7231#section-6.3.1](https://datatracker.ietf.org/doc/html/rfc7231#section-6.3.1)
## Operation
*No fields.*
## OperatorMetadata
`name`: [string]
`description`: [string]
[string]: /types/string
## OperatorParams
`operator`: [string]
`metadata`: [OperatorMetadata]
[string]: /types/string
[OperatorMetadata]: /types/operator_metadata
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## OraclePriceMarket
`oraclePrice`: [`Price`]
`effectiveAt`: [`DateTime`]
`effectiveAtHeight`: [`Height`]
`marketId`: [`u64`]
[`Price`]: /types/price
[`DateTime`]: /types/date_time
[`Height`]: /types/height
[`u64`]: /types/u64
import Opt from '../../components/Opt';
## Order
Order represents a single order belonging to a `Subaccount` for a particular `ClobPair`.
`order_id`: [OrderId]
* The unique ID of this order
* Meant to be unique across all orders
`side`: [OrderSide]
* The direction of the order (buy or sell)
`quantums`: [u64]
* The size of this order in base quantums
* Must be a multiple of `ClobPair.StepBaseQuantums` (where `ClobPair.Id = orderId.ClobPairId`)
`subticks`: [u64]
* The price level that this order will be placed at on the orderbook, in subticks
* Must be a multiple of `ClobPair.SubticksPerTick` (where `ClobPair.Id = orderId.ClobPairId`)
`time_in_force`: [i32]
* The time in force of this order
`reduce_only`: bool
* Enforces that the order can only reduce the size of an existing position
* If a ReduceOnly order would change the side of the existing position, its size is reduced to that of the remaining size of the position
* If existing orders on the book with ReduceOnly would already close the position, the least aggressive (out-of-the-money) ReduceOnly orders are resized and canceled first
`client_metadata`: [u32]
* Set of bit flags set arbitrarily by clients and ignored by the protocol
* Used by indexer to infer information about a placed order
`condition_type`: [i32]
* The type of condition for this order
`conditional_order_trigger_subticks`: [u64]
* The price at which this order will be triggered, in subticks
* If condition\_type is CONDITION\_TYPE\_UNSPECIFIED, this value must be 0
* If this value is nonzero, condition\_type cannot be CONDITION\_TYPE\_UNSPECIFIED
* Must be a multiple of ClobPair.SubticksPerTick (where `ClobPair.Id = orderId.ClobPairId`)
`twap_parameters`: [TwapParameters]
* Configuration for a TWAP order
* Must be set for TWAP orders
* When `twap_parameters` is supplied, `OrderFlags` must be set to 128 (TWAP) on `OrderId.OrderFlags`
* Ignored for all other order types
`builder_code_parameters`: [BuilderCodeParameters]
* Metadata for the partner or builder of an order specifying the fees charged
`good_til_oneof`: [GoodTilOneof]
* Information about when the order expires
`order_router_address`: string
* Router address to share the revenue
[OrderId]: /types/order_id
[OrderSide]: /types/order_side
[i32]: /types/i32
[u32]: /types/u32
[u64]: /types/u64
[GoodTilOneof]: /types/good_til_oneof
[TwapParameters]: /types/twap_parameters
[BuilderCodeParameters]: /types/builder_code_parameters
## OrderBatch
`clob_pair_id`: [u32]
`client_ids`: [u32] ⛁
[u32]: /types/u32
## OrderBookResponseObject
`bids`: List of [OrderbookResponsePriceLevel]
`asks`: List of [OrderbookResponsePriceLevel]
[OrderBookResponsePriceLevel]: /types/order_book_response_price_level
## OrderbookResponsePriceLevel
`price`: [Price]
`size`: [Quantity]
[Price]: /types/price
[Quantity]: /types/quantity
## OrderFillState
`fill_amount`: [u64]
`prunable_block_height`: [u32]
[u64]: /types/u64
[u32]: /types/u32
## OrderFlags
`OrderFlags` is an enum represented by the following values
* `ShortTerm`
* `Conditional`
* `LongTerm`
* `TWAP`
## OrderId
A string value that uniquely identifies a specific order. Used to track and reference orders within the system.
## OrderId
`subaccount_id`: [SubaccountId]
`client_id`: [u32]
`order_flags`: [u32]
`clob_pair_id`: [u32]
[SubaccountId]: /types/subaccount_id
[u32]: /types/u32
## OrderMarketParams
`atomic_resolution`: [i32]
`clob_pair_id`: [ClobPairId]
`oracle_price`: [Price]
`quantum_conversion_exponent`: [i32]
`step_base_quantums`: [u64]
`subticks_per_ticks`: [u32]
[i32]: /types/i32
[ClobPairId]: /types/clob_pair_id
[Price]: /types/price
[u64]: /types/u64
[u32]: /types/u32
## OrderPlaceV1
`order`: [IndexerOrder]
`placement_status`: [OrderPlacementStatus]
`time_stamp`: [Timestamp]
[IndexerOrder]: /types/indexer_order
[OrderPlacementStatus]: /types/order_placement_status
[Timestamp]: /types/timestamp
## OrderRemoval
`order_id`: [OrderId]
`removal_reason`: [RemovalReason]
[OrderId]: /types/order_id
[RemovalReason]: /types/removal_reason
## OrderRemovalReason
`OrderRemovalReason` is an enum with the following values:
* `ORDER_REMOVAL_REASON_UNSPECIFIED`
* `ORDER_REMOVAL_REASON_EXPIRED`
* `ORDER_REMOVAL_REASON_USER_CANCELED`
* `ORDER_REMOVAL_REASON_UNDERCOLLATERALIZED`
* `ORDER_REMOVAL_REASON_INTERNAL_ERROR`
* `ORDER_REMOVAL_REASON_SELF_TRADE_ERROR`
* `ORDER_REMOVAL_REASON_POST_ONLY_WOULD_CROSS_MAKER_ORDER`
* `ORDER_REMOVAL_REASON_IMMEDIATE_OR_CANCEL_WOULD_REST_ON_BOOK`
* `ORDER_REMOVAL_REASON_FOK_ORDER_COULD_NOT_BE_FULLY_FULLED`
* `ORDER_REMOVAL_REASON_REDUCE_ONLY_RESIZE`
* `ORDER_REMOVAL_REASON_INDEXER_EXPIRED`
* `ORDER_REMOVAL_REASON_REPLACED`
* `ORDER_REMOVAL_REASON_FULLY_FILLED`
* `ORDER_REMOVAL_REASON_EQUITY_TIER`
* `ORDER_REMOVAL_REASON_FINAL_SETTLEMENT`
* `ORDER_REMOVAL_REASON_VIOLATES_ISOLATED_SUBACCOUNT_CONSTRAINTS`
## OrderRemoveV1
`removed_order_id`: [IndexerOrderId]
`reason`: [OrderRemovalReason]
`removal_status`: [OrderRemovalStatus]
`time_stamp`: [Timestamp]
[IndexerOrderId]: /types/indexer_order_id
[OrderRemovalReason]: /types/order_removal_reason
[OrderRemovalStatus]: /types/order_removal_status
[Timestamp]: /types/timestamp
## OrderReplaceV1
`order`: [IndexerOrder]
`time_stamp`: [Timestamp]
[IndexerOrder]: /types/indexer_order
[Timestamp]: /types/timestamp
import Opt from '../../components/Opt';
## OrderResponseObject
`client_id`: [ClientId]
`client_metadata`: [ClientMetadata]
`clob_pair_id`: [ClobPairId]
`created_at_height`: [Height]
`good_til_block`: [Height]
`good_til_block_time`: [DateTime in UTC]
`id`: [OrderId]
`order_flags`: [OrderFlags]
`post_only`: `bool`
`price`: [Price]
`reduce_only`: `bool`
`side`: [OrderSide]
`size`: [Quantity]
`status`: [ApiOrderStatus]
`subaccount_id`: [SubaccountId]
`subaccount_number`: [SubaccountNumber]
`ticker`: [Ticker]
`time_in_force`: [ApiTimeInForce]
`total_filled`: [BigDecimal]
`type`: [OrderType]
`updated_at`: [DateTime in UTC]
`updated_at_height`: [Height]
`trigger_price`: [Price]
`builder_fee`: [BigDecimal]
> **Note:** Builder fee fields will be introduced in a future version of the API (v9.0).
`fee_ppm`: [BigDecimal]
[ClientId]: /types/client_id
[ClientMetadata]: /types/client_metadata
[ClobPairId]: /types/clob_pair_id
[Height]: /types/height
[DateTime in UTC]: /types/date_time
[OrderId]: /types/order_id
[OrderFlags]: /types/order_flags
[Price]: /types/price
[OrderSide]: /types/order_side
[Quantity]: /types/quantity
[ApiOrderStatus]: /types/api_order_status
[SubaccountId]: /types/subaccount_id
[SubaccountNumber]: /types/subaccount_number
[Ticker]: /types/ticker
[ApiTimeInForce]: /types/api_time_in_force
[BigDecimal]: /types/big_decimal
[OrderType]: /types/order_type
## OrderRouterRevShare
`address`: string
`share_ppm`: int
## OrderSide
An enum representing the direction of an order. Possible string values are:
* `BUY` – Indicates a purchase order.
* `SELL` – Indicates a sell order.
## OrderStatus
`OrderStatus` is an enum consists of the following values
* `Open`
* `Filled`
* `Canceled`
* `BestEffortCanceled`
* `Untriggered`
* `BestEffortOpened`
* `Pending`
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## OrderSubaccountMessage
Update sub-message received on the `v4_subaccounts` channel.
`id`: string
`subaccountId`: [`SubaccountId`]
`clientId`: [`ClientId`]
`clobPairId`: [`ClobPairId`]
`side`: [`OrderSide`]
`size`: [`Quantity`]
`ticker`: [`Ticker`]
`price`: [`Price`]
`type`: [`OrderType`]
`timeInForce`: [`ApiTimeInForce`]
`postOnly`: bool
`reduceOnly`: bool
`status`: [`ApiOrderStatus`]
`orderFlags`: [`OrderFlags`]
`totalFilled`: [`BigDecimal`]
`totalOptimisticFilled`: [`BigDecimal`]
`goodTilBlock`: [`Height`]
`goodTilBlockTime`: [`DateTime`]
`triggerPrice`: [`Price`]
`updatedAt`: [`DateTime`]
`updatedAtHeight`: [`Height`]
`removalReason`: string
`createdAtHeight`: [`Height`]
`clientMetadata`: [`ClientMetadata`]
[`SubaccountId`]: /types/subaccount_id
[`ClientId`]: /types/client_id
[`OrderSide`]: /types/order_side
[`ClobPairId`]: /types/clob_pair_id
[`OrderType`]: /types/order_type
[`Ticker`]: /types/ticker
[`OrderFlags`]: /types/order_flags
[`ApiTimeInForce`]: /types/api_time_in_force
[`ApiOrderStatus`]: /types/api_order_status
[`BigDecimal`]: /types/big_decimal
[`Height`]: /types/height
[`DateTime`]: /types/date_time
[`Price`]: /types/price
[`ClientMetadata`]: /types/client_metadata
[`Quantity`]: /types/quantity
## OrderType
An enum specifying the type of order to be placed or processed. Possible string values include:
* `LIMIT` – Executes at a specified price or better.
* `MARKET` – Executes immediately at the best available price.
* `STOP_LIMIT` – Becomes a limit order once a stop price is reached.
* `STOP_MARKET` – Becomes a market order once a stop price is reached.
* `TRAILING_STOP` – A dynamic stop order that adjusts based on market movement.
* `TAKE_PROFIT` – A limit order to secure profits once a target price is reached.
* `TAKE_PROFIT_MARKET` – A market order to secure profits once a target price is reached.
* `HARD_TRADE` – A special internal trade type, typically used in matching engines.
* `FAILED_HARD_TRADE` – Represents a failed execution of a `HardTrade`.
* `TRANSFER_PLACEHOLDER` – A placeholder type used internally for transfers.
## OrderUpdateV1
`order_id`: [IndexerOrderId]
`total_filled_quantums`: [u64]
[IndexerOrderId]: /types/indexer_order_id
[u64]: /types/u64
## OrderbookMessage
`contents`: [string]
`clob_pair_id`: [string]
`version`: [string]
[string]: /types/string
## OrdersFilledDuringLatestBlock
`order_ids`: [OrderId][]
[OrderId]: /types/order_id
import Array from '../../components/Array';
## OrdersInitialMessage
Initial message received on the `v4_orderbook` channel.
`bids`: [`OrderbookResponsePriceLevel`]
`asks`: [`OrderbookResponsePriceLevel`]
[`OrderbookResponsePriceLevel`]: /types/order_book_response_price_level
import Array from '../../components/Array';
import Opt from '../../components/Opt';
## OrdersInitialMessage
Update message received on the `v4_orderbook` channel.
`bids`: [`OrderbookResponsePriceLevel`]
`asks`: [`OrderbookResponsePriceLevel`]
[`OrderbookResponsePriceLevel`]: /types/order_book_response_price_level
## OwnerShare
`owner`: [string]
`shares`: [NumShares]
[string]: /types/string
[NumShares]: /types/num_shares
## OwnerShareUnlocks
`owner_address`: [string]
`share_unlocks`: [ShareUnlock][]
[string]: /types/string
[ShareUnlock]: /types/share_unlock
## Params
`layers`: [u32]
`spread_min_ppm`: [u32]
`spread_buffer_ppm`: [u32]
`skew_factor_ppm`: [u32]
`order_size_pct_ppm`: [u32]
`order_expiration_seconds`: [u32]
`activation_threshold_quote_quantums`: [bytes]
[u32]: /types/u32
[bytes]: /types/bytes
## ParentSubaccountNumber
The value is represented by [u32].
[u32]: /types/u32
## ParentSubaccountResponseObject
`address`: [Address]
`parent_subaccount`: [SubaccountNumber]
`equity`: [BigDecimal]
`free_collateral`: [BigDecimal]
`margin_enabled`: bool
`child_subaccounts`: [SubaccountResponseObject] ⛁
[Address]: /types/address
[SubaccountNumber]: /types/subaccount_number
[BigDecimal]: /types/big_decimal
[SubaccountResponseObject]: /types/subaccount_response_object
## ParentSubaccountTransferResponseObject
`id`: [TransferId]
`sender`: [AccountWithParentSubaccountNumber]
`recipient`: [AccountWithParentSubaccountNumber]
`size`: [BigDecimal]
`created_at`: [DateTime]
`created_at_height`: [Height]
`symbol`: [Symbol]
`type`: [TransferType]
`transaction_hash`: [TxHash]
[TransferId]: /types/transfer_id
[AccountWithParentSubaccountNumber]: /types/account_with_parent_subaccount_number
[BigDecimal]: /types/big_decimal
[DateTime]: /types/date_time
[Height]: /types/height
[Symbol]: /types/symbol
[TransferType]: /types/transfer_type
[TxHash]: /types/tx_hash
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## ParentSubaccountsInitialMessage
Initial message received on the `v4_parent_subaccounts` channel.
`subaccount`: [`ParentSubaccountResponseObject`]
`orders`: [`OrderResponseObject`]
`block_height`: [`Height`]
[`ParentSubaccountResponseObject`]: /types/parent_subaccount_response_object
[`OrderResponseObject`]: /types/order_response_object
[`Height`]: /types/height
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## ParentSubaccountsUpdateMessage
Update message received on the `v4_parent_subaccounts` channel.
`perpetualPositions`: [`PerpetualPositionSubaccountMessage`]
`assetPositions`: [`AssetPositionSubaccountMessage`]
`orders`: [`OrderSubaccountMessage`]
`fills`: [`FillSubaccountMessage`]
`transfers`: [`TransferSubaccountMessage`]
`tradingReward`: [`TradingRewardSubaccountMessage`]
`blockHeight`: [`Height`]
[`PerpetualPositionSubaccountMessage`]: /types/perpetual_position_subaccount_message
[`AssetPositionSubaccountMessage`]: /types/asset_position_subaccount_message
[`OrderSubaccountMessage`]: /types/order_subaccount_message
[`FillSubaccountMessage`]: /types/fill_subaccount_message
[`TransferSubaccountMessage`]: /types/transfer_subaccount_message
[`TradingRewardSubaccountMessage`]: /types/trading_reward_subaccount_message
[`Height`]: /types/height
## PartSetHeader
`total`: [u32]
`hash`: [u8] ⛁
[u8]: /types/u8
[u32]: /types/u32
## PendingFinalityEvent
`event`: [BridgeEvent]
`acknowledged_at_block`: [i64]
[BridgeEvent]: /types/bridge_event
[i64]: /types/i64
## PendingSendPacket
`channel_id`: [string]
`sequence`: [u64]
[string]: /types/string
[u64]: /types/u64
## PerMarketFeeDiscountParams
`clob_pair_id`: [u32]
`start_time`: [Timestamp]
`end_time`: [Timestamp]
`charge_ppm`: [u32]
[u32]: /types/u32
[Timestamp]: /types/timestamp
## Perpetual
`params`: [PerpetualParams]
`funding_index`: [u8] ⛁
`open_interest`: [u8] ⛁
[PerpetualParams]: /types/perpetual_params
[u8]: /types/u8
## PerpetualClobMetadata
`perpetual_id`: [u32]
[u32]: /types/u32
## PerpetualFeeParams
`tiers`: [PerpetualFeeTier][]
[PerpetualFeeTier]: /types/perpetual_fee_tier
## PerpetualFeeTier
`name`: string
`absolute_volume_requirement`: [u64]
`total_volume_share_requirement_ppm`: [u32]
`maker_volume_share_requirement_ppm`: [u32]
`maker_fee_ppm`: [i32]
`taker_fee_ppm`: [i32]
[u64]: /types/u64
[u32]: /types/u32
[i32]: /types/i32
## PerpetualLeverageEntry
`perpetual_id`: [u32]
`custom_imf_ppm`: [u32]
[u32]: /types/u32
## PerpetualLiquidationInfo
`subaccount_id`: [SubaccountId]
`perpetual_id`: [u32]
[SubaccountId]: /types/subaccount_id
[u32]: /types/u32
import Opt from '../../components/Opt';
## PerpetualMarket
`atomicResolution`: [i32]
`baseOpenInterest`: [BigDecimal]
`clobPairId`: [ClobPairId]
`defaultFundingRate1H`: [BigDecimal]
`initialMarginFraction`: [BigDecimal]
`maintenanceMarginFraction`: [BigDecimal]
`marketType`: [PerpetualMarketType]
`nextFundingRate`: [BigDecimal]
`openInterest`: [BigDecimal]
`openInterestLowerCap`: [BigDecimal]
`openInterestUpperCap`: [BigDecimal]
`oraclePrice`: [Price]
`priceChange24H`: [BigDecimal]
`quantumConversionExponent`: [i32]
`status`: [PerpetualMarketStatus]
`stepBaseQuantums`: [u64]
`stepSize`: [BigDecimal]
`subticksPerTick`: [u32]
`tickSize`: [BigDecimal]
`ticker`: [Ticker]
`trades24H`: [u64]
`volume24H`: [Quantity]
`defaultFundingRate1H`: [BigDecimal]
[i32]: /types/i32
[u64]: /types/u64
[u32]: /types/u32
[Ticker]: /types/ticker
[BigDecimal]: /types/big_decimal
[ClobPairId]: /types/clob_pair_id
[PerpetualMarketType]: /types/perpetual_market_type
[Price]: /types/price
[PerpetualMarketStatus]: /types/perpetual_market_status
[Quantity]: /types/quantity
## PerpetualMarketMap
Key-value pair of [Ticker] and [PerpetualMarket] where [Ticker] is the `key`.
[Ticker]: /types/ticker
[PerpetualMarket]: /types/perpetual_market
## PerpetualMarketStatus
`PerpetualMarketStatus` is an enum represented by following values
* `Active`
* `Paused`
* `CancelOnly`
* `PostOnly`
* `Initializing`
* `FinalSettlement`
## PerpetualMarketType
`PerpetualMarketType` is an enum consists of the following values
* `Cross`
* `Isolated`
## PerpetualParams
`id`: [u32]
`ticker`: string
`market_id`: [u32]
`atomic_resolution`: [i32]
`default_funding_ppm`: [i32]
`liquidity_tier`: [u32]
`market_type`: [i32]
[u32]: /types/u32
[i32]: /types/i32
## PerpetualPosition
`perpetual_id`: [u32]
`quantums`: [u8] ⛁
`funding_index`: [u8] ⛁
`quote_balance`: [u8] ⛁
[u32]: /types/u32
[u8]: /types/u8
## PerpetualPositionResponseObject
`market`: [Ticker]
`status`: [PerpetualPositionStatus]
`side`: [PositionSide]
`size`: [Quantity]
`maxSize`: [Quantity]
`entryPrice`: [Price]
`exitPrice`: [Price]
`realizedPnl`: [BigDecimal]
`createdAt`: [DateTime in UTC]
`createdAtHeight`: [Height]
`sumOpen`: [BigDecimal]
`sumClose`: [BigDecimal]
`netFunding`: [BigDecimal]
`unrealizedPnl`: [BigDecimal]
`closedAt`: [DateTime in UTC]
`subaccount_number`: [SubaccountNumber]
[Ticker]: /types/ticker
[PerpetualPositionStatus]: /types/perpetual_position_status
[PositionSide]: /types/position_side
[Quantity]: /types/quantity
[Price]: /types/price
[DateTime in UTC]: /types/date_time
[Height]: /types/height
[SubaccountNumber]: /types/subaccount_number
[BigDecimal]: /types/big_decimal
## PerpetualPositionStatus
A `PerpetualPositionStatus` is an enum having one of the following string in case insensitive manner
* `OPEN`
* `CLOSED`
* `LIQUIDATED`
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## PerpetualPositionSubaccountMessage
Update sub-message received on the `v4_subaccounts` channel.
`address`: [`Address`]
`subaccountNumber`: [`SubaccountNumber`]
`positionId`: string
`market`: [`Ticker`]
`side`: [`PositionSide`]
`status`: [`PerpetualPositionStatus`]
`size`: [`Quantity`]
`maxSize`: [`Quantity`]
`netFunding`: [`BigDecimal`]
`entryPrice`: [`Price`]
`exitPrice`: [`Price`]
`sumOpen`: [`BigDecimal`]
`sumClose`: [`BigDecimal`]
`realizedPnl`: [`BigDecimal`]
`unrealizedPnl`: [`BigDecimal`]
[`Address`]: /types/address
[`SubaccountNumber`]: /types/subaccount_number
[`Ticker`]: /types/ticker
[`Quantity`]: /types/quantity
[`BigDecimal`]: /types/big_decimal
[`Price`]: /types/price
[`PositionSide`]: /types/position_side
[`PerpetualPositionStatus`]: /types/perpetual_position_status
## PerpetualPositionsMap
Key: [Ticker]
Value: [PerpetualPositionResponseObject]
[Ticker]: /types/ticker
[PerpetualPositionResponseObject]: /types/perpetual_position_response_object
## PnlTickId
`PnlTickId` is represented by `string`.
## PnlTickInterval
`PnlTickInterval` is an enum consists of the following values
* `hour`
* `day`
## PnlTicksResponseObject
`blockHeight`: [Height]
`blockTime`: [DateTime in UTC]
`createdAt`: [DateTime in UTC]
`equity`: [BigDecimal]
`totalPnl`: [BigDecimal]
`netTransfer`: [BigDecimal]
[Height]: /types/height
[BigDecimal]: /types/big_decimal
[DateTime in UTC]: /types/date_time
## PositionBlockLimits
`min_position_notional_liquidated`: [u64]
`max_position_portion_liquidated_ppm`: [u32]
[u64]: /types/u64
[u32]: /types/u32
## PositionSide
An enum representing the direction of a position, with possible case-insensitive string values:
* `LONG`
* `SHORT`
## PositionStatus
A PositionStatus is an enum having one of the following string in case insensitive manner
* `OPEN`
* `CLOSED`
* `LIQUIDATED`
## PotentiallyPrunableOrders
`order_ids`: [OrderId][]
[OrderId]: /types/order_id
## PremiumStore
`all_market_premiums`: [MarketPremiums][]
`num_premiums`: [u32]
[MarketPremiums]: /types/market_premiums
[u32]: /types/u32
## Price
A [BigDecimal] value that is representing the execution price of a trade. Uses high-precision decimal format to ensure accuracy in financial calculations.
[BigDecimal]: /types/big_decimal
## ProcessProposerMatchesEvents
`placed_long_term_order_ids`: [OrderId][]
`expired_stateful_order_ids`: [OrderId][]
`order_ids_filled_in_last_block`: [OrderId][]
`placed_stateful_cancellation_order_ids`: [OrderId][]
`removed_stateful_order_ids`: [OrderId][]
`placed_conditional_order_ids`: [OrderId][]
`block_height`: [u32]
[OrderId]: /types/order_id
[u32]: /types/u32
## ProposeParams
`max_bridges_per_block`: [u32]
`propose_delay_duration`: [Duration]
`skip_rate_ppm`: [u32]
`skip_if_block_delayed_by_duration`: [Duration]
[u32]: /types/u32
[Duration]: /types/duration
## Quantity
A numeric value representing the amount of an asset.
It must be a positive [BigDecimal] number, typically expressed as a string to preserve precision.
[BigDecimal]: /types/big_decimal
## QueryAllSubaccountRequest
`pagination`: [PageRequest]
[PageRequest]: /types/page_request
## QueryAssetRequest
*No fields.*
## QueryCollateralPoolAddressRequest
*No fields.*
## QueryEventParamsRequest
*No fields.*
## QueryGetClobPairRequest
*No fields.*
## QueryGetEpochInfoRequest
*No fields.*
## QueryGetSubaccountRequest
`owner`: [string]
`number`: [u32]
[string]: /types/string
[u32]: /types/u32
## QueryGetWithdrawalAndTransfersBlockedInfoRequest
`perpetual_id`: [u32]
[u32]: /types/u32
## QueryGetWithdrawalAndTransfersBlockedInfoResponse
`negative_tnc_subaccount_seen_at_block`: [u32]
`chain_outage_seen_at_block`: [u32]
`withdrawals_and_transfers_unblocked_at_block`: [u32]
[u32]: /types/u32
## QueryMarketMapperRevenueShareParams
*No fields.*
## QueryMarketPriceRequest
*No fields.*
## QueryMarketsHardCap
*No fields.*
## QueryNextDelayedMessageIdRequest
*No fields.*
## QueryParamsRequest
*No fields.*
## QueryPerpetualFeeParamsRequest
*No fields.*
## QueryPerpetualRequest
*No fields.*
## QuerySubaccountAllResponse
`subaccount`: [Subaccount][]
`pagination`: [PageResponse]
[Subaccount]: /types/subaccount
[PageResponse]: /types/page_response
## QuerySubaccountResponse
`subaccount`: [Subaccount]
[Subaccount]: /types/subaccount
## QuerySynchronyParamsRequest
*No fields.*
## QueryVestEntryRequest
*No fields.*
## QuotingParams
`layers`: [u32]
`spread_min_ppm`: [u32]
`spread_buffer_ppm`: [u32]
`skew_factor_ppm`: [u32]
`order_size_pct_ppm`: [u32]
`order_expiration_seconds`: [u32]
`activation_threshold_quote_quantums`: [bytes]
[u32]: /types/u32
[bytes]: /types/bytes
## RecipientConfig
`address`: string
`share_ppm`: int
## RedisOrder
`id`: [string]
`order`: [IndexerOrder]
`ticker`: [string]
`ticker_type`: [TickerType]
`price`: [string]
`size`: [string]
[string]: /types/string
[IndexerOrder]: /types/indexer_order
[TickerType]: /types/ticker_type
## ReferredByRequest
`address`: [string]
[string]: /types/string
## ReferredByResponse
`affiliate_address`: [string]
[string]: /types/string
## ReviewMessage
`contents`: [string]
`id`: [string]
`version`: [string]
[string]: /types/string
## RewardShare
`address`: [string]
`weight`: [bytes]
[string]: /types/string
[bytes]: /types/bytes
## RewardParams
`treasury_account`: string
`denom`: string
`denom_exponent`: [i32]
`market_id`: [u32]
`fee_multiplier_ppm`: [u32]
[i32]: /types/i32
[u32]: /types/u32
## SafetyParams
`is_disabled`: [bool]
`delay_blocks`: [u32]
[bool]: /types/bool
[u32]: /types/u32
## ShareUnlock
`shares`: [NumShares]
`unlock_block_height`: [u32]
[NumShares]: /types/num_shares
[u32]: /types/u32
## SkippedBridgeEvent
`id`: [u32]
`eth_chain_id`: [u64]
`eth_block_height`: [u64]
[u32]: /types/u32
[u64]: /types/u64
## SparklineResponseObject
`SparklineResponseObject` is a key-value pair of [Ticker] and List of [BigDecimal]
[Ticker]: /types/ticker
[BigDecimal]: /types/big_decimal
## SparklineTimePeriod
`SparklineTimePeriod` is an enum consists of the following values
* `OneDay`
* `SevenDays`
## SpotClobMetadata
`base_asset_id`: [u32]
`quote_asset_id`: [u32]
[u32]: /types/u32
## StagedFinalizeBlockEvent
*No fields.*
## StakingLevel
`min_staked_base_tokens`: [bytes]
`fee_discount_ppm`: [u32]
[bytes]: /types/bytes
[u32]: /types/u32
## StakingTier
`fee_tier_name`: [string]
`levels`: [StakingLevel][]
[string]: /types/string
[StakingLevel]: /types/staking_level
## StatefulOrderTimeSliceValue
`order_ids`: [OrderId][]
[OrderId]: /types/order_id
## StatsMetadata
`trailing_epoch`: [u32]
[u32]: /types/u32
## StreamLiquidationOrder
`liquidation_info`: [PerpetualLiquidationInfo]
`clob_pair_id`: [u32]
`is_buy`: [bool]
`quantums`: [u64]
`subticks`: [u64]
[PerpetualLiquidationInfo]: /types/perpetual_liquidation_info
[u32]: /types/u32
[bool]: /types/bool
[u64]: /types/u64
## StreamPriceUpdate
`market_id`: [u32]
`price`: [MarketPrice]
`snapshot`: [bool]
[u32]: /types/u32
[MarketPrice]: /types/market_price
[bool]: /types/bool
## StreamSubaccountUpdate
`subaccount_id`: [SubaccountId]
`updated_perpetual_positions`: [SubaccountPerpetualPosition][]
`updated_asset_positions`: [SubaccountAssetPosition][]
`snapshot`: [bool]
[SubaccountId]: /types/subaccount_id
[SubaccountPerpetualPosition]: /types/subaccount_perpetual_position
[SubaccountAssetPosition]: /types/subaccount_asset_position
[bool]: /types/bool
## String
String
## Subaccount
`address`: [Address]
`number`: [SubaccountNumber]
[Address]: /types/address
[SubaccountNumber]: /types/subaccount_number
## SubaccountAssetPosition
`asset_id`: [u32]
`quantums`: [u64]
[u32]: /types/u32
[u64]: /types/u64
## SubaccountBlockLimits
`max_notional_liquidated`: [u64]
`max_quantums_insurance_lost`: [u64]
[u64]: /types/u64
## SubaccountId
`SubaccountId` is represented by `string`.
## SubaccountInfo
`id`: [SubaccountId]
`asset_position`: [AssetPosition] ⛁
`perpetual_positions`: [PerpetualPosition] ⛁
`margin_enabled`: bool
[SubaccountId]: /types/subaccount_id
[AssetPosition]: /types/asset_position
[PerpetualPosition]: /types/perpetual_position
## SubaccountLiquidationInfo
`perpetuals_liquidated`: [u32][]
`notional_liquidated`: [u64]
`quantums_insurance_lost`: [u64]
[u32]: /types/u32
[u64]: /types/u64
## SubaccountMessage
`block_height`: [string]
`transaction_index`: [i32]
`event_index`: [u32]
`contents`: [string]
`subaccount_id`: [IndexerSubaccountId]
`version`: [string]
[string]: /types/string
[i32]: /types/i32
[u32]: /types/u32
[IndexerSubaccountId]: /types/indexer_subaccount_id
## SubaccountNumber
A [u32] integer used to identify a specific subaccount within a main account.
Enables organizing and managing multiple positions or strategies under a single user account.
[u32]: /types/u32
## SubaccountOpenPositionInfo
`perpetual_id`: [u32]
[u32]: /types/u32
## SubaccountPerpetualPosition
`perpetual_id`: [u32]
`quantums`: [i64]
[u32]: /types/u32
[i64]: /types/i64
## SubaccountResponseObject
`assetPositions`: [AssetPositionsMap]
`address`: [Address]
`subaccountNumber`: [SubaccountNumber]
`equity`: [BigDecimal]
`freeCollateral`: [BigDecimal]
`latestProcessedBlockHeight`: [Height]
`marginEnabled`: bool
`openPerpetualPositions`: [PerpetualPositionsMap]
`updatedAtHeight`: [Height]
[Address]: /types/address
[SubaccountNumber]: /types/subaccount_number
[BigDecimal]: /types/big_decimal
[AssetPositionsMap]: /types/asset_positions_map
[PerpetualPositionsMap]: /types/perpetual_positions_map
[Height]: /types/height
import Array from '../../components/Array';
## SubaccountsInitialMessage
Initial message received on the `v4_subaccounts` channel.
`subaccount`: [`SubaccountMessageObject`]
`orders`: [`OrderMessageObject`]
`blockHeight`: [`Height`]
[`SubaccountMessageObject`]: /types/subaccount_response_object
[`OrderMessageObject`]: /types/order_response_object
[`Height`]: /types/height
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## SubaccountsUpdateMessage
Update message received on the `v4_subaccounts` channel.
`perpetualPositions`: [`PerpetualPositionSubaccountMessage`]
`assetPositions`: [`AssetPositionSubaccountMessage`]
`orders`: [`OrderSubaccountMessage`]
`fills`: [`FillSubaccountMessage`]
`transfers`: [`TransferSubaccountMessage`]
`tradingReward`: [`TradingRewardSubaccountMessage`]
`blockHeight`: [`Height`]
[`PerpetualPositionSubaccountMessage`]: /types/perpetual_position_subaccount_message
[`AssetPositionSubaccountMessage`]: /types/asset_position_subaccount_message
[`OrderSubaccountMessage`]: /types/order_subaccount_message
[`FillSubaccountMessage`]: /types/fill_subaccount_message
[`TransferSubaccountMessage`]: /types/transfer_subaccount_message
[`TradingRewardSubaccountMessage`]: /types/trading_reward_subaccount_message
[`Height`]: /types/height
## Symbol
A string identifier representing a trading pair or asset (e.g., "BTC-USD").
It is used to specify markets or instruments and must be provided as a string.
:::code-group
```rust [Rust]
String
```
```python [Python]
str
```
```typescript [TypeScript]
string
```
:::
## SynchronyParams
`next_block_delay`: [Duration]
[Duration]: /types/duration
## Ticker
A Ticker is a pair of currency like "BTC-USD", represented by a string.
:::code-group
```rust [Rust]
String
```
```python [Python]
str
```
```typescript [TypeScript]
string
```
:::
## Time in Force
An enum which indicates how long an order will remain active before it is executed or expires.
* `UNSPECIFIED`: represents the default behavior where an order will first match with existing orders on the book, and any remaining size will be added to the book as a maker order;
* `IOC` enforces that an order only be matched with maker orders on the book. If the order has remaining size after matching with existing orders on the book, the remaining size is not placed on the book;
* `POST_ONLY`: enforces that an order only be placed on the book as a maker order. Note this means that validators will cancel any newly-placed post only orders that would cross with other maker orders;
* `FILL_OR_KILL`: enforces that an order will either be filled completely and immediately by maker orders on the book or canceled if the entire amount can‘t be matched.
:::warning
The `FILL_OR_KILL` option is deprecated and will be removed in a future version.
:::
## Timestamp
`seconds`: [i64]
`nanos`: [i32]
[i64]: /types/i64
[i32]: /types/i32
## TimestampNonceDetails
`timestamp_nonces`: [u64][]
`max_ejected_nonce`: [u64]
[u64]: /types/u64
## TokenMapping
`eth_token_address`: [string]
`asset_id`: [u32]
`instant_bridge_max_amount`: [string]
[string]: /types/string
[u32]: /types/u32
## TokenReserve
`asset_id`: [u32]
`chain_id`: [u64]
`reserved_amount`: [string]
`token_address`: [string]
[u32]: /types/u32
[u64]: /types/u64
[string]: /types/string
## Tokenized
`denom`: [Denom]
`coin`: [Coin]
[Denom]: /types/denom
[Coin]: /types/coin
## TradeId
`TradeId` is represented by `string`
## TradeMessage
`block_height`: [string]
`contents`: [string]
`clob_pair_id`: [string]
`version`: [string]
[string]: /types/string
## TradeResponseObject
`id`: [TradeId]
`created_at_height`: [Height]
`created_at`: [DateTime in UTC]
`side`: [OrderSide]
`price`: [Price]
`size`: [Quantity]
`trade_type`: [TradeType]
[TradeId]: /types/trade_id
[Height]: /types/height
[DateTime in UTC]: /types/date_time
[OrderSide]: /types/order_type
[Price]: /types/price
[Quantity]: /types/quantity
[TradeType]: /types/trade_type
## TradeType
`TradeType` is an enum represented by the following values
* `Limit`
* `Liquidated`
* `Deleveraged`
## TradeUpdate
`id`: [`TradeId`]
`createdAt`: [`DateTime`]
`side`: [`OrderSide`]
`price`: [`Price`]
`size`: [`Quantity`]
`type`: [`TradeType`]
[`TradeId`]: /types/trade_id
[`DateTime`]: /types/date_time
[`OrderSide`]: /types/order_side
[`TradeType`]: /types/trade_type
[`Price`]: /types/price
[`Quantity`]: /types/quantity
import Array from '../../components/Array';
## TradesInitialMessage
`trades`: [`TradeResponseObject`]
[`TradeResponseObject`]: /types/trade_response_object
import Array from '../../components/Array';
## TradesUpdateMessage
Update message received on the `v4_trades` channel.
`trades`: [`TradeUpdate`]
[`TradeUpdate`]: /types/trade_update
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## TradingPerpetualMarket
`atomicResolution`: [`i32`]
`baseAsset`: string
`base_openInterest`: [`BigDecimal`]
`basePositionSize`: [`Quantity`]
`clobPairId`: [`ClobPairId`]
`id`: string
`marketId`: [`u64`]
`incrementalPositionSize`: [`Quantity`]
`initialMarginFraction`: [`BigDecimal`]
`maintenanceMarginFraction`: [`BigDecimal`]
`maxPositionSize`: [`Quantity`]
`openInterest`: [`BigDecimal`]
`quantum_conversion_exponent`: [`i32`]
`quoteAsset`: string
`status`: [`PerpetualMarketStatus`]
`stepBaseQuantums`: [`i32`]
`subticksPerTick`: [`i32`]
`ticker`: [`Ticker`]
`priceChange24H`: [`BigDecimal`]
`trades24H`: [`u64`]
`volume24H`: [`Quantity`]
`nextFundingRate`: [`BigDecimal`]
[`ClobPairId`]: /types/clob_pair_id
[`Quantity`]: /types/quantity
[`BigDecimal`]: /types/big_decimal
[`i32`]: /types/i32
[`u64`]: /types/u64
[`Ticker`]: /types/ticker
[`PerpetualMarketStatus`]: /types/perpetual_market_status
## TradingRewardAggregationPeriod
A `TradingRewardAggregationPeriod` is an enum having one of the following string
* `DAILY`
* `WEEKLY`
* `MONTHLY`
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## TradingRewardSubaccountMessage
Update sub-message received on the `v4_subaccounts` channel.
`tradingReward`: [`BigDecimal`]
`createdAt`: [`DateTime`]
`createdAtHeight`: [`Height`]
[`BigDecimal`]: /types/big_decimal
[`DateTime`]: /types/date_time
[`Height`]: /types/height
## TransactionOrdering
`block_height`: [u32]
`transaction_index`: [u32]
[u32]: /types/u32
## Transfer
`sender`: [SubaccountId]
`recipient`: [SubaccountId]
`asset_id`: [u32]
`amount`: [u64]
`memo`: [string]
[SubaccountId]: /types/subaccount_id
[u32]: /types/u32
[u64]: /types/u64
[string]: /types/string
## TransferResponseObject
`id`: string
`created_at`: [DateTime in UTC]
`created_at_height`: [u32]
`sender`: [Account]
`recipient`: [Account]
`size`: [BigDecimal]
`symbol`: [Symbol]
`transaction_hash`: string
`transfer_type`: [TransferType]
[DateTime in UTC]: /types/date_time
[u32]: /types/u32
[Account]: /types/account
[BigDecimal]: /types/big_decimal
[Symbol]: /types/symbol
[TransferType]: /types/transfer_type
import Opt from '../../components/Opt';
import Array from '../../components/Array';
## TransferSubaccountMessageContents
Update sub-message received on the `v4_subaccounts` channel.
`sender`: [`Account`]
`recipient`: [`Account`]
`symbol`: [`Symbol`]
`size`: [`Quantity`]
`type`: [`TransferType`]
`transaction_hash`: string
`created_at`: [`DateTime`]
`created_at_height`: [`Height`]
[`Account`]: /types/account
[`Symbol`]: /types/symbol
[`Quantity`]: /types/quantity
[`TransferType`]: /types/transfer_type
[`DateTime`]: /types/date_time
[`Height`]: /types/height
## TransferType
TransferType is an enum having one of the following value
* `TransferIn`
* `TransferOut`
* `Deposit`
* `Withdrawal`
## TwapOrderPlacement
`order`: [Order]
`remaining_legs`: [u32]
`remaining_quantums`: [u64]
[Order]: /types/order
[u32]: /types/u32
[u64]: /types/u64
## TwapParameters
When using TWAP parameters, the `OrderFlags` value must be set to 128 (TWAP) on `OrderId.OrderFlags` in the order placement message.
`duration`: [`u32`]
* Duration of the TWAP order execution in seconds
* Must be between 300 (5 minutes) and 86,400 (24 hours)
`interval`: [`u32`]
* Interval in seconds for each suborder execution
* Must be a whole number and a factor of the duration
* Must be between 30 seconds and 3,600 (1 hour)
`price_tolerance`: [`u32`]
* Price tolerance in parts per million (ppm) for each suborder
* Applied to the oracle price when each suborder is triggered
* Must be between 0 and 1,000,000
[`u32`]: /types/u32
## Tx
`Tx` is represented by binary/byte data.
## TxHash
`TxHash` is represented by a string.
## TxOptions
`authenticators`: [i32] ⛁
`sequence`: [i32]
`account_number`: [i32]
[i32]: /types/i32
## u32
An unsigned 32-bit integer type, representing whole numbers in the range from **0** to **4,294,967,295** (2³² − 1).
It cannot store negative values.
## u64
unsigned 64 bit integer
## u8
An unsigned 8-bit integer type, representing whole numbers in the range from **0** to **255** (28 − 1).
It cannot store negative values.
## UnbondingDelegation
`delegator_address`: string
`validator_address`: string
`entries`: [UnbondingDelegationEntry] ⛁
[UnbondingDelegationEntry]: /types/unbounding_delegation_entry
## UnbondingDelegationEntry
`created_height`: [i64]
`completion_time`: [Timestamp]
`initial_balance`: string
`balance`: string
`unbonding_id`: [u64]
`unbonding_on_hold_ref_count`: [i64]
[i64]: /types/i64
[u64]: /types/u64
[Timestamp]: /types/timestamp
## UnconditionalRevShareConfig
`configs`: [RecipientConfig]
[RecipientConfig]: /types/recipient_config
## UpdateMarketPricesRequest
`market_price_updates`: [MarketPriceUpdate][]
[MarketPriceUpdate]: /types/market_price_update
## UpdateMarketPricesResponse
*No fields.*
## UserStats
`taker_notional`: [u64]
`maker_notional`: [u64]
[u64]: /types/u64
## Validator
`operator_address`: string
`consensus_pubkey`: Any
`jailed`: bool
`status`: [i32]
`token`: string
`delegator_shares`: string
`description`: [Description]
`unbounding_height`: [i64]
`unbounding_time`: [Timestamp]
`commission`: [Commission]
`min_self_delegation`: string
`unbounding_on_hold_ref_count`: [i64]
`unbounding_ids`: [u64] ⛁
[i32]: /types/i32
[Description]: /types/description
[i64]: /types/i64
[Timestamp]: /types/timestamp
[Commission]: /types/commission
[u64]: /types/u64
## ValidatorEvmAddress
`validator_address`: [string]
`evm_address`: [string]
`registered_at_block`: [i64]
[string]: /types/string
[i64]: /types/i64
## ValidatorMevMatches
`matches`: [MEVMatch][]
`liquidation_matches`: [MEVLiquidationMatch][]
[MEVMatch]: /types/m_e_v_match
[MEVLiquidationMatch]: /types/m_e_v_liquidation_match
## Vault
`vault_id`: [VaultId]
`vault_params`: [VaultParams]
`most_recent_client_ids`: [u32][]
[VaultId]: /types/vault_id
[VaultParams]: /types/vault_params
[u32]: /types/u32
## VaultHistoricalPnl
`ticker`: string
`historical_pnl`: [PnlTicksResponseObject]
[PnlTicksResponseObject]: /types/pnl_ticks_response_object
## VaultId
`type`: [VaultType]
`number`: [u32]
[VaultType]: /types/vault_type
[u32]: /types/u32
## VaultParams
`status`: [VaultStatus]
`quoting_params`: [QuotingParams]
[VaultStatus]: /types/vault_status
[QuotingParams]: /types/quoting_params
## VaultPosition
`ticker`: string
`asset_position`: [AssetPositionResponseObject]
`perpetual_position`: [PerpetualPositionResponseObject]
`equity`: [BigDecimal]
[AssetPositionResponseObject]: /types/asset_position_response_object
[PerpetualPositionResponseObject]: /types/perpetual_position_response_object
[BigDecimal]: /types/big_decimal
## VaultRevShareConfig
`share_ppm`: [u32]
[u32]: /types/u32
## VaultStatus
`VaultStatus` is an enum with the following values:
* `VAULT_STATUS_UNSPECIFIED`
* `VAULT_STATUS_DEACTIVATED`
* `VAULT_STATUS_STAND_BY`
* `VAULT_STATUS_QUOTING`
* `VAULT_STATUS_CLOSE_ONLY`
## VaultType
`VaultType` is an enum with the following values:
* `VAULT_TYPE_UNSPECIFIED`
* `VAULT_TYPE_CLOB`
## VaultV6
`vault_id`: [VaultId]
`total_shares`: [NumShares]
`owner_shares`: [OwnerShare][]
`vault_params`: [VaultParams]
`most_recent_client_ids`: [u32][]
[VaultId]: /types/vault_id
[NumShares]: /types/num_shares
[OwnerShare]: /types/owner_share
[VaultParams]: /types/vault_params
[u32]: /types/u32
## VersionInfo
`name`: string
`app_name`: string
`version`: string
`git_commit`: string
`build_tags`: string
`go_version`: string
`build_deps`: [Module] ⛁
[Module]: /types/module
## VestEntry
`vester_account`: [string]
`treasury_account`: [string]
`denom`: [string]
`start_time`: [Timestamp]
`end_time`: [Timestamp]
[string]: /types/string
[Timestamp]: /types/timestamp
## Wallet
`key`: [KeyPair]
`account_number`: [i32]
`sequence`: [i32]
[KeyPair]: /types/key_pair
[i32]: /types/i32
## Withdrawal
`id`: [u64]
`amount`: [string]
`eth_recipient`: [string]
`sender`: [string]
`status`: [WithdrawalStatus]
`created_at_block`: [i64]
`timelock_blocks`: [u64]
`eth_chain_id`: [u64]
`eth_tx_hash`: [string]
`error_message`: [string]
`asset_id`: [u32]
`relay_attempts`: [u32]
`ready_at_block`: [i64]
`fee`: [Coin][]
`fee_payer`: [string]
[u64]: /types/u64
[string]: /types/string
[WithdrawalStatus]: /types/withdrawal_status
[i64]: /types/i64
[u32]: /types/u32
[Coin]: /types/coin
## WithdrawalConfirmationEvent
`event_id`: [u32]
`withdrawal_id`: [u64]
`eth_chain_id`: [u64]
`eth_block_height`: [u64]
`sender`: [string]
`coin`: [Coin]
`eth_token_address`: [string]
`log_index`: [u32]
`chain_block_height`: [u64]
[u32]: /types/u32
[u64]: /types/u64
[string]: /types/string
[Coin]: /types/coin
## WithdrawalConfirmationInfo
`next_event_id`: [u32]
`eth_block_height`: [u64]
[u32]: /types/u32
[u64]: /types/u64
## WithdrawalParams
`chain_withdrawal_configs`: [ChainWithdrawalConfig][]
`daily_limit_configs`: [AssetChainDailyLimitConfig][]
`withdrawals_disabled`: [bool]
`signing_timeout_blocks`: [u64]
`max_relay_attempts`: [u32]
`relay_timeout_blocks`: [u64]
`confirmation_timeout_blocks`: [u64]
[ChainWithdrawalConfig]: /types/chain_withdrawal_config
[AssetChainDailyLimitConfig]: /types/asset_chain_daily_limit_config
[bool]: /types/bool
[u64]: /types/u64
[u32]: /types/u32
## WithdrawalSignature
`withdrawal_id`: [u64]
`validator_address`: [string]
`validator_eth_address`: [string]
`eth_signature`: [bytes]
`signed_at_block`: [i64]
[u64]: /types/u64
[string]: /types/string
[bytes]: /types/bytes
[i64]: /types/i64
## WithdrawalSignatureProto
`validator_eth_address`: [string]
`withdrawal_id`: [u64]
`eth_signature`: [bytes]
`eth_chain_id`: [u64]
[string]: /types/string
[u64]: /types/u64
[bytes]: /types/bytes
## WithdrawalStatus
`WithdrawalStatus` is an enum with the following values:
* `WITHDRAWAL_STATUS_UNSPECIFIED`
* `WITHDRAWAL_STATUS_PENDING_TIMELOCK`
* `WITHDRAWAL_STATUS_SIGNING`
* `WITHDRAWAL_STATUS_READY`
* `WITHDRAWAL_STATUS_RELAYED`
* `WITHDRAWAL_STATUS_ERROR`
* `WITHDRAWAL_STATUS_EXPIRED`
## Quick Start with Python
This guide will walk you through the steps to set up and start using the Rubin API Python library.
:::steps
### Install Python3 and Poetry
Choose and install [Python 3.9+](https://www.python.org/downloads/) and [Poetry](https://python-poetry.org/docs#installing-with-the-official-installer) for your system.
### Clone the ritbit client repo
```bash
git clone https://github.com/ritbit/v4-clients.git
```
### Install all dependencies
Go to the Python client library.
```bash
cd v4-clients/v4-client-py-v2
```
Install the project dependencies using the following command:
```bash
poetry install
```
### Run an example
Now, we can run an example file. Let's run `example/accounts_endpoint.py` file.
```bash
poetry run python -m examples.account_endpoints
```
:::
**Now, you can play around with all the available examples. Happy trading!**
:::tip[Python Package]
The Python client is also available through the PyPI [package](https://pypi.org/project/ritbit-v4-client/) `ritbit-v4-client`.
```bash [Installation]
pip install ritbit-v4-client
```
:::
## Quick Start with Rust
This guide will walk you through the steps to set up and start using the Rubin API Rust library.
:::steps
### Install Rust and Cargo
Choose and install [Rust](https://www.rust-lang.org/tools/install) and [Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html) for your system.
### Clone the ritbit client repo
```bash
git clone https://github.com/ritbit/v4-clients.git
```
### Run an example
Go to the Rust client library.
```bash
cd v4-clients/v4-client-rs
```
Now, we can run an example file. Let's run `accounts_endpoint` example.
```bash
cargo run --example account_endpoint
```
:::
**Now, you can play around with all the available examples. Happy trading!**
::::tip[Rust Crate]
The Rust client is also available through the crates.io [crate](https://crates.io/crates/ritbit) `ritbit`.
:::details[Installation]
```bash [Terminal]
cargo add ritbit
```
Or add it manually to `Cargo.toml`.
```toml [Cargo.toml]
[dependencies]
ritbit = "0.2.0" # Replace with the latest version // [!code ++]
```
:::
::::
:::::note[Configuration File]
The Rust client uses a TOML configuration file to configure several required parameters.
::::details[Examples]
:::code-group
```toml [mainnet.toml]
[node]
endpoint = "https://grpc.mainnet.rubin.trade:443"
chain_id = "ritbit-mainnet"
fee_denom = "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5"
[indexer]
http.endpoint = "https://indexer.mainnet.rubin.trade"
ws.endpoint = "wss://indexer.mainnet.rubin.trade/v4/ws"
[noble] # optional
endpoint = "http://noble-grpc.polkachu.com:21590"
chain_id = "noble-1"
fee_denom = "uusdc"
```
```toml [testnet.toml]
[node]
endpoint = "https://grpc.testnet.rubin.trade"
chain_id = "ritbit-testnet"
fee_denom = "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5"
[indexer]
http.endpoint = "https://indexer.testnet.rubin.trade"
ws.endpoint = "wss://indexer.testnet.rubin.trade/v4/ws"
[noble] # optional
endpoint = "http://noble-testnet-grpc.polkachu.com:21590"
chain_id = "grand-1"
fee_denom = "uusdc"
[faucet] # optional
endpoint = "https://faucet.v4testnet.rubin.trade"
```
:::
::::
:::::
## Quick Start with TypeScript
This guide will walk you through the steps to set up and start using the Rubin API TypeScript library.
:::steps
### Install Node and npm
Choose and install [node](https://nodejs.org/en/download) for your system.
### Clone the ritbit client repo
```bash
git clone https://github.com/ritbit/v4-clients.git
```
### Run an example
Go to the TypeScript client library.
```bash
cd v4-clients/v4-client-js
```
Install and use required node version using `nvm`
```bash
nvm install
nvm use
```
Install and build the examples
```bash
npm install
npm run build
```
Now, we can run an example file. Let's run `example/accounts_endpoint.js` file.
```bash
node ../build/examples/account_endpoints.js
```
:::
**Now, you can play around with all the available examples. Happy trading!**
:::tip[JavaScript Package]
The JavaScript/TypeScript client is also available through the npm [package](https://www.npmjs.com/package/@ritbit/v4-client-js) `v4-client-js`.
```bash [Installation]
npm i @ritbit/v4-client-js
```
:::
import Details from '../../../components/Details';
## Accounts
All of your trading activity is associated with your account which corresponds to an address.
In Rubin, accounts are also composed by subaccounts. All trading is done through a subaccount. See more on the [Accounts and Subaccounts](/concepts/trading/accounts) page.
### Account Data
An account can have multiple subaccounts. To fetch all known (with some activity) subaccounts associated with an account the account's address is required.
:::code-group
```python [Python]
response = await indexer.account.get_subaccounts(ADDRESS)
```
```typescript [TypeScript]
const response = await indexer.account.getSubaccounts(ADDRESS);
```
```rust [Rust]
let subaccounts = indexer.accounts().get_subaccounts(address).await?;
```
:::
To fetch a specific subaccount, use the account's address the the subaccount number.
:::code-group
```python [Python]
# Fetch subaccount '0' information.
subaccount_resp = await indexer.account.get_subaccount(ADDRESS, 0)
```
```typescript [TypeScript]
// Fetch subaccount '0' information.
const subaccountResp = await indexer.account.getSubaccount(ADDRESS, 0);
```
```rust [Rust]
// Fetch subaccount '0' information.
let subaccount_resp = indexer.accounts().get_subaccount(&subaccount).await?;
```
:::
#### Balance
The responses above will contain information such as the subaccount's equity, also known as the total account value. Your equity is a combination of the account's USDC balance and sum of the open positions values. A minimum amount of funds is required to trade, see more on [Margin](/concepts/trading/margin) and [Equity Tier Limits](/concepts/trading/limits/equity-tier-limits).
:::code-group
```python [Python]
subaccount = subaccount_resp["subaccount"]
print("Equity: ", subaccount["equity"])
print("Open positions: ", subaccount["openPerpetualPositions"])
```
```typescript [TypeScript]
const subaccount = subaccountResp.subaccount;
console.log('Equity: ', subaccount.equity);
console.log('Open positions: ', subaccount.openPerpetualPositions);
```
```rust [Rust]
println!("Equity: {:?}", subaccount_resp.equity);
println!("Open positions: {:?}", subaccount_resp.open_perpetual_positions);
```
:::
::::note
Rubin is built on the Cosmos SDK and therefore has related methods available. To see the balances of your assets/tokens please see the methods below.
Get the account balance of all assets types (currently USDC and RIT tokens).
:::code-group
```python [Python]
response = await node.get_account_balances(ADDRESS)
```
```typescript [TypeScript]
const coins = await node.get.getAccountBalances(ADDRESS);
```
```rust [Rust]
let balance = client
.get_account_balances(&address)
.await?;
```
:::
The balance of a specific asset can also be fetched instead.
:::code-group
```python [Python]
# `urit` is the RIT token denomination (same on mainnet and testnet).
response = await node.get_account_balance(ADDRESS, "urit") # [!code focus]
```
```typescript [TypeScript]
// `urit` is the RIT token denomination (same on mainnet and testnet).
const coins = await node.get.getAccountBalance(ADDRESS, "urit"); // [!code focus]
```
```rust [Rust]
// `urit` is the RIT token denomination (same on mainnet and testnet).
let balance = node // [!code focus]
.get_account_balance(&address, &"urit".parse()?) // [!code focus]
.await?; // [!code focus]
```
:::
::::
### Asset Transfers
Methods are available to transfer [assets](/concepts/trading/assets#assets-and-collateral) among accounts and subaccounts. See the table below for the different transfer paths.
Links point to the API reference.
| Source | Destination | Method |
| ---------- | ----------- | --------------------------------------------- |
| Account | Subaccount | [Deposit](/node-client/private#deposit) |
| Subaccount | Account | [Withdraw](/node-client/private#withdraw) |
| Subaccount | Subaccount | [Transfer](/node-client/private#transfer) |
| Account | Account | [Send Token](/node-client/private#send-token) |
:::info
To transfer assets in and out of the Rubin network, please see the [Deposits and Withdawals](/interaction/deposits-withdrawals/overview) page.
:::
import Details from '../../../components/Details';
## WebSockets
The Indexer can provide realtime data through its WebSockets endpoint.
Below an example is provided of how to establish a connection and watch realtime **trades** updates. See the full API specification [here](/indexer-client/websockets) for other data feeds.
::::steps
### Connect
To get realtime updates, we first need to establish a connection with the WebSockets endpoint.
:::code-group
```python [Python]
# The message handler, triggered when a message is received.
def handler(ws: IndexerSocket, message: dict):
print(message)
```
```typescript [TypeScript]
// The message handler, triggered when a message is received.
function handler(message) {
console.log(message);
}
// Create a socket.
const mySocket = new SocketClient(
Network.testnet().indexerConfig,
// On-connection callback
() => { console.log('socket opened'); },
// On-disconnection callback
() => { console.log('socket closed'); },
// Message handler
(message) => { handler(message); },
// WebSockets event handler
(event) => { console.error('Encountered error:', event.message); },
);
// Establish the connection.
mySocket.connect();
```
```rust [Rust]
// Establish the connection.
// An internal loop is spawned which handles the connection state.
let mut indexer = IndexerClient::new(config.indexer);
```
:::
Upon a successful connection you will receive an initial connection message.
This message maybe abstracted away, depending on the client.
```tsx
{
"type": "connected",
"connection_id": "004a1efa-21bb-4b19-a2e9-a8ffadd6dc53",
"message_id": 0
}
```
### Subscribe
After a connection is established, you may subscribe to several feeds, containing different types of data.
WebSockets include information on **markets**, **trades**, **orders**, **candles**, and **subaccounts**.
:::code-group
```python [Python]
# Modify the `handler()` function.
# Subscribe only after a succesful connection.
def handler(ws: IndexerSocket, message: dict):
if message["type"] == "connected":
# Subscribe.
ws.trades.subscribe(ETH_USD)
print(message)
```
```typescript [TypeScript]
// Modify the `handler()` function.
// Subscribe only after a succesful connection.
function handler(message) {
console.log(message);
if (typeof message.data === 'string') {
const jsonString = message.data as string;
try {
const data = JSON.parse(jsonString);
if (data.type === IncomingMessageTypes.CONNECTED) {
// Subscribe.
mySocket.subscribeToTrades('ETH-USD');
}
console.log(data);
} catch (e) {
console.error('Error parsing JSON message:', e);
}
}
}
```
```rust [Rust]
// Subscribe.
let trades_feed = indexer.feed().trades(&"ETH-USD", false).await?;
```
:::
### Handling the data
After subscription, you will start receiving the update messages.
Here, the update messages contain the finalized trades (matched orders) for the `ETH-USD` ticker.
For each received message, the `handler()` function will be called on it. Modify it to implement your desired logic.
In Rust, callbacks are not used. Intead, the handle returned on subscription must be polled.
```rust [Rust]
// Continuous loop running until the feed is stopped.
while let Some(msg) = trades_feed.recv().await {
println!("New trades update: {msg:?}");
}
```
### Unsubscribe
When the data feed is not needed anymore, you may stop it and unsubscribe from it.
:::code-group
```python [Python]
ws.trades.unsubscribe(ETH_USD)
```
```typescript [TypeScript]
mySocket.unsubscribeFromTrades('ETH-USD');
```
```rust [Rust]
// To unsubscribe, drop the feed handle (here `trades_feed`).
```
:::
::::
### Details
#### Rate Limiting
The default rate limiting config for WebSockets is:
* 2 subscriptions per (connection + channel + channel ID) per second.
* 2 invalid messages per connection per second.
#### Maintaining a Connection
Every 30 seconds, the WebSockets API will send a [heartbeat `ping` control frame](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#pings_and_pongs_the_heartbeat_of_websockets) to the connected client.
If a `pong` event is not received within 10 seconds back, the websocket API will disconnect.
#### CLI example
You can use a command-line WebSockets client such as [`interactive-websocket-cli`](https://www.npmjs.com/package/interactive-websocket-cli) to connect and subscribe to channels.
Example (with `interactive-websocket-cli`):
```tsx
# For the deployment by RIT token holders (mainnet), use
# wscli connect wss://indexer.mainnet.rubin.trade/v4/ws
wscli connect wss://indexer.testnet.rubin.trade/v4/ws