# What Is Reya

Reya is a breakthrough high-performance onchain exchange that delivers institutional grade execution, whilst delivering superior speed, security and reliability guarantees to users.

Reya achieves this as **a novel trading-specific based Zk rollup on Ethereum.** This design gives users superior:

* Speed: <1ms trade execution
* Security: verifiable order execution and settlement, via zk-proofs, with executed trades settling on Ethereum
* Reliability: no single point of failure, with the rollup design having multiple rotating L2 nodes (unlike generation-1 rollups)

The based-design also makes Reya synchronously composable with all of Ethereum L1 DeFi, unlocking novel use cases for traders and builders. No sidecar. No Alt-L1. Instead, a DEX enshrined into the Ethereum L1.


# Why Reya Exists

Global Capital Markets are moving onchain to Ethereum because it is credibly neutral, has never had downtime and has the economic security capable of supporting the world’s financial system. However, Ethereum isn’t fast enough to support trading - it wasn’t built for it.

Meanwhile, attempts to build fast onchain trading environments have led teams to centralize parts of the trading system. This creates security, reliability and neutrality concerns for a system designed to be global. These concerns are in direct conflict with the benefits Ethereum provides, and why it has been chosen as the chain for global finance.

Reya exists to solve these issues - delivering a DEX with institutional-grade execution and Ethereum-level security. One that is as fast as TradFi but simultaneously secure, reliable and credibly neutral.

In doing so, we won’t just create a ‘faster DEX’. Instead, we will create a credible path for price-discovery to move onchain to Ethereum. In turn, creating a **foundation for open markets and globally accessible capital formation.**


# Who Is Behind Reya

Reya was founded by [Simon](https://x.com/0xSimonJones) and [Artur](https://x.com/arturbegyan) who are both serial-entrepreneurs, having previously built successful web2 and web3 financial startups. They are supported by a team of traders and crypto-native builders, with backgrounds at Optiver, Wintermute, Goldman, Coinbase and Citi.

Reya has raised $12m from investors including Framework, Coinbase Ventures, Wintermute Ventures, Selini Capital, Amber Group, Brevan Howard Digital Assets and Leadblock Ventures. Alongside prominent Angels like Stani of Aave/Lens, David and Ryan of Bankless and Kain of Synthetix/Infinex.


# How Reya Is Different

Based-rollups are novel mechanisms through which developers can create isolated and performant application specific environments that still leverage the security and consensus of Ethereum L1 validators. These types of rollups haven’t been possible until now; for example some of the key technological unlocks, like the introduction of a [Deterministic Proposer Lookahead](https://eips.ethereum.org/EIPS/eip-7917), have only just got the required R\&D momentum.

Previously, the main successful attempts at creating a performant onchain DEXs have been via

1. An alt-L1
2. A single-Sequencer Zk Rollup

A based zk rollup is superior to these choices in every way:

|                                        | **Single-Sequencer Zk Rollup**                           | **Alt-L1**                                             | **Based Zk Rollup**                                   |
| -------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------- |
| **Speed**                              | Very fast                                                | Fast                                                   | Very Fast                                             |
| **Economic Security**                  | None                                                     | Medium - dependant on L1 assets staked                 | Excellent - Ethereum L1 Proposers and Execution Nodes |
| **Liveness / Reliability**             | Low - Single point of failure                            | Medium - dependant on number of L1 nodes and operators | Excellent - Ethereum L1 Proposers and Execution Nodes |
| **Censorship Resistance / Neutrality** | Low - Single point of failure                            | Medium - dependant on number of L1 nodes and operators | Excellent - Ethereum L1 Proposers and Execution Nodes |
| **Composability**                      | Low - not possible with Ethereum L1 in sychronous manner | Medium - dependant on size of L1 ecosystem             | Excellent - synchronous with Ethereum L1              |

Reya is the first ever trading-specific based zk rollup and a transformational moment for DEX design.


# Architecture (at a glance)

<figure><img src="/files/HQUVs5neUFo7cNJk5NIR" alt=""><figcaption></figcaption></figure>

A based-rollup works through a model comparable to proposer-builder-separation (PBS). Simply, Ethereum L1 validators delegate execution and sequencing rights to a third party. In PBS they delegate to builders. In a based-rollup they delegate to gateways, which we refer to as “Execution Nodes”.

This delegation means Execution Nodes know they will be able to include their transactions in the L1 block. Since this is known, they can they give lightening fast ‘pre-confirmations’ back to traders who are executing trades through the exchange operated within an Execution Node. As a result, Reya has 2 confirmation levels:

1. Pre-confirmed: sequenced by the Execution Node and an execution receipt is available to the user
2. Finalised: the transaction has been batched and included in an L1 block

A based-rollup must post transaction data through to the Ethereum L1. However, posting order data (from the orderbook) would be uneconomical, since order data is orders of magnitude greater than executions data. To solve this problem Reya has a hybrid DA structure:

* Trade Executions data goes to Ethereum L1
* Order data goes to EigenDA

Both are verifiable via ZK-proofs.

The outcome for users is:

* A lightening fast execution environment, achieving sub-millisecond trade speed
* A highly secure structure
  * Ethereum L1 validators are the ultimate owners of block building
  * ZK-proofs allow for full verifiability of the entire trading system, from orders to executions
  * Execution nodes can be slashed if they misbehave, creating economic security
* Synchronous composability with Ethereum, the biggest DeFi ecosystem in the world.

For full details please read the whitepaper here: <https://x.com/0xSimonJones/status/1944737748381839671>


# Reya Roadmap

Unlocking the breakthrough based zk rollup design has been an iterative path. To begin with, Reya was launched using a forked and heavily customised version of Arbitrum Orbit. This allowed the product to launch, deliver value to users and generate the necessary learnings required to unlock the based zk rollup design.

This means Reya will transition to a based rollup iteratively over time. This will be done without any impact to users. This infrastructure upgrade will happen in stages

* Stage 1: Orderbook launch (expected Q1 2026)
* Stage 2: Migrate to based design, with single Execution Node (expected Q2 2026)
* Stage 3: Introduce multiple rotating Execution Nodes (expected Q3 2026)

Alongside this infrastructure upgrade, the trading venue will continue with a roadmap covering:

* Spot markets
* RWA-Crypto Perp Expansion
* Launchpad
* srUSD Tokenization


# Derivatives Clearing

## A clearing protocol built for capital efficiency

Reya Derivatives Clearing is a **non-custodial clearing protocol for derivatives instruments.** The Derivatives Clearing Protocol is the cornerstone that allows Reya to act as a self-reinforcing liquidity network. One of its distinguishing features is that it can aggregate positions from multiple markets *and* multiple exchanges into a single margin account. In particular, this provides both traders and LPs with unprecedented capital efficiency by offsetting:

1. **Losses from one position with profits another**, and enabling leveraging of all portfolio profits immediately
2. **Margin requirements,** by recognizing the P\&L offset that can happen between positions
3. **P\&L and margin&#x20;*****across*****&#x20;exchanges,** by aggregating all positions into a single settlement and clearing layer

Connecting exchanges can be both DeFi or CeFi venues supporting the trading of any linear derivative contract (e.g., Futures, Swaps) via any on- or off-chain trading mechanism (e.g. Orderbook, AMM, Passive LP pool). By deploying its own appchain, Reya aims at providing these benefits while bringing on-chain the experience and speed of traditional centralized exchanges.

The basic concept in the Derivatives Clearing Protocol is that of a *collateral pool.* This is a compartment within the smart contract where margin deposits for any given market are kept and managed. Each of the user’s margin accounts is associated with one such collateral pool. Cashflow obligations are settled peer-to-pool. To make sure these are properly settled, the protocol has three main components:

1. Margin system that manages margin requirements for different settlement tokens and ensures safe levels of collateralization
2. Cross-collateralization module that manages features around collateralization with tokens other than the settlement token, as well as the auto-exchange mechanism which forces conversion to manage risk levels
3. Liquidation module that manages liquidation procedures when an account is declared liquidateable by the margin system.

<figure><img src="/files/T85LJ3le2vVpztkjy7jG" alt=""><figcaption></figcaption></figure>

## Peer-to-pool, non-custodial, on-chain trading

Reya fully embraces the non-custodial nature of DeFi. This means that the entire flow of execution, clearing and settlement is done on the blockchain itself, in a transparent and secure way. Every user can verify their transactions as they get registered, as well as their balances, margin requirements and accrued cashflows.

The Derivatives Clearing Protocol is non-custodial, meaning that all settlement and margin funds are are safeguarded cryptographically by the Protocol rather than by an administrator (eliminating ‘FTX’ risk). The Protocol includes mechanisms to ensure that all funds are correctly managed and settled.

Furthermore, the architecture of the Derivatives Clearing around collateral pools means that trading in Reya is peer-to-pool: although positions are originated in pairs at associated exchanges to ensure pool neutrality, subsequent margining and settlement is between the user and the collateral pool itself. In particular, the counterparty at the origin of the position might completely unwind their exposure with no difference for the user.

Peer-to-pool trading is the decentralized version of the CCP’s novation: rather than splitting a contract into two, between each of the two counterparties and a central party, the smart contract and the collateral pool itself lies at the center of the system, with every party facing it. Importantly, the single insolvency and liquidation of the counterparty has no direct bearing on a user, and their settlement cashflows are guaranteed as long as the pool as a whole remains solvent. Accordingly, if the pool’s solvency is threatened by a contract or instrument, positions are shortcut or, in the extreme case, losses are distributed in a socialized manner through auto-deleveraging as discussed below.

## Margin accounts

Users can create multiple accounts per wallet, where each account is represented as an ERC-721 Token. This provides users with the ability to create segregated accounts for trades they don’t want cross-margined with other positions. The use of an ERC-721 Token also provides the following benefits:

* Users can transfer these accounts to another wallet without unwinding any positions. In many ways, this is akin to in-specie transfers and provides a significant improvement in functionality for sophisticated actors on the protocol.
* Segregated account owners, which can be EOAs or smart contracts, are able to prescribe granular permissioning rules to other EOA and smart contract addresses. This may, for example, allow a user to have a cold wallet for withdrawals but grant permissions to their hot wallet to conduct trades without giving it withdrawal access
* Since addresses are decoupled from accounts, it is possible to layer in further abstractions that govern delegation and authorization flows improving account management operational security.


# Perpetual Futures

Reya Exchange is a perpetual futures exchange built on top of Reya Network. It will display all of the features unlocked by the financial logic of Reya Network. In particular, it provides both traders and LPs with unprecedented capital efficiency by:

1. **offsetting losses from one position with profits another**, and enabling leveraging of all portfolio profits immediately;
2. **offsetting and reducing margin requirements,** by recognizing the P\&L offset that can happen between positions.

All of this is accomplished with all the security of on-chain settlement and clearing. All your capital is guarded safe by a smart contract, and there is no “FTX-risk” that someone will just run away with it.

### Perpetual Futures <a href="#perpetual-futures" id="perpetual-futures"></a>

Perpetual futures are derivatives contracts where traders can have a PnL matching that of a given token without actually buying that token. For example, a trader that holding a long position for a unit of ETH will have the same PnL that they would have if they actually held one unit of ETH: when the ETH price goes up from 3,000rUSD to 3,100rUSD they will earn 100rUSD; on the other hand, if the price goes down to 2,900rUSD, they will have to pay 100rUSD. These amounts are interchanges with accounts holding short positions, in other words, traders that earn when the price goes down and vice versa.

Additionally to the PnL from price variations, longs and shorts will also interchange a funding rate. This funding rate is used to incentivize balancing of long and short open interest, and to keep the perpetual futures in line with the spot market.

When a trader enters a perpetual futures contract, they need to deposit collateral to ensure that they will be able to cover losses that they suffer in their positions. Managing these collateral requirements, settling PnLs, as well as resolving accounts when a trader has an insufficient balance is the main work of Reya’s Derivatives Clearing Module.


# Cross-margining

One of Reya’s fundamental innovation is a system for full cross-margining of positions, made possible by the extensive liquidation engine and its innovative waterfall structure. Reya Network’s margin system has a holistic view of a traders portfolio. This means when setting margin requirements, it takes into account that certain positions in a portfolio can win when others lose, in effect reducing the aggregate losses that a portfolio as a whole can suffer. As a result, a trader would need to deposit less capital as margin for those aggregate losses. Cross-margining is the system of accounting for these synergies in the portfolio and consequent margin savings.

In particular, cross-margining enables very capital efficient relative value (long-short) trades. While it is completely fair to trade on whether a given token will go up or down, whether a given project is winner or a loser, more often than not, true trading opportunities are in betting on whether two projects will converge or diverge relative to one another. By longing one and shorting the other, a trader stands to gain precisely with those movements, irrespective of whether the market as whole goes up or down.

Using two-year data up until December 31, 2023 and a preliminary margin model, Reya’s cross-margining system would have resulted in >350% more capital efficient ETH-BTC spread trading.

Margin efficiencies are the cornerstone for capital efficiency and are essential for liquidity providers, as they will accumulate large portfolios with many offsetting pieces, and by recognizing them, cross margining frees up LP’s resources to provide further liquidity


# Margin System

## Exposures

Instruments in REYA have linear exposures to these risk factors. Explicitly, this means that if risk factors are a multivariate random variable $$R\_t$$ of $$n$$ factors, then each instrument determines a vector $$E\_t$$such that the price of the instrument is

$$
P\_t=E\_t'R\_t
$$

This means in particular that the entries of $E\_t'$ transform the risk factors into token amounts. As a consequence, note that the exposure vector will often be a function of more than just time: for example, if a given risk factor is the relative (percentual) returns $$r\_{t,i}$$ of some asset, then $$e\_{t,i}$$ will generally have the price $$p\_{t,i}$$ as a factor to transform the percentual return $$r\_{t,i}$$ into an absolute return $$p\_{t,i}r\_{t,i}$$ in token amount. For example, if a user holds exposure of two units of ETH when its price is $1500, then their exposure is $3000.

Finally, note that by linearity, exposures are additive, meaning that a portfolio’s exposure is simply the weighted sum (with portfolio weights) of the exposure vectors of each component.

## The risk matrix

Having established the fundamental framework, pools in REYA take as risk parameters an $$n\times n$$ matrix $$A$$, as well as two multipliers $$\lambda\_M$$ and $$\lambda\_I$$. Given this matrix, REYA computes the liquidation margin requirement for a portfolio exposure vector $$E$$ as

$$
\mathrm{LMR}=\sqrt{E'AE}
$$

and then $$\mathrm{MMR}=\lambda\_M\mathrm{LMR}$$ and $$\mathrm{IMR}=\lambda\_I\mathrm{LMR}$$.

The matrix $$A$$of course, must be carefully chosen and updated for the system to appropriately margin portfolios. The cases of multivariate normal and Student's t-distribution are instructive in getting intuition about the risk matrix.

However, REYA will generally rely on a more flexible version, where the components can be independently adjusted according to risk estimates mixing, e.g., Value-at-Risk and Expected Shortfall methods.


# Cross-collateralization

REYA creates a new type of margin account that allows both for:

* posting of collateral in any token, so that users may leverage their preferred tokens while holding on to them. As example use cases, users can hold onto their yield bearing tokens (e.g., stETH) while backing a portfolio in their base token (e.g. ETH); or holding ETH to back a USDC position, perhaps ensuring a constant collateralization ratio by posting ETH to back a short USDC-denominated ETH perp.
* Aggregation of portfolios in different settlement tokens, unprecedently. This is a unique feature in Reya, which allows users to share PnL across portfolios in different denominations, analogously to the sharing of PnL with a settlement token. By doing so, users can automatically virtually borrow from one portfolio onto another with actual conversion happening only as needed, ensuring maximal synergy.

Reya’s cross-collateralization module uses a system of bubbles and haircuts based in USDC to manage collateral mismatch. This means that:

* when converting amounts from one token into another, a haircut is applied to conservatively account for possible future movements of the exchange rate;
* margin requirements are first netted out, as much as possible, within each bubble, to avoid distorting effects of the haircuts;
* closely associated tokens (e.g. yield bearing tokens) are included at the bubble level to minimize unnecessary haircuts;
* all surplus or deficit margin in the bubbles is then rebased and netted off.

The following diagram illustrates the system, where we use USD as the root of the diagram as an example.

<figure><img src="/files/uoPPHIVqHsemJnI2xrBG" alt=""><figcaption></figcaption></figure>


# Haircuts

A haircut is a percentage decrease in the exchange rate applied for risk reasons: specifically, given two tokens or currencies $$T$$ and $$T'$$, we convert $$T'$$ a collateral not simply by multiplying by the exchange rate $$X\_{T'/T}$$, but rather by multiplying by

$$
(1-\textrm{haircut}*{T'})X*{T'/T}
$$

The resulting amount is less than the market value of the collateral, the difference serving as a cushion for future exchange rate fluctuations that might happen if and until the collateral is converted to cover margin requirements. The haircut, then, can be thought of as margin, but applied statically and in a segregated fashion to the collateral. The methodologies for calculating its values will need risk measures like margin models.

The previous multiplier assumed that the worst scenario is when the exchange rate goes down, which is indeed the case when converting positive quantities. If we convert negative quantities, however, the worst outcome is actually when the exchange rate goes up instead. Therefore, when moving around margin requirements or negative balances, one multiplies instead by

$$
\frac{1}{1-\textrm{haircut}*{T'}}X*{T'/T}
$$

The advantage of this form is that

$$
\frac{1}{(1-\textrm{haircut}{T'})X\_{T'/T}}=\frac{1}{1-\textrm{haircut}{T'}}X\_{T/T'}
$$

so that the multipliers get interchanges when reversing the sense of the arrows in the graph.


# Auto-exchange conditions

In the first instance, Reya Network’s cross-collateralization features allow users to accumulate a T-specific insolvency for T a settlement token, even while remaining globally solvent. This, however, creates the risk that the pool itself will become T-insolvent if enough of these T-insolvencies accumulate. To avoid this scenario, Reya Network has a set of **auto-exchange** conditions, one set limiting the size of negative T-balances both in absolute and relative terms, and the other set forcing collateral matching (T-solvency) when liquidating.

The auto-exchange conditions can be organized in two groups:

1. **Conditions that limit negative balances:** whereas cross-collateralization allows users to run negative balances, there are three conditions that put limits on this:
   * *Individual token threshold*: for each $$T$$, $$Bal\_T \geq -bound\_T$$where $$bound\_T$$ is a governance set (positive) parameter.
   * *Global threshold*: given all settlement $$T$$ in the margin account, $$\sum\_{Bal\_T<0} \frac{X\_{T/USD}}{1-\mathrm{haircut}\_{T/USD}}Bal\_T \geq - bound$$, where $$bound$$ is a governance set (positive) parameter.
   * *Negative ratio threshold*: given all settlement $$T$$ in the margin account, $$\sum\_{Bal\_T<0} X\_{T/USD}Bal\_T \geq -\eta\cdot \mathrm{AV}$$where $$0<\eta<1$$ is a governance set parameter, and $$\mathrm{AV}$$, the total value of collateral in the account (without haircuts).
2. **Condition that limits mismatched margin coverage:** whereas the Boss Mode margin coverage condition allows users to cover even the entirety initial or maintenance margin requirements with surplus collateral of other bubbles, once an account breaches the maintenance margin condition, we further require that for every bubble for which there is a deficit maintenance margin the following condition holds:

   $$Bal\_T-LMR\_T\geq 0$$

   The purpose of this condition is to isolate the liquidation processes of the different bubbles. In particular, the liquidation margin requirement can be separately verified individually for every bubble, and the liquidation process applies always to a single token situation.


# Auto-exchange mechanism

When one of the auto-excange conditions is breached, the system will forcefully convert other tokens into T by relying in external ‘auto-exchangers’ who receive a discount over market price as incentive. The amounts available will take into account both the amounts in the T-bubble, as well as those that can be moved from other bubbles.

The amount of collateral $$m$$ of token $$S$$ the auto-exchanger receives in exchange is computed as

$$
(1-\mathrm{discount}*{S/T})X*{S/T}\times m=n
$$

where both $$\mathrm{discount}*{S/T}$$ and $$X*{S/T}$$ will generally be a compound term, computed as products/quotients of the official pool discounts and exchange rates (one needs to trace the S→T path on the directed graph).

The following diagram illustrates the general flow.

<figure><img src="/files/NgYb76LyNtiI7EHJUlCa" alt=""><figcaption></figcaption></figure>


# Liquidation Engine

Liquidations are the procedures through which Reya cuts positions off to stop accounts from accumulating losses larger than their margin balance. They are triggered whenever the liquidation margin requirement (LMR) is breached for a bubble. In the presence of cross-margining, for a given settlement token $$T$$ we need to verify the LMR both at the ‘local’

$$
\mathrm{NDelta}\_T=\mathrm{BBal}\_T-\mathrm{LMR}\_T\leq 0
$$

as well as the ‘global’ level:

$$
\mathrm{NDelta}{USD}=\sum{S\_{T'}>0}(1-\mathrm{haircut}T)X{T'/USD}S\_{T'}\leq 0
$$

where . Essentially, even if a bubble cannot satisfy the LMR autonomously, we check if there are funds in the other bubbles that can be auto-exchanged.

## The liquidation waterfall

*Reya Network introduces a series of liquidation features that guarantee the health of its collateral pool for the first time on-chain.* These are all gathered in an innovative waterfall structure, each lower layer being deployed as the account’s health worsens:

1. **Open bidding**, where in anticipation of LMR breach, liquidators submit liquidations proposals that get filtered, ranked and executed once LMR actually is breached, where the ranking takes into account both the requested discount and the liquidity profile of the requested assets, and is designed to disincentivize over-liquidations;
2. **Dutch auction**, where liquidation bids are immediately accepted at a given margin reward (risk-weighted discount), and which is activated if the open bidding was insufficient to bring an account back to health, or if the LMR was breached directly.
3. Pushing positions onto backstop LPs, who provide a liquidity pool against which to push the portfolio when the margin balance falls below a threshold level;
4. Auto-deleveraging, where losses are socialized: the system tries to act early enough so that only other users’ potential PnL will be curtailed (by pushing positions at market prices with insolvencies covered by the insurance funds), but will also socialize losses in last resort (by pushing positions at the bankruptcy price.

In other words, the waterfall serves as a series of backstops to ensure that the account can be fully liquidated while preserving the pool’s health.

The important design choices are:

* By introducing the concept of maintenance margin as distinct from liquidation margin, Reya Network allows for price optimization while maintaining speedy liquidations once the accounts threaten insolvency.
* Liquidations within Reya always work through position transfer to particular parties, in practice outsourcing the optimization of unwinding cross-margined exposures to liquidators: the Protocol is able to organically grow in scope as portfolios and liquidators become more sophisticated.
* Positions are always transferred by referencing the price index: as explained above, this ensures the coherence between margin requirements, marking to market, and liquidation losses.
* Untrusted liquidators are compensated with a margin balance (’cash’) transfer proportion to the reduction in LMR. In this way, no untrusted liquidator can cause the account to lose more than the LMR, which should prevent different types of attacks. Also, the liquidator’s reward being in ‘cash’ (rather than a discount on price index) should incentivize them, since it means their liquidation profits are always immediately realized.

<figure><img src="/files/6HEhe2c1UZEFpGgQuYxm" alt=""><figcaption></figcaption></figure>


# Ranked liquidations

The first level is the open bidding process, during which bidder will submit a series of volumes $${Q\_i}$$ that they are willing to take on from the liquidated account, as well as a percentage of the resulting change in LMR that they request as reward. The open competitive process should ensure that the reward parameter is optimized.

<figure><img src="/files/VCFUQhfbmaK2B29mMQBM" alt="" width="563"><figcaption></figcaption></figure>

The other cornerstone for this procedure is a scoring function used for liquidation bids, which summarizes the reward parameter and the market impact. For a bid requesting volumes $${Q\_i}$$ of $$n$$ assets for a reward parameter $$d$$, the score is

$$
\mathrm{score}({Q\_i},d) = \frac{1}{n}\left(w(1-d) + (1-w)\frac{\sum\_i Q\_i \times\mathrm{pSlippage}i\left((Q\_i(Q{i,max}-Q\_i))^{1/2}\right)}{\sum\_i Q\_i}\right)
$$

where $$\mathrm{pSlippage}\_i(Q)=\phi Q^\beta/\mathrm{price}\_i$$ is the estimated percentual price slippage (using governance set parameters).

An important feature is of this scoring function is that it disincentives over-liquidations by multiplying by $$1/n$$ (which in practice stratifies bids according to the number of requested assets), as well as maxing out the slippage benefit at half the available volume.


# Dutch auction

The Dutch auction process kicks in either when the open bidding process has failed to bring the account back to health, or when the liquidation margin requirement was breached directly and there was no time for the preparatory bidding. Recognizing the urgency of such cases, the Protocol consecutively quotes decreasing $$d$$, starting at some predefined maximum, and ending at a predefined minimum, and immediately allows execution of liquidation proposals with margin reward parameter smaller than $$d$$.


# Backstop LPs

The backstop LP pool would be a pool where people deposit funds which can be used to force positions onto them. It is important to not that the liquidation process never pushes losses onto backstop LPs, as positions, as this mechanism is only activated while possible losses can be covered by the insurance fund. The true drawback for backstop LPs, then, is not having to absorb liquidation losses, but rather the need to actively manage the positions that were pushed onto them so as to avoid subsequent losses while holding the portfolio.

In return for providing liquidity to backstop the liquidation process, backstop LPs get (at least) the following benefits:

1. a portion of collected liquidation fees is distributed to backstop LPs.
2. Exemption from liquidation fees when a position is pushed onto them, regardless of whether it is at profit.
3. the system will actually try to push the positions at profit: when we reach say 25% of LMR, the positions would be pushed onto backstop LPs at bankruptcy price, that is, the entirety of the margin would be transferred (as opposed to the earlier stage, where the Protocol is trying to minimize a discount). This will generally be below market price.
4. In any case, the worst that can happen is that a position gets pushed at market (TWAP) price if the account’s losses have exhausted the margin balance, and then only below the ADL threshold.


# Insurance Funds

Reya Network includes a system of insurance funds to backstop potential collateral pool insolvencies. These insurance funds accumulate the greater part of the liquidation fees, and fill the shortfall when losses exceeded the deposited margin. But two important aspects:

1. There are set limits on how much the insurance funds can cover (depending on size of account). ADL at a loss would kick in beyond that limit.
2. The insurance funds plug in the shortfall, but only **realized shortfalls resulting from the liquidation** (i.e., measured as the realized loss of the liquidated account resulting from the liquidation)
3. The insurance funds plug the shortfall to the pool as whole and not to any particular account.

A development of the full ecosystem of exchanges on top of Reya Network will most likely introduce a second layer of backstop after the insurance funds.


# Automatic leveraging of PnL across instruments

Even in the basic token-matched case above, $REYA unlocks capital efficiency by automatically leveraging all PnL into a user’s balance. In practice, this means that all PnL is automatically part of a user’s balance. Explanation of all terms follows below:

$$Bal\_T = \mathrm{netDeposits}\_T + \mathrm{realizedPnL}\_T + \mathrm{unrealizedPnL}\_T$$

This feature is sometime known as cross-margining, although the term is more appropriately used for offsetting of margin requirements, also offered in Reya as explained below.

One consequence is that gains from any position can offset losses in other positions, an in particular hedged positions have their PnL reflect their hedging. Furthermore, any PnL that accrues beyond the initial margin requirement can be used and truly leverage into new positions. All of this is essential to incentivize liquidity provision, since LPs accumulate large hedged portfolios and the PnL leveraging reflects that. It is also a big incentive for traders, of course.

The following diagram illustrates the automatic leveraging of PnL when instruments are separately margined with a single margin account.

<figure><img src="/files/cHY1BDb0XwRnfEic1IK6" alt=""><figcaption></figcaption></figure>


# Spot markets

Although not included at the initial deployment, Reya will include spot markets in addition to derivatives trading. This will unlock synergies with the rest of the Network, in particular related to rUSD distribution by creating markets against other stablecoins, as well as auto-exchange and CDP liquidations, which imply conversion of different types of collateral.

When spot markets within Reya Network attract enough liquidity, they will also enable the Network to internalize the spot benchmarking needs both in the clearing and the liquidity layers.


# Reya Governance

Reya Network will decentralise, ensuring the network isn’t controlled by any single entity and providing transparency and trust through to the end users of the system. Because the network will be an interlocked system of components, a single governance layer will be introduced for the entire network.

Trust and transparency also improves the composability of the network giving other exchanges confidence they can operate on the network, too. In turn this will help accelerate adoption of Reya Network and further deepen liquidity for end users.

Details will follow when appropriate.


# The Liquidity Layer

What is the passive liquidity mechanism?

The passive mechanism is an on-chain trading protocol which preserves the best features of the original AMMs:

1. **unique meeting point:** it creates a unique meeting point between makers and takers, aggregating all of the liquidity and generating a single price for every trade;
2. **no liquidity drainage:** it permanently offers liquidity and quotes a price, which allows traders to always trade if they found the price acceptable;
3. **passive LPing:** it allows LPs to make their capital available without having to actively manage their position and keep updating their quote price.

Funds deposited by passive LPs are to bridge between long and short open interests as the pool acts as a temporary counterparty making up the market’s *net imbalance.*

<figure><img src="/files/srKJW5AEPhl3YeCr5Azr" alt=""><figcaption></figcaption></figure>

Passive liquidity pools permanently quote a price for each requested volume by pegging themselves to a reference market. As the Network grows and becomes more robust, the endgame will be to have the passive pools in the Liquidity Layer reference internal markets only, through the use of price indices.

<figure><img src="/files/ECxZWuo72STYTi2IdJM3" alt=""><figcaption></figcaption></figure>


# Reya’s pool for perpetual futures

Reya Network’s initial deployment already includes a passive liquidity mechanism for perpetual fututes. It uses a novel constant-product pegging mechanism for perpetual futures. It powers any exchange operating on Reya Network, and allows for unprecedented capital efficiency, both for traders as well as LPs. For the first time ever on-chain:

1. Traders can leverage positions with full portfolio cross-margining
2. LPs can offer capital at collateralization ratio of less than 100% of nominal in addition to cross-margining

Reya Network’s passive pool mechanism accomplishes this by introducing a series of new safety mechanism designs, such as:

1. a constant product pegging mechanism to the spot market, a novel price impact function based on the constant product curve, which, uniquely, automatically adapts to changes in liquidity while incentivizing rebalancing of the pool’s exposure;
2. a dynamic funding rate that, also based on the constant product pegging, further strongly incentivizing rebalancing of the pool’s net exposure by using the price impact function to determine the funding rate velocity;
3. a margin system of Reya’s Derivatives Clearing mechanism, allowing for wide control of the risk profile while also enabling full portfolio cross-margining;
4. an open trading system, enabling developers to build their exchanges on top of the instrument and clearing systems, further incentivizing liquidity and trading in Reya Network.

At heart, the constant-product-pegged passive liquidity mechanism is a market making model that provides the best features of a traditional constant product AMM while allowing LPs to offer price-passive liquidity in a highly efficient manner. This means that LPs can offer liquidity without continuously pricing crypto assets while fully leveraging their capital.

To enable price-passive LPing, the passive LP mechanism makes full use of the spot market prices, which can be used to index the futures. It also aggregates all liquidity, creating a unique interface between makers and takers.

Critically, the pool only acts as a temporary counterparty to trades, by offsetting trade flow automatically and freeing up capital for new trades. Finally, the price impact function based on the constant curve not only allows the pool to automatically adjust to changes in liquidity conditions, but also strongly disincentivizes liquidity drainage.


# Offering liquidity in the passive pool

LPs can provide funds to the pool via a segregated margin account dedicated to providing liquidity to the passive mechanism, distinct from a participants trading margin account. Once users make a deposit, they are entitled to the proportional returns of the pool.

Direct returns of the pool can come from four different components:

1. Trade spreads: as the pool quotes prices based on the net exposure after the trade, long-short trades that immediately follow each other generate a spread;
2. Funding fees: as the funding rate velocity depends on the pool’s net exposure, the funding fees *eventually* are in the pool’s favour, and so the pool accrues funding most of the time. The exception is when net exposure changes sign, and the change in the velocity takes sometime to take effect and to change the funding rate sign as well.
3. Protocol fees: the fees generated from the trades are shared with LPs.
4. Backstop PnL: if the pool is designated as a backstop LP for the passive perps, it derives two other sources of PnL:

   1. a portion of the insurance fees derived from liquidations;
   2. profits from taking on the liquidated positions.

   Note that backstop LPs always take on positions at a favorable price, and never at a loss; the insurance fund or ADL are triggered if needed.

As with any investment, providing liquidity to the passive pool includes risks:

1. Although the mechanism design works to make aggregate trading profitable, not all trades are closed at a profit;
2. Although the dynamic funding rate responds to correct persistent imbalances, the pool could in an extreme case be locked into positions, rather than follow the typical pattern of opening and closing exposure;
3. Extreme insolvencies in the protocol could trigger an auto-deleveraging event, which could hit the pool;
4. Even if the pool is profitable, the capital in it might be locked to collateralize exposure and therefore LP withdrawals might be restricted to keep the pool well-collateralized. Again, this is an extreme circumstance that the mechanism design works to both disincentivize and correct if it ever happens. As soon as the pool rebalances, LP funds are again automatically unlocked.


# Deepdive into passive perps

The perpetual futures give traders to gain leveraged exposure to a reference market by paying a funding rate. Each market is determined as an instance of the passive perp instrument determined by an oracle. Like any ‘cash-settled’ derivative, it is full determined by its cashflows:

$$
\mathrm{PnL}=\mathrm{priceVariation} + \mathrm{fundingFee}
$$

## Price variation

For Reya’s passive perps, the intermediate price variation (before position closing) are computed using the *spot* price given by the oracle, consistent with the pegging. This means that at any time, for each unit of exposure the account’s unrealized PnL is

$$
\mathrm{spotPrice}-\mathrm{entryPrice}
$$

where $$\mathrm{entryPrice}$$ might be an average of actual entry prices, or also of prices at the last PnL realization.

In Reya perps, this mark to market due to price variation is credited initially to the account’s unrealized PnL. This is so that the system keeps profits on escrow for a while, in case an extreme event makes an auto-deleveraging (ADL) necessary: ADL computes bankruptcy prices on the basis of unrealized PnL (see the documentation for the Derivatives Clearing Protocol).

## Dynamic funding rate

Rather than a traditional funding rate mechanism, Reya Network uses a **dynamic** funding rate, introduced by Synthetix, adapted to the constant-product pegging. In a dynamic funding rate, the price deviation determines not the funding rate itself, but its **velocity**.

Details of how the funding rate velocity is set can be found below. But if $$\dot{r}$$ denotes the current funding rate velocity, and the original funding rate is $$r\_0$$ at time $$t\_0$$, the funding rate at subsequent time $$T$$ is

$$
r\_T=r\_0+\dot{r}\Delta^d(t,T)
$$

Here, $$\Delta^d(t,T)$$ is the time interval between and $$T$$ measured in *days.* The convention for traditional perps is to express the time interval in hours, in which case a factor of $$1/24$$ must be included.

In the absence of ADL events, the funding fee accrued by a single exposure token while the velocity remains constant is

$$
\int\_{0}^{\Delta^d(T\_1,T\_2)}p\_t\left(r\_{T\_1}+\dot{r}\_{T\_1}\Delta^h(T\_1,t)\right)d\Delta^h
$$

where $$p\_t$$ is the spot price. This could be approximated by querying the spot price at regular interval, but this is not practical given the smart contract limitations. Instead, the accrued funding is approximated as

$$
p\_{T\_2}\left(r\_{T\_1}+\dot{r}\_{T\_1}\Delta^h(T\_1,t)\right)\Delta^h(T\_1,T\_2)
$$

This accrued amount is added every time the funding rate velocity changes, and so the accuracy of this approximation depends on the frequency of transactions and so should it is expected to be high. On the other hand, the use of $$p\_{T\_2}$$ means that the actual amount is not known until the end of the interval, and so intermediate queries are estimations only — but the frequency of transactions should make this sufficiently accurate.

## The constant-product pegging mechanism

### The constant-product pegging formula

Reya’s constant-product pegging mechanism takes into consideration:

1. the spot price
2. the available liquidity in the pool;
3. the pool’s net exposure.

The pegging is ‘constant-product’ because it uses the slippage implied by the constant product curve known, for example, from Uniswap and other AMMs. It immediately adjusts trade prices in response to any of these three variable. Concretely,

$$
\mathrm{tradePrice}=\mathrm{spotPrice}\times \left( 1-\frac{\mathrm{netExposure}}{\mathrm{maxExposure}+\mathrm{netExposure}}\right)
$$

Here, $$\mathrm{netExposure}=\mathrm{longOI} - \mathrm{shortOI}$$ is the pool’s net exposure ***after*** the trade.

<figure><img src="/files/PazJbySJuHYLRiVtOLZh" alt=""><figcaption></figcaption></figure>

Notice a couple of important features of the pegging formula:

1. if there is no net exposure (i.e., the long and short sides are perfectly balanced), the quoted price is actually the spot price;
2. however, whenever previous trades cause an imbalance, the price gets adjusted in a way that disincentivizes further unbalancing, and does so increasingly stronger.

This price deviation is *approximately linear* when the trade volume is much smaller that the maximum exposure, but, as it approaches the limit, the constant product effect kicks in and it quickly shoots up. The following table illustrates this effect for a maximal exposure of 100,000.

| Units:          | 0 (spot) | 60      | 600     | 6,000   | 60,000 |
| --------------- | -------- | ------- | ------- | ------- | ------ |
| Price:          | $2000    | $2001.2 | $2012.1 | $2127.7 | $5,000 |
| Deviation (bp): | 0        | 6       | 60      | 638     | 15000  |

Uniquely, in Reya Network’s constant-product-pegged passive liquidity mechanism the price impact function automatically adjusts *both* trade prices and the funding rate in response to liquidity changes. This optimizes trading conditions to the risk profile of the pool at any moment: increasing the price impact and the funding rate if liquidity were drained; but also improving trading conditions in response to increases in liquidity both from new deposits and accumulated PnL.

### The maximal exposure

Because the pool is not a spot exchange, but rather trading in ‘cash-settled’ derivatives, the maximal exposure is a measure of capital consumption by margin requirements. The capital locked for the existing exposure is expressed as a Protocol-set multiple $$\lambda$$ of the initial margin requirement $$\mathrm{IMR}$$. The pool’s capital would be exhausted if

$$
\mathrm{totalCapital}=\lambda\mathrm{IMR}
$$

since it could take on more positions. Maximal exposure is so defined that this is never verified as trading the pool to this level would set an infinite trade price.

The maximal exposure for a given market is the maximum exposure that would result in the pool’s exhaustion, *holding all other exposures constant*. Holding the other exposures constant might both have a positive or negative effect in the maximal exposure, because cross-margining might actually offset the net exposure in a market with those of others.

### Funding rate velocity

The net exposure of the pool determines the funding rate velocity through:

$$
\dot{r}^{hourly}=\alpha \times \frac{1}{24}\frac{\mathrm{tradePrice}-\mathrm{spotPrice}}{\mathrm{spotPrice}}=-\alpha \times \frac{1}{24}\frac{\mathrm{netExposure}}{\mathrm{depth}\times\mathrm{maxExposure}+\mathrm{netExposure}}
$$

where $$\alpha$$ is a scaling parameter. If the original funding rate is $$r\_0$$ at time $$t\_0$$, the funding rate at subsequent time $$T$$ is

$$
\begin{align\*} r\_T&=r\_0+\dot{r}\Delta^h(t,T)\ &=r\_0-\alpha \Delta^d(t,T) \times \frac{\mathrm{netExposure}}{\mathrm{depth}\times\mathrm{maxExposure}+\mathrm{netExposure}} \end{align\*}
$$

where the superscript in $$\Delta^h$$ denotes time measured in days, while $$\Delta^d$$ in days.

**Relation to traditional funding rates:** If nothing changed, under a traditional funding rate with a recovery period of 24 hours, we would incentivize convergence between the two prices by charging, every one-hour period, the amount

$$
\frac{1}{24}\frac{\mathrm{tradePrice}-\mathrm{spotPrice}}{\mathrm{spotPrice}}=\alpha \times \dot{r}\times \frac{1}{24}
$$

In other words, one hour after a change in net exposure, if the funding rate was at zero and the scaling parameter is one, the velocity will add precisely the amount that the normal funding rate would charge. However, a dynamic funding rate will keep *increasing* until the pool is rebalanced (or its net exposure changes sign).


# Network Owned Liquidity

Reya Network is a trading-optimised network. This is made possible through a novel network-owned-liquidity design which serves a dual purpose:

1. \[Immediate Term] Providing applications on the network with liquidity
2. \[Medium Term] Acting as economic security of the network

<figure><img src="/files/AUlnXJJG8K37P5LUTncc" alt=""><figcaption></figcaption></figure>

The primary objective of the liquidity network is to create a mechanism that attracts and retains Liquidity Managers (LMs) who offer the most competitive risk-adjusted returns to Network Stakers (LPs). This acts as a liquidity backbone for ecosystem dApps that in turn bring end-users and order flow into the network discussed in more detail in the following [blog post](https://blog.reya.network/reya-network-phase-2-becoming-defis-liquidity-hub-supercharged-by-connecting-35-trillion-of-offchain-orderflow/).

It is worth noting that a Liquidity Manager can come in various different forms:

1. A passive market-making algorithm
2. An active market-maker allocating capital to enable on-Network or off-Network order flow
3. A passive optimiser across lend/borrow primitives on Reya Network

## Elixir Liquidity Manager

Following [RNIP1](https://reya-network.discourse.group/t/rnip1-the-next-step-for-network-stakers-and-an-early-insight-into-reya-network-v2/10) vote, Elixir is leveraging a share of network liquidity to acquire deUSD and sdeUSD in order to give stakers exposure to yield opportunities from a basis trade strategy. This is enabled via the following adaptations to the pool design.

Reya’s Passive Pool (which acts as a market maker on Reya Dex) is able to support two additional collateral tokens (deUSD & sdeUSD) alongside rUSD. This enables the pool to reallocate some of its rUSD holdings towards deUSD & sdeUSD at the current oracle prices and leverage them as margin in order to market make and boost liquidity available on Reya Dex.

Reya Governance will have the power to decide what percentage of Passive Pool TVL is allocated towards rUSD vs. acquiring deUSD vs. acquiring sdeUSD. Currently pool collateral holding target ratios are set to the following values:

1. rUSD target ratio = 20%.
2. deUSD target ratio = 32%
3. sdeUSD target ratio = 48%

A rebalancer bot(s) is responsible for maintaining the target ratios by exchanging rUSD, deUSD and sdeUSD at the oracle price as long as the makeup of pool holdings deviates from the target ratios beyond a deviation threshold. The deviation threshold is a buffer that is used in order to avoid frequent rebalancing events happening from day to day fluctuations in the pool make up as a result of pool deposits, withdrawals and yield accrual.

It is worth noting that the rUSD denominated value of the passive pool shares is impacted by both the PnL from passive perp market making activity on Reya Dex and changes in the price of deUSD and sdeUSD in rUSD terms. Since sdeUSD is a dollar-yield generating token which is able to capture yield from basis trading activity, reya stakers are able to get exposure to that PnL through an increase in the Passive Pool share price as a result of an increase in the sdeUSD oracle price relative to rUSD.


# Reya DEX

THE UNSTOPPABLE DEX

ReyaDEX is the flagship trading platform built on Reya Network, designed to deliver the future of on-chain trading with unmatched liquidity, performance, and capital efficiency.

### Superior Liquidity

* **Shared Network Liquidity**: All markets share the same pool, ensuring maximum liquidity availability
* **CEX Price Pegging**: Uses Stork's ultra-fast price feeds from major CEXs (Binance, OKX, ByBIT) for optimal pricing
* **Unrivalled Market Depth**: Lowest price impacts and smoothly distributed liquidity along a continuous curve
* **Reliable Execution**: Trading against the pool ensures consistent liquidity even during extreme volatility

### Exceptional Performance

* **High-Speed Infrastructure**: 100ms block times with 99.9% uptime
* **Ultra-Fresh Pricing**: Stork's 10ms data feed updates ensure the most accurate pricing on-chain
* **MEV & Front-Running Protection**: Architecture designed to eliminate front-running and minimize MEV
* **Advanced Programmatic Access**: High-quality REST API and websocket connections for sophisticated trading strategies

### Maximized Capital Efficiency

* **Unified Margin Account**: Trade both perpetuals and spot from the same margin account
* **Cross-Collateralization**: Use multiple asset types as collateral, including yield-bearing assets
* **Flash Swaps**: Swap collateral assets with deferred margin checks
* **Portfolio Cross-Margining**: Optimize capital by recognizing your portfolio holistically across DEXs
* **Intelligent Liquidations**: Secure, automated, and designed to protect trader positions

### Get Started

Ready to experience superior on-chain trading? [Trade on ReyaDEX now](https://app.reya.xyz)


# Auto-exchange and Liquidations

## Position liquidations

### My position was liquidated. Why is that?

Positions are liquidated when they are *undercollateralized*. What this means is that your margin balance went below the minimum level (the *liquidation margin requirement*, LMR) that the margin system considered safe for the exposure you were holding with that position. In other words, too little money to cover for the potential losses you could suffer.

### How can I avoid being liquidated?

For your convenience, the trading app shows the *margin ratio* of your different positions/accounts. The margin ratio is the ratio of your LMR over your margin balance:

<figure><img src="/files/IvLmlA5zY3zSZKLrBSAw" alt=""><figcaption></figcaption></figure>

* If this ratio is below 100%, it means your margin balance is bigger than your LMR, so you are not subject to liquidations.
* However, the margin ratio is constantly changing due market movements, meaning that values under but close to 100% put your account in danger and you should either reduce/close your position voluntarily, or top up your account.
* Once the margin ratio goes over 100%, you account can be liquidated.

### What exactly *is* a liquidation, anyway?

A liquidation is a forceful closure of positions to reduce or entirely stop the losses your account is accumulating, before your account becomes insolvent. This exposure, however, doesn’t just vanish — there are traders on the opposite side who expect the ‘mirror PnL’ of your position. This means the exposure needs to be transferred to someone else, who receives the position at a discount. This entire operation is handled by a special component called the *Liquidation Module*.

### In addition to the losses from closing my position, I also see money was sent in transfers. What are they for and where do they go?

Whenever an account is liquidated, in addition to having your position closed with a penalty, you will be charged *liquidations fees*. These liquidations fees are proportional to the risk that was removed from your account, and they go to two essential elements of the system: the **insurance fund**, which is a rainy day fund used (and only used) to cover insolvencies; and the **passive pool**, which works as a backstop to all liquidations whenever conditions require it.

### So, basically, liquidations just close my trades at bad prices, and then charge me for it.

Not quite. In fact, in almost all instances, liquidations are only *partial.* The liquidation module will try to close as little exposure as possible, at the least discount possible. Essentially, it tries to bring your LMR down, but just enough to get your margin balance back just below 100%. It accomplishes this by closing only one portion of exposure at a time.

This explains why you might see a series of liquidations in your transaction history: each one closed part of your exposure to bring your account back over water, until markets moved in your favor again, or you are left with no exposure.

### Actually, I can see one big liquidation at a price that is worse than any on the candle graph. And my account has no money in it. What’s up with that?

This means your account was liquidated through the ‘**backstop flow**’. Remember how we said that the passive pool acts as a backstop to liquidations? This happens when the partial liquidations fail to keep your account healthy, or the markets move very quickly against you. Due to the increased urgency in getting your account liquidated, your *entire* position is pushed directly onto the passive pool, which also takes the *entirety* of your margin balance as compensation.

The backstop flow is the last resort measure to prevent the **collateral pool** from going insolvent, guaranteeing it can make good on any profits that traders make. The backstop threshold is the margin ratio at which the backstop flow is enabled, and currently set at 125%.

### Does this mean the passive pool is making up my losses?

No. The pool only absorbs positions at a profit, that is, at a price that is favorable. This is why the backstop threshold exists: it’s a level at which the pool can still use the remaining margin balance to create a positions without immediately losing money on it.

So, if you are an LP, rest assured you are not making up any losses from traders. In particular, the passive pool will stop taking on positions as soon as an account’s funds aren’t enough to at least cover the liquidation fees. And remember, the pool gets 50% of fees of *every* liquidation, not just backstop.

### But then how does the collateral pool stay solvent if my account goes insolvent?

Depending on the circumstances, two things can happen (even both at the same time):

* There is an **insurance fund** which is a rainy day fund that is used (*and can only be used*) to make up any insolvencies resulting after a liquidation. Remember those liquidation fees? That’s what they’re used for.
* In the extreme circumstance that an account were to end up with such a large insolvency that the insurance fund could not cover it, the backstop flow would then activate *auto-deleveraging.*\*\* Essentially, as a last resort, the liquidation module will distribute the exposure of the liquidated account proportionally to every trader on the opposing side, partially closing *their* position.

This last layer of the backstop flow has never been activated, and we hope that is never needed. But it ensures that the collateral pool **always** has enough funds to cover its obligations to traders. And importantly, accomplishes this in the fairest way possible: as unpleasant as it is to have your position closed when you are profiting, *everyone* gets hit proportionally in the same way. This way, no one can ‘front run’ anyone else on the way out; and no human intervention can tip the scales in anyone’s favor.

Oh! And by the way, *Reya’s the only one DEX that can do this.* Reya is bringing performance *and confidence* to DeFi.

### What about cross-margined accounts?

Cross-margined accounts are dealt in a holistic way. This means that all positions are liquidated in the same proportion, therefore preserving any hedges that you might have in place. In other words, we take your risk management seriously.

### But wouldn’t it be better to just liquidate the losing positions?

Well… no. If you assume the market is moving directionally (e.g., tanking), then cutting off the losing positions makes sense. But what if the market bounces? Then, the previously profitable positions (which would have been left open) will start losing money when the market reverses, and the liquidated positions won’t be there to profit off the bounce.

The important thing is that we respect any risk mitigations you put in place, including hedges. Ultimately, you should make active risk management an integral part of your trading.

Stay safe out there!


# Conditional Orders

ReyaDEX supports setting a “Stop Loss” or "Take Profit" conditional order against open positions. Traders can set a Stop Loss and Take Profit price for each position. When the market price reaches this trigger price, the position is closed by executing a Market Order of the same size but in the opposite direction of the current exposure. Stop Loss or Take Profit conditional orders can be canceled by traders at any time.

Traders can edit positions without adjusting the conditional orders against that position. The Conditional orders will apply to the whole position at the time of execution. If a position is closed, then the associated conditional orders will be canceled. If a trader has Long exposure in a given market and trades short (Sell-side) such that the net exposure is short after the trade, Reya assumes the original long exposure to have been closed and clears any conditional orders.

Against a Long (Buy-side) position in a given market, traders can set a stop loss (trigger) price below the current estimated execution price. Against a Short (Sell-side) position, traders can set a Stop Loss (trigger) price above the current estimated execution price. With Take Profit orders, long positions need a trigger price above the current market (estimated execution) price and short positions need a trigger below the current price.

To ensure traders remain in control of their funds, traders must first authorize Reya to execute Conditional orders on their behalf and then generate a signature for each conditional order placed. The order will only be executed if Reya has both authorization and a valid signature. This is for the safety of the trader. Traders only need to authorise Reya once per account, but will need to generate a signature for each new conditional order (so two if setting both a stop loss and take profit) or edit or cancel of existing order.

*ReyaDEX cannot guarantee that any specific price will be achieved in connection with a conditional order. Markets in digital tokens are underdeveloped and can be volatile and illiquid. Traders should consider the risks associated with digital token markets before deciding to invest.*


# Collateral liquidations

### I less have cross-collateral than I deposited. What happened?

If your balance of collateral tokens other than rUSD was reduced, you were subject to collateral liquidation. This can happen for two reasons:

1. your rUSD balance dropped to zero, and the collateral was needed to cover further losses;
2. your account approached LMR (Liquidation Margin Requirement): your collateral is progressively converted to rUSD to prepare for liquidation procedures (not least, to fix and maximize the amount of rUSD available in your account).

### What exactly is collateral liquidation?

Collateral liquidation, also known as auto-exchange, is a forceful conversion of a token into rUSD. This conversion uses the same oracle prices as the margin balance, but:

* a **percentual penalty** is included in the price, both to disincentivize collateral mis-management, as well as reward the liquidator who ultimately takes on the price risk of the liquidated collateral;
* **liquidation fees** are also charged, as a percentage of the liquidated amount (in rUSD), towards the insurance fund.

This is similar to what happens with position liquidations. The biggest difference for collateral, everything is assessed in terms of the total amount of liquidated collateral, whereas for positions, which imply leverage, reference LMR instead.


# Settlement and cross-collateralization

### The perps on Reya DEX settle in rUSD. What does that mean?

To settle in rUSD means that all prices and PnL payments are denominated in rUSD. So, for example, if you follow the price of ETH on the Reya dApp and see it price go up from 3500rUSD to 3550rUSD, that means shorts pay longs 50rUSD. Funding payments and fees are also paid entirely in rUSD.

*A direct consequence of this is that your margin requirements are also denominated in rUSD.* Margin requirements, after all, are funds locked by the Network to ensure you have enough funds to pay for possible losses.

### Does that mean I need to hold rUSD in my account to cover my margin requirements?

Only partially so. **One of the killer features of Reya DEX is that enables&#x20;*****cross-collateralization*****:** you can hold some tokens other than rUSD in your margin account, and have them count towards your margin requirements. For example, you can cover them instead with a yield bearing collateral: (s)USDe or deUSD. This way, your collateral can earn yield while you trade.

**However, you still have to pay your losses in rUSD.** The perps, after all, still settle in rUSD! In other words, you should still keep a minimum amount of rUSD in your account, otherwise you may be subject to asset liquidation procedures\[link].

### So, my account can hold a variety of tokens, but my margin requirement is still rUSD. How does that work out?

That’s where your ***margin balance*** comes in: it’s the rUSD-denominated amount used to assess your margin coverage. It converts the value of any token into rUSD using oracle prices (using the same ultra fast Stork data feeds that the perps use), then compares the total amount to your margin requirement. The margin balance is the balance figure that you can find in the trading screen.

### Why does my margin balance show up lower than the value of the assets in my account?

Although you can cover your margin requirement with a variety of tokens other than rUSD, their value is taken into account with a *haircut*, i.e., their value is reduced by a percentage that depends on the particular token.

Haircuts cover for the risk that your tokens reduce in rUSD value by the time they are needed to cover losses. This would leave your account insolvent. You can think of the haircut as a sort of margin requirement in reverse: it’s the amount of rUSD Reya can safely credit your margin balance after taking price fluctuations and volatility into account.

If you want to know the actual value of all your collateral without haircuts, the number you are looking for is the a**ccount value** or **equity**, which you can find in your portfolio dashboard.

### If not all the collateral value is taken into account *and* it runs the risk of liquidation, why would I use cross-collateralization?

Cross-collateralization is useful for many reasons, but there are two very big use cases:

1. **accrue yield while trading:** if you deposit a yield bearing token into your margin account, that token will still be accruing yield even while you are using it to trade!
2. **boost capital efficiency and reduce liquidation risk:** for example, the PnL of an asset is (approximately) matched by the price variations of that asset. Using that asset as collateral will then minimize value fluctuations in your account, it being *market neutral* while accruing the funding rate.

*Remember that perps still settle in rUSD!* This means that the cross-collateralization can optimize your capital deployment, but you still need to carefully manage your rUSD balance to avoid collateral liquidations.


# Margin

### Margin account <a href="#margin-account" id="margin-account"></a>

A margin account is used to hold and collateralize your derivatives positions. Each margin account can only hold contracts for which sharing of PnL and/or cross-margining is enabled. For example, you will need a specific margin account to hold a position in a contract which is isolated margined.

On the other hand, each of your margin accounts enables:

1. **offsetting losses from one position with profits another**, and enabling leveraging of all portfolio profits immediately;
2. **offsetting and reducing margin requirements,** by recognizing the P\&L offset that can happen between positions.
3. **and, finally, offsetting both P\&L and margin&#x20;*****across*****&#x20;exchanges,** by aggregating all positions into a single settlement and clearing layer.

### Margin Balance <a href="#margin-balance" id="margin-balance"></a>

You margin balance are the funds, in rUSD, which you have available to satisfy your margin requirements. Profits will be credited to your margin balance, and losses will be deducted from it. You will be required to have enough rUSD funds to cover the Initial Margin Requirement of your portfolio (in a given account) when opening a new position. You must also keep enough collateral at all times to cover your Liquidation Margin Requirement to avoid being liquidated.

Thanks to Reya’s cross-collateralization features, you can deposit a variety of tokens as collateral. Those tokens will be credited to you margin balance in rUSD terms with a haircut to account for exchange risk: this means that if you deposit 1ETH which is worth 2000rUSD at market prices, you will be credited slightly less than 2000rUSD. **Your ETH will not be automatically converted to rUSD unless you trigger any of the auto-exchange conditions.**


# Reya Network

The Three Pillars of Reya Network

Reya Network liberates the application layer of DeFi by creating an autonomous, specialized and optimized infrastructure that solves for the following 3 core pillars:

<figure><img src="/files/9XTD0Q48FB9Zjd16RSk1" alt=""><figcaption></figcaption></figure>

## Liquidity

Capital staked into Reya Network is used productively to support trading via a novel passive liquidity pool mechanism. This design creates instant shared liquidity for all exchanges operating within the Reya ecosystem, enhancing market depth, lowering the barriers for market entry and enhancing users' trading experience.

But the liquidity benefits don’t stop there. With financial logic incorporated into the network design, Reya acts as a clearing protocol across exchanges. This removes liquidity fragmentation and allows liquidity to be organised as a network between exchanges.

With market makers free to share liquidity across exchanges, ecosystem growth enhances the potential trading conditions for each individual exchange. In this way, we create a flywheel of 'interoperable liquidity' for the very first time in DeFi.

## Capital Efficiency

Margin engine logic is embedded into the Reya Network itself, meaning that users have a single margin account that can be used across multiple exchanges. In many respects, this creates the first decentralised clearinghouse.

Reya Network’s margin engine logic is the most advanced in crypto, providing up to 3.5x improvements in capital efficiency for traders, and up to 6x improvements in capital efficiency for LPs. Any exchange on the Reya Network automatically inherits this logic just by operating on the network.

## Performance

Performance improvements are critical, and so we’ve made Reya Network lightning fast. With blocktimes of 100ms and throughput of up to 30,000 transactions per second, Reya Network is one of the fastest EVM rollups.

Moreover, transactions are executed on a ‘first-in-first-out’ (FIFO) basis with zero gas fees, removing front-running and harmful MEV. This functionality is built leveraging the Arbitrum Orbit tech stack. Over time, additional optimisations will be built, including the continued movement of application-specific logic into the network design itself.

The significance of performance cannot be understated - DeFi presently represents less than 5% of all crypto volume, in part because it cannot compete with the high performance and powerful user experience of CeFi venues. However, when performance improvements are combined with modularisation and blending of the underlying financial logic, we have to start asking why we can’t finally capture CeFi volume and bring it on-chain for the first time. Not only will this bring huge volume to DeFi, but it will also dramatically improve the transparency, robustness and composability for all the traders joining our DeFi ecosystem.


# The structure of Reya Network

Right now, Reya Network is composed of two layers.

<figure><img src="/files/jHIww7KP9nTfOr1u51Vf" alt=""><figcaption></figcaption></figure>

## **The chain layer**

This layer optimises the speed and throughput of the network, alongside addressing some important issues on generalisable chains such as front-running and harmful MEV. This layer is powered by Arbitrum Orbit and can achieve 100ms blocktimes and up to 30,000 transactions per second - making it one of the fastest EVM rollups around.

The chain operates with transactions ordered on a FIFO basis - a critical UX improvement for a network optimised for trading. This also removes the ability to front-run and takes away the opportunity for harmful MEV to occur. Overtime, more of the application specific logic associated with trading will be moved into the block-building process itself, driving further improvements to the network.

## **The protocol layer**

The protocol layer directly tackles the vertical integration of DeFi applications by breaking the chain into modular components to support trading, such as PnL settlements, margin requirements, liquidations. It directly provides the components which trading applications can deploy.

This layer is itself composed of multiple parts. Let’s understand each of them in turn:

### **Financial Layer**

This is the cornerstone layer that makes holding value, settling payments and trading in a capital efficient manner possible on Reya Network. Importantly, the architecture is open, allowing other exchanges to integrate into the network too.

Reya Network’s architecture has two main modules:

* **Derivatives Clearing Protocol**: this is a decentralised, non-custodial clearing protocol that provides the financial logic for calculating margin requirements, facilitating liquidations and enabling P\&L attribution. The margin system within the protocol is advanced, enabling cross-collateralisation of tokens different to the settlement token, along with full portfolio cross-margining. This means trading and providing liquidity is highly capital efficient. For example, ETH-BTC perp trading can be over 350% more capital efficient than on other networks.
* **Stablecoin Protocol**: trades on Reya Network can settle in any governance-approved asset. However, the majority of markets will settle in rUSD, a stablecoin that is native to Reya Network. This allows for neutral settlement between users bridging from different chains. It will also enable the implementation of a payments clearing protocol to help facilitate settlement, as well as a savings protocol that will make it attractive to not just trade in rUSD, but to hold wealth in it, ensuring rUSD transcends from payments settlement into a long-term store of value.

### **A Liquidity Layer**

A Passive-LP Pool is embedded into the network. This leverages Reya Network’s ability to generate price indices to create contracts at an index. In the first instance external indices will be used, allowing traders to get exposure at a well defined index with reduced execution risk. The mechanism is built on the derivatives clearing logic, and therefore inherits the same features — making it highly capital efficient for passive LPs. This mechanism also acts as the ultimate liquidity backstop of the system and boosts the liquidity of any exchange operating on Reya Network.

### **Governance**

Reya Network will decentralise, ensuring the network isn’t controlled by any single entity and providing transparency and trust through to the end users of the system. Trust and transparency also improves the composability of the network giving other exchanges confidence they can operate on the network, too. In turn this will help accelerate adoption of Reya Network and further deepen liquidity for end users.


# Who's Behind Reya Network

Reya Labs, the creator of Reya Network, is run by a team of DeFi OGs with multiple successful start-ups launched in the past, including Voltz Protocol, which grew to over $30B of notional traded within just 12 months.

We are backed by some of the best names in the industry and have raised almost $10M from VCs, including Framework, Coinbase and Wintermute.

Alongside this, we’re supported by an incredible community! Many of our community members have been with us through our previous projects, and now help drive product development and accelerate the adoption of Reya Network.

<figure><img src="https://lh7-us.googleusercontent.com/zdVeiQXUByvipWGF9WCXJUXx2jhkR9mVaR1wD19C5m6IK22DQtIrARwewDZcfT-G8zYQ_QcYzBy_yZk7qKNDzoKrMvpIJ_c69gAkA8elL8k0MfGQQLxktf_LFp8BOGAmJByKa_EOMf8JqWQ-p-X0QWE" alt=""><figcaption></figcaption></figure>


# Introduction

ReyaChain is the next iteration of Reya - designed to provide millisecond-level trading speed, whilst inhereting Ethereum's security. We achieve this by being the first ever trading-specific based rollup. You can find the technical details here: <https://x.com/0xSimonJones/status/1944737748381839671>

Today, Reya uses a forked and heavily customised version of Arbitrum Orbit. The infrastructure upgrade - as Reya transitions from an optimistic rollup to a based rollup - will happen in stages without any impact to trading.


# Context

## Building Ethereum’s execution layer

Settlement and execution are very distinct components of financial trading, each with its own specific challenges as well as security requirements. Because of this, monolithic L1s that try to satisfy both functions force false trade-offs that ultimately limit the growth and development of a truly decentralized financial system. These false trade-offs fall into the general ‘performance vs decentralization’ theme.

At Reya, we strongly believe that the future of decentralized finance passes through Ethereum. Ethereum is unparalleled in terms of the security and decentralization assurances it offers as a settlement layer. Furthermore, it has benefited from the wide participation of contributors in various areas of expertise, resulting in a flexible and cutting-edge roadmap that incentivizes innovation across all areas of DeFi and crypto in general.

Based rollups have been an important recent development. Rollups are key components in scaling Ethereum’s. They precisely offer the possibility of a divide-and-conquer approach to application/execution and settlement. However, L2s in their current form risk being centralized systems that aren’t credibly neutral and reliable long-term. This is the problem that based rollups tackle head-on: they allow for true expansion of Ethereum’s capabilities while inheriting its security and decentralization guarantees.

[Based rollups—superpowers from L1 sequencing - Layer 2 - Ethereum Research](https://ethresear.ch/t/based-rollups-superpowers-from-l1-sequencing/15016)

By being a based-rollup, Reya will specifically become an execution layer tailored to the microstructural properties of financial trading, bringing execution to unparalleled performance levels while still providing traders with full Ethereum assurances on their capital.

<figure><img src="/files/zsorCNYZPrioBUzbAgRr" alt=""><figcaption></figcaption></figure>

In a based-rollup, Ethereum L1 validators ultimately control transaction ordering. By anchoring sequencing to validators who restake ETH, Reya strengthens liveness and censorship resistance versus single‑sequencer designs while keeping the system tightly aligned with Ethereum.

Ethereum validators can operate or delegate to high-performance nodes under a lookahead schedule that maps L1 slots to execution node identities, providing predictable and sticky leadership windows. Transactions follow two key confirmation levels: pre‑confirmed (execution receipt issued) and finalized (batched to L1).

The rotating execution nodes process trades and issue millisecond pre-confirmations. They run Reya’s rust-based trading engine, which is cross-compiled into zero-knowledge circuits enabling asynchronous proof generation and independent stateless validation of state transitions.

Orders and executions have different bandwidth needs, motivating Reya to adopt a hybrid data availability (DA) setup where account state updates are published to Ethereum using EIP‑4844 blobs, while high‑throughput order data leverages a specialized external DA provider.

Execution misbehavior is deterred via slashing and provable discrepancies between signed pre‑confirmations and on‑chain data. Notably, Ethereum validators will also face penalties if the execution node they delegated to is slashed.


# Token Design

## Objectives

The REYA token is embedded into the broader Reya architecture in order to satisfy the following objectives:<br>

1. **Network security**: secure the network through sustainable incentive structures for the network of operators required to run Reya Execution Nodes
2. **Fuel economic activity**: align the activity of the Reya Protocol with REYA and ETH holders
3. **Accountable, Ethereum‑native governance**: ensure sREYA holders receive additional benefits within Reya DEX alongside governance rights<br>

In the following sections, we go deeper into mechanisms and flows that implement these objectives.


# Network Security and Economic Incentives

Reya’s security model anchors sequencing to Ethereum and uses the REYA token to align incentives for the mechanisms that keep the network live and neutral:

1. The Insurance Fund serves as a risk buffer to maintain protocol solvency
2. The Assistance Fund (AF) serves as the policy module for REYA and ETH buybacks
3. sReya holders stake REYA to delegate execution rights to execution node operators
4. Ethereum validators re-stake ETH to delegate sequencing to execution node operators

<figure><img src="/files/SRApHbhLM6skSly6S1ph" alt=""><figcaption></figcaption></figure>

**Insurance fund** serves as a risk reserve to maintain protocol solvency during adverse market conditions, with governance-defined rules for deployment and replenishment priorities. It is also capitalised through a governance-set allocation from trading fees, liquidation fees, and RLP staking yield.

**Assistance Fund (AF)** receives a governance set allocation from trading fees, liquidation fees, and yield generated by RLP. The AF executes open-market purchases targeting an 80% REYA, 20% ETH split by mark-to-market value at the time of purchase. In this setup, governance is responsible for defining the execution cadence and safeguards around the buybacks (e.g. TWAP windows). Governance is also responsible for deciding when the AF should start receiving fees, with the option to keep sharing fees with front-ends and RLP to accelerate growth in the early stages of Reya.

**REYA stakers** stake REYA on Ethereum mainnet, thereby delegating execution responsibilities to an execution node operator of their choice. They are incentivised through:

* REYA distributions
* Trading fee discounts
* Governance rights proportional to their stake
* The ability to use sREYA as trading collateral, in the medium term

It is important to note that the REYA stakers earn yield in REYA terms, and their realized yield is a function of network activity as well as the TVL of the staking contract.

Ethereum validators need to re-stake their ETH to delegate sequencing to execution node operators according to the based lookahead schedule governing the execution node rotation. They are incentivised through:

* REYA distributions

Correlated penalties between Reya stakers and Ethereum validators are defined and enforced on Ethereum, reinforcing careful operator selection and neutral, reliable sequencing.

This design grounds Reya’s security directly to Ethereum while ensuring that value created through trading and RLP staking flows back into the Reya ecosystem.


# Monetary Policy

Reya’s has a fixed supply model of 8 Billion tokens. Initially, network participants are incentivized through Reya distributions. However, once all the supply is in circulation, new Reya tokens may only be minted should a corresponding number of tokens be burnt. These burnt tokens will come from the Assistance Fund, ensuring the fixed supply is maintained.


# Governance

Reya is governed by sREYA holders. Through this process, governance sets the policies and parameters that keep the network safe, neutral, and sustainable, while remaining transparent and predictable for participants. Specifically, its scope includes the Insurance Fund policy, Assistance Fund policy, issuance schedules, trading fee parameters and risk parameter settings. In addition, governance configures the rollup slashing rules.


# sREYA Additional Utility

Beyond the benefits described above, sREYA has a growing set of use cases for everyday participants on Reya. Staking REYA to mint sREYA can lower trading costs for those on Premium Accounts, through a tiered fee schedule, with tiers determined by the amount staked. In the medium-term, sREYA will also be recognized as collateral for trading on Reya, meaning positions backed by sREYA follow the same liquidation framework as other collateral types.


# Allocation & Release Schedule

Allocation of the token supply is as important as the token design. Incentivising and rewarding those who actively use and run the protocol is critical for long-term success. Most important within this is the community of traders, builders and liquidity providers who make up the Reya Community; and the tokenomics allocations are designed to reflect this.

<figure><img src="/files/Voakg6e696Q45qmJpaiq" alt=""><figcaption></figcaption></figure>

Distribution will start at the TGE, through an airdrop to Reya users. Multiple subsequent airdrops are then planned, with precise timing and allocation to be decided by governance and the Reya Foundation. Reya Labs team and investors are locked for 1 year, highlighting their commitment to build long-term, with linear monthly vesting for 3 years after.

<figure><img src="/files/BiXD29jdezlKjq3gzEHK" alt=""><figcaption></figcaption></figure>

<br>


# Reya Chain Points: FAQs

## Core RCP Mechanics

#### What are Reya Chain Points?

Reya Chain Points (RCP) are the points system used to track meaningful contributions to ReyaChain across trading, staking, and community actions. They serve as the basis for distributing ownership in the network through the future airdrop.

#### How many RCP are there?

ReyaChain Points have a fixed weekly supply. The supply will change slightly each week across the three actions of trading, staking and signal, particularly as trading activity grows. However, trading actions are generally the most rewarded given traders pay fees and take risk.

#### How often are RCP distributed?

RCP is distributed weekly based on your activity across trading, staking, and signal. You’ll see your new points allocation each week, even if you didn’t earn any that cycle.

#### Is RCP transferable or tradable?

No. RCP is non-transferable and not tradable. It’s designed purely to measure and reward contribution to the network.

#### Is there a leaderboard for RCP?

Yes. The public leaderboard allows anyone to track their standing across all three tracks and see the top 20 RCP earners per week and in total.

## How to Earn RCP

#### What actions earn me RCP?

You can earn RCP through three tracks:

* Trading: Trade any supported market on Reya
* Staking: Convert rUSD into srUSD and hold it in your margin account or external third party applications for additional rewards
* Signal: Contribute high-signal content or code that helps grow Reya — think trading tools, smart threads, or helping bring new whales onboard

#### How is RCP weighted between Trading, Staking, and Signal?

Trading carries the highest risk and rightly earns the highest weight, followed by staking. Signal is discretionary and designed to reward outsized contributions that drive real value to the ecosystem.

#### Is Trading the most heavily weighted activity?

Yes. Trading is the primary engine of the protocol and traders carry the most risk, so it earns the majority of weekly points. The actions rewarded are generally focused on volume and open interest. But will vary week on week.

#### How do referrals impact RCP?

You earn 10% of the RCP earned by any wallet you refer. This doesn’t take anything away from them — it’s a bonus to you. You will also earn 10% of their trading fees, and the user you refer will enjoy a 10% discount in trading fees for themselves too. It’s a win-win.

#### Can I earn RCP without trading or staking?

Yes — through Signal. If you’re helping Reya grow through code, content, or connections, you can earn RCP. We recognise there are broader contributions than capital alone.

#### What happens if I stake and then unstake? Do I lose future RCP eligibility?

If you unstake before the weekly snapshot, you won’t earn staking RCP for that week. Staked balances need to be in place at the time of snapshot to count.

## Product Design and Transparency

#### How do you ensure fairness in RCP distribution?

RCP is calculated based on actual impact — trading activity, staking balance, and meaningful community contributions. The system is designed to reward real engagement, not vanity metrics. Weekly distributions mean it’s always up to date and reflects recent effort.

#### What stops people from sybil attacking RCP?

We actively monitor for sybil behavior and can exclude ineligible wallets from RCP rewards. The system also requires effort over time not just one-off actions making it costly to exploit. Alongside this, we will instruct a sybil analytics team to remove those suspected of sybil farming in advance of the community airdrop. This ensures more rewards go to real users.

<br>


# Introduction

The Native Stablecoin of Reya Network

**rUSD is wrapped USDC and will be renamed as USDC to avoid confusion.**

**srUSD** is the the liquidity provisioning token native to Reya's design. You can stake your rUSD and earn superior yield from providing liquidity to the DEX.


# srUSD

## What is rUSD staking?

**The power of diversification**

**On-chain liquidity provision mechanisms are generally siloed and application specific. Reya’s unified liquidity model makes it possible for capital to be allocated in a diversified manner, improving its risk profile orders of magnitude over what you can find elsewhere in DeFi.**

#### **Shared liquidity**

Reya introduced a model of unified liquidity which allows LP capital to be dynamically allocated to the best opportunity. The AMM model, in particular, relies on a single pool of capital to provide liquidity across all markets, while safely weighing them according to their risk profile. This allows it to provide superior depth, with use cases as a DeFi internalized ‘hedging venue’ with CEX-like execution.

#### **Bridging DeFi and CeFi**

Reya introduced a Liquidity Manager framework, through which Network Liquidity is allocated for different uses through smart contracts or partners. Institutional partners Amber Group and Selini Capital joined efforts with Reya to showcase how this can unlock superior returns for LPs, while also being ‘weaponized’ for Network growth.

### Current Managers

Liquidity Managers can be both on-chain protocols or active institutional managers. Their allocation of assets is subject to a clear mandate, although it includes some discretionarity.

### **Allocations**

### Reya’s risk-adjusted returns outperform market benchmarks

Liquidity Managers broadly provide two types of strategy: market neutral ones through cash & carry trades and/or cross-exchange arbitrages; and liquidity provisioning ones (currently, Reya’s AMM supports perp trading on Reya DEX).

#### **Consistently High Returns with minimal drawdowns**

The POC of the unified liquidity framework has proven itself not only resilient, but thriving amid the extreme volatility since its roll out in early December 2024. **Averaging a 10.45% APY, it has had only 6 negative days, with APY over negative days averaging only -0.99% (or a -0.27bp drawdown).**

### Risks associated with rUSD staking

All financial products carry a certain degree of risk, and even low risk investment strategies contain an element of uncertainty. Different instruments involve different levels of exposure to risk and you should be aware of the risks associated with each of these instruments. The information contained in this brochure is a general description of the risks associated with the specific products or services which we may provide to you. You should not rely on the highlighted risks as being the only risks in relation to the product or service. You should always satisfy yourself that a product or service is suitable for you in light of your financial circumstances and that you fully understand the nature and risk associated with that product or service. Any risks highlighted are not to be relied upon as investment advice or a personal recommendation.

#### **Market risk**

Staked rUSD is exposed to market risk, due to the movement of token prices.

* Funding rates are not necessarily positive. Prolonged periods of negative rates would pose a risk to the staked capital. Among other criteria, Reya selects the tokens for this strategy so as to minimize the risk of such episodes.
* While the AMM nets out exposure as the trading flow oscillates between the different sides, it still holds some exposure and market movements may cause losses to the capital. The trading fees compensate for this possibility, as well as the mechanism design which shifts incentives as needed to rebalance the pool.

#### **Smart contract risk**

Staked rUSD is works through smart contracts on Reya Network. Reya smart contracts undergo a rigorous development process with both internal and external audits, however any smart contract has specific risks associated with possible loopholes or bugs in their logic.

A full list of audits can be found at: <https://docs.reya.xyz/technical-docs/audits>

#### **Counterparty risk**

Staked rUSD is subject to counterparty risk in two main respects:

* Funds are apportioned among the Liquidity Managers (Selini and Amber), and therefore their management and solvency might affect the staked rUSD. The delegation of funds to Liquidity Managers is done through legal agreements ensure the segregation of staked rUSD funds from their general capital, and, where possible, manage the allocation of capital through on-chain custodial solutions (in particular, CEFU and Fordefi) to ensure the safety of the funds.
* The strategies employed in staked rUSD imply trades on centralized exchanges, and therefore are subject to counterparty risk of those exchanges. Extreme insolvency of the exchanges could impact the funds locked as margin.

#### **Exchange risk**

All settlement amounts on Reya Network are denominated in rUSD, which is a wrapped version of USDC. This means that capital is at risk in the event of a USDC de-peg v USD.

## Using srUSD to trade

Whenever you stake rUSD, your deposit is *tokenized*. In other words, you receive a new token — srUSD — which represents your deposit. The conversion between these two tokens depends on the price of srUSD, which changes over time according to the returns of Network Liquidity. So if Network Liquidity has a 1% return, then srUSD becomes 1% more expensive; conversely, if Network Liquidity suffers a 1% loss, then srUSD will be 1% cheaper.

<figure><img src="/files/xxfrHrfTdBYc0BnCJl08" alt=""><figcaption></figcaption></figure>

You cannot trade your srUSD, because it is for now non-transferrable. But you *can* use your srUSD as collateral for trading by moving it to your margin accounts. The margin engine will recognize these tokens and count them towards your margin balance (denominated in rUSD) using the srUSD price *with a haircut*. What this means is that not all the value of your srUSD counts towards the margin balance because of the price risk of srUSD; instead, a small percentage, e.g. 10%, is ignored, and only the rest is counted towards the margin balance. So, in the following example, while your account has a total asset value of 202 rUSD, you can only lock up to 190.90 rUSd as margin for your trading.

<figure><img src="/files/f0CqzTiGxN2MeV9hODeV" alt=""><figcaption></figcaption></figure>

Whenever you use any non-rUSD collateral, you need to be mindful of the fact that PnL still settles in rUSD. What this means is that all your profits will be delivered in rUSD, *and so will your losses be paid out.* So, if you suffer losses but you do not have any actual rUSD to cover them, the liquidation engine will forcefully sell a portion of your collateral at a discount.

Given how closely integrated srUSD is with the Network, for srUSD this discount is set to zero. Using a flash swap functionality (which allows for swaps of assets with deferred IM checks), the cross-collateralization system goes and redeems srUSD for the underlying rUSD whenever needed.

You can learn more about cross-collateralization and collateral liquidations [`here`](https://docs.reya.xyz/reya-products/reyadex/trading-on-reya-dex/auto-exchange-and-liquidations).


# FAQs

### **srUSD: How-To Guide & FAQ**

**srUSD** is a yield-bearing stablecoin on **ReyaChain** that lets you earn passive yield while using the same capital to trade.

#### **How to Mint srUSD**

1. **Access the Platform:** Navigate to [app.reya.xyz](http://app.reya.xyz/).
2. **Connect Your Wallet:** Ensure your wallet is connected and set to ReyaChain.
3. **Deposit USDC:** Transfer USDC into your account.
4. **Mint srUSD:** Use the deposited USDC to mint srUSD directly through the platform.
5. **Ready to Use:** Your srUSD is now earning yield and can be utilized as trading margin.

#### **Understanding srUSD Yield**

* **Yield Generation:** srUSD holders earn yield derived from protocol fees within the Reya ecosystem, including trading and funding fees. Alongside yield generated by Reya’s unique “Liquidity Manager” model
* **Automatic Accrual:** Yield accrues automatically; there is no need for staking or manual claiming.
* **Stable Balance:** While your srUSD balance remains constant, its value appreciates through the accrued yield.

#### **Utilizing srUSD**

* **Trading on Reya DEX:** Use srUSD as margin for trading perpetual futures on Reya DEX.
* **Cross-Margin Support:** srUSD supports cross-margining, allowing a single balance to back multiple positions.
* **Liquidity Provision:** Provide liquidity within the Reya ecosystem using srUSD.

#### **Key Benefits**

* **Dual Functionality:** srUSD combines yield generation with trading utility.
* **Capital Efficiency:** Maximize the utility of your assets by earning yield while maintaining trading capability.
* **Seamless Integration:** srUSD is designed to work natively within the Reya ecosystem, ensuring smooth operations.

### Multi-Account Safety: How Margin Accounts Work

Reya supports **multiple margin accounts**, each siloed from one another.

So if you're holding srUSD in **Account A** and trading with leverage in **Account B**, your balance in **Account A is NOT at risk** from trades made in B.

**Only the srUSD in the margin account you trade from is exposed to PnL.**

This gives you more control over risk and capital allocation.

### ❓ **FAQ**

**Q: What’s the difference between rUSD and srUSD?**

rUSD is used for LP staking and earning protocol rewards.

srUSD is a **yield-bearing stablecoin** designed for trading and margin use.

**Q: Can I convert srUSD back to rUSD?**

Yes. You can redeem srUSD back into **rUSD** at any time via the dApp.

**Q: Do I need to move srUSD to a special account to earn yield?**

No. Yield accrues automatically—just by holding srUSD in your wallet or account.

**Q: Has srUSD been audited?**

Yes. srUSD has been fully audited as part of Reya’s security framework.

**Q: Are there RCP incentives for using srUSD?**

Currently, RCP accrues at the standard rate. Additional boosts are available if you hold srUSD in your margin account.

**Q: Is srUSD available outside of ReyaChain?**

Not yet. srUSD is native to ReyaChain and integrated into its ecosystem.


# Reya DEX REST API v2

**Base URL**: `https://api.reya.xyz/v2`

## Overview

The Reya DEX REST API v2 provides programmatic access to the Reya Perpetual Exchange, enabling traders to interact with the platform algorithmically. This API is designed for developers and professional traders who want to build automated trading systems, integrate with existing platforms, or develop custom interfaces for the Reya DEX ecosystem.

## Key Features

* **Market Data**: Access comprehensive market information, including asset definitions, market summaries, and real-time price data
* **Order Management**: Create, cancel, and monitor orders with support for various order types (limit, trigger)
* **Position Tracking**: Monitor your current positions and historical executions
* **Wallet Integration**: Manage wallet configurations and access wallet-specific data
* **Price Data**: Access historical price data with customizable time intervals through candle endpoints

## API Structure

The API is organized into several logical sections:

* **Reference Data**: Discover markets and assets definitions, trading fees
* **Market Data**: Access real-time and historical market data, including prices, candles and order execution
* **Wallet Data**: Get information about the wallet's accounts, positions and orders
* **Order Entry**: Create and cancel orders

## Signatures

For private endpoints that access user-specific data or perform actions on behalf of a user, authentication is required through wallet signatures. This ensures that only authorized users can create and update orders.

## Rate Limits

To ensure fair usage and optimal performance, the API implements rate limiting. For more information, see the [Rate Limits ](/technical-docs/reya-dex-rest-api-v2/rate-limits)documentation.

For real-time data needs, consider using our [WebSocket Market Data API](https://github.com/Reya-Labs/reya-docs/blob/main/developers/websocket-api-reference.md) for streaming updates. To place and cancel orders over a persistent connection, see the [WebSocket Order Entry API](https://github.com/Reya-Labs/reya-docs/blob/main/developers/ws-exec-api-reference.md).


# Specs

OpenAPI and AsyncAPI specs

## Get OpenAPI specification

> Returns the complete OpenAPI specification for this API in YAML format

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Specs","description":"OpenAPI and AsyncAPI specs"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/openapi-spec.yaml":{"get":{"summary":"Get OpenAPI specification","description":"Returns the complete OpenAPI specification for this API in YAML format","operationId":"getOpenApiSpec","tags":["Specs"],"responses":{"200":{"description":"OpenAPI specification in YAML format","content":{"application/yaml":{"schema":{"type":"string","format":"binary"}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"responses":{"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}},"schemas":{"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## Get AsyncAPI specification

> Returns the complete AsyncAPI specification for WebSocket API in YAML format

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Specs","description":"OpenAPI and AsyncAPI specs"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/asyncapi-spec.yaml":{"get":{"summary":"Get AsyncAPI specification","description":"Returns the complete AsyncAPI specification for WebSocket API in YAML format","operationId":"getAsyncApiSpec","tags":["Specs"],"responses":{"200":{"description":"AsyncAPI specification in YAML format","content":{"application/yaml":{"schema":{"type":"string","format":"binary"}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"responses":{"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}},"schemas":{"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```


# Reference Data

Market definitions, global parameters, liquidity parameters, etc.

## Get market definitions

> Deprecated: use \`/perpMarketDefinitions\` instead. This un-prefixed route still works but will be removed once integrators have migrated to the \`perp\*\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/marketDefinitions":{"get":{"summary":"Get market definitions","description":"Deprecated: use `/perpMarketDefinitions` instead. This un-prefixed route still works but will be removed once integrators have migrated to the `perp*` naming.","operationId":"getMarketDefinitions","deprecated":true,"tags":["Reference Data"],"responses":{"200":{"description":"List of market definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketDefinition":{"title":"MarketDefinition","$id":"#MarketDefinition","type":"object","required":["symbol","marketId","minOrderQty","qtyStepSize","tickSize","liquidationMarginParameter","initialMarginParameter","maxLeverage","oiCap"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each market, only needed to generate signatures"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"},"liquidationMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered to avoid liquidation procedures for a given market; below this value, your account is subject to liquidation procedures. When cross margining, all requirements across markets are covered by the same balance, and all positions are subject to liquidations."},"initialMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered post trade; if the account does not satisfy this requirement, trades will not get executed."},"maxLeverage":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maximum leverage allowed"},"oiCap":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Maximum one-sided open interest in units for a given market."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp market definitions

> Alias of \`/marketDefinitions\`, mirroring the \`/spotMarketDefinitions\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/perpMarketDefinitions":{"get":{"summary":"Get perp market definitions","description":"Alias of `/marketDefinitions`, mirroring the `/spotMarketDefinitions` naming.","operationId":"getPerpMarketDefinitions","tags":["Reference Data"],"responses":{"200":{"description":"List of perp market definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketDefinition":{"title":"MarketDefinition","$id":"#MarketDefinition","type":"object","required":["symbol","marketId","minOrderQty","qtyStepSize","tickSize","liquidationMarginParameter","initialMarginParameter","maxLeverage","oiCap"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each market, only needed to generate signatures"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"},"liquidationMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered to avoid liquidation procedures for a given market; below this value, your account is subject to liquidation procedures. When cross margining, all requirements across markets are covered by the same balance, and all positions are subject to liquidations."},"initialMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered post trade; if the account does not satisfy this requirement, trades will not get executed."},"maxLeverage":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maximum leverage allowed"},"oiCap":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Maximum one-sided open interest in units for a given market."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /spotMarketDefinitions

> Get spot market definitions

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/spotMarketDefinitions":{"get":{"summary":"Get spot market definitions","operationId":"getSpotMarketDefinitions","tags":["Reference Data"],"responses":{"200":{"description":"List of spot market definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SpotMarketDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"SpotMarketDefinition":{"title":"SpotMarketDefinition","$id":"#SpotMarketDefinition","type":"object","required":["symbol","marketId","baseAsset","quoteAsset","minOrderQty","qtyStepSize","tickSize"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each spot market"},"baseAsset":{"type":"string","description":"Base asset symbol"},"quoteAsset":{"type":"string","description":"Quote asset symbol"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum order quantity (base asset)"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment (base asset)"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /assetDefinitions

> Get asset definitions

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/assetDefinitions":{"get":{"summary":"Get asset definitions","operationId":"getAssetDefinitions","tags":["Reference Data"],"responses":{"200":{"description":"List of asset definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"AssetDefinition":{"title":"AssetDefinition","$id":"#AssetDefinition","type":"object","required":["asset","priceHaircut","liquidationDiscount","status","decimals","displayDecimals"],"properties":{"asset":{"$ref":"#/components/schemas/Asset"},"spotMarketSymbol":{"$ref":"#/components/schemas/Symbol"},"priceHaircut":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Notional discount to the value of a collateral when used to satisfy the margin requirements; it does not imply any token conversion, but is rather an accounting adjustment."},"liquidationDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Discount in the token price when liquidating collateral."},"status":{"type":"string","enum":["ENABLED","WITHDRAWAL_ONLY"],"description":"Status of asset (ENABLED = deposits and withdrawals allowed, WITHDRAWAL_ONLY = only withdrawals allowed)"},"decimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places for record keeping amounts of this asset (e.g. 18 for ETH, 6 for RUSD)"},"displayDecimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places shown for display purposes in frontends"}},"additionalProperties":true},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /liquidityParameters

> Get liquidity parameters

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/liquidityParameters":{"get":{"summary":"Get liquidity parameters","operationId":"getLiquidityParameters","tags":["Reference Data"],"responses":{"200":{"description":"List of liquidity parameters","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/LiquidityParameters"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"LiquidityParameters":{"title":"LiquidityParameters","$id":"#LiquidityParameters","type":"object","required":["symbol","depth","velocityMultiplier"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"depth":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the liquidity distribution along the AMM pricing curve, in particular expanding or contracting the max exposure parameter that would otherwise be determined by the capital available."},"velocityMultiplier":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the sensitivity of the dynamic funding rate to the size of the imbalances; higher multiplier means that the funding rate will diverge faster, all else being equal."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /globalFeeParameters

> Get global fee parameters

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/globalFeeParameters":{"get":{"summary":"Get global fee parameters","operationId":"getGlobalFeeParameters","tags":["Reference Data"],"responses":{"200":{"description":"Global fee parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GlobalFeeParameters"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"GlobalFeeParameters":{"title":"GlobalFeeParameters","$id":"#GlobalFeeParameters","type":"object","required":["ogDiscount","refereeDiscount","referrerRebate","affiliateReferrerRebate"],"properties":{"ogDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"OG user discount"},"refereeDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referee discount"},"referrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referrer rebate"},"affiliateReferrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Affiliate referrer rebate"}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /feeTiers

> Get fee tiers

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/feeTiers":{"get":{"summary":"Get fee tiers","operationId":"getFeeTierParameters","tags":["Reference Data"],"responses":{"200":{"description":"List of fee tier parameters","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/FeeTierParameters"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"FeeTierParameters":{"title":"FeeTierParameters","$id":"#FeeTierParameters","type":"object","required":["tierId","takerFee","makerFee","volume14d","tierType"],"properties":{"tierId":{"$ref":"#/components/schemas/UnsignedInteger"},"takerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Taker fee rate (fee will be qty * takerFee)"},"makerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Maker fee rate (fee will be qty * makerFee)"},"volume14d":{"$ref":"#/components/schemas/UnsignedDecimal","description":"14-day volume level required this fee tier to be applied to a wallet"},"tierType":{"$ref":"#/components/schemas/TierType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"TierType":{"title":"TierType","$id":"#TierType","type":"string","enum":["REGULAR","VIP"],"description":"Fee tier type (REGULAR = Standard tier, VIP = VIP tier)"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Market Data

Prices, market-level trades, depth, candles, etc.

## Get spot market summaries

> Statistics and throttled market data for all spot markets. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/spotMarkets/summary":{"get":{"summary":"Get spot market summaries","description":"Statistics and throttled market data for all spot markets. Recalculated every 0.5s","operationId":"getSpotMarketsSummary","tags":["Market Data"],"responses":{"200":{"description":"List of spot market summaries","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SpotMarketSummary"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"SpotMarketSummary":{"title":"SpotMarketSummary","$id":"#SpotMarketSummary","type":"object","required":["symbol","updatedAt","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the spot market summary was last calculated (milliseconds)"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal","description":"24-hour trading volume in USD"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal","description":"Absolute 24-hour price change"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Current oracle price"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get spot market summary

> Statistics and throttled market data for a specific spot market. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/spotMarket/{symbol}/summary":{"get":{"summary":"Get spot market summary","description":"Statistics and throttled market data for a specific spot market. Recalculated every 0.5s","operationId":"getSpotMarketSummary","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Spot market summary data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotMarketSummary"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SpotMarketSummary":{"title":"SpotMarketSummary","$id":"#SpotMarketSummary","type":"object","required":["symbol","updatedAt","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the spot market summary was last calculated (milliseconds)"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal","description":"24-hour trading volume in USD"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal","description":"Absolute 24-hour price change"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Current oracle price"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get market summaries

> Deprecated: use \`/perpMarkets/summary\` instead. Statistics and throttled market data for all markets. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the \`perp\*\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/markets/summary":{"get":{"summary":"Get market summaries","description":"Deprecated: use `/perpMarkets/summary` instead. Statistics and throttled market data for all markets. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the `perp*` naming.","operationId":"getMarketsSummary","deprecated":true,"tags":["Market Data"],"responses":{"200":{"description":"List of market summaries","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketSummary"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp market summaries

> Alias of \`/markets/summary\`, mirroring the \`/spotMarkets/summary\` naming. Statistics and throttled market data for all perp markets. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/perpMarkets/summary":{"get":{"summary":"Get perp market summaries","description":"Alias of `/markets/summary`, mirroring the `/spotMarkets/summary` naming. Statistics and throttled market data for all perp markets. Recalculated every 0.5s","operationId":"getPerpMarketsSummary","tags":["Market Data"],"responses":{"200":{"description":"List of perp market summaries","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketSummary"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get market summary

> Deprecated: use \`/perpMarket/{symbol}/summary\` instead. Statistics and throttled data for a specific market. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the \`perp\*\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/summary":{"get":{"summary":"Get market summary","description":"Deprecated: use `/perpMarket/{symbol}/summary` instead. Statistics and throttled data for a specific market. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the `perp*` naming.","operationId":"getMarketSummary","deprecated":true,"tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Market summary","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketSummary"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp market summary

> Alias of \`/market/{symbol}/summary\`, mirroring the \`/spotMarket/{symbol}/summary\` naming. Statistics and throttled data for a specific perp market. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/perpMarket/{symbol}/summary":{"get":{"summary":"Get perp market summary","description":"Alias of `/market/{symbol}/summary`, mirroring the `/spotMarket/{symbol}/summary` naming. Statistics and throttled data for a specific perp market. Recalculated every 0.5s","operationId":"getPerpMarketSummary","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Market summary","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketSummary"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /prices

> Get all prices

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/prices":{"get":{"summary":"Get all prices","operationId":"getPrices","tags":["Market Data"],"responses":{"200":{"description":"List of prices","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Price"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"Price":{"title":"Price","$id":"#Price","type":"object","required":["symbol","updatedAt","oraclePrice"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Price given by the Stork feeds, used both as the peg price for prices on Reya, as well as Mark Prices. The Stork price feed is usually the perp prices across three major CEXs"},"poolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"The price currently quoted by the AMM for zero volume, from which trades are priced (equivalent to mid price in an order book); a trade of any size will be move this price up or down depending on the direction."},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /prices/{symbol}

> Get price by symbol

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/prices/{symbol}":{"get":{"summary":"Get price by symbol","operationId":"getPrice","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Price information","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Price"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Price":{"title":"Price","$id":"#Price","type":"object","required":["symbol","updatedAt","oraclePrice"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Price given by the Stork feeds, used both as the peg price for prices on Reya, as well as Mark Prices. The Stork price feed is usually the perp prices across three major CEXs"},"poolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"The price currently quoted by the AMM for zero volume, from which trades are priced (equivalent to mid price in an order book); a trade of any size will be move this price up or down depending on the direction."},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp executions for market

> Returns up to 100 perp executions for a given market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/perpExecutions":{"get":{"summary":"Get perp executions for market","description":"Returns up to 100 perp executions for a given market.","operationId":"getMarketPerpExecutions","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"},{"$ref":"#/components/parameters/ExecutionTypeParam"}],"responses":{"200":{"description":"List of perp executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PerpExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"ExecutionTypeParam":{"name":"type","in":"query","required":false,"description":"Filter perp executions by type. Omit to return executions of all types.","schema":{"type":"string","enum":["ORDER_MATCH","LIQUIDATION"]}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"PerpExecutionList":{"title":"PerpExecutionList","$id":"#PerpExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PerpExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get market depth snapshot

> Returns an L2 order book snapshot with aggregated price levels for the specified market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/depth":{"get":{"summary":"Get market depth snapshot","description":"Returns an L2 order book snapshot with aggregated price levels for the specified market.","operationId":"getMarketDepth","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Depth snapshot","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Depth"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Depth":{"title":"Depth","$id":"#Depth","type":"object","required":["symbol","type","bids","asks","updatedAt"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"type":{"$ref":"#/components/schemas/DepthType"},"bids":{"type":"array","description":"Bid side levels aggregated by price, sorted descending by price","items":{"$ref":"#/components/schemas/Level"}},"asks":{"type":"array","description":"Ask side levels aggregated by price, sorted ascending by price","items":{"$ref":"#/components/schemas/Level"}},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Snapshot generation timestamp (milliseconds)"}},"additionalProperties":true},"DepthType":{"title":"DepthType","$id":"#DepthType","type":"string","enum":["SNAPSHOT","UPDATE"],"description":"Depth message type (SNAPSHOT = full book, UPDATE = single level change)"},"Level":{"title":"Level","$id":"#Level","type":"object","required":["px","qty"],"properties":{"px":{"$ref":"#/components/schemas/SignedDecimal","description":"Price level"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Aggregated quantity at this price level"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get spot executions for market

> Returns up to 100 spot executions for a given market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/spotExecutions":{"get":{"summary":"Get spot executions for market","description":"Returns up to 100 spot executions for a given market.","operationId":"getMarketSpotExecutions","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionList":{"title":"SpotExecutionList","$id":"#SpotExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get spot execution busts for market

> Returns up to 100 spot execution busts (failed spot fills) for a given market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/spotExecutionBusts":{"get":{"summary":"Get spot execution busts for market","description":"Returns up to 100 spot execution busts (failed spot fills) for a given market.","operationId":"getMarketSpotExecutionBusts","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot execution busts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionBustList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionBustList":{"title":"SpotExecutionBustList","$id":"#SpotExecutionBustList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecutionBust"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get historical candles

> Returns up to 200 candles for a given market, sorted by time in descending order, and ending at the specified end time.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/candleHistory/{symbol}/{resolution}":{"get":{"summary":"Get historical candles","description":"Returns up to 200 candles for a given market, sorted by time in descending order, and ending at the specified end time.","operationId":"getCandles","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/ResolutionParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"Historical candle data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CandleHistoryData"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"ResolutionParam":{"name":"resolution","in":"path","required":true,"description":"Candle resolution","schema":{"type":"string","enum":["1m","5m","15m","30m","1h","4h","1d"]}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"CandleHistoryData":{"title":"CandleHistoryData","$id":"#CandleHistoryData","type":"object","required":["t","o","h","l","c"],"properties":{"t":{"type":"array","items":{"$ref":"#/components/schemas/UnsignedInteger"},"description":"Array of timestamps (seconds)"},"o":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of opening prices"},"h":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of high prices"},"l":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of low prices"},"c":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of closing prices"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Wallet Data

Accounts, positions, trades, etc.

## GET /wallet/{address}/accounts

> Get wallet accounts

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/accounts":{"get":{"summary":"Get wallet accounts","operationId":"getWalletAccounts","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of accounts","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Account"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"Account":{"title":"Account","$id":"#Account","type":"object","required":["accountId","name","type"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"name":{"type":"string"},"type":{"$ref":"#/components/schemas/AccountType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"AccountType":{"title":"AccountType","$id":"#AccountType","type":"string","enum":["MAINPERP","SUBPERP","SPOT"],"description":"SPOT = account that can only trade spot, MAINPERP = main perp account, SUBPERP = sub perp account"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet spot execution busts

> Returns up to 100 spot execution busts (failed spot fills) for a given wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/spotExecutionBusts":{"get":{"summary":"Get wallet spot execution busts","description":"Returns up to 100 spot execution busts (failed spot fills) for a given wallet.","operationId":"getWalletSpotExecutionBusts","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot execution busts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionBustList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionBustList":{"title":"SpotExecutionBustList","$id":"#SpotExecutionBustList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecutionBust"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet perp executions

> Returns up to 100 perp executions for a given wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/perpExecutions":{"get":{"summary":"Get wallet perp executions","description":"Returns up to 100 perp executions for a given wallet.","operationId":"getWalletPerpExecutions","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"},{"$ref":"#/components/parameters/ExecutionTypeParam"}],"responses":{"200":{"description":"List of perpetual executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PerpExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"ExecutionTypeParam":{"name":"type","in":"query","required":false,"description":"Filter perp executions by type. Omit to return executions of all types.","schema":{"type":"string","enum":["ORDER_MATCH","LIQUIDATION"]}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"PerpExecutionList":{"title":"PerpExecutionList","$id":"#PerpExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PerpExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet spot executions

> Returns up to 100 spot executions for a given wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/spotExecutions":{"get":{"summary":"Get wallet spot executions","description":"Returns up to 100 spot executions for a given wallet.","operationId":"getWalletSpotExecutions","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionList":{"title":"SpotExecutionList","$id":"#SpotExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /wallet/{address}/positions

> Get wallet positions

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/positions":{"get":{"summary":"Get wallet positions","operationId":"getWalletPositions","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of positions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Position"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"Position":{"title":"Position","$id":"#Position","type":"object","required":["exchangeId","symbol","accountId","qty","side","avgEntryPrice","avgEntryFundingValue","lastTradeSequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"avgEntryPrice":{"$ref":"#/components/schemas/SignedDecimal"},"avgEntryFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Average of funding values at the entry times of currently open exposure, which serves as a baseline from which to compute the accrued funding in the position: units x (fundingValue - avgEntryFundingValue)"},"lastTradeSequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Sequence number of last execution taken into account for the position."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet account balances

> Returns all account real balances for a wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/accountBalances":{"get":{"summary":"Get wallet account balances","description":"Returns all account real balances for a wallet.","operationId":"getWalletAccountBalances","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of account balances","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AccountBalance"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"AccountBalance":{"title":"AccountBalance","$id":"#AccountBalance","type":"object","required":["accountId","asset","realBalance","balanceDEPRECATED"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"asset":{"$ref":"#/components/schemas/Asset"},"realBalance":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals) and realized pnl from closed positions. Realized pnl only applies to RUSD given it is the only settlement asset"},"balanceDEPRECATED":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals). This field is deprecated and will be removed in a future release"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet open orders

> Returns all pending orders for a wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/openOrders":{"get":{"summary":"Get wallet open orders","description":"Returns all pending orders for a wallet.","operationId":"getWalletOpenOrders","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of open orders","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Order"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"Order":{"title":"Order","$id":"#Order","type":"object","required":["exchangeId","symbol","accountId","orderId","side","limitPx","orderType","status","createdAt","lastUpdateAt"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"orderId":{"type":"string"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this update represents. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. For a taker update, the first fill of its matching round; for a maker update, its single fill. Present only on fill updates; absent for non-fill updates and resting-order snapshots."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this update represents — the length of the contiguous nonce range starting at firstFillId. For a taker update, the fills produced in its matching round; for a maker update, 1. Present only on fill updates; absent otherwise (so it is >= 1 whenever present)."},"side":{"$ref":"#/components/schemas/Side"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Price at which TP/SL orders will be triggered, should not be set for other order types."},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"status":{"$ref":"#/components/schemas/OrderStatus"},"createdAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Creation timestamp (milliseconds)"},"lastUpdateAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet configuration

> Returns trading configuration for a wallet

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/configuration":{"get":{"summary":"Get wallet configuration","description":"Returns trading configuration for a wallet","operationId":"getWalletConfiguration","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"Wallet configuration","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WalletConfiguration"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"WalletConfiguration":{"title":"WalletConfiguration","$id":"#WalletConfiguration","type":"object","required":["feeTierId","ogStatus","affiliateStatus","refereeStatus"],"properties":{"feeTierId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Fee tier identifier"},"ogStatus":{"type":"boolean","description":"OG status"},"affiliateStatus":{"type":"boolean","description":"Affiliate status"},"refereeStatus":{"type":"boolean","description":"Referee status"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Order Entry

Order entry operations

## Create order

> Create a new order (IOC, GTC, SL, TP)

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Order Entry","description":"Order entry operations"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/createOrder":{"post":{"summary":"Create order","description":"Create a new order (IOC, GTC, SL, TP)","operationId":"createOrder","tags":["Order Entry"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderRequest"}}}},"responses":{"200":{"description":"Order creation response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"CreateOrderRequest":{"title":"CreateOrderRequest","$id":"#CreateOrderRequest","type":"object","required":["exchangeId","accountId","isBuy","limitPx","orderType","signature","nonce","signerWallet"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"isBuy":{"type":"boolean","description":"Whether this is a buy order"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Trigger price, only for TP/SL orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"Order nonce, see signatures and nonces section for more details."},"signerWallet":{"$ref":"#/components/schemas/Address"},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for PERP IOC orders and all SPOT orders). In seconds since epoch. The order will only be filled before this timestamp."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. Optional field that allows clients to assign their own unique identifier to orders."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"CreateOrderResponse":{"title":"CreateOrderResponse","$id":"#CreateOrderResponse","type":"object","required":["status"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"orderId":{"type":"string","description":"Created order ID (currently generated for all order types except IOC)"},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID echoed back from the request"},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this order produced on entry. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. Absent if the order did not fill on entry. For a non-IOC (resting) taker, the same first nonce also appears on the order's taker update in the orderChanges channel; an IOC taker is not published to orderChanges, so this response is the only place its fill range is delivered."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this order produced on entry — the length of the contiguous nonce range starting at firstFillId. Absent if the order did not fill on entry (so it is >= 1 whenever present)."}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Cancel order

> Cancel an existing order

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Order Entry","description":"Order entry operations"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/cancelOrder":{"post":{"summary":"Cancel order","description":"Cancel an existing order","operationId":"cancelOrder","tags":["Order Entry"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderRequest"}}}},"responses":{"200":{"description":"Order cancellation response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"CancelOrderRequest":{"title":"CancelOrderRequest","$id":"#CancelOrderRequest","type":"object","required":["signature"],"properties":{"orderId":{"type":"string","description":"Internal matching engine order ID to cancel. At least one of `orderId` or `clientOrderId` must be provided; if both are supplied the server treats `orderId` as the canonical identifier and `clientOrderId` is ignored. For spot markets, this is the order ID returned in the CreateOrderResponse."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. At least one of `orderId` or `clientOrderId` must be provided; `clientOrderId` is consulted only when `orderId` is absent. This is the same clientOrderId provided in CreateOrderRequest."},"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID that owns the order. Required for spot markets."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Market symbol for the order.Required for spot market orders. If not provided, assumes perp market for backwards compatibility."},"signature":{"type":"string","description":"See signatures section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details. Compulsory for spot orders."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for SPOT orders). In seconds since epoch."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"CancelOrderResponse":{"title":"CancelOrderResponse","$id":"#CancelOrderResponse","type":"object","required":["status","orderId"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"orderId":{"type":"string","description":"Cancelled order ID"},"clientOrderId":{"type":"integer","description":"Client-provided order ID echoed back from the request"}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Cancel all orders

> Cancel all orders matching the specified filters (mass cancel)

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Order Entry","description":"Order entry operations"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/cancelAll":{"post":{"summary":"Cancel all orders","description":"Cancel all orders matching the specified filters (mass cancel)","operationId":"cancelAll","tags":["Order Entry"],"requestBody":{"required":false,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MassCancelRequest"}}}},"responses":{"200":{"description":"Mass cancel response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MassCancelResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MassCancelRequest":{"title":"MassCancelRequest","$id":"#MassCancelRequest","type":"object","required":["signature","nonce","accountId","expiresAfter"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID to cancel orders for."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Symbol to cancel orders for. If not specified, cancels orders for all symbols."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp. In seconds since epoch."}},"additionalProperties":true,"description":"Request to cancel all orders matching the specified filters"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"MassCancelResponse":{"title":"MassCancelResponse","$id":"#MassCancelResponse","type":"object","required":["cancelledCount"],"properties":{"cancelledCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of orders that were cancelled"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Models

## The RequestError object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The ServerError object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The MarketDefinition object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MarketDefinition":{"title":"MarketDefinition","$id":"#MarketDefinition","type":"object","required":["symbol","marketId","minOrderQty","qtyStepSize","tickSize","liquidationMarginParameter","initialMarginParameter","maxLeverage","oiCap"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each market, only needed to generate signatures"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"},"liquidationMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered to avoid liquidation procedures for a given market; below this value, your account is subject to liquidation procedures. When cross margining, all requirements across markets are covered by the same balance, and all positions are subject to liquidations."},"initialMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered post trade; if the account does not satisfy this requirement, trades will not get executed."},"maxLeverage":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maximum leverage allowed"},"oiCap":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Maximum one-sided open interest in units for a given market."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The SpotMarketDefinition object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotMarketDefinition":{"title":"SpotMarketDefinition","$id":"#SpotMarketDefinition","type":"object","required":["symbol","marketId","baseAsset","quoteAsset","minOrderQty","qtyStepSize","tickSize"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each spot market"},"baseAsset":{"type":"string","description":"Base asset symbol"},"quoteAsset":{"type":"string","description":"Quote asset symbol"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum order quantity (base asset)"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment (base asset)"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The AssetDefinition object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"AssetDefinition":{"title":"AssetDefinition","$id":"#AssetDefinition","type":"object","required":["asset","priceHaircut","liquidationDiscount","status","decimals","displayDecimals"],"properties":{"asset":{"$ref":"#/components/schemas/Asset"},"spotMarketSymbol":{"$ref":"#/components/schemas/Symbol"},"priceHaircut":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Notional discount to the value of a collateral when used to satisfy the margin requirements; it does not imply any token conversion, but is rather an accounting adjustment."},"liquidationDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Discount in the token price when liquidating collateral."},"status":{"type":"string","enum":["ENABLED","WITHDRAWAL_ONLY"],"description":"Status of asset (ENABLED = deposits and withdrawals allowed, WITHDRAWAL_ONLY = only withdrawals allowed)"},"decimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places for record keeping amounts of this asset (e.g. 18 for ETH, 6 for RUSD)"},"displayDecimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places shown for display purposes in frontends"}},"additionalProperties":true},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The FeeTierParameters object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"FeeTierParameters":{"title":"FeeTierParameters","$id":"#FeeTierParameters","type":"object","required":["tierId","takerFee","makerFee","volume14d","tierType"],"properties":{"tierId":{"$ref":"#/components/schemas/UnsignedInteger"},"takerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Taker fee rate (fee will be qty * takerFee)"},"makerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Maker fee rate (fee will be qty * makerFee)"},"volume14d":{"$ref":"#/components/schemas/UnsignedDecimal","description":"14-day volume level required this fee tier to be applied to a wallet"},"tierType":{"$ref":"#/components/schemas/TierType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"TierType":{"title":"TierType","$id":"#TierType","type":"string","enum":["REGULAR","VIP"],"description":"Fee tier type (REGULAR = Standard tier, VIP = VIP tier)"}}}}
```

## The GlobalFeeParameters object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"GlobalFeeParameters":{"title":"GlobalFeeParameters","$id":"#GlobalFeeParameters","type":"object","required":["ogDiscount","refereeDiscount","referrerRebate","affiliateReferrerRebate"],"properties":{"ogDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"OG user discount"},"refereeDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referee discount"},"referrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referrer rebate"},"affiliateReferrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Affiliate referrer rebate"}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The LiquidityParameters object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"LiquidityParameters":{"title":"LiquidityParameters","$id":"#LiquidityParameters","type":"object","required":["symbol","depth","velocityMultiplier"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"depth":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the liquidity distribution along the AMM pricing curve, in particular expanding or contracting the max exposure parameter that would otherwise be determined by the capital available."},"velocityMultiplier":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the sensitivity of the dynamic funding rate to the size of the imbalances; higher multiplier means that the funding rate will diverge faster, all else being equal."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The WalletConfiguration object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"WalletConfiguration":{"title":"WalletConfiguration","$id":"#WalletConfiguration","type":"object","required":["feeTierId","ogStatus","affiliateStatus","refereeStatus"],"properties":{"feeTierId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Fee tier identifier"},"ogStatus":{"type":"boolean","description":"OG status"},"affiliateStatus":{"type":"boolean","description":"Affiliate status"},"refereeStatus":{"type":"boolean","description":"Referee status"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The MarketSummary object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The SpotMarketSummary object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotMarketSummary":{"title":"SpotMarketSummary","$id":"#SpotMarketSummary","type":"object","required":["symbol","updatedAt","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the spot market summary was last calculated (milliseconds)"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal","description":"24-hour trading volume in USD"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal","description":"Absolute 24-hour price change"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Current oracle price"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Position object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Position":{"title":"Position","$id":"#Position","type":"object","required":["exchangeId","symbol","accountId","qty","side","avgEntryPrice","avgEntryFundingValue","lastTradeSequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"avgEntryPrice":{"$ref":"#/components/schemas/SignedDecimal"},"avgEntryFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Average of funding values at the entry times of currently open exposure, which serves as a baseline from which to compute the accrued funding in the position: units x (fundingValue - avgEntryFundingValue)"},"lastTradeSequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Sequence number of last execution taken into account for the position."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Order object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Order":{"title":"Order","$id":"#Order","type":"object","required":["exchangeId","symbol","accountId","orderId","side","limitPx","orderType","status","createdAt","lastUpdateAt"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"orderId":{"type":"string"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this update represents. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. For a taker update, the first fill of its matching round; for a maker update, its single fill. Present only on fill updates; absent for non-fill updates and resting-order snapshots."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this update represents — the length of the contiguous nonce range starting at firstFillId. For a taker update, the fills produced in its matching round; for a maker update, 1. Present only on fill updates; absent otherwise (so it is >= 1 whenever present)."},"side":{"$ref":"#/components/schemas/Side"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Price at which TP/SL orders will be triggered, should not be set for other order types."},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"status":{"$ref":"#/components/schemas/OrderStatus"},"createdAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Creation timestamp (milliseconds)"},"lastUpdateAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"}}}}
```

## The Account object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Account":{"title":"Account","$id":"#Account","type":"object","required":["accountId","name","type"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"name":{"type":"string"},"type":{"$ref":"#/components/schemas/AccountType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"AccountType":{"title":"AccountType","$id":"#AccountType","type":"string","enum":["MAINPERP","SUBPERP","SPOT"],"description":"SPOT = account that can only trade spot, MAINPERP = main perp account, SUBPERP = sub perp account"}}}}
```

## The AccountBalance object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"AccountBalance":{"title":"AccountBalance","$id":"#AccountBalance","type":"object","required":["accountId","asset","realBalance","balanceDEPRECATED"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"asset":{"$ref":"#/components/schemas/Asset"},"realBalance":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals) and realized pnl from closed positions. Realized pnl only applies to RUSD given it is the only settlement asset"},"balanceDEPRECATED":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals). This field is deprecated and will be removed in a future release"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The PerpExecutionList object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"PerpExecutionList":{"title":"PerpExecutionList","$id":"#PerpExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PerpExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true}}}}
```

## The SpotExecutionList object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecutionList":{"title":"SpotExecutionList","$id":"#SpotExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true}}}}
```

## The SpotExecutionBustList object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecutionBustList":{"title":"SpotExecutionBustList","$id":"#SpotExecutionBustList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecutionBust"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true}}}}
```

## The Price object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Price":{"title":"Price","$id":"#Price","type":"object","required":["symbol","updatedAt","oraclePrice"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Price given by the Stork feeds, used both as the peg price for prices on Reya, as well as Mark Prices. The Stork price feed is usually the perp prices across three major CEXs"},"poolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"The price currently quoted by the AMM for zero volume, from which trades are priced (equivalent to mid price in an order book); a trade of any size will be move this price up or down depending on the direction."},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The CandleHistoryData object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CandleHistoryData":{"title":"CandleHistoryData","$id":"#CandleHistoryData","type":"object","required":["t","o","h","l","c"],"properties":{"t":{"type":"array","items":{"$ref":"#/components/schemas/UnsignedInteger"},"description":"Array of timestamps (seconds)"},"o":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of opening prices"},"h":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of high prices"},"l":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of low prices"},"c":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of closing prices"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The CreateOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CreateOrderRequest":{"title":"CreateOrderRequest","$id":"#CreateOrderRequest","type":"object","required":["exchangeId","accountId","isBuy","limitPx","orderType","signature","nonce","signerWallet"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"isBuy":{"type":"boolean","description":"Whether this is a buy order"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Trigger price, only for TP/SL orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"Order nonce, see signatures and nonces section for more details."},"signerWallet":{"$ref":"#/components/schemas/Address"},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for PERP IOC orders and all SPOT orders). In seconds since epoch. The order will only be filled before this timestamp."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. Optional field that allows clients to assign their own unique identifier to orders."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}}}
```

## The CreateOrderResponse object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CreateOrderResponse":{"title":"CreateOrderResponse","$id":"#CreateOrderResponse","type":"object","required":["status"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"orderId":{"type":"string","description":"Created order ID (currently generated for all order types except IOC)"},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID echoed back from the request"},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this order produced on entry. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. Absent if the order did not fill on entry. For a non-IOC (resting) taker, the same first nonce also appears on the order's taker update in the orderChanges channel; an IOC taker is not published to orderChanges, so this response is the only place its fill range is delivered."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this order produced on entry — the length of the contiguous nonce range starting at firstFillId. Absent if the order did not fill on entry (so it is >= 1 whenever present)."}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The CancelOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CancelOrderRequest":{"title":"CancelOrderRequest","$id":"#CancelOrderRequest","type":"object","required":["signature"],"properties":{"orderId":{"type":"string","description":"Internal matching engine order ID to cancel. At least one of `orderId` or `clientOrderId` must be provided; if both are supplied the server treats `orderId` as the canonical identifier and `clientOrderId` is ignored. For spot markets, this is the order ID returned in the CreateOrderResponse."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. At least one of `orderId` or `clientOrderId` must be provided; `clientOrderId` is consulted only when `orderId` is absent. This is the same clientOrderId provided in CreateOrderRequest."},"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID that owns the order. Required for spot markets."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Market symbol for the order.Required for spot market orders. If not provided, assumes perp market for backwards compatibility."},"signature":{"type":"string","description":"See signatures section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details. Compulsory for spot orders."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for SPOT orders). In seconds since epoch."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"}}}}
```

## The CancelOrderResponse object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CancelOrderResponse":{"title":"CancelOrderResponse","$id":"#CancelOrderResponse","type":"object","required":["status","orderId"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"orderId":{"type":"string","description":"Cancelled order ID"},"clientOrderId":{"type":"integer","description":"Client-provided order ID echoed back from the request"}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"}}}}
```

## The MassCancelRequest object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MassCancelRequest":{"title":"MassCancelRequest","$id":"#MassCancelRequest","type":"object","required":["signature","nonce","accountId","expiresAfter"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID to cancel orders for."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Symbol to cancel orders for. If not specified, cancels orders for all symbols."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp. In seconds since epoch."}},"additionalProperties":true,"description":"Request to cancel all orders matching the specified filters"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"}}}}
```

## The MassCancelResponse object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MassCancelResponse":{"title":"MassCancelResponse","$id":"#MassCancelResponse","type":"object","required":["cancelledCount"],"properties":{"cancelledCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of orders that were cancelled"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The Depth object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Depth":{"title":"Depth","$id":"#Depth","type":"object","required":["symbol","type","bids","asks","updatedAt"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"type":{"$ref":"#/components/schemas/DepthType"},"bids":{"type":"array","description":"Bid side levels aggregated by price, sorted descending by price","items":{"$ref":"#/components/schemas/Level"}},"asks":{"type":"array","description":"Ask side levels aggregated by price, sorted ascending by price","items":{"$ref":"#/components/schemas/Level"}},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Snapshot generation timestamp (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"DepthType":{"title":"DepthType","$id":"#DepthType","type":"string","enum":["SNAPSHOT","UPDATE"],"description":"Depth message type (SNAPSHOT = full book, UPDATE = single level change)"},"Level":{"title":"Level","$id":"#Level","type":"object","required":["px","qty"],"properties":{"px":{"$ref":"#/components/schemas/SignedDecimal","description":"Price level"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Aggregated quantity at this price level"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The ServerErrorCode object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The Symbol object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"}}}}
```

## The UnsignedInteger object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The UnsignedDecimal object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The RequestErrorCode object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The SignedDecimal object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Asset object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"}}}}
```

## The TierType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"TierType":{"title":"TierType","$id":"#TierType","type":"string","enum":["REGULAR","VIP"],"description":"Fee tier type (REGULAR = Standard tier, VIP = VIP tier)"}}}}
```

## The Side object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"}}}}
```

## The ExecutionType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"}}}}
```

## The PerpExecution object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"}}}}
```

## The PaginationMeta object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The DepthType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"DepthType":{"title":"DepthType","$id":"#DepthType","type":"string","enum":["SNAPSHOT","UPDATE"],"description":"Depth message type (SNAPSHOT = full book, UPDATE = single level change)"}}}}
```

## The Level object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Level":{"title":"Level","$id":"#Level","type":"object","required":["px","qty"],"properties":{"px":{"$ref":"#/components/schemas/SignedDecimal","description":"Price level"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Aggregated quantity at this price level"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The SpotExecution object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"}}}}
```

## The SpotExecutionBust object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Address object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}}}
```

## The AccountType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"AccountType":{"title":"AccountType","$id":"#AccountType","type":"string","enum":["MAINPERP","SUBPERP","SPOT"],"description":"SPOT = account that can only trade spot, MAINPERP = main perp account, SUBPERP = sub perp account"}}}}
```

## The OrderType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"}}}}
```

## The TimeInForce object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"}}}}
```

## The OrderStatus object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"}}}}
```


# Rate Limits

To ensure fair usage and maintain optimal performance for all users, the Reya API implements rate limiting. The enforced rate limits are the following:

* **1,000 requests** per 60-second window per IP address/API key
* Rate limit counters reset at the end of each 60-second window

### Important Notes

* You can consume your entire quota at any point within the window (for example, all 1,000 requests in the first second)
* Once the limit is reached, additional requests will be rejected with a `429 Too Many Requests` status code until the current window expires
* Rate limits apply across all API endpoints collectively, not per endpoint

For most real-time data needs, we recommend using our [WebSocket Market Data API](https://github.com/Reya-Labs/reya-docs/blob/main/developers/websocket-api-reference.md) instead of polling the REST API. For order entry, the [WebSocket Order Entry API](https://github.com/Reya-Labs/reya-docs/blob/main/developers/ws-exec-api-reference.md) lets you place and cancel orders over a persistent connection with id-correlated responses.

If your application requires higher rate limits, please contact the Reya team. The team will review your request and determine if higher limits can be granted based on your specific needs and usage patterns.


# Signatures and Nonces

Signatures are required to safely execute orders in the name of your wallet. The API endpoints for order creation require a user signature that must be created on the client side using your private key. These signatures are validated on-chain for all order details you specified to ensure no unintended action is executed on your account. Internal nonces for your wallet address, tracked in the smart contracts, are used to prevent replay attacks.

## Nonces

The internal nonces are different from Ethereum wallet nonce. These are instead tracked in Reya DEX's smart contracts under unordered `uint256` values. Nonces are generated based on a combination of account ID, market ID, and timestamp, which ensures uniqueness for each action.

### Nonce Generation

The Python SDK provides a method to generate nonces automatically:

```python
def create_orders_gateway_nonce(self, account_id: int, market_id: int, timestamp_ms: int) -> int:
    """Create a nonce for Orders Gateway orders."""
    # Validate the input ranges
    if market_id < 0 or market_id >= 2**32:
        raise ValueError("marketId is out of range")
    if account_id < 0 or account_id >= 2**128:
        raise ValueError("accountId is out of range")
    if timestamp_ms < 0 or timestamp_ms >= 2**64:
        raise ValueError("timestamp is out of range")

    hash_uint256 = (account_id << 98) | (timestamp_ms << 32) | market_id

    return hash_uint256
```

This function takes three parameters:

* `account_id`: Your account ID on Reya DEX
* `market_id`: The ID of the market for the order. This is required and is an alternative for the symbol used in the API. To get the market ID for a symbol, use the endpoint: <https://api.reya.xyz/v2/marketDefinitions>
* `timestamp_ms`: Current timestamp in milliseconds, which ensures the nonce is unique even if other parameters are reused

### On-Chain Nonce Validation

When an order with a signature is submitted, the on-chain smart contracts verify that the nonce has not been used before. Once a signature with a specific nonce successfully executes a transaction, that nonce is marked as "used" in the contract. Any subsequent attempt to use the same nonce will fail, preventing replay attacks.

With the pattern of using millisecond timestamps as part of the nonce generation, there should be sufficient for no overlaps in normal usage. Each nonce is unique to the specific combination of account, market, and timestamp. This format is recommended but can be modified if the use-case requires it.

## Signatures

For order creation, Reya DEX requires a signature from the account owner to confirm the intended order details match what is received by the contracts at execution. This is to prevent any unintended action from being executed on your account.

Reya DEX uses the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard for structured data signing. This standard provides a secure way to sign typed structured data, making it more readable and secure compared to raw message signing.

The Python SDK offers a good [example](https://github.com/Reya-Labs/reya-python-sdk/blob/main/sdk/reya_rest_api/auth/signatures.py) of what values are required to be signed and how signatures are generated.

### Domain Structure

The following is the domain required as part of the EIP-712 structure:

```python
domain = {
    "name": "Reya", 
    "version": "1", 
    "verifyingContract": self.config.default_orders_gateway_address
}
```

### Type Definitions for Order Creation

Order creation uses the following type structure:

```python
types = {
    "ConditionalOrder": [
        {"name": "verifyingChainId", "type": "uint256"},
        {"name": "deadline", "type": "uint256"},
        {"name": "order", "type": "ConditionalOrderDetails"},
    ],
    "ConditionalOrderDetails": [
        {"name": "accountId", "type": "uint128"},
        {"name": "marketId", "type": "uint128"},
        {"name": "exchangeId", "type": "uint128"},
        {"name": "counterpartyAccountIds", "type": "uint128[]"},
        {"name": "orderType", "type": "uint8"},
        {"name": "inputs", "type": "bytes"},
        {"name": "signer", "type": "address"},
        {"name": "nonce", "type": "uint256"},
    ],
}
```

### Order Type Inputs Encoding

The `inputs` field in the order structure requires different encoding based on the order type:

1. **Limit Order**:

   ```
   int256 base, uint256 limitPrice
   ```
2. **Trigger Order**:

   ```
   bool is_buy, uint256 trigger_price, uint256 limit_price
   ```

The inputs for each action need to be encoded into bytes and are different for each order type. The SDK handles this encoding along with the message signature.

## Cancelling signatures

Similar to creation, cancelling \[[`https://api.reya.xyz/v2/cancelOrder`](https://api.reya.xyz/v2/cancelOrder)] an open order requires a signature. This is not EIP712, but a simple signed message:

```python
 cancel_message = {
            "orderId": your_order_id,
            "status": "cancelled",
            "actionType": "changeStatus",
 }
```

The Python SDK provides a nice [example](https://github.com/Reya-Labs/reya-python-sdk/blob/276357727261e540dd34fcb01a71a8e190c0ecf6/sdk/reya_rest_api/auth/signatures.py#L171) of how to create this signature.


# Contract Functions

Documenting the key external functions of the Reya smart contracts.

Reya Protocol is separated into 3 main components:

* Core - the margin engine contract which imposes margin requirements and coordinates liquidations, manages margin accounts and their collateral holdings
* Passive Perp Instrument - manages perpetual future markets, pricing of market orders executed against the passive pool, matching as well as keeping track of account exposures and PnLs in available markets
* Passive Pool - liquidity pool which allows anyone to stake rUSD and get pool shares in return (currently pool shares are not available as tokens, but are rather just trackers in the contract). The share price of the pool is dependent on its PnL and fees from trades executed against passive perp traders.


# Core

The margin engine contract which imposes margin requirements and coordinates liquidations, manages margin accounts and their collateral holdings

#### createAccount <a href="#createaccount" id="createaccount"></a>

```
function createAccount(address accountOwner) external returns (uint128 accountId);
```

Creates a margin account for the given address, returns its id. An address can have multiple margin accounts in order to separate exposure and margin.

#### activateFirstMarketForAccount <a href="#activatefirstmarketforaccount" id="activatefirstmarketforaccount"></a>

```
function activateFirstMarketForAccount(uint128 accountId, uint128 marketId) external;
```

This function is used to register an account to a collateral pool. In order to trade or to be a liquidator, the account needs to be registered to a collateral pool. This is set implicitly for trading but not for liquidations.

#### getUsdNodeMarginInfo <a href="#getusdnodemargininfo" id="getusdnodemargininfo"></a>

```
function getUsdNodeMarginInfo(uint128 accountId) external view returns (MarginInfo memory);
```

<details>

<summary>MarginInfo</summary>

Copy

```
struct MarginInfo {
    /// The collateral token for which the information below is defined
    address collateral;
    /// These are all amounts that are available to contribute to cover margin requirements.
    int256 marginBalance;
    /// The real balance is the balance that is in ‘cash’, that is, actually held in the settlement
    /// collateral and not as value of an instrument which settles in that collateral
    int256 realBalance;
    /// Difference between margin balance and initial margin requirement
    int256 initialDelta;
    /// Difference between margin balance and maintenance margin requirement
    int256 maintenanceDelta;
    /// Difference between margin balance and liquidation margin requirement
    int256 liquidationDelta;
    /// Difference between margin balance and dutch margin requirement
    int256 dutchDelta;
    /// Difference between margin balance and adl margin requirement
    int256 adlDelta;
    /// Difference between margin balance and initial buffer margin requirement (for backstop lps)
    int256 initialBufferDelta;
    /// Information required to compute health of position in the context of adl liquidations
    uint256 liquidationMarginRequirement;
}
```

</details>

Get the margin requirements and collateral balance for the entire account denoted in USD terms with 18 decimals precision. This means the balance in different collaterals is aggregated and the current exchange rate is used (with a small risk haircut applied). The real balance represents the net balance (deposits and withdrawals) plus the realised PnL, while the margin balance also includes the unrealised PnL. The delta represents the distance until the respective risk/liquidation threshold is hit (represented in USD as well). The liquidation margin requirement is the threshold for liquidation. If the margin balance depreciates under this value, the account will be liquidated.

#### getNodeMarginInfo <a href="#getnodemargininfo" id="getnodemargininfo"></a>

```
function getNodeMarginInfo(uint128 accountId, address collateral) external view returns (MarginInfo memory);
```

This function returns the same values as the `getUsdNodeMarginInfo` when the collateral is rUSD.

#### getTokenMarginInfo <a href="#gettokenmargininfo" id="gettokenmargininfo"></a>

```
function getTokenMarginInfo(uint128 accountId, address collateral) external view returns (MarginInfo memory);
```

This function returns the margin information in the given token with its respective decimal precision. Passing rUSD as collateral would result in the same value as getNodeMarginInfo if the account does not have margin in other tokens (e.g. sUSDe). If the account has margin in other tokens, it will aggregate the net margin and return the same values as `getUsdNodeMarginInfo`. When passing sUSDe as collateral, it will return only net balances and zero deltas and margin requirements as this token is not a quote token and accounts cannot carry exposure in it.

#### getCollateralInfo <a href="#getcollateralinfo" id="getcollateralinfo"></a>

```
function getCollateralInfo(uint128 accountId, address collateral) external view returns (CollateralInfo memory);
```

<details>

<summary>CollateralInfo</summary>

Copy

```
struct CollateralInfo {
    /// The account's collateral balance
    int256 netDeposits;
    /// These are all amounts that are available to contribute to cover margin requirements.
    int256 marginBalance;
    /// The real balance is the balance that is in ‘cash’, that is, actually held in the settlement
    /// collateral and not as value of an instrument which settles in that collateral
    int256 realBalance;
}
```

</details>

Get the collateral information of an account. The net deposits track only the in-and-out movements of the collateral, including deposits, withdrawals, fees paid. The real balance is the net plus the realised PnL gained from the markets exposure. This represents the amount that can be withdrawn and is also used to determine the liquidation status of this account. The margin balance also includes the unrealised PnL, which is not permitted for withdraw.

#### getActiveMarketsPerQuoteCollateral <a href="#getactivemarketsperquotecollateral" id="getactivemarketsperquotecollateral"></a>

```
function getActiveMarketsPerQuoteCollateral(uint128 accountId, address quoteCollateral) external view returns (uint128[] memory);
```

Returns the list of market IDs where the account is exposed. Note, rUSD is the only quote used so far.

#### triggerAutoExchange <a href="#triggerautoexchange" id="triggerautoexchange"></a>

```
function triggerAutoExchange(TriggerAutoExchangeInput memory input) external returns (AutoExchangeAmounts memory);
```

<details>

<summary>TriggerAutoExchangeInput</summary>

Copy

```
struct TriggerAutoExchangeInput {
    /*
     * @dev accountId The id of the auto-exchanged account.
     * @dev liquidatorAccountId The id of the liquidator's account.
     * @dev amountToAutoExchangeQuote The max amount of quote collaterals the liquidator wants to provide
     * @dev collateral The address of the collateral collateral to be paid to the liquidator
     * @dev inCollateral The address of the quote collateral the liquidator provides
    */
    uint128 accountId;
    uint128 liquidatorAccountId;
    uint256 requestedQuoteAmount;
    address collateral;
    address inCollateral;
}
```

</details>

Auto-exchange can be triggered if the user does not have enough quote tokens to cover exposure but owns collateral in other tokens. More details about the auto-exchange mechanics are found [here](https://docs.reya.network/derivatives-clearing/cross-collateralization/auto-exchange-conditions). If conditions apply, this function triggers an auto-exchange between the liquidator's quote and the account's collateral. The liquidator receives a discount on the collateral received based on the maximum between the amount requested by the liquidator, the maximum quote to be covered and the available collateral in the liquidated account.

The requestedQuoteAmount is denominated in rUSD, with 6 decimals precision. The `collateral` represents the token to be extracted by the liquidator and `inCollateral` represents the quote token, rUSD.

The following function can be used to calculate the amount that can be auto-exchanged: `calculateMaxQuoteToCoverInAutoExchange` and `calculateAvailableCollateralToBeAutoExchanged`.

<details>

<summary>AutoExchangeAmounts</summary>

Copy

```
struct AutoExchangeAmounts {
    /*
    * @dev collateralAmountToLiquidator Amount of collateral collaterals received by liquidator
    * @dev quoteAmountToIF Amount of quote collaterals paid to the insurance fund by the liquidator
    * @dev quoteAmountToAccount Amount of quote collaterals received by the auto-exchanged account
    */
    uint256 collateralAmountToLiquidator;
    uint256 quoteAmountToIF;
    uint256 quoteAmountToAccount;
}
```

</details>

This function returns AutoExchangeAmounts specifying the collateral tokens that went to the liquidator (denoted in the token with its own decimal precision), the quote amount that went to the insurance fund (small fee paid for the protocol’s safety) and the quote that reached the liquidated account.

#### calculateMaxQuoteToCoverInAutoExchange <a href="#calculatemaxquotetocoverinautoexchange" id="calculatemaxquotetocoverinautoexchange"></a>

```
function calculateMaxQuoteToCoverInAutoExchange(uint128 accountId, address inCollateral) external view returns (uint256);
```

Calculates the maximum amount of quote that can be covered by auto-exchange. The inCollateral should be rUSD and the output will be denoted in rUSD with 6 decimals precision. If the account id does not fall under any of the auto-exchange conditions [here](https://docs.reya.network/derivatives-clearing/cross-collateralization/auto-exchange-conditions)., this value is zero.

#### calculateAvailableCollateralToBeAutoExchanged <a href="#calculateavailablecollateraltobeautoexchanged" id="calculateavailablecollateraltobeautoexchanged"></a>

```
function calculateAvailableCollateralToBeAutoExchanged(uint128 accountId, address outCollateral, address quoteCollateral) external view returns (uint256);
```

Returns the maximum amount of collateral that can be extracted from the user’s account in exchange for quote. The out collateral represents the token to be received by the auto-exchanger and the quote collateral should be rUSD, the token paid by the auto-exchanger. It returns the amount denoted in the collateral token with its decimal precision.

#### execute <a href="#execute" id="execute"></a>

```
function execute(uint128 accountId, Command[] calldata commands) external returns (bytes[] memory outputs, MarginInfo memory marginInfo);
```

<details>

<summary>Command and CommandType</summary>

```
enum CommandType {
    Deposit, // (core command) deposit collaterals
    Withdraw, // (core command) withdraw collaterals
    DutchLiquidation, // (core command) dutch liquidation of an account
    MatchOrder, // (market command) propagation of matched orders
    TransferBetweenMarginAccounts // (core command) transfer between two margin accounts

}

struct Command {
    /**
     * @dev Identifies the command to be executed
     */
    CommandType commandType;
    /**
     * @dev Command inputs encoded in bytes
     */
    bytes inputs;
    /**
     * @dev Market id that identifies the instrument to execute
     * this command. If zero, the command will be sent to core.
     */
    uint128 marketId;
    /**
     * @dev Exchange id that identifies the exchange that executes
     * this command. If zero, the command does not involve an exchange (e.g. propagate cashflow)
     */
    uint128 exchangeId;
}
```

</details>

This is a router-type function, it allows the user to call multiple protocol functionalities in the same transaction e.g. deposit, trade, withdraw. For Core commands (Deposit, Withdraw, DutchLiquidation, TransferBetweenMarginAccounts) the market id and exchange id should be zero. For the MatchOrder, the values should be specified. These commands have to act on a single account account, the one globally specified in the function parameters. If the msg.sender does not have permissions to modify this account, the transaction will fail.

Each command requires a different set of encoded inputs, sent under bytes inputs:

* Deposit and Withdraw: `(address collateral, uint256 collateralAmount)`
* DutchLiquidation: (DutchLiquidationInput inputs) with `DutchLiquidationInput{uint128 liquidatableAccountId; address quoteCollateral; uint128[] marketIds; bytes[] inputs;}` where the inputs are encoded `(int56 liquidatedBase, uint256 priceLimit)` into bytes. This command allows the execution of Dutch liquidation on multiple markets in the same transaction.
* TransferBetweenMarginAccounts: (TransferInput inputs) with `TransferInput{uint128 destAccountId;address collateral;uint256 collateralAmount;}`
* MatchOrder: `(uint128[] memory counterpartyAccountIds, bytes memory orderInputs)`

`DutchLiquidation command`

This command triggers the liquidation of the `liquidatableAccountId` if its margin balance fell under the liquidation margin requirement, queried using `getUsdNodeMarginInfo` . This liquidation type moved the exposure (the `liquidatedBase`) to the liquidator at the market price (without the Pool slippage) within the specified price limit. The liquidator must remain above the initial margin requirements after this exchange, otherwise the transaction fails. The liquidator reward is a fixed percentage of the LMR delta, the improvement in the account's margin requirement after reducing exposure.

#### executeBySig <a href="#executebysig" id="executebysig"></a>

```
function executeBySig(uint128 accountId, Command[] calldata commands, EIP712Signature memory sig, bytes memory extraSignatureData) external returns (bytes[] memory outputs, MarginInfo memory marginInfo);
```

This function provides the same functionality as `execute()` with the added benefit that the msg.sender does not have to be the owner/admin of the provided `accountId`. The owner/admin’s signature is required but the transaction can be called from any address, enabling the use of relayer or external peripheries.

The EIP712Signature contains of the commands and inputs the owner intended to run, alongside a nonce, deadline. Read more about the EIP712 standard [here](https://eips.ethereum.org/EIPS/eip-712). The extraSignatureData is only a utility variable, can be left empty for external use.

#### executeBackstopLiquidation <a href="#executebackstopliquidation" id="executebackstopliquidation"></a>

```
function executeBackstopLiquidation(uint128 liquidatableAccountId, uint128 keeperAccountId, address quoteCollateral, UD60x18 backstopPercentage) external;
```

Triggers backstop liquidation of the gives account id. This sends the position to the backstop keeper (more details [here](https://docs.reya.network/derivatives-clearing/the-liquidation-engine/backstop-lps)). The backstop percentage is the percentage of the account's exposure to be transferred to the backstop LP.

Backstop is a type of liquidation that can be triggered on an account if its margin decreases below the ADL requirement. This can be queried using `getUsdNodeMarginInfo`. This type of liquidation sells the position at a better price to the designated backstop LP. The backstop LP account must be registered in Core. The keeper receives a set percentage of the liquidated amount (`backstopPercentage * liquidationMarginRequirement`).


# Passive Perp Instrument

This contract manages perpetual future markets, pricing of market orders executed against the passive pool, matching as well as keeping track of account exposures and PnLs in available markets

#### getUpdatedPositionInfo <a href="#getupdatedpositioninfo" id="getupdatedpositioninfo"></a>

```
function getUpdatedPositionInfo(uint128 marketId, uint128 accountId) external view returns (PerpPosition memory);
```

<details>

<summary>PerpPosition</summary>

```
/**
 * @notice Structure containing information about a position
 */
struct PerpPosition {
    /// The net base of the position
    SD59x18 base;
    /// The realized pnl of the position
    SD59x18 realizedPnL;
    /// The last price data used to mark-to-market the position
    PriceData lastPriceData;
    /// The last trackers used to update the position's base and realized pnl
    FundingAndADLTrackers trackers;
}

```

</details>

For a given market and margin account id, it returns the latest position information. The ‘base’ has precision 18 but represents the market underlying exposure, positive for long positions and negative for short ones. The realised PnL is represented in the quote token of the market, it shows PnL available for withdraw. The price and timestamp correspond to the last observation of the oracle fr the market underlying token. The trackers are internal auditing parameters used to update the position.

#### getPoolMaxExposures <a href="#getpoolmaxexposures" id="getpoolmaxexposures"></a>

```
function getPoolMaxExposures(uint128 marketId) external view returns (UD60x18 maxShortExposure, UD60x18 maxLongExposure)
```

Returns the maximum absolute exposure the current market can support in both directions (exposure supported by the Passive Pool exchange). The actual maximum amount that can be traded in one direction is only a proportion of this, amount controlled by the maxExposureFactor parameter. These values are in base amounts, with precision 18.

#### getLatestFundingRate <a href="#getlatestfundingrate" id="getlatestfundingrate"></a>

```
function getLatestFundingRate(uint128 marketId) external view returns (SD59x18)
```

Returns the latest funding rate of a given market. The funding rate has precision 18 decimals and represents the rate that will be applied per day and unit of price to obtain the funding rate PnL

#### getLatestMTMData <a href="#getlatestmtmdata" id="getlatestmtmdata"></a>

```
function getLatestMTMData(uint128 marketId) external view returns (PriceData memory);
```

<details>

<summary>PriceData</summary>

```
struct PriceData {
    /// The price represented with 18 decimals precision
    UD60x18 price;
    /// The timestamp at which the price was retrieved.
    uint256 timestamp;
}
```

</details>

Returns the latest mark-to-market (MTM) data: the pegging price (futures price provided by oracles) at the last MTM and its registration timestamp. If the MTM window hap passed but a transaction was not yet submitted to record the MTM event, it will return the current oracle price.

#### getFundingVelocity <a href="#getfundingvelocity" id="getfundingvelocity"></a>

```
function getFundingVelocity(uint128 marketId) external view returns (SD59x18);
```

Returns the latest funding velocity for a given market. This represents the change per day in funding rate and is determined by the Pool’s current slippage and a velocity multiplier parameter. The funding rate is continuously adjusted by this velocity.

#### getOpenBaseInterest <a href="#getopenbaseinterest" id="getopenbaseinterest"></a>

```
function getOpenBaseInterest(uint128 marketId) external view returns (UD60x18);
```

Returns the current open interest with WAD precision of the given market.

#### getInstantaneousPoolPrice <a href="#getinstantaneouspoolprice" id="getinstantaneouspoolprice"></a>

```
function getInstantaneousPoolPrice(uint128 marketId) external view returns (UD60x18);
```

Returns the current price offered by the Passive Pool. This price is equal to the oracle price adjusted by the Pool’s slippage. The price deviation (pSlippage) can either be negative or positive depending on the direction of the pool's net imbalance in the given market, always giving the Pool a better price. This is the price a taker would be given if the traded base is close to zero.

#### getSimulatedPoolPrice <a href="#getsimulatedpoolprice" id="getsimulatedpoolprice"></a>

```
function getSimulatedPoolPrice(uint128 marketId, SD59x18 orderBase) external view returns (UD60x18);
```

Returns the price the Passive Pool would offer for a match order of the given size. Similar to the `getInstantaneousPoolPrice`, this is the oracle price adjusted by the Pool’s slippage but also taking to account its exposure after the trade. This can be used to check the execution price before a trade is made.


# Passive Pool

Liquidity pool that acts as a counter-party for all trades on the Reya DEX.

#### getPoolQuoteToken <a href="#getpoolquotetoken" id="getpoolquotetoken"></a>

```
function getPoolQuoteToken(uint128 id) external view returns (address quoteToken);
```

Given the pool id, it returns the liquidity token address. Currently there is only 1 pool, id = 1, and its quote token is rUSD.

#### getPoolAccountId <a href="#getpoolaccountid" id="getpoolaccountid"></a>

```
function getPoolAccountId(uint128 id) external view returns (uint128 accountId);
```

Given the pool id, it returns the pool's margin account id registered in Core.

#### addLiquidity <a href="#addliquidity" id="addliquidity"></a>

```
function addLiquidity(uint128 poolId, address owner, uint256 amount, uint256 minShares) external returns (uint256);
```

Transfers the specified `amount` of liquidity from the caller to the pool and, based on the current price, mints a corresponding amount of shares to the given 'owner' address. For example, if 3 rUSD is deposited (3\* 10^6 with precision) and the share per share is 1.5 (1.2 \* 10^18 with precision), then the amount of shares received will be 3/1.5 = 2 shares (2 \* 10^30 with precision).

#### removeLiquidity <a href="#removeliquidity" id="removeliquidity"></a>

```
function removeLiquidity(uint128 poolId, uint256 sharesAmount, uint256 minOut) external returns (uint256 tokenAmount);
```

Burns the specified `sharesAmount` of shares and, based on the current price, withdraws the corresponding amount of liquidity to the caller's address. 'minOut' is the minimum amount of quote tokens expected to be received by the caller.

#### removeLiquidityBySig <a href="#removeliquiditybysig" id="removeliquiditybysig"></a>

```
function removeLiquidityBySig(address owner, uint128 poolId, uint256 sharesAmount, uint256 minOut, EIP712Signature memory sig, bytes memory extraSignatureData) external returns (uint256 tokenAmount);
```

Additionally to `removeLiquidity`, this function allows liquidity removal from a user's account by validating their signature instead of validating msg.sender. It sends the funds to the given 'owner'.

#### getAccountBalance <a href="#getaccountbalance" id="getaccountbalance"></a>

```
function getAccountBalance(uint128 poolId, address account) external view returns (uint256);
```

Given the user’s address, it returns the user's share balance in the specified pool. Shares have precision 30.

#### getPoolMarginBalance <a href="#getpoolmarginbalance" id="getpoolmarginbalance"></a>

```
function getPoolMarginBalance(uint128 poolId) external view returns (uint256);
```

Returns the margin balance of the pool margin account in Core in the pool’s quote token.

#### getSharePrice <a href="#getshareprice" id="getshareprice"></a>

```
function getSharePrice(uint128 poolId) external view returns (UD60x18)
```

This is the margin balance of the pool divided by the share supply. Note, the precision of the margin balance is adjusted from the quote token decimals to 30 decimals precision. The price has 18 decimals precision.

#### getShareSupply <a href="#getsharesupply" id="getsharesupply"></a>

```
function getShareSupply(uint128 poolId) external view returns (uint256)
```

Returns the total amount of shares tracked by the pool. When adding liquidity this amount increases by the number of shares minted based on the share price and the liquidity provided. When removing liquidity, supply decreases by the amount of shares burnt. The share supply has 30 decimals precision.


# Oracle Adapter

Receives and track the latest price updates given by a trusted off-chain source.

#### getLatestPricePayload <a href="#getlatestpricepayload" id="getlatestpricepayload"></a>

```
function getLatestPricePayload(string memory assetPairId) external view returns (StorkPricePayload memory)
```

<details>

<summary>StorkSignedPayload</summary>

```
struct StorkSignedPayload {
    address oraclePubKey;
    StorkPricePayload pricePayload;
    bytes32 r;
    bytes32 s;
    uint8 v;
}

struct StorkPricePayload {
    string assetPairId;
    uint256 timestamp;
    uint256 price;
}
```

</details>

Returns the latest price payload for the given Stork asset pair ID (e.g 'AAVEUSDMARK' for futures prices of Aave). This payload has been signed by a trusted source and gives the latest price used by the Perpetuals Instrument as the reference price for match orders.

#### fulfillOracleQuery <a href="#fulfilloraclequery" id="fulfilloraclequery"></a>

```
function fulfillOracleQuery(bytes calldata signedOffchainData) external payable override
```

Updates the latest reference price of the asset pair. The `signedOffchainData` is a bytes encoding of the `StorkSignedPayload`. This is a payload of the latest price details with a signature given by a trusted source. The signature is verified against the received data and must match for the new price to be accepted.

Anyone can update the prices at any point, the only constraint is that they have to be signed by a trusted source. One can subscribe to price updates from this source and send `fulfillOracleQuery` transactions with the latest prices. It is recommended to append updates for every market before executing a match order or a liquidation (e.g. by using a Multicall [contract](broken://spaces/b3btfuLSfJJJXBJGFc5f/pages/QY1O5dn64uLbu9VCelNy)), such that the Core operations use the latest prices.

Submit signed payload of price update.


# Contract Addresses

The Reya contracts are deployed on Reya Network (mainnet) and Reya Cronos (testnet).

### Reya Network (chain id 1729)

| Core                             | ​0xA763B6a5E09378434406C003daE6487FbbDc1a80 |
| -------------------------------- | ------------------------------------------- |
| Passive Perp Instrument          | ​0x27E5cb712334e101B3c232eB0Be198baaa595F5F |
| Passive Pool                     | ​0xB4B77d6180cc14472A9a7BDFF01cc2459368D413 |
| Oracle Adapter                   | ​0x32edABC058C1207fE0Ec5F8557643c28E4FF379e |
| rUSD                             | ​0xa9F32a851B1800742e47725DA54a09A7Ef2556A3 |
| Multicall                        | 0xed28d27dfca47ad2513c9f2e2d3c098c2ea5a47f  |
| RoPassive Pool margin account ID | 2                                           |

#### Reya Cronos (chain id 89346162) <a href="#reya-cronos-chain-id-89346162" id="reya-cronos-chain-id-89346162"></a>

| Text                           | Text                                        |
| ------------------------------ | ------------------------------------------- |
| Core                           | ​0xC6fB022962e1426F4e0ec9D2F8861c57926E9f72 |
| Passive Perp Instrument        | ​0x9EC177fed042eF2307928BE2F5CDbf663B20244B |
| Passive Pool                   | ​0x9A3A664987b88790A6FDC1632e3b607813fd94fF |
| Oracle Adapter                 | ​0xc501A2356703CD351703D68963c6F4136120f7CF |
| rUSD                           | ​0x9DE724e7b3facF87Ce39465D3D712717182e3e55 |
| Multicall                      | 0x5abde4f0af8eaf3c9967f7fa126e59a103357b5c  |
| Passive Pool margin account ID | ​4​                                         |

<br>


# Smart Contract Withdrawals

As shown in the dApp funds on Reya Network are non-custodial and available to withdraw at anytime. You may use the withdrawal buttons on the dApp, or alternative you can withdraw directly from the Reya Network smart contracts.

**Follow the guide below to withdraw from the smart contracts.**

***

1. Bridge ETH to Reya Network for gas fees and Socket bridge fees by using this bridge: <https://bridge.gelato.network/bridge/reya-network>. Note that:

   1. The bridge does not support ETH withdrawals for the time being, so make sure you don’t bridge too much ETH.
   2. Trading on Reya Network is made gas-free via a relayer architecture, if you’re interacting with the contracts directly you will need to pay a small amount of gas (hence the ETH needed).

   ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FaYn82zYOMm7iFAfnjhYp%252Fimage.png%3Falt%3Dmedia%26token%3D175dfb8f-b628-418b-8ed0-6874fd01cdbd\&width=768\&dpr=4\&quality=100\&sign=2bfc19e9\&sv=2)
2. Withdraw funds from the Passive Pool into your wallet on Reya Network by calling the removeLiquidity function here: <https://usecannon.com/packages/reya-omnibus/latest/1729-main/interact/reya-omnibus/PassivePoolProxy/0xB4B77d6180cc14472A9a7BDFF01cc2459368D413#selector-0x0b7c92f9>. To do this, you need to input the following parameters:

   1. poolId: 1
   2. sharesAmount: the amount you want to withdraw multiplied by 10^30 (10 to the power of 30).
   3. minAmount: the amount you want to withdraw multiplied by 10^6

   For example, if you want to withdraw 99.5 rUSD, the parameters will be:

   1. poolId: 1
   2. sharesAmount: 99500000000000000000000000000000
   3. minAmount: 99500000
3. Unwrap rUSD into USDC by calling the withdraw function here: <https://usecannon.com/packages/reya-omnibus/latest/1729-main/interact/reya-omnibus/RUSDProxy/0xa9F32a851B1800742e47725DA54a09A7Ef2556A3#selector-0x2e1a7d4d>. To do this, you need to input the following parameters:
   1. amount: the amount withdrawn at the previous step, same as minAmount (multiplied by 1000000). For example, if you withdrawn 99.5 rUSD, the parameters will be amount = 99500000
4. Confirm you have USDC in your Reya Wallet.
   1. Add the chain to your wallet. There is a link in the footer of: <https://explorer.reya.network/> ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FmQFS3KfuEx5eVQamrkW2%252Fimage.png%3Falt%3Dmedia%26token%3Db0825ced-080e-4ee0-9a0d-d9c8df6e03b3\&width=300\&dpr=4\&quality=100\&sign=aa83514e\&sv=2)
   2. Add the token at address: 0x3B860c0b53f2e8bd5264AA7c3451d41263C933F2 For example using Metamask: ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FlagVs3y8tJKlcI7VKyfG%252Fimage.png%3Falt%3Dmedia%26token%3D6513882f-6622-462f-b389-334a9149f93d\&width=300\&dpr=4\&quality=100\&sign=7f0b7758\&sv=2) Enter the contract address and the symbol and decimals should auto-populate. Press Next ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FDRHuHJdi2GeZp76DMDkc%252Fimage.png%3Falt%3Dmedia%26token%3D594bf99b-00ef-4112-8834-b278aa77be9e\&width=300\&dpr=4\&quality=100\&sign=d475d9df\&sv=2)
5. Once confirmed, you should bridge funds from Reya Network to a source chain (Ethereum Mainnet/Arbitrum/Optimism/Polygon). To do this, you have to call the bridge function on the Socket contract here: <https://explorer.reya.network/address/0x1d43076909Ca139BFaC4EbB7194518bE3638fc76?tab=write_contract#405e720a>.

   ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FIImwsvtmdBvDQQD9BG05%252Fimage.png%3Falt%3Dmedia%26token%3Dfd994820-d3b2-42ba-abca-d2ff0b66b4d3\&width=300\&dpr=4\&quality=100\&sign=c66e47c8\&sv=2) To do this, you have to provide the following parameters:

   1. receiver: your wallet address on the source chain (the chain you are withdrawing to)
   2. amount: the amount withdrawn at the previous steps, same as minAmount (still multiplied by 1000000).
      1. note: the pull down at the end of the row will help you multiply by 10^6 but this number should be the same as the one used in the previous steps
   3. msgGasLimit: 10000000
   4. connector: the socket connector address assigned to the source chain you want to withdraw to.

      NetworkConnector Address

      Ethereum Mainnet

      0x807B2e8724cDf346c87EEFF4E309bbFCb8681eC1

      Arbitrum

      0x663dc7E91157c58079f55C1BF5ee1BdB6401Ca7a

      Optimism

      0xe48AE3B68f0560d4aaA312E12fD687630C948561

      Polygon

      0x54CAA0946dA179425e1abB169C020004284d64D3
   5. execPayload: 0x
   6. options: 0x
   7. Send native ETH (uint256): the socket bridge fees. As these are dynamic, you can use 10000000000000000 to account for most cases (this is equivalent to 0.01 ETH). Note that you can use lower amount as well (e.g. 1000000000000000, which is equivalent to 0.001 ETH), but it might fail if Socket fees increase.

   Upon completion of these steps, funds should be in the destination wallet address entered, on the network corresponding to the network connecter address used, in 10-15min. If you have not received your funds after an hour, please open a support ticket in our Discord and we can try and help.


# Audits

## ABDK

{% file src="/files/zaTH0sFyMhjflnEg6uod" %}

{% file src="/files/VVJZ0Aun0Q6BdKVkmZe1" %}

{% file src="/files/uKukDRumwzuLNSDSxUHA" %}

## Pashov

{% file src="/files/WPzrGZpnkn2FfBSlnqwI" %}

{% file src="/files/N0Kfn46I66GcN90f2CFl" %}

{% file src="/files/N61oPXJR18tReAzKw7zk" %}

{% file src="/files/N61oPXJR18tReAzKw7zk" %}


# Rest API Reference

**Base URL**: `https://api.reya.xyz/v2`

## Overview

The Reya DEX REST API v2 provides programmatic access to the Reya Perpetual Exchange, enabling traders to interact with the platform algorithmically. This API is designed for developers and professional traders who want to build automated trading systems, integrate with existing platforms, or develop custom interfaces for the Reya DEX ecosystem.

## Key Features

* **Market Data**: Access comprehensive market information, including asset definitions, market summaries, and real-time price data
* **Order Management**: Create, cancel, and monitor orders with support for various order types (limit, trigger)
* **Position Tracking**: Monitor your current positions and historical executions
* **Wallet Integration**: Manage wallet configurations and access wallet-specific data
* **Price Data**: Access historical price data with customizable time intervals through candle endpoints

## API Structure

The API is organized into several logical sections:

* **Reference Data**: Discover markets and assets definitions, trading fees
* **Market Data**: Access real-time and historical market data, including prices, candles and order execution
* **Wallet Data**: Get information about the wallet's accounts, positions and orders
* **Order Entry**: Create and cancel orders

## Signatures

For private endpoints that access user-specific data or perform actions on behalf of a user, authentication is required through wallet signatures. This ensures that only authorized users can create and update orders.

## Rate Limits

To ensure fair usage and optimal performance, the API implements rate limiting. For more information, see the [Rate Limits](/developers/rate-limits) documentation.

For real-time data needs, consider using our [WebSocket Info API](/developers/websocket-api-reference/websocket-api-reference) for streaming updates. To place and cancel orders over a persistent connection, see the [WebSocket Order Entry API](/developers/websocket-api-reference/ws-exec-api-reference).


# Specs

OpenAPI and AsyncAPI specs

## Get OpenAPI specification

> Returns the complete OpenAPI specification for this API in YAML format

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Specs","description":"OpenAPI and AsyncAPI specs"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/openapi-spec.yaml":{"get":{"summary":"Get OpenAPI specification","description":"Returns the complete OpenAPI specification for this API in YAML format","operationId":"getOpenApiSpec","tags":["Specs"],"responses":{"200":{"description":"OpenAPI specification in YAML format","content":{"application/yaml":{"schema":{"type":"string","format":"binary"}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"responses":{"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}},"schemas":{"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## Get AsyncAPI specification

> Returns the complete AsyncAPI specification for WebSocket API in YAML format

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Specs","description":"OpenAPI and AsyncAPI specs"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/asyncapi-spec.yaml":{"get":{"summary":"Get AsyncAPI specification","description":"Returns the complete AsyncAPI specification for WebSocket API in YAML format","operationId":"getAsyncApiSpec","tags":["Specs"],"responses":{"200":{"description":"AsyncAPI specification in YAML format","content":{"application/yaml":{"schema":{"type":"string","format":"binary"}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"responses":{"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}},"schemas":{"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```


# Reference Data

Market definitions, global parameters, liquidity parameters, etc.

## Get market definitions

> Deprecated: use \`/perpMarketDefinitions\` instead. This un-prefixed route still works but will be removed once integrators have migrated to the \`perp\*\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/marketDefinitions":{"get":{"summary":"Get market definitions","description":"Deprecated: use `/perpMarketDefinitions` instead. This un-prefixed route still works but will be removed once integrators have migrated to the `perp*` naming.","operationId":"getMarketDefinitions","deprecated":true,"tags":["Reference Data"],"responses":{"200":{"description":"List of market definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketDefinition":{"title":"MarketDefinition","$id":"#MarketDefinition","type":"object","required":["symbol","marketId","minOrderQty","qtyStepSize","tickSize","liquidationMarginParameter","initialMarginParameter","maxLeverage","oiCap"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each market, only needed to generate signatures"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"},"liquidationMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered to avoid liquidation procedures for a given market; below this value, your account is subject to liquidation procedures. When cross margining, all requirements across markets are covered by the same balance, and all positions are subject to liquidations."},"initialMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered post trade; if the account does not satisfy this requirement, trades will not get executed."},"maxLeverage":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maximum leverage allowed"},"oiCap":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Maximum one-sided open interest in units for a given market."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp market definitions

> Alias of \`/marketDefinitions\`, mirroring the \`/spotMarketDefinitions\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/perpMarketDefinitions":{"get":{"summary":"Get perp market definitions","description":"Alias of `/marketDefinitions`, mirroring the `/spotMarketDefinitions` naming.","operationId":"getPerpMarketDefinitions","tags":["Reference Data"],"responses":{"200":{"description":"List of perp market definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketDefinition":{"title":"MarketDefinition","$id":"#MarketDefinition","type":"object","required":["symbol","marketId","minOrderQty","qtyStepSize","tickSize","liquidationMarginParameter","initialMarginParameter","maxLeverage","oiCap"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each market, only needed to generate signatures"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"},"liquidationMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered to avoid liquidation procedures for a given market; below this value, your account is subject to liquidation procedures. When cross margining, all requirements across markets are covered by the same balance, and all positions are subject to liquidations."},"initialMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered post trade; if the account does not satisfy this requirement, trades will not get executed."},"maxLeverage":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maximum leverage allowed"},"oiCap":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Maximum one-sided open interest in units for a given market."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /spotMarketDefinitions

> Get spot market definitions

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/spotMarketDefinitions":{"get":{"summary":"Get spot market definitions","operationId":"getSpotMarketDefinitions","tags":["Reference Data"],"responses":{"200":{"description":"List of spot market definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SpotMarketDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"SpotMarketDefinition":{"title":"SpotMarketDefinition","$id":"#SpotMarketDefinition","type":"object","required":["symbol","marketId","baseAsset","quoteAsset","minOrderQty","qtyStepSize","tickSize"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each spot market"},"baseAsset":{"type":"string","description":"Base asset symbol"},"quoteAsset":{"type":"string","description":"Quote asset symbol"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum order quantity (base asset)"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment (base asset)"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /assetDefinitions

> Get asset definitions

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/assetDefinitions":{"get":{"summary":"Get asset definitions","operationId":"getAssetDefinitions","tags":["Reference Data"],"responses":{"200":{"description":"List of asset definitions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetDefinition"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"AssetDefinition":{"title":"AssetDefinition","$id":"#AssetDefinition","type":"object","required":["asset","priceHaircut","liquidationDiscount","status","decimals","displayDecimals"],"properties":{"asset":{"$ref":"#/components/schemas/Asset"},"spotMarketSymbol":{"$ref":"#/components/schemas/Symbol"},"priceHaircut":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Notional discount to the value of a collateral when used to satisfy the margin requirements; it does not imply any token conversion, but is rather an accounting adjustment."},"liquidationDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Discount in the token price when liquidating collateral."},"status":{"type":"string","enum":["ENABLED","WITHDRAWAL_ONLY"],"description":"Status of asset (ENABLED = deposits and withdrawals allowed, WITHDRAWAL_ONLY = only withdrawals allowed)"},"decimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places for record keeping amounts of this asset (e.g. 18 for ETH, 6 for RUSD)"},"displayDecimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places shown for display purposes in frontends"}},"additionalProperties":true},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /liquidityParameters

> Get liquidity parameters

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/liquidityParameters":{"get":{"summary":"Get liquidity parameters","operationId":"getLiquidityParameters","tags":["Reference Data"],"responses":{"200":{"description":"List of liquidity parameters","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/LiquidityParameters"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"LiquidityParameters":{"title":"LiquidityParameters","$id":"#LiquidityParameters","type":"object","required":["symbol","depth","velocityMultiplier"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"depth":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the liquidity distribution along the AMM pricing curve, in particular expanding or contracting the max exposure parameter that would otherwise be determined by the capital available."},"velocityMultiplier":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the sensitivity of the dynamic funding rate to the size of the imbalances; higher multiplier means that the funding rate will diverge faster, all else being equal."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /globalFeeParameters

> Get global fee parameters

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/globalFeeParameters":{"get":{"summary":"Get global fee parameters","operationId":"getGlobalFeeParameters","tags":["Reference Data"],"responses":{"200":{"description":"Global fee parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GlobalFeeParameters"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"GlobalFeeParameters":{"title":"GlobalFeeParameters","$id":"#GlobalFeeParameters","type":"object","required":["ogDiscount","refereeDiscount","referrerRebate","affiliateReferrerRebate"],"properties":{"ogDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"OG user discount"},"refereeDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referee discount"},"referrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referrer rebate"},"affiliateReferrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Affiliate referrer rebate"}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /feeTiers

> Get fee tiers

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Reference Data","description":"Market definitions, global parameters, liquidity parameters, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/feeTiers":{"get":{"summary":"Get fee tiers","operationId":"getFeeTierParameters","tags":["Reference Data"],"responses":{"200":{"description":"List of fee tier parameters","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/FeeTierParameters"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"FeeTierParameters":{"title":"FeeTierParameters","$id":"#FeeTierParameters","type":"object","required":["tierId","takerFee","makerFee","volume14d","tierType"],"properties":{"tierId":{"$ref":"#/components/schemas/UnsignedInteger"},"takerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Taker fee rate (fee will be qty * takerFee)"},"makerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Maker fee rate (fee will be qty * makerFee)"},"volume14d":{"$ref":"#/components/schemas/UnsignedDecimal","description":"14-day volume level required this fee tier to be applied to a wallet"},"tierType":{"$ref":"#/components/schemas/TierType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"TierType":{"title":"TierType","$id":"#TierType","type":"string","enum":["REGULAR","VIP"],"description":"Fee tier type (REGULAR = Standard tier, VIP = VIP tier)"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Market Data

Prices, market-level trades, depth, candles, etc.

## Get spot market summaries

> Statistics and throttled market data for all spot markets. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/spotMarkets/summary":{"get":{"summary":"Get spot market summaries","description":"Statistics and throttled market data for all spot markets. Recalculated every 0.5s","operationId":"getSpotMarketsSummary","tags":["Market Data"],"responses":{"200":{"description":"List of spot market summaries","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SpotMarketSummary"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"SpotMarketSummary":{"title":"SpotMarketSummary","$id":"#SpotMarketSummary","type":"object","required":["symbol","updatedAt","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the spot market summary was last calculated (milliseconds)"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal","description":"24-hour trading volume in USD"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal","description":"Absolute 24-hour price change"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Current oracle price"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get spot market summary

> Statistics and throttled market data for a specific spot market. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/spotMarket/{symbol}/summary":{"get":{"summary":"Get spot market summary","description":"Statistics and throttled market data for a specific spot market. Recalculated every 0.5s","operationId":"getSpotMarketSummary","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Spot market summary data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotMarketSummary"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SpotMarketSummary":{"title":"SpotMarketSummary","$id":"#SpotMarketSummary","type":"object","required":["symbol","updatedAt","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the spot market summary was last calculated (milliseconds)"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal","description":"24-hour trading volume in USD"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal","description":"Absolute 24-hour price change"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Current oracle price"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get market summaries

> Deprecated: use \`/perpMarkets/summary\` instead. Statistics and throttled market data for all markets. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the \`perp\*\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/markets/summary":{"get":{"summary":"Get market summaries","description":"Deprecated: use `/perpMarkets/summary` instead. Statistics and throttled market data for all markets. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the `perp*` naming.","operationId":"getMarketsSummary","deprecated":true,"tags":["Market Data"],"responses":{"200":{"description":"List of market summaries","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketSummary"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp market summaries

> Alias of \`/markets/summary\`, mirroring the \`/spotMarkets/summary\` naming. Statistics and throttled market data for all perp markets. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/perpMarkets/summary":{"get":{"summary":"Get perp market summaries","description":"Alias of `/markets/summary`, mirroring the `/spotMarkets/summary` naming. Statistics and throttled market data for all perp markets. Recalculated every 0.5s","operationId":"getPerpMarketsSummary","tags":["Market Data"],"responses":{"200":{"description":"List of perp market summaries","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/MarketSummary"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get market summary

> Deprecated: use \`/perpMarket/{symbol}/summary\` instead. Statistics and throttled data for a specific market. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the \`perp\*\` naming.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/summary":{"get":{"summary":"Get market summary","description":"Deprecated: use `/perpMarket/{symbol}/summary` instead. Statistics and throttled data for a specific market. Recalculated every 0.5s. This un-prefixed route still works but will be removed once integrators have migrated to the `perp*` naming.","operationId":"getMarketSummary","deprecated":true,"tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Market summary","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketSummary"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp market summary

> Alias of \`/market/{symbol}/summary\`, mirroring the \`/spotMarket/{symbol}/summary\` naming. Statistics and throttled data for a specific perp market. Recalculated every 0.5s

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/perpMarket/{symbol}/summary":{"get":{"summary":"Get perp market summary","description":"Alias of `/market/{symbol}/summary`, mirroring the `/spotMarket/{symbol}/summary` naming. Statistics and throttled data for a specific perp market. Recalculated every 0.5s","operationId":"getPerpMarketSummary","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Market summary","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketSummary"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /prices

> Get all prices

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/prices":{"get":{"summary":"Get all prices","operationId":"getPrices","tags":["Market Data"],"responses":{"200":{"description":"List of prices","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Price"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"Price":{"title":"Price","$id":"#Price","type":"object","required":["symbol","updatedAt","oraclePrice"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Price given by the Stork feeds, used both as the peg price for prices on Reya, as well as Mark Prices. The Stork price feed is usually the perp prices across three major CEXs"},"poolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"The price currently quoted by the AMM for zero volume, from which trades are priced (equivalent to mid price in an order book); a trade of any size will be move this price up or down depending on the direction."},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /prices/{symbol}

> Get price by symbol

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/prices/{symbol}":{"get":{"summary":"Get price by symbol","operationId":"getPrice","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Price information","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Price"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Price":{"title":"Price","$id":"#Price","type":"object","required":["symbol","updatedAt","oraclePrice"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Price given by the Stork feeds, used both as the peg price for prices on Reya, as well as Mark Prices. The Stork price feed is usually the perp prices across three major CEXs"},"poolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"The price currently quoted by the AMM for zero volume, from which trades are priced (equivalent to mid price in an order book); a trade of any size will be move this price up or down depending on the direction."},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get perp executions for market

> Returns up to 100 perp executions for a given market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/perpExecutions":{"get":{"summary":"Get perp executions for market","description":"Returns up to 100 perp executions for a given market.","operationId":"getMarketPerpExecutions","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"},{"$ref":"#/components/parameters/ExecutionTypeParam"}],"responses":{"200":{"description":"List of perp executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PerpExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"ExecutionTypeParam":{"name":"type","in":"query","required":false,"description":"Filter perp executions by type. Omit to return executions of all types.","schema":{"type":"string","enum":["ORDER_MATCH","LIQUIDATION"]}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"PerpExecutionList":{"title":"PerpExecutionList","$id":"#PerpExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PerpExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get market depth snapshot

> Returns an L2 order book snapshot with aggregated price levels for the specified market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/depth":{"get":{"summary":"Get market depth snapshot","description":"Returns an L2 order book snapshot with aggregated price levels for the specified market.","operationId":"getMarketDepth","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"}],"responses":{"200":{"description":"Depth snapshot","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Depth"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Depth":{"title":"Depth","$id":"#Depth","type":"object","required":["symbol","type","bids","asks","updatedAt"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"type":{"$ref":"#/components/schemas/DepthType"},"bids":{"type":"array","description":"Bid side levels aggregated by price, sorted descending by price","items":{"$ref":"#/components/schemas/Level"}},"asks":{"type":"array","description":"Ask side levels aggregated by price, sorted ascending by price","items":{"$ref":"#/components/schemas/Level"}},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Snapshot generation timestamp (milliseconds)"}},"additionalProperties":true},"DepthType":{"title":"DepthType","$id":"#DepthType","type":"string","enum":["SNAPSHOT","UPDATE"],"description":"Depth message type (SNAPSHOT = full book, UPDATE = single level change)"},"Level":{"title":"Level","$id":"#Level","type":"object","required":["px","qty"],"properties":{"px":{"$ref":"#/components/schemas/SignedDecimal","description":"Price level"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Aggregated quantity at this price level"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get spot executions for market

> Returns up to 100 spot executions for a given market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/spotExecutions":{"get":{"summary":"Get spot executions for market","description":"Returns up to 100 spot executions for a given market.","operationId":"getMarketSpotExecutions","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionList":{"title":"SpotExecutionList","$id":"#SpotExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get spot execution busts for market

> Returns up to 100 spot execution busts (failed spot fills) for a given market.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/market/{symbol}/spotExecutionBusts":{"get":{"summary":"Get spot execution busts for market","description":"Returns up to 100 spot execution busts (failed spot fills) for a given market.","operationId":"getMarketSpotExecutionBusts","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot execution busts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionBustList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionBustList":{"title":"SpotExecutionBustList","$id":"#SpotExecutionBustList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecutionBust"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get historical candles

> Returns up to 200 candles for a given market, sorted by time in descending order, and ending at the specified end time.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Market Data","description":"Prices, market-level trades, depth, candles, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/candleHistory/{symbol}/{resolution}":{"get":{"summary":"Get historical candles","description":"Returns up to 200 candles for a given market, sorted by time in descending order, and ending at the specified end time.","operationId":"getCandles","tags":["Market Data"],"parameters":[{"$ref":"#/components/parameters/SymbolParam"},{"$ref":"#/components/parameters/ResolutionParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"Historical candle data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CandleHistoryData"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"SymbolParam":{"name":"symbol","in":"path","required":true,"description":"Trading symbol (e.g., BTCRUSDPERP)","schema":{"$ref":"#/components/schemas/Symbol"}},"ResolutionParam":{"name":"resolution","in":"path","required":true,"description":"Candle resolution","schema":{"type":"string","enum":["1m","5m","15m","30m","1h","4h","1d"]}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"CandleHistoryData":{"title":"CandleHistoryData","$id":"#CandleHistoryData","type":"object","required":["t","o","h","l","c"],"properties":{"t":{"type":"array","items":{"$ref":"#/components/schemas/UnsignedInteger"},"description":"Array of timestamps (seconds)"},"o":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of opening prices"},"h":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of high prices"},"l":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of low prices"},"c":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of closing prices"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Wallet Data

Accounts, positions, trades, etc.

## GET /wallet/{address}/accounts

> Get wallet accounts

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/accounts":{"get":{"summary":"Get wallet accounts","operationId":"getWalletAccounts","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of accounts","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Account"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"Account":{"title":"Account","$id":"#Account","type":"object","required":["accountId","name","type"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"name":{"type":"string"},"type":{"$ref":"#/components/schemas/AccountType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"AccountType":{"title":"AccountType","$id":"#AccountType","type":"string","enum":["MAINPERP","SUBPERP","SPOT"],"description":"SPOT = account that can only trade spot, MAINPERP = main perp account, SUBPERP = sub perp account"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet spot execution busts

> Returns up to 100 spot execution busts (failed spot fills) for a given wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/spotExecutionBusts":{"get":{"summary":"Get wallet spot execution busts","description":"Returns up to 100 spot execution busts (failed spot fills) for a given wallet.","operationId":"getWalletSpotExecutionBusts","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot execution busts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionBustList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionBustList":{"title":"SpotExecutionBustList","$id":"#SpotExecutionBustList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecutionBust"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet perp executions

> Returns up to 100 perp executions for a given wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/perpExecutions":{"get":{"summary":"Get wallet perp executions","description":"Returns up to 100 perp executions for a given wallet.","operationId":"getWalletPerpExecutions","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"},{"$ref":"#/components/parameters/ExecutionTypeParam"}],"responses":{"200":{"description":"List of perpetual executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PerpExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"ExecutionTypeParam":{"name":"type","in":"query","required":false,"description":"Filter perp executions by type. Omit to return executions of all types.","schema":{"type":"string","enum":["ORDER_MATCH","LIQUIDATION"]}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"PerpExecutionList":{"title":"PerpExecutionList","$id":"#PerpExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PerpExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet spot executions

> Returns up to 100 spot executions for a given wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/spotExecutions":{"get":{"summary":"Get wallet spot executions","description":"Returns up to 100 spot executions for a given wallet.","operationId":"getWalletSpotExecutions","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"},{"$ref":"#/components/parameters/StartTimeParam"},{"$ref":"#/components/parameters/EndTimeParam"}],"responses":{"200":{"description":"List of spot executions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpotExecutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}},"StartTimeParam":{"name":"startTime","in":"query","required":false,"description":"Return results at or after this time (inclusive lower bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}},"EndTimeParam":{"name":"endTime","in":"query","required":false,"description":"Return results at or before this time (inclusive upper bound). Millisecond POSIX timestamp, matched against each execution's on-chain block timestamp. Results are returned newest-first and capped at a maximum that varies by endpoint; to page backward through history, pass the oldest timestamp from the previous page.","schema":{"$ref":"#/components/schemas/UnsignedInteger"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SpotExecutionList":{"title":"SpotExecutionList","$id":"#SpotExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## GET /wallet/{address}/positions

> Get wallet positions

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/positions":{"get":{"summary":"Get wallet positions","operationId":"getWalletPositions","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of positions","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Position"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"Position":{"title":"Position","$id":"#Position","type":"object","required":["exchangeId","symbol","accountId","qty","side","avgEntryPrice","avgEntryFundingValue","lastTradeSequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"avgEntryPrice":{"$ref":"#/components/schemas/SignedDecimal"},"avgEntryFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Average of funding values at the entry times of currently open exposure, which serves as a baseline from which to compute the accrued funding in the position: units x (fundingValue - avgEntryFundingValue)"},"lastTradeSequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Sequence number of last execution taken into account for the position."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet account balances

> Returns all account real balances for a wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/accountBalances":{"get":{"summary":"Get wallet account balances","description":"Returns all account real balances for a wallet.","operationId":"getWalletAccountBalances","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of account balances","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AccountBalance"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"AccountBalance":{"title":"AccountBalance","$id":"#AccountBalance","type":"object","required":["accountId","asset","realBalance","balanceDEPRECATED"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"asset":{"$ref":"#/components/schemas/Asset"},"realBalance":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals) and realized pnl from closed positions. Realized pnl only applies to RUSD given it is the only settlement asset"},"balanceDEPRECATED":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals). This field is deprecated and will be removed in a future release"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet open orders

> Returns all pending orders for a wallet.

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/openOrders":{"get":{"summary":"Get wallet open orders","description":"Returns all pending orders for a wallet.","operationId":"getWalletOpenOrders","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"List of open orders","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Order"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"Order":{"title":"Order","$id":"#Order","type":"object","required":["exchangeId","symbol","accountId","orderId","side","limitPx","orderType","status","createdAt","lastUpdateAt"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"orderId":{"type":"string"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this update represents. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. For a taker update, the first fill of its matching round; for a maker update, its single fill. Present only on fill updates; absent for non-fill updates and resting-order snapshots."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this update represents — the length of the contiguous nonce range starting at firstFillId. For a taker update, the fills produced in its matching round; for a maker update, 1. Present only on fill updates; absent otherwise (so it is >= 1 whenever present)."},"side":{"$ref":"#/components/schemas/Side"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Price at which TP/SL orders will be triggered, should not be set for other order types."},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"status":{"$ref":"#/components/schemas/OrderStatus"},"createdAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Creation timestamp (milliseconds)"},"lastUpdateAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Get wallet configuration

> Returns trading configuration for a wallet

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Wallet Data","description":"Accounts, positions, trades, etc."}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/wallet/{address}/configuration":{"get":{"summary":"Get wallet configuration","description":"Returns trading configuration for a wallet","operationId":"getWalletConfiguration","tags":["Wallet Data"],"parameters":[{"$ref":"#/components/parameters/AddressParam"}],"responses":{"200":{"description":"Wallet configuration","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WalletConfiguration"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"parameters":{"AddressParam":{"name":"address","in":"path","required":true,"schema":{"$ref":"#/components/schemas/Address"}}},"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"WalletConfiguration":{"title":"WalletConfiguration","$id":"#WalletConfiguration","type":"object","required":["feeTierId","ogStatus","affiliateStatus","refereeStatus"],"properties":{"feeTierId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Fee tier identifier"},"ogStatus":{"type":"boolean","description":"OG status"},"affiliateStatus":{"type":"boolean","description":"Affiliate status"},"refereeStatus":{"type":"boolean","description":"Referee status"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Order Entry

Order entry operations

## Create order

> Create a new order (IOC, GTC, SL, TP)

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Order Entry","description":"Order entry operations"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/createOrder":{"post":{"summary":"Create order","description":"Create a new order (IOC, GTC, SL, TP)","operationId":"createOrder","tags":["Order Entry"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderRequest"}}}},"responses":{"200":{"description":"Order creation response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"CreateOrderRequest":{"title":"CreateOrderRequest","$id":"#CreateOrderRequest","type":"object","required":["exchangeId","accountId","isBuy","limitPx","orderType","signature","nonce","signerWallet"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"isBuy":{"type":"boolean","description":"Whether this is a buy order"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Trigger price, only for TP/SL orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"Order nonce, see signatures and nonces section for more details."},"signerWallet":{"$ref":"#/components/schemas/Address"},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for PERP IOC orders and all SPOT orders). In seconds since epoch. The order will only be filled before this timestamp."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. Optional field that allows clients to assign their own unique identifier to orders."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"},"CreateOrderResponse":{"title":"CreateOrderResponse","$id":"#CreateOrderResponse","type":"object","required":["status"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"orderId":{"type":"string","description":"Created order ID (currently generated for all order types except IOC)"},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID echoed back from the request"},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this order produced on entry. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. Absent if the order did not fill on entry. For a non-IOC (resting) taker, the same first nonce also appears on the order's taker update in the orderChanges channel; an IOC taker is not published to orderChanges, so this response is the only place its fill range is delivered."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this order produced on entry — the length of the contiguous nonce range starting at firstFillId. Absent if the order did not fill on entry (so it is >= 1 whenever present)."}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Cancel order

> Cancel an existing order

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Order Entry","description":"Order entry operations"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/cancelOrder":{"post":{"summary":"Cancel order","description":"Cancel an existing order","operationId":"cancelOrder","tags":["Order Entry"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderRequest"}}}},"responses":{"200":{"description":"Order cancellation response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"CancelOrderRequest":{"title":"CancelOrderRequest","$id":"#CancelOrderRequest","type":"object","required":["signature"],"properties":{"orderId":{"type":"string","description":"Internal matching engine order ID to cancel. At least one of `orderId` or `clientOrderId` must be provided; if both are supplied the server treats `orderId` as the canonical identifier and `clientOrderId` is ignored. For spot markets, this is the order ID returned in the CreateOrderResponse."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. At least one of `orderId` or `clientOrderId` must be provided; `clientOrderId` is consulted only when `orderId` is absent. This is the same clientOrderId provided in CreateOrderRequest."},"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID that owns the order. Required for spot markets."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Market symbol for the order.Required for spot market orders. If not provided, assumes perp market for backwards compatibility."},"signature":{"type":"string","description":"See signatures section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details. Compulsory for spot orders."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for SPOT orders). In seconds since epoch."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"CancelOrderResponse":{"title":"CancelOrderResponse","$id":"#CancelOrderResponse","type":"object","required":["status","orderId"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"orderId":{"type":"string","description":"Cancelled order ID"},"clientOrderId":{"type":"integer","description":"Client-provided order ID echoed back from the request"}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```

## Cancel all orders

> Cancel all orders matching the specified filters (mass cancel)

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"tags":[{"name":"Order Entry","description":"Order entry operations"}],"servers":[{"url":"https://api.reya.xyz/v2","description":"Production server"},{"url":"https://api-test.reya.xyz/v2","description":"Testnet server"}],"paths":{"/cancelAll":{"post":{"summary":"Cancel all orders","description":"Cancel all orders matching the specified filters (mass cancel)","operationId":"cancelAll","tags":["Order Entry"],"requestBody":{"required":false,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MassCancelRequest"}}}},"responses":{"200":{"description":"Mass cancel response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MassCancelResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalServerError"}}}}},"components":{"schemas":{"MassCancelRequest":{"title":"MassCancelRequest","$id":"#MassCancelRequest","type":"object","required":["signature","nonce","accountId","expiresAfter"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID to cancel orders for."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Symbol to cancel orders for. If not specified, cancels orders for all symbols."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp. In seconds since epoch."}},"additionalProperties":true,"description":"Request to cancel all orders matching the specified filters"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"MassCancelResponse":{"title":"MassCancelResponse","$id":"#MassCancelResponse","type":"object","required":["cancelledCount"],"properties":{"cancelledCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of orders that were cancelled"}},"additionalProperties":true},"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"},"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}},"responses":{"BadRequest":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestError"}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerError"}}}}}}}
```


# Models

## The RequestError object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"RequestError":{"title":"RequestError","$id":"#RequestError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/RequestErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The ServerError object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"ServerError":{"title":"ServerError","$id":"#ServerError","type":"object","required":["error","message"],"properties":{"error":{"$ref":"#/components/schemas/ServerErrorCode"},"message":{"type":"string","description":"Human-readable error message"}},"additionalProperties":true},"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The MarketDefinition object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MarketDefinition":{"title":"MarketDefinition","$id":"#MarketDefinition","type":"object","required":["symbol","marketId","minOrderQty","qtyStepSize","tickSize","liquidationMarginParameter","initialMarginParameter","maxLeverage","oiCap"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each market, only needed to generate signatures"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"},"liquidationMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered to avoid liquidation procedures for a given market; below this value, your account is subject to liquidation procedures. When cross margining, all requirements across markets are covered by the same balance, and all positions are subject to liquidations."},"initialMarginParameter":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum percentage of notional that needs to be covered post trade; if the account does not satisfy this requirement, trades will not get executed."},"maxLeverage":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maximum leverage allowed"},"oiCap":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Maximum one-sided open interest in units for a given market."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The SpotMarketDefinition object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotMarketDefinition":{"title":"SpotMarketDefinition","$id":"#SpotMarketDefinition","type":"object","required":["symbol","marketId","baseAsset","quoteAsset","minOrderQty","qtyStepSize","tickSize"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"marketId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Numerical identifier for each spot market"},"baseAsset":{"type":"string","description":"Base asset symbol"},"quoteAsset":{"type":"string","description":"Quote asset symbol"},"minOrderQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum order quantity (base asset)"},"qtyStepSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum size increment (base asset)"},"tickSize":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Minimum price increment"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The AssetDefinition object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"AssetDefinition":{"title":"AssetDefinition","$id":"#AssetDefinition","type":"object","required":["asset","priceHaircut","liquidationDiscount","status","decimals","displayDecimals"],"properties":{"asset":{"$ref":"#/components/schemas/Asset"},"spotMarketSymbol":{"$ref":"#/components/schemas/Symbol"},"priceHaircut":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Notional discount to the value of a collateral when used to satisfy the margin requirements; it does not imply any token conversion, but is rather an accounting adjustment."},"liquidationDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Discount in the token price when liquidating collateral."},"status":{"type":"string","enum":["ENABLED","WITHDRAWAL_ONLY"],"description":"Status of asset (ENABLED = deposits and withdrawals allowed, WITHDRAWAL_ONLY = only withdrawals allowed)"},"decimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places for record keeping amounts of this asset (e.g. 18 for ETH, 6 for RUSD)"},"displayDecimals":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of decimal places shown for display purposes in frontends"}},"additionalProperties":true},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The FeeTierParameters object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"FeeTierParameters":{"title":"FeeTierParameters","$id":"#FeeTierParameters","type":"object","required":["tierId","takerFee","makerFee","volume14d","tierType"],"properties":{"tierId":{"$ref":"#/components/schemas/UnsignedInteger"},"takerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Taker fee rate (fee will be qty * takerFee)"},"makerFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Maker fee rate (fee will be qty * makerFee)"},"volume14d":{"$ref":"#/components/schemas/UnsignedDecimal","description":"14-day volume level required this fee tier to be applied to a wallet"},"tierType":{"$ref":"#/components/schemas/TierType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"TierType":{"title":"TierType","$id":"#TierType","type":"string","enum":["REGULAR","VIP"],"description":"Fee tier type (REGULAR = Standard tier, VIP = VIP tier)"}}}}
```

## The GlobalFeeParameters object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"GlobalFeeParameters":{"title":"GlobalFeeParameters","$id":"#GlobalFeeParameters","type":"object","required":["ogDiscount","refereeDiscount","referrerRebate","affiliateReferrerRebate"],"properties":{"ogDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"OG user discount"},"refereeDiscount":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referee discount"},"referrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Referrer rebate"},"affiliateReferrerRebate":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Affiliate referrer rebate"}},"additionalProperties":true},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The LiquidityParameters object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"LiquidityParameters":{"title":"LiquidityParameters","$id":"#LiquidityParameters","type":"object","required":["symbol","depth","velocityMultiplier"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"depth":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the liquidity distribution along the AMM pricing curve, in particular expanding or contracting the max exposure parameter that would otherwise be determined by the capital available."},"velocityMultiplier":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Parameter determining the sensitivity of the dynamic funding rate to the size of the imbalances; higher multiplier means that the funding rate will diverge faster, all else being equal."}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The WalletConfiguration object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"WalletConfiguration":{"title":"WalletConfiguration","$id":"#WalletConfiguration","type":"object","required":["feeTierId","ogStatus","affiliateStatus","refereeStatus"],"properties":{"feeTierId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Fee tier identifier"},"ogStatus":{"type":"boolean","description":"OG status"},"affiliateStatus":{"type":"boolean","description":"Affiliate status"},"refereeStatus":{"type":"boolean","description":"Referee status"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The MarketSummary object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MarketSummary":{"title":"MarketSummary","$id":"#MarketSummary","type":"object","required":["symbol","updatedAt","longOiQty","shortOiQty","oiQty","fundingRate","longFundingValue","shortFundingValue","fundingRateVelocity","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the market summary was last calculated (milliseconds)"},"longOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Long open interest in lots"},"shortOiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Short open interest in lots"},"oiQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total open interest quantity"},"fundingRate":{"$ref":"#/components/schemas/SignedDecimal","description":"Current hourly funding rate"},"longFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"shortFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Current reference value of funding accrued by one unit of exposure; there is one funding value per market and per direction, with short v long funding values differing possibly due to Auto-Deleveraging (ADL)"},"fundingRateVelocity":{"$ref":"#/components/schemas/SignedDecimal","description":"Funding rate velocity"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal"},"throttledOraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last oracle price, at the moment of the last market summary update"},"throttledPoolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Last pool price, at the moment of the last market summary update"},"pricesUpdatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of the last price update (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The SpotMarketSummary object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotMarketSummary":{"title":"SpotMarketSummary","$id":"#SpotMarketSummary","type":"object","required":["symbol","updatedAt","volume24h"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Time when the spot market summary was last calculated (milliseconds)"},"volume24h":{"$ref":"#/components/schemas/UnsignedDecimal","description":"24-hour trading volume in USD"},"pxChange24h":{"$ref":"#/components/schemas/SignedDecimal","description":"Absolute 24-hour price change"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Current oracle price"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Position object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Position":{"title":"Position","$id":"#Position","type":"object","required":["exchangeId","symbol","accountId","qty","side","avgEntryPrice","avgEntryFundingValue","lastTradeSequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"avgEntryPrice":{"$ref":"#/components/schemas/SignedDecimal"},"avgEntryFundingValue":{"$ref":"#/components/schemas/SignedDecimal","description":"Average of funding values at the entry times of currently open exposure, which serves as a baseline from which to compute the accrued funding in the position: units x (fundingValue - avgEntryFundingValue)"},"lastTradeSequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Sequence number of last execution taken into account for the position."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Order object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Order":{"title":"Order","$id":"#Order","type":"object","required":["exchangeId","symbol","accountId","orderId","side","limitPx","orderType","status","createdAt","lastUpdateAt"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"orderId":{"type":"string"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this update represents. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. For a taker update, the first fill of its matching round; for a maker update, its single fill. Present only on fill updates; absent for non-fill updates and resting-order snapshots."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this update represents — the length of the contiguous nonce range starting at firstFillId. For a taker update, the fills produced in its matching round; for a maker update, 1. Present only on fill updates; absent otherwise (so it is >= 1 whenever present)."},"side":{"$ref":"#/components/schemas/Side"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Price at which TP/SL orders will be triggered, should not be set for other order types."},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"status":{"$ref":"#/components/schemas/OrderStatus"},"createdAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Creation timestamp (milliseconds)"},"lastUpdateAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"}}}}
```

## The Account object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Account":{"title":"Account","$id":"#Account","type":"object","required":["accountId","name","type"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"name":{"type":"string"},"type":{"$ref":"#/components/schemas/AccountType"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"AccountType":{"title":"AccountType","$id":"#AccountType","type":"string","enum":["MAINPERP","SUBPERP","SPOT"],"description":"SPOT = account that can only trade spot, MAINPERP = main perp account, SUBPERP = sub perp account"}}}}
```

## The AccountBalance object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"AccountBalance":{"title":"AccountBalance","$id":"#AccountBalance","type":"object","required":["accountId","asset","realBalance","balanceDEPRECATED"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"asset":{"$ref":"#/components/schemas/Asset"},"realBalance":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals) and realized pnl from closed positions. Realized pnl only applies to RUSD given it is the only settlement asset"},"balanceDEPRECATED":{"$ref":"#/components/schemas/SignedDecimal","description":"Sum of account net deposits (transfers, deposits and withdrawals). This field is deprecated and will be removed in a future release"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The PerpExecutionList object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"PerpExecutionList":{"title":"PerpExecutionList","$id":"#PerpExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PerpExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true}}}}
```

## The SpotExecutionList object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecutionList":{"title":"SpotExecutionList","$id":"#SpotExecutionList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecution"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true}}}}
```

## The SpotExecutionBustList object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecutionBustList":{"title":"SpotExecutionBustList","$id":"#SpotExecutionBustList","type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SpotExecutionBust"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"additionalProperties":true},"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true}}}}
```

## The Price object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Price":{"title":"Price","$id":"#Price","type":"object","required":["symbol","updatedAt","oraclePrice"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"oraclePrice":{"$ref":"#/components/schemas/SignedDecimal","description":"Price given by the Stork feeds, used both as the peg price for prices on Reya, as well as Mark Prices. The Stork price feed is usually the perp prices across three major CEXs"},"poolPrice":{"$ref":"#/components/schemas/SignedDecimal","description":"The price currently quoted by the AMM for zero volume, from which trades are priced (equivalent to mid price in an order book); a trade of any size will be move this price up or down depending on the direction."},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Last update timestamp (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The CandleHistoryData object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CandleHistoryData":{"title":"CandleHistoryData","$id":"#CandleHistoryData","type":"object","required":["t","o","h","l","c"],"properties":{"t":{"type":"array","items":{"$ref":"#/components/schemas/UnsignedInteger"},"description":"Array of timestamps (seconds)"},"o":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of opening prices"},"h":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of high prices"},"l":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of low prices"},"c":{"type":"array","items":{"$ref":"#/components/schemas/SignedDecimal"},"description":"Array of closing prices"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The CreateOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CreateOrderRequest":{"title":"CreateOrderRequest","$id":"#CreateOrderRequest","type":"object","required":["exchangeId","accountId","isBuy","limitPx","orderType","signature","nonce","signerWallet"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"isBuy":{"type":"boolean","description":"Whether this is a buy order"},"limitPx":{"$ref":"#/components/schemas/SignedDecimal"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"orderType":{"$ref":"#/components/schemas/OrderType"},"timeInForce":{"$ref":"#/components/schemas/TimeInForce","description":"Order time in force, exclusively used for LIMIT orders"},"triggerPx":{"$ref":"#/components/schemas/SignedDecimal","description":"Trigger price, only for TP/SL orders"},"reduceOnly":{"type":"boolean","description":"Whether this is a reduce-only order, exclusively used for LIMIT IOC orders."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"Order nonce, see signatures and nonces section for more details."},"signerWallet":{"$ref":"#/components/schemas/Address"},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for PERP IOC orders and all SPOT orders). In seconds since epoch. The order will only be filled before this timestamp."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. Optional field that allows clients to assign their own unique identifier to orders."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"},"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"},"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}}}
```

## The CreateOrderResponse object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CreateOrderResponse":{"title":"CreateOrderResponse","$id":"#CreateOrderResponse","type":"object","required":["status"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"execQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Executed quantity in the current order update."},"cumQty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Total Executed quantity accross all fills where the order is involved."},"orderId":{"type":"string","description":"Created order ID (currently generated for all order types except IOC)"},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID echoed back from the request"},"firstFillId":{"type":"string","description":"Matching-engine fill nonce of the first fill this order produced on entry. Together with fillCount it identifies the fills as a contiguous nonce range [firstFillId, firstFillId + fillCount - 1]. Absent if the order did not fill on entry. For a non-IOC (resting) taker, the same first nonce also appears on the order's taker update in the orderChanges channel; an IOC taker is not published to orderChanges, so this response is the only place its fill range is delivered."},"fillCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of fills this order produced on entry — the length of the contiguous nonce range starting at firstFillId. Absent if the order did not fill on entry (so it is >= 1 whenever present)."}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The CancelOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CancelOrderRequest":{"title":"CancelOrderRequest","$id":"#CancelOrderRequest","type":"object","required":["signature"],"properties":{"orderId":{"type":"string","description":"Internal matching engine order ID to cancel. At least one of `orderId` or `clientOrderId` must be provided; if both are supplied the server treats `orderId` as the canonical identifier and `clientOrderId` is ignored. For spot markets, this is the order ID returned in the CreateOrderResponse."},"clientOrderId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Client-provided order ID for tracking and correlation. At least one of `orderId` or `clientOrderId` must be provided; `clientOrderId` is consulted only when `orderId` is absent. This is the same clientOrderId provided in CreateOrderRequest."},"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID that owns the order. Required for spot markets."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Market symbol for the order.Required for spot market orders. If not provided, assumes perp market for backwards compatibility."},"signature":{"type":"string","description":"See signatures section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details. Compulsory for spot orders."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp (exclusively for SPOT orders). In seconds since epoch."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"}}}}
```

## The CancelOrderResponse object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"CancelOrderResponse":{"title":"CancelOrderResponse","$id":"#CancelOrderResponse","type":"object","required":["status","orderId"],"properties":{"status":{"$ref":"#/components/schemas/OrderStatus"},"orderId":{"type":"string","description":"Cancelled order ID"},"clientOrderId":{"type":"integer","description":"Client-provided order ID echoed back from the request"}},"additionalProperties":true},"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"}}}}
```

## The MassCancelRequest object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MassCancelRequest":{"title":"MassCancelRequest","$id":"#MassCancelRequest","type":"object","required":["signature","nonce","accountId","expiresAfter"],"properties":{"accountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Account ID to cancel orders for."},"symbol":{"$ref":"#/components/schemas/Symbol","description":"Symbol to cancel orders for. If not specified, cancels orders for all symbols."},"signature":{"type":"string","description":"See signatures and nonces section for more details on how to generate."},"nonce":{"type":"string","description":"See signatures and nonces section for more details."},"expiresAfter":{"$ref":"#/components/schemas/UnsignedInteger","description":"Expiration timestamp. In seconds since epoch."}},"additionalProperties":true,"description":"Request to cancel all orders matching the specified filters"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"}}}}
```

## The MassCancelResponse object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"MassCancelResponse":{"title":"MassCancelResponse","$id":"#MassCancelResponse","type":"object","required":["cancelledCount"],"properties":{"cancelledCount":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of orders that were cancelled"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The Depth object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Depth":{"title":"Depth","$id":"#Depth","type":"object","required":["symbol","type","bids","asks","updatedAt"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"type":{"$ref":"#/components/schemas/DepthType"},"bids":{"type":"array","description":"Bid side levels aggregated by price, sorted descending by price","items":{"$ref":"#/components/schemas/Level"}},"asks":{"type":"array","description":"Ask side levels aggregated by price, sorted ascending by price","items":{"$ref":"#/components/schemas/Level"}},"updatedAt":{"$ref":"#/components/schemas/UnsignedInteger","description":"Snapshot generation timestamp (milliseconds)"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"DepthType":{"title":"DepthType","$id":"#DepthType","type":"string","enum":["SNAPSHOT","UPDATE"],"description":"Depth message type (SNAPSHOT = full book, UPDATE = single level change)"},"Level":{"title":"Level","$id":"#Level","type":"object","required":["px","qty"],"properties":{"px":{"$ref":"#/components/schemas/SignedDecimal","description":"Price level"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Aggregated quantity at this price level"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The ServerErrorCode object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"ServerErrorCode":{"title":"ServerErrorCode","$id":"#ServerErrorCode","type":"string","enum":["INTERNAL_SERVER_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The Symbol object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"}}}}
```

## The UnsignedInteger object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The UnsignedDecimal object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The RequestErrorCode object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"RequestErrorCode":{"title":"RequestErrorCode","$id":"#RequestErrorCode","type":"string","enum":["SYMBOL_NOT_FOUND","NO_ACCOUNTS_FOUND","NO_PRICES_FOUND_FOR_SYMBOL","INPUT_VALIDATION_ERROR","CREATE_ORDER_OTHER_ERROR","CANCEL_ORDER_OTHER_ERROR","ORDER_DEADLINE_PASSED_ERROR","ORDER_DEADLINE_TOO_HIGH_ERROR","INVALID_NONCE_ERROR","UNAVAILABLE_MATCHING_ENGINE_ERROR","UNAUTHORIZED_SIGNATURE_ERROR","NUMERIC_OVERFLOW_ERROR"],"description":"Standardized error codes for API responses"}}}}
```

## The SignedDecimal object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Asset object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Asset":{"title":"Asset","$id":"#Asset","type":"string","pattern":"^[A-Za-z0-9]+$"}}}}
```

## The TierType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"TierType":{"title":"TierType","$id":"#TierType","type":"string","enum":["REGULAR","VIP"],"description":"Fee tier type (REGULAR = Standard tier, VIP = VIP tier)"}}}}
```

## The Side object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"}}}}
```

## The ExecutionType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"}}}}
```

## The PerpExecution object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"PerpExecution":{"title":"PerpExecution","$id":"#PerpExecution","type":"object","required":["exchangeId","symbol","accountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal","description":"Total execution fee in rUSD"},"openingFee":{"$ref":"#/components/schemas/SignedDecimal","description":"Opening fee portion of the total fee in rUSD. Absent for position-extending executions."},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every perp execution in reya chain"},"realizedPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions."},"priceVariationPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from price movement in rUSD. Absent for position-extending executions."},"fundingPnl":{"$ref":"#/components/schemas/SignedDecimal","description":"PnL component from funding payments in rUSD. Absent for position-extending executions."}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"}}}}
```

## The PaginationMeta object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"PaginationMeta":{"title":"PaginationMeta","$id":"#PaginationMeta","type":"object","required":["limit","count"],"properties":{"limit":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items requested"},"count":{"$ref":"#/components/schemas/UnsignedInteger","description":"Number of items returned"},"endTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of last result, in milliseconds"},"startTime":{"$ref":"#/components/schemas/UnsignedInteger","description":"Timestamp of first result, in milliseconds"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0}}}}
```

## The DepthType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"DepthType":{"title":"DepthType","$id":"#DepthType","type":"string","enum":["SNAPSHOT","UPDATE"],"description":"Depth message type (SNAPSHOT = full book, UPDATE = single level change)"}}}}
```

## The Level object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Level":{"title":"Level","$id":"#Level","type":"object","required":["px","qty"],"properties":{"px":{"$ref":"#/components/schemas/SignedDecimal","description":"Price level"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Aggregated quantity at this price level"}},"additionalProperties":true},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The SpotExecution object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecution":{"title":"SpotExecution","$id":"#SpotExecution","type":"object","required":["symbol","accountId","makerAccountId","qty","side","fee","price","type","timestamp","sequenceNumber"],"properties":{"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"side":{"$ref":"#/components/schemas/Side"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"fee":{"$ref":"#/components/schemas/SignedDecimal"},"type":{"$ref":"#/components/schemas/ExecutionType"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution in reya chain"}},"additionalProperties":true},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"ExecutionType":{"title":"ExecutionType","$id":"#ExecutionType","type":"string","enum":["ORDER_MATCH","LIQUIDATION","ADL"],"description":"Type of execution"}}}}
```

## The SpotExecutionBust object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"SpotExecutionBust":{"title":"SpotExecutionBust","$id":"#SpotExecutionBust","type":"object","required":["symbol","accountId","exchangeId","makerAccountId","orderId","makerOrderId","qty","side","price","reason","timestamp","sequenceNumber"],"properties":{"symbol":{"$ref":"#/components/schemas/Symbol"},"accountId":{"$ref":"#/components/schemas/UnsignedInteger"},"exchangeId":{"$ref":"#/components/schemas/UnsignedInteger"},"makerAccountId":{"$ref":"#/components/schemas/UnsignedInteger","description":"Maker account ID (counterparty)"},"orderId":{"type":"string","description":"Order ID for the taker"},"makerOrderId":{"type":"string","description":"Order ID for the maker"},"qty":{"$ref":"#/components/schemas/UnsignedDecimal","description":"Failed base quantity"},"side":{"$ref":"#/components/schemas/Side"},"price":{"$ref":"#/components/schemas/SignedDecimal"},"reason":{"type":"string","description":"Hex-encoded revert reason bytes"},"timestamp":{"$ref":"#/components/schemas/UnsignedInteger","description":"Block timestamp (milliseconds)"},"sequenceNumber":{"$ref":"#/components/schemas/UnsignedInteger","description":"Execution sequence number, increases by 1 for every spot execution bust in reya chain"}},"additionalProperties":true},"Symbol":{"title":"Symbol","$id":"#Symbol","type":"string","pattern":"^[A-Za-z0-9]+$","description":"Trading symbol (e.g., BTCRUSDPERP, WETHRUSD)"},"UnsignedInteger":{"title":"UnsignedInteger","$id":"#UnsignedInteger","type":"integer","minimum":0},"UnsignedDecimal":{"title":"UnsignedDecimal","$id":"#UnsignedDecimal","type":"string","pattern":"^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"},"Side":{"title":"Side","$id":"#Side","type":"string","enum":["B","A"],"description":"Order side (B = Buy/Bid, A = Ask/Sell)"},"SignedDecimal":{"title":"SignedDecimal","$id":"#Decimal","type":"string","pattern":"^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$"}}}}
```

## The Address object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"Address":{"title":"Address","$id":"#Address","type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}}}
```

## The AccountType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"AccountType":{"title":"AccountType","$id":"#AccountType","type":"string","enum":["MAINPERP","SUBPERP","SPOT"],"description":"SPOT = account that can only trade spot, MAINPERP = main perp account, SUBPERP = sub perp account"}}}}
```

## The OrderType object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"OrderType":{"title":"OrderType","$id":"#OrderType","type":"string","enum":["LIMIT","TP","SL"],"description":"Order type, (LIMIT = Limit, TP = Take Profit, SL = Stop Loss)"}}}}
```

## The TimeInForce object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"TimeInForce":{"title":"TimeInForce","$id":"#TimeInForce","type":"string","enum":["IOC","GTC"],"description":"Order time in force (IOC = Immediate or Cancel, GTC = Good Till Cancel)"}}}}
```

## The OrderStatus object

```json
{"openapi":"3.0.3","info":{"title":"Reya DEX Trading API v2","version":"2.3.6"},"components":{"schemas":{"OrderStatus":{"title":"OrderStatus","$id":"#OrderStatus","type":"string","enum":["OPEN","FILLED","CANCELLED","REJECTED"],"description":"Order status"}}}}
```


# Signatures and Nonces

Signatures are required to safely execute orders in the name of your wallet. The API endpoints for order management require a user signature that must be created on the client side using your private key. These signatures are validated on-chain for all order details you specified to ensure no unintended action is executed on your account. Internal nonces for your wallet address, tracked in the smart contracts, are used to prevent replay attacks. Creating your own signatures and nonces can be a bit tricky, and a single detail being wrong will result in an "invalid signature" error which are notably hard to debug. Our recommendation is to check our python SDK's code to fully understand every detail on how signatures need to be produced.


# WebSocket API Reference


# Heartbeats

Reya's WebSocket APIs (both [Info](/developers/websocket-api-reference/websocket-api-reference) and [Order Entry](/developers/websocket-api-reference/ws-exec-api-reference)) use **identical** heartbeat mechanics. This page is the single source of truth for how heartbeats work on both surfaces and what clients need to do — or, more accurately, what they don't need to do.

For most clients, no action is required. Any standards-compliant WebSocket library handles heartbeats automatically at the protocol layer: the server periodically issues protocol-level pings, the client library replies with the corresponding pongs, and the connection stays alive without any application-level involvement. There is no ping handler to write, no pong to send, and no timer to track.

The exception is clients running behind network middleboxes — corporate firewalls or load balancers that drop "idle" connections more aggressively than the server's own idle threshold. Even in those cases, the resolution is a single line of WebSocket-library configuration rather than any application-level work. See [Behind a strict middlebox?](#behind-a-strict-middlebox) for the specifics.

## The Two Layers — Why This Page Exists

There are two completely different "ping/pong" concepts in a WebSocket connection, and confusing them is the most common source of integration bugs. Reya uses one of them for connection health; the other is an optional convenience feature.

### Layer 1 — Protocol-level heartbeat (RFC 6455 control frames)

This is the actual mechanism Reya uses to detect dead connections. It runs **below the application layer**, at the WebSocket protocol itself ([RFC 6455 §5.5.2](https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2)).

* The server periodically sends a special binary frame called a **PING control frame** (opcode `0x9`).
* The client's WebSocket library — every standards-compliant one — automatically replies with a **PONG control frame** (opcode `0xA`). This happens without any application code running.
* If the client is dead (TCP disconnected, process crashed, network gone), the server gets no PONG. After a configured timeout, the server closes the connection.

The key property: **this layer is invisible to your application code.** You never see a `ping` or `pong` event. Your `onMessage` handler is never invoked. The browser's `WebSocket.onmessage`, Python `websocket-client`'s callback, Node `ws`'s `'message'` event — none of them fire for protocol-level pings or pongs.

### Layer 2 — Application-level JSON ping (optional)

This is a *separate*, *optional* feature. Reya supports a JSON-level `{"type":"ping"}` frame that clients can send if they want explicit round-trip measurement or correlation. The server replies with `{"type":"pong"}`. **This does not contribute to keeping the connection alive** — the protocol-level heartbeat in Layer 1 already handles that. Layer 2 is purely for use cases like:

* Measuring application-level round-trip latency
* Correlating a specific probe to its response (the `id` field round-trips)
* Asserting "the server is alive and processing application messages" (vs just "the TCP socket is up")

If you don't have one of these specific needs, you can ignore Layer 2 entirely.

## How Reya's Servers Are Configured

Both WebSocket APIs run on Bun's WebSocket server with the same two flags:

| Setting           | Value       | What it does                                                                                                                               |
| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `sendPings: true` | enabled     | The server periodically sends RFC 6455 PING control frames to every connected client. The client's WS library auto-replies with PONG.      |
| `idleTimeout`     | 120 seconds | If the server receives **no inbound traffic** (data messages, RFC 6455 PONGs, or anything else) for 120 seconds, it closes the connection. |

These two work together: as long as your client is responsive at the protocol level (which it is, automatically), the auto-pong replies count as inbound traffic and the idle timeout never fires.

If your client truly stops responding — TCP died, process crashed, network dropped — no pong arrives, no other traffic arrives, and after 120 seconds the server closes the socket. Your `onclose` handler fires (with a non-1000 close code), and you reconnect.

## What Your Client Has to Do

**Nothing, for the default case.** The chain of events for a healthy idle connection is:

1. Server sends a protocol-level PING.
2. Your WebSocket library's networking layer receives the PING, generates a PONG, sends it back. None of this surfaces to your application code.
3. The PONG arrives at the server. The server's idle counter resets.
4. Repeat every \~half of `idleTimeout`.

Your application doesn't see steps 1–4. It only sees data messages you care about. Your `onmessage` / `on_message` / etc. handler is never invoked for any of this.

## Behind a Strict Middlebox?

Some networks (corporate firewalls, mobile carriers, aggressive load balancers) drop "idle" TCP connections after \~30–60 seconds even if both ends would prefer to keep them alive. Reya's server-sent pings happen well within the server's 120-second timeout, but they're paced for the server's needs — not for the most aggressive middleboxes on the planet.

If you encounter spurious disconnects through such a network, configure your **client** to send its own protocol-level pings at a shorter interval. This is one line of config in every common WebSocket library:

**Python (`websocket-client`):**

```python
ws.run_forever(ping_interval=20, ping_timeout=10)
```

**Python (`websockets`, async):**

```python
async with websockets.connect(url, ping_interval=20, ping_timeout=10) as ws:
    ...
```

**Node (`ws`):**

```javascript
setInterval(() => ws.ping(), 20_000);  // ws library auto-handles pong replies
```

**Rust (`tokio-tungstenite`):**

```rust
// Send a Ping control frame manually
ws.send(Message::Ping(vec![])).await?;
```

**Browser (vanilla `WebSocket`):** The browser handles protocol-level pings internally and exposes no API to send them from JavaScript. If your browser-based client gets dropped by a middlebox, the only knob is application-level: send a `{"type":"ping"}` JSON frame periodically. See the next section.

The "20 seconds" figure above is conservative — fast enough for almost any middlebox, light enough to be invisible in traffic volume. Adjust if your environment requires something more aggressive.

## The Optional Application-Level Probe

If you need it, here's how Layer 2 looks on the wire:

### Client sends a ping

```json
{
  "type": "ping",
  "id": "probe-001"
}
```

* `type`: required, must be the literal string `"ping"`.
* `id`: optional. A free-form string you choose. Use it if you want to correlate this specific probe with its reply; omit it if you just want a round-trip sanity check.

### Server replies with a pong

```json
{
  "type": "pong",
  "id": "probe-001"
}
```

* `type`: literal string `"pong"`.
* `id`: echoed back **if** the client sent one. If the client's ping had no `id`, the pong has no `id`.

That's the entire payload — there are no other fields, no `timestamp`, no `serverTimeMs`, nothing else. The server doesn't include its own time and doesn't echo any client time.

### When to use Layer 2 vs trust Layer 1

| Need                                                  | Solution                                                                               |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------- |
| "Keep my connection alive"                            | Layer 1 (automatic, do nothing)                                                        |
| "Detect a half-dead server / unresponsive backend"    | Layer 2 (send a JSON ping, expect a JSON pong)                                         |
| "Measure round-trip latency from my application code" | Layer 2 (timestamp your ping send, subtract from pong receive)                         |
| "Correlate a probe with its specific reply"           | Layer 2 (use the `id` field)                                                           |
| "Survive an aggressive middlebox"                     | Configure your WS library's protocol-level `ping_interval` (Layer 1, client-initiated) |

Note that Layer 2 is purely additive — using it doesn't disable or replace the Layer 1 mechanism. Both run in parallel.

## What Happens When the Server Closes the Connection

The server can close a connection for several reasons; you'll see different close codes depending on cause:

| Close code               | Meaning                                                        | Recommended client action                |
| ------------------------ | -------------------------------------------------------------- | ---------------------------------------- |
| `1000`                   | Normal closure (you or the server called close cleanly)        | Reconnect if you still want a connection |
| `1001`                   | Server going away (e.g. during a rolling deploy / pod restart) | Reconnect after a short backoff          |
| `1006` / `1011` / others | Idle timeout, server error, abrupt closure                     | Reconnect with exponential backoff       |

In all cases, the right pattern is the same: reconnect with backoff, replay your subscription state (for Info) or your in-flight order state (for Order Entry — but note in-flight orders are independently durable on-chain or in the matching engine, so you don't typically need to replay anything).

For the surface-specific post-reconnect steps, see [Reconnection Pattern](/developers/websocket-api-reference/websocket-api-reference#reconnection-pattern) on the Info WebSocket reference and [Reconnection Pattern](/developers/websocket-api-reference/ws-exec-api-reference#reconnection-pattern) on the Order Entry WebSocket reference.

### Server-Side Graceful Shutdown

During a server-side rolling deploy or pod restart, the server closes connections with WS close code `1001 SERVER_SHUTTING_DOWN` after a drain period (currently 10 seconds) in which:

1. The `/ready` health endpoint returns `503` so the load balancer stops sending new connections to this pod.
2. In-flight requests are allowed to complete.
3. Idle connections are closed first; busy connections wait for their in-flight handler to finish.

After the drain timeout, any still-open connections are force-closed with `1001`. Clients should treat `1001` as a soft reconnect signal — the next pod is already accepting new connections.

This applies to both the Info and Order Entry WebSocket APIs. The drain period matters more in practice for Order Entry (where an in-flight `createOrder` whose response is lost can still settle on-chain — see [Reconnection Pattern](/developers/websocket-api-reference/ws-exec-api-reference#reconnection-pattern) for how to reconcile), but the close-code sequence is the same on both surfaces.

## Frequently Asked Questions

**Q: Do I need to implement a ping handler in my client?** No. The protocol-level heartbeat is handled by your WebSocket library automatically. You only need an application-level ping handler if you choose to use the Layer 2 probe.

**Q: How do I know if the server-side pings are actually firing?** You generally don't, and you don't need to. They happen at a layer below your application code. If your connection survives 5+ minutes of application-level silence, the pings are firing correctly. If it dies after exactly 120 seconds of silence and you didn't see any application-level activity, your client's WS library isn't responding to protocol pings — which is unusual but worth investigating.

**Q: Can I send `{"type":"pong"}` from my client?** No, and you shouldn't. The server has no handler for client-initiated JSON pong frames — sending one will result in an "Invalid type" / `UNKNOWN_TYPE` error. The only `pong` direction is server→client, in response to a client-initiated `{"type":"ping"}` (Layer 2).

**Q: Does the optional `id` on a ping need to be unique?** No. It's just a string you choose. If you send multiple pings in flight at once and want to match each pong to its ping, use unique `id`s. If you only ever have one ping in flight at a time, you can reuse the same `id` or omit it entirely.

**Q: What's the `timestamp` field I see in the spec?** The AsyncAPI spec declares `timestamp?: integer` on both `PingMessagePayload` and `PongMessagePayload`. Today the server doesn't read or set it — it's reserved for potential future use (e.g. server-side time for clock-sync). You can safely ignore it.


# WebSocket Info API Reference

## Overview

The Reya DEX Trading WebSocket API v2 provides real-time streaming data for decentralized exchange operations on the Reya Network. This version offers user-friendly data structures with human-readable formats, removing blockchain-specific details while maintaining comprehensive trading functionality.

For placing and cancelling orders over WebSocket, see [WebSocket Order Entry API Reference](/developers/websocket-api-reference/ws-exec-api-reference). The recommended Market Maker integration runs both connections in parallel: that surface for order entry, this surface for read-side fanout.

## Server Endpoints

### Production Environment

* **URL**: `wss://ws.reya.xyz`
* **Protocol**: WSS
* **Description**: Production WebSocket server for live trading

### Staging Environment

* **URL**: `wss://websocket-staging.reya.xyz`
* **Protocol**: WSS
* **Description**: Staging WebSocket server for pre-production testing

### Test Environment

* **URL**: `wss://websocket-testnet.reya.xyz`
* **Protocol**: WSS
* **Description**: Test WebSocket server for development

## Channel Architecture

The API uses a hierarchical channel structure with clear separation between different data types:

{% stepper %}
{% step %}

#### Market Data Channels

* `/v2/markets/summary` - Perp market summaries
* `/v2/market/{symbol}/summary` - Individual perp market summary
* `/v2/spotMarkets/summary` - Spot market summaries
* `/v2/spotMarket/{symbol}/summary` - Individual spot market summary
* `/v2/market/{symbol}/perpExecutions` - Market-specific perpetual executions
* `/v2/market/{symbol}/depth` - L2 order book depth snapshots, only relevant for markets using the Reya Order Book instead of the AMM
* `/v2/market/{symbol}/spotExecutions` - Market-specific spot executions
* `/v2/market/{symbol}/spotExecutionBusts` - Market-specific spot execution busts (failed spot fills)
* `/v2/prices` - All symbol prices
* `/v2/prices/{symbol}` - Individual symbol prices
  {% endstep %}

{% step %}

#### Wallet Data Channels

* `/v2/wallet/{address}/positions` - Position updates
* `/v2/wallet/{address}/orderChanges` - Order change updates
* `/v2/wallet/{address}/perpExecutions` - Wallet-specific perpetual executions
* `/v2/wallet/{address}/spotExecutions` - Wallet-specific spot executions
* `/v2/wallet/{address}/spotExecutionBusts` - Wallet-specific spot execution busts
* `/v2/wallet/{address}/accountBalances` - Account balance updates
  {% endstep %}
  {% endstepper %}

### Parameter Validation

#### Symbol Parameter

* **Pattern**: `^[A-Za-z0-9]+$`
* **Examples**: `BTCRUSDPERP`, `ETHRUSD`, `kBONKRUSDPERP`, `AI16ZRUSDPERP`
* **Description**: Trading symbol supporting alphanumeric characters

#### Address Parameter

* **Pattern**: `^0x[a-fA-F0-9]{40}$`
* **Example**: `0x6c51275fd01d5dbd2da194e92f920f8598306df2`
* **Description**: Ethereum wallet address (40 hexadecimal characters)

## Message Structure

The Info surface uses one envelope shape for streamed channel data, plus a small set of control envelopes for subscription management. All envelopes share a `type` discriminator at the top level; the rest of the body is type-specific.

### Channel Data Envelope (Server → Client)

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/market/BTCRUSDPERP/summary",
  "data": { /* channel-specific data */ }
}
```

* **type**: Always `"channel_data"` for data updates
* **timestamp**: Server timestamp in milliseconds
* **channel**: Specific channel identifier
* **data**: Channel-specific payload (object or array)

### Subscribe Envelope (Client → Server)

```json
{
  "type": "subscribe",
  "channel": "/v2/markets/summary",
  "id": "req123"
}
```

The `id` is an optional client-chosen correlation marker. The server does not echo it back in the confirmation and does not enforce uniqueness across in-flight subscribes; it is purely for client-side bookkeeping.

### Subscribed Confirmation (Server → Client)

```json
{
  "type": "subscribed",
  "channel": "/v2/markets/summary",
  "contents": { /* optional initial data */ }
}
```

The `contents` field carries an initial snapshot for channels that provide one (e.g. `/v2/market/{symbol}/depth`); otherwise it is omitted.

### Unsubscribe Envelope (Client → Server)

```json
{
  "type": "unsubscribe",
  "channel": "/v2/markets/summary",
  "id": "req123"
}
```

### Unsubscribed Confirmation (Server → Client)

```json
{
  "type": "unsubscribed",
  "channel": "/v2/markets/summary"
}
```

### Error Envelope (Server → Client)

```json
{
  "type": "error",
  "message": "Invalid channel",
  "channel": "/v2/invalid/channel"
}
```

The shape and the full set of possible `message` values are documented in [Error Catalog](#error-catalog) below.

### Heartbeats

The heartbeat / connection-liveness mechanism is documented in detail on its own page — see [Heartbeats](/developers/websocket-api-reference/heartbeats). Short version: protocol-level pings handle liveness automatically, no application-level code is required on the client.

## Channels Reference

### 1. Market Data Channels

#### `/v2/markets/summary`

**Purpose**: Real-time updates for all market summaries

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/markets/summary"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/markets/summary",
  "data": [
    {
      "symbol": "BTCRUSDPERP",
      "updatedAt": 1747927089946,
      "longOiQty": "154.741",
      "shortOiQty": "154.706",
      "oiQty": "154.741",
      "fundingRate": "-0.000509373441021089",
      "longFundingValue": "412142.26",
      "shortFundingValue": "412142.26",
      "fundingRateVelocity": "-0.00000006243",
      "volume24h": "917833.49891",
      "pxChange24h": "92.6272285500004",
      "throttledOraclePrice": "2666.48162040777",
      "throttledPoolPrice": "2666.48166680625",
      "pricesUpdatedAt": 1747927089597
    }
  ]
}
```

<details>

<summary><strong>Data Type - MarketSummary</strong></summary>

* `symbol` (string): Trading symbol
* `updatedAt` (integer): Last calculation timestamp (milliseconds)
* `longOiQty` (string): Long open interest in lots
* `shortOiQty` (string): Short open interest in lots
* `oiQty` (string): Total open interest quantity
* `fundingRate` (string): Current hourly funding rate
* `longFundingValue` (string): Current long funding value
* `shortFundingValue` (string): Current short funding value
* `fundingRateVelocity` (string): Funding rate velocity
* `volume24h` (string): 24-hour trading volume
* `pxChange24h` (string, optional): 24-hour price change
* `throttledOraclePrice` (string, optional): Last oracle price at summary update
* `throttledPoolPrice` (string, optional): Last pool price at summary update
* `pricesUpdatedAt` (integer, optional): Last price update timestamp

</details>

#### `/v2/market/{symbol}/summary`

**Purpose**: Real-time updates for a specific market's summary

**Parameters**:

* `symbol`: Trading symbol (e.g., `BTCRUSDPERP`, `kBONKRUSDPERP`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/market/BTCRUSDPERP/summary"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/market/BTCRUSDPERP/summary",
  "data": {
    "symbol": "BTCRUSDPERP",
    "updatedAt": 1747927089946,
    "longOiQty": "154.741",
    "shortOiQty": "154.706",
    "oiQty": "154.741",
    "fundingRate": "-0.000509373441021089",
    "longFundingValue": "412142.26",
    "shortFundingValue": "412142.26",
    "fundingRateVelocity": "-0.00000006243",
    "volume24h": "917833.49891",
    "pxChange24h": "92.6272285500004",
    "throttledOraclePrice": "2666.48162040777",
    "throttledPoolPrice": "2666.48166680625",
    "pricesUpdatedAt": 1747927089597
  }
}
```

<details>

<summary><strong>Data Type - MarketSummary</strong></summary>

Same as above - see `/v2/markets/summary` channel for complete field definitions.

</details>

#### `/v2/spotMarkets/summary`

**Purpose**: Real-time updates for all spot market summaries

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/spotMarkets/summary"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/spotMarkets/summary",
  "data": [
    {
      "symbol": "WETHRUSD",
      "updatedAt": 1747927089946,
      "volume24h": "917833.49891",
      "pxChange24h": "92.6272285500004",
      "oraclePrice": "2666.48162040777"
    }
  ]
}
```

<details>

<summary><strong>Data Type - SpotMarketSummary</strong></summary>

* `symbol` (string): Trading symbol
* `updatedAt` (integer): Last calculation timestamp (milliseconds)
* `volume24h` (string): 24-hour trading volume in USD
* `pxChange24h` (string, optional): Absolute 24-hour price change
* `oraclePrice` (string, optional): Current oracle price

</details>

#### `/v2/spotMarket/{symbol}/summary`

**Purpose**: Real-time updates for a specific spot market's summary

**Parameters**:

* `symbol`: Trading symbol (e.g., `WETHRUSD`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/spotMarket/WETHRUSD/summary"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/spotMarket/WETHRUSD/summary",
  "data": {
    "symbol": "WETHRUSD",
    "updatedAt": 1747927089946,
    "volume24h": "917833.49891",
    "pxChange24h": "92.6272285500004",
    "oraclePrice": "2666.48162040777"
  }
}
```

<details>

<summary><strong>Data Type - SpotMarketSummary</strong></summary>

Same as above - see `/v2/spotMarkets/summary` channel for complete field definitions.

</details>

#### `/v2/market/{symbol}/perpExecutions`

**Purpose**: Real-time perpetual executions for a specific market

**Parameters**:

* `symbol`: Trading symbol (e.g., `BTCRUSDPERP`, `AI16ZRUSDPERP`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/market/BTCRUSDPERP/perpExecutions"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/market/BTCRUSDPERP/perpExecutions",
  "data": [
    {
      "exchangeId": 1,
      "symbol": "BTCRUSDPERP",
      "accountId": 12345,
      "qty": "1.0",
      "side": "B",
      "price": "43000.00",
      "fee": "0.50",
      "type": "ORDER_MATCH",
      "timestamp": 1747927089946,
      "sequenceNumber": 152954
    }
  ]
}
```

<details>

<summary><strong>Data Type - PerpExecution</strong></summary>

* `exchangeId` (integer): Exchange identifier
* `symbol` (string): Trading symbol
* `accountId` (integer): Account identifier
* `qty` (string): Execution quantity
* `side` (Side): Execution side (B=Buy, A=Sell)
* `fee` (string): Total execution fee in rUSD
* `openingFee` (string, optional): Opening fee portion of the total fee in rUSD. Absent for position-extending executions.
* `price` (string): Execution price
* `type` (ExecutionType): Execution type (ORDER\_MATCH, LIQUIDATION, ADL)
* `timestamp` (integer): Execution timestamp (milliseconds)
* `sequenceNumber` (integer): Global sequence number
* `realizedPnl` (string, optional): Realized PnL from this execution in rUSD (priceVariationPnl + fundingPnl). Absent for position-extending executions.
* `priceVariationPnl` (string, optional): PnL component from price movement in rUSD. Absent for position-extending executions.
* `fundingPnl` (string, optional): PnL component from funding payments in rUSD. Absent for position-extending executions.

</details>

#### `/v2/prices`

**Purpose**: Real-time price updates for all symbols

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/prices"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/prices",
  "data": [
    {
      "symbol": "BTCRUSDPERP",
      "oraclePrice": "43000.00",
      "poolPrice": "42999.50",
      "updatedAt": 1747927089946
    },
    {
      "symbol": "ETHRUSDPERP",
      "oraclePrice": "2500.00",
      "poolPrice": "2499.75",
      "updatedAt": 1747927089946
    }
  ]
}
```

<details>

<summary><strong>Data Type - Price</strong></summary>

* `symbol` (string): Trading symbol
* `oraclePrice` (string): Oracle price - Price given by the Stork feeds, used both as the peg price for prices on Reya, as well as Mark Prices
* `poolPrice` (string, optional): Pool price - The price currently quoted by the AMM for zero volume
* `updatedAt` (integer): Last update timestamp (milliseconds)

</details>

#### `/v2/prices/{symbol}`

**Purpose**: Real-time price updates for a specific symbol

**Parameters**:

* `symbol`: Trading symbol (e.g., `BTCRUSDPERP`, `kBONKRUSDPERP`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/prices/BTCRUSDPERP"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/prices/BTCRUSDPERP",
  "data": {
    "symbol": "BTCRUSDPERP",
    "oraclePrice": "43000.00",
    "poolPrice": "42999.50",
    "updatedAt": 1747927089946
  }
}
```

<details>

<summary><strong>Data Type - Price</strong></summary>

Same as above - see `/v2/prices` channel for complete field definitions.

</details>

#### `/v2/market/{symbol}/depth`

**Purpose**: Real-time L2 order book depth snapshots for a specific market

**Parameters**:

* `symbol`: Trading symbol (e.g., `BTCRUSDPERP`, `DOGERUSDPERP`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/market/BTCRUSDPERP/depth"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/market/BTCRUSDPERP/depth",
  "data": {
    "symbol": "BTCRUSDPERP",
    "type": "SNAPSHOT",
    "bids": [
      { "px": "42999.50", "qty": "1.5" },
      { "px": "42998.00", "qty": "2.0" }
    ],
    "asks": [
      { "px": "43000.50", "qty": "1.0" },
      { "px": "43001.00", "qty": "3.0" }
    ],
    "updatedAt": 1747927089946
  }
}
```

<details>

<summary><strong>Data Type - Depth</strong></summary>

* `symbol` (string): Trading symbol
* `type` (DepthType): Depth message type (SNAPSHOT, UPDATE)
* `bids` (array): Bid side levels aggregated by price, sorted descending by price
  * `px` (string): Price level
  * `qty` (string): Aggregated quantity at this price level
* `asks` (array): Ask side levels aggregated by price, sorted ascending by price
  * `px` (string): Price level
  * `qty` (string): Aggregated quantity at this price level
* `updatedAt` (integer): Snapshot generation timestamp (milliseconds)

</details>

#### `/v2/market/{symbol}/spotExecutions`

**Purpose**: Real-time spot executions for a specific market

**Parameters**:

* `symbol`: Trading symbol (e.g., `ETHRUSD`, `BTCRUSD`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/market/ETHRUSD/spotExecutions"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/market/ETHRUSD/spotExecutions",
  "data": [
    {
      "exchangeId": 1,
      "symbol": "ETHRUSD",
      "accountId": 12345,
      "makerAccountId": 67890,
      "orderId": "63552420354981888",
      "makerOrderId": "63552420037263360",
      "qty": "1.0",
      "side": "B",
      "price": "2500.00",
      "fee": "0.0",
      "type": "ORDER_MATCH",
      "timestamp": 1747927089946,
      "sequenceNumber": 152954
    }
  ]
}
```

<details>

<summary><strong>Data Type - SpotExecution</strong></summary>

* `exchangeId` (integer, optional): Exchange identifier
* `symbol` (string): Trading symbol
* `accountId` (integer): Account identifier of the taker side of the trade
* `makerAccountId` (integer): Maker account ID (counterparty providing liquidity)
* `orderId` (string, optional): Taker-side order ID. Absent when the taker order was filled and removed in the same matching round.
* `makerOrderId` (string, optional): Maker-side order ID. Absent when the maker order was fully filled in this execution.
* `qty` (string): Execution quantity in base asset units
* `side` (Side): Taker side (B=Buy, A=Sell). The maker is always the opposite side.
* `price` (string): Execution price in quote-per-base units
* `fee` (string): Fee charged to the taker, in the market's fee asset
* `type` (ExecutionType): Execution type (ORDER\_MATCH, LIQUIDATION, ADL)
* `timestamp` (integer): Execution timestamp (milliseconds since epoch)
* `sequenceNumber` (integer): Monotonic per-execution sequence number across the spot matching engine; increases by 1 for every spot execution on Reya. Use this to dedup and gap-detect on the consumer side after a reconnect.

</details>

#### `/v2/market/{symbol}/spotExecutionBusts`

**Purpose**: Real-time spot execution busts (failed spot fills) for a specific market

**Parameters**:

* `symbol`: Trading symbol (e.g., `ETHRUSD`, `BTCRUSD`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/market/ETHRUSD/spotExecutionBusts"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/market/ETHRUSD/spotExecutionBusts",
  "data": [
    {
      "symbol": "ETHRUSD",
      "accountId": 12345,
      "exchangeId": 1,
      "makerAccountId": 67890,
      "orderId": "63552420354981888",
      "makerOrderId": "63552420037263360",
      "qty": "1.0",
      "side": "B",
      "price": "2500.00",
      "reason": "08c379a0...",
      "timestamp": 1747927089946
    }
  ]
}
```

<details>

<summary><strong>Data Type - SpotExecutionBust</strong></summary>

A bust is emitted when the matching engine matched two orders but the on-chain settlement attempt reverted (e.g. insufficient balance, signature staleness, market paused). The match is rolled back; both orders are released back to their owners' state. See [Trade Busts](/developers/trade-busts) for the full trade lifecycle, when busts happen, and how clients should handle them.

* `symbol` (string): Trading symbol
* `accountId` (integer): Account identifier of the taker side of the failed trade
* `exchangeId` (integer): Exchange identifier
* `makerAccountId` (integer): Maker account ID (counterparty)
* `orderId` (string): Taker-side order ID
* `makerOrderId` (string): Maker-side order ID
* `qty` (string): Failed base quantity in base asset units
* `side` (Side): Taker side (B=Buy, A=Sell)
* `price` (string): Price at which the failed match was attempted
* `reason` (string): Hex-encoded revert reason bytes from the on-chain settlement attempt. Clients can ABI-decode this against the OrdersGateway error ABI to recover the specific revert (e.g. `InsufficientBalance`, `UnauthorizedSigner`). The first 4 bytes are the selector; subsequent bytes are the ABI-encoded args.
* `timestamp` (integer): Block timestamp of the failed settlement (milliseconds since epoch). This is the chain-side timestamp, not the original off-chain match timestamp.

</details>

### 2. Wallet Data Channels

#### `/v2/wallet/{address}/positions`

**Purpose**: Real-time position updates for a wallet

**Parameters**:

* `address`: Ethereum wallet address (e.g., `0x6c51275fd01d5dbd2da194e92f920f8598306df2`)

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/positions"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/positions",
  "data": [
    {
      "exchangeId": 1,
      "symbol": "BTCRUSDPERP",
      "accountId": 12345,
      "qty": "1.5",
      "side": "B",
      "avgEntryPrice": "43000.00",
      "avgEntryFundingValue": "100.25",
      "lastTradeSequenceNumber": 152954
    }
  ]
}
```

<details>

<summary><strong>Data Type - Position</strong></summary>

* `exchangeId` (integer): Exchange identifier
* `symbol` (string): Trading symbol
* `accountId` (integer): Account identifier
* `qty` (string): Position quantity
* `side` (Side): Position side (B=Buy, A=Sell)
* `avgEntryPrice` (string): Average entry price
* `avgEntryFundingValue` (string): Average entry funding value
* `lastTradeSequenceNumber` (integer): Last execution sequence number

</details>

#### `/v2/wallet/{address}/orderChanges`

**Purpose**: Real-time order change updates for wallet

**Parameters**:

* `address`: Ethereum wallet address

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/orderChanges"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/orderChanges",
  "data": [
    {
      "exchangeId": 1,
      "symbol": "BTCRUSDPERP",
      "accountId": 12345,
      "orderId": "123456789-123123123",
      "qty": "1.0",
      "execQty": "0.5",
      "side": "B",
      "limitPx": "43000.00",
      "orderType": "LIMIT",
      "triggerPx": "50000.0",
      "timeInForce": "GTC",
      "reduceOnly": false,
      "status": "OPEN",
      "createdAt": 1747927089946,
      "lastUpdateAt": 1747927089946
    }
  ]
}
```

<details>

<summary><strong>Data Type - Order</strong></summary>

* `exchangeId` (integer): Exchange identifier
* `symbol` (string): Trading symbol
* `accountId` (integer): Account identifier
* `side` (Side): Order side (B=Buy, A=Sell)
* `limitPx` (string): Limit price
* `orderType` (OrderType): Order type (LIMIT, TP, SL)
* `status` (OrderStatus): Order status (OPEN, FILLED, CANCELLED, REJECTED)
* `createdAt` (integer): Creation timestamp (milliseconds)
* `lastUpdateAt` (integer): Last update timestamp (milliseconds)
* `orderId` (string): Order identifier
* `qty` (string, optional): Order quantity
* `execQty` (string, optional): Executed quantity in the current order update
* `cumQty` (string, optional): Total executed quantity across all fills
* `triggerPx` (string, optional): Trigger price for TP/SL orders
* `timeInForce` (TimeInForce, optional): Time in force (IOC, GTC)
* `reduceOnly` (boolean, optional): Reduce-only flag (exclusively for LIMIT IOC orders)

</details>

#### `/v2/wallet/{address}/perpExecutions`

**Purpose**: Real-time perpetual execution updates for a wallet

**Parameters**:

* `address`: Ethereum wallet address

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/perpExecutions"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/perpExecutions",
  "data": [
    {
      "exchangeId": 1,
      "symbol": "BTCRUSDPERP",
      "accountId": 12345,
      "qty": "1.0",
      "side": "B",
      "price": "43000.00",
      "fee": "0.50",
      "type": "ORDER_MATCH",
      "timestamp": 1747927089946,
      "sequenceNumber": 152954
    }
  ]
}
```

<details>

<summary><strong>Data Type - PerpExecution</strong></summary>

Same as above - see `/v2/market/{symbol}/perpExecutions` channel for complete field definitions.

</details>

#### `/v2/wallet/{address}/spotExecutions`

**Purpose**: Real-time spot execution updates for a wallet

**Parameters**:

* `address`: Ethereum wallet address

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/spotExecutions"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/spotExecutions",
  "data": [
    {
      "exchangeId": 1,
      "symbol": "ETHRUSD",
      "accountId": 12345,
      "makerAccountId": 67890,
      "orderId": "63552420354981888",
      "makerOrderId": "63552420037263360",
      "qty": "1.0",
      "side": "B",
      "price": "2500.00",
      "fee": "0.0",
      "type": "ORDER_MATCH",
      "timestamp": 1747927089946,
      "sequenceNumber": 152954
    }
  ]
}
```

<details>

<summary><strong>Data Type - SpotExecution</strong></summary>

Same as above - see `/v2/market/{symbol}/spotExecutions` channel for complete field definitions.

</details>

#### `/v2/wallet/{address}/spotExecutionBusts`

**Purpose**: Real-time spot execution bust updates for a wallet

**Parameters**:

* `address`: Ethereum wallet address

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/spotExecutionBusts"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/spotExecutionBusts",
  "data": [
    {
      "symbol": "ETHRUSD",
      "accountId": 12345,
      "exchangeId": 1,
      "makerAccountId": 67890,
      "orderId": "63552420354981888",
      "makerOrderId": "63552420037263360",
      "qty": "1.0",
      "side": "B",
      "price": "2500.00",
      "reason": "08c379a0...",
      "timestamp": 1747927089946
    }
  ]
}
```

<details>

<summary><strong>Data Type - SpotExecutionBust</strong></summary>

Same as above - see `/v2/market/{symbol}/spotExecutionBusts` channel for complete field definitions.

</details>

#### `/v2/wallet/{address}/accountBalances`

**Purpose**: Real-time account balance updates for a wallet

**Parameters**:

* `address`: Ethereum wallet address

**Subscription**:

```json
{
  "type": "subscribe",
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/accountBalances"
}
```

**Message Structure**:

```json
{
  "type": "channel_data",
  "timestamp": 1747927089946,
  "channel": "/v2/wallet/0x6c51275fd01d5dbd2da194e92f920f8598306df2/accountBalances",
  "data": [
    {
      "accountId": 12345,
      "asset": "WSTETH",
      "realBalance": "1.25",
      "balanceDEPRECATED": "1.25"
    }
  ]
}
```

<details>

<summary><strong>Data Type - AccountBalance</strong></summary>

* `accountId` (integer): Account identifier
* `asset` (string): Asset symbol (e.g., WSTETH, RUSD)
* `realBalance` (string): Sum of account net deposits and realized PnL from closed positions
* `balanceDEPRECATED` (string): Sum of account net deposits only (deprecated, will be removed)

</details>

## Error Catalog

The server emits an `error` envelope when it cannot process a frame. The connection stays open; only the offending operation is rejected. Every error envelope shares this shape:

```json
{
  "type": "error",
  "message": "<human-readable description>",
  "channel": "<channel path, present when applicable>"
}
```

The `channel` field is included when the error relates to a specific channel (e.g. an invalid subscribe target). It is omitted for frame-level errors that aren't tied to a particular channel.

The full set of `message` strings emitted by the server:

| Message                                        | When emitted                                                                                                                                                                     | Client action                                                                                                                             |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `Invalid JSON`                                 | The frame body could not be parsed as JSON.                                                                                                                                      | Fix the client serializer.                                                                                                                |
| `Invalid type`                                 | The frame's `type` field is not one of `subscribe`, `unsubscribe`, `ping`. (`pong` is server-only — clients don't send JSON pong frames.)                                        | Verify the request `type`.                                                                                                                |
| `Invalid channel name`                         | The subscribe / unsubscribe target does not match a known channel path or has malformed parameters (e.g. an invalid symbol or address).                                          | Check the channel name against the [Channels Reference](#channels-reference) and the [Parameter Validation](#parameter-validation) rules. |
| `Error while fetching snapshot from {channel}` | The server failed to compute the initial snapshot for a freshly-subscribed channel (typically a transient backend issue). The subscription is rolled back; the client may retry. | Retry the subscribe after a short backoff. If the problem persists, contact support with the channel name and timestamp.                  |

## Data Types & Schemas

### Enumeration Types

<details>

<summary><strong>Side</strong> - Order/position side indicator</summary>

* `B`: Buy/Bid
* `A`: Ask/Sell

</details>

<details>

<summary><strong>ExecutionType</strong> - Type of execution that occurred</summary>

* `ORDER_MATCH`: Regular order matching
* `LIQUIDATION`: Liquidation execution
* `ADL`: Auto-deleveraging execution

</details>

<details>

<summary><strong>OrderStatus</strong> - Current status of an order</summary>

* `OPEN`: Order is active and can be filled
* `FILLED`: Order has been completely filled
* `CANCELLED`: Order has been cancelled
* `REJECTED`: Order was rejected

</details>

<details>

<summary><strong>OrderType</strong> - Type of order placed</summary>

* `LIMIT`: Limit order
* `TP`: Take profit order
* `SL`: Stop loss order

</details>

<details>

<summary><strong>TimeInForce</strong> - Order duration specification</summary>

* `IOC`: Immediate or Cancel
* `GTC`: Good Till Cancel

</details>

<details>

<summary><strong>DepthType</strong> - Order book depth message type</summary>

* `SNAPSHOT`: Full order book snapshot
* `UPDATE`: Single level change update

</details>

<details>

<summary><strong>AccountType</strong> - Account type classification</summary>

* `MAINPERP`: Main perpetual trading account
* `SUBPERP`: Sub perpetual trading account
* `SPOT`: Spot trading only account

</details>

## Connection Management

### Reconnection Pattern

Reconnect with the usual exponential-backoff-with-jitter pattern any robust WebSocket client should use. The Reya-specific bits are:

1. **Re-subscribe to every channel.** The server holds no per-connection subscription state across disconnects — a client that had three channels subscribed before the drop has zero subscribed after the new connection opens. Track active subscriptions client-side and replay them on reconnect.
2. **Reconcile missed events from REST.** Channels are best-effort streams. Between disconnect and re-subscribe the client may miss order updates, executions, or balance changes. After reconnect, refresh from REST (e.g. `GET /v2/wallet/{address}/openOrders`, `GET /v2/wallet/{address}/perpExecutions`) before trusting cached state.

For the meaning of WS close codes you'll see on `onclose` (`1000`, `1001`, `1006`, etc.), see [What Happens When the Server Closes the Connection](/developers/websocket-api-reference/heartbeats#what-happens-when-the-server-closes-the-connection).

### Graceful Shutdown

The server's drain-and-close behavior on rolling deploys (10s drain, `/ready` returns `503`, idle connections closed first, `1001 SERVER_SHUTTING_DOWN` on close) is shared with the Order Entry WebSocket and documented in [Server-Side Graceful Shutdown](/developers/websocket-api-reference/heartbeats#server-side-graceful-shutdown).

## Python SDK Example

Worked examples are included in the [Reya Python SDK](https://github.com/Reya-Labs/reya-python-sdk) under [`examples/websocket/`](https://github.com/Reya-Labs/reya-python-sdk/tree/main/examples/websocket). The directory is split by market type:

* [`examples/websocket/perps/market_monitoring.py`](https://github.com/Reya-Labs/reya-python-sdk/blob/main/examples/websocket/perps/market_monitoring.py) — subscribe to perp market summaries
* [`examples/websocket/perps/prices_monitoring.py`](https://github.com/Reya-Labs/reya-python-sdk/blob/main/examples/websocket/perps/prices_monitoring.py) — subscribe to the price stream
* [`examples/websocket/perps/wallet_monitoring.py`](https://github.com/Reya-Labs/reya-python-sdk/blob/main/examples/websocket/perps/wallet_monitoring.py) — subscribe to wallet-scoped channels (positions, order changes, executions, balances)
* [`examples/websocket/spot/spot_executions.py`](https://github.com/Reya-Labs/reya-python-sdk/blob/main/examples/websocket/spot/spot_executions.py) — subscribe to spot execution streams
* [`examples/websocket/spot/depth_market_maker.py`](https://github.com/Reya-Labs/reya-python-sdk/blob/main/examples/websocket/spot/depth_market_maker.py) — bootstrap state via REST, then drive a market-maker loop off of `depth`, `accountBalances`, `openOrders`, and `spotExecutions` updates

Run any of them with:

```bash
poetry shell
python -m examples.websocket.perps.market_monitoring  # for example
```

See each script's docstring for prerequisites (`.env` setup, funded test accounts on cronos).


# WebSocket Order Entry API Reference

## Overview

The Reya DEX WebSocket Order Entry API v2 is a request/response surface for placing and cancelling orders over a persistent WebSocket connection. It carries the same operations and payload bodies as the REST `/v2` endpoints (`POST /v2/createOrder`, `POST /v2/cancelOrder`, `POST /v2/cancelAll`), with lower per-operation overhead and id-correlated responses on the same channel.

Payload bodies are reused verbatim from REST. Request and response envelopes are id-correlated; the server replies on the same connection with a frame carrying the same `id` the client sent.

This surface is **order-entry only**. For real-time market data, position updates, and fill streaming, see the [WebSocket Info API Reference](/developers/websocket-api-reference/websocket-api-reference). The recommended Market Maker integration runs both connections in parallel: this surface for order entry, the streaming surface for read-side fanout.

## Server Endpoints

### Production Environment

* **URL**: `wss://ws-exec.reya.xyz`
* **Protocol**: WSS
* **Description**: Production WebSocket order entry server

### Staging Environment

* **URL**: `wss://ws-exec-staging.reya.xyz`
* **Protocol**: WSS
* **Description**: Staging WebSocket order entry server for pre-production testing

### Test Environment

* **URL**: `wss://ws-exec-testnet.reya.xyz`
* **Protocol**: WSS
* **Description**: Test WebSocket order entry server (cronos)

## Connection & Auth Model

The connection itself is **anonymous** — no handshake, no login, no API key. There is no concept of a session-bound wallet identity.

Authentication is **per-frame**: every order-bearing request carries an EIP-712 signature in its `payload` (`signature`, `nonce`, `signerWallet`, `expiresAfter`). The server validates the signature against the order contents on every request — identical to the REST `/v2/createOrder` etc. body shape. See [Signatures and Nonces](/developers/readme/signatures-and-nonces) for the signing model; both transports use the same scheme and the same Python SDK helpers.

A consequence of per-frame authentication is that a single WebSocket connection can carry orders signed by **multiple different `signerWallet` values** — useful for market makers operating multiple subaccounts on one connection.

**Rate limits are keyed off the signing wallet, not the connection.** Sending `createOrder` / `cancelOrder` / `cancelAll` over WebSocket Order Entry counts toward the same per-wallet bucket as sending the same operation over REST — choosing the transport doesn't change the limits. See [Rate Limits](/developers/rate-limits) for the full picture (default limits, tiers, open-order caps, and recommended client patterns).

## Message Structure

All WebSocket messages follow a standardized envelope structure with a `type` discriminator and a client-chosen `id` for correlation.

### Request Envelope (Client → Server)

```json
{
  "type": "createOrder",
  "id": "req-7f3c1a",
  "payload": { /* operation-specific request body */ }
}
```

#### Components

* **type** (string, required): One of `createOrder`, `cancelOrder`, `cancelAll`, `ping`. (`pong` is server-only — see [Heartbeats](/developers/websocket-api-reference/heartbeats).)
* **id** (string, required): Client-chosen correlation identifier. Must be unique across in-flight requests on the connection — see [In-Flight `id` Uniqueness](#in-flight-id-uniqueness) below.
* **payload** (object, required for `createOrder` / `cancelOrder` / `cancelAll`): Operation-specific request body, byte-identical to the corresponding REST endpoint's request body.

### Response Envelope (Server → Client)

```json
{
  "type": "createOrder",
  "id": "req-7f3c1a",
  "ok": true,
  "payload": { /* operation-specific success body */ }
}
```

or, on failure:

```json
{
  "type": "createOrder",
  "id": "req-7f3c1a",
  "ok": false,
  "error": {
    "error": "INPUT_VALIDATION_ERROR",
    "message": "qty is missing"
  }
}
```

#### Components

* **type** (string, required): Echoes the request `type`.
* **id** (string, required): Echoes the request `id`.
* **ok** (boolean, required): `true` for success, `false` for failure.
* **payload** (object, required when `ok = true`, forbidden when `ok = false`): Operation-specific success body, byte-identical to the REST `200` response body.
* **error** (object, required when `ok = false`, forbidden when `ok = true`): See [Error Catalog](#error-catalog) for the shape and possible codes.

### Top-Level Error Envelope (Server → Client)

The server emits a top-level `error` envelope when it cannot parse a request at all (malformed JSON, unknown `type`, in-flight `id` collision, internal failure). Connection stays open. Operation-specific errors instead come back as `{ ok: false, error }` on the corresponding response envelope correlated by `id`.

```json
{
  "type": "error",
  "id": "req-7f3c1a",
  "error": {
    "error": "DUPLICATE_REQUEST_ID",
    "message": "Request id already in-flight on this connection"
  }
}
```

* **id** is present when the offending request carried one (e.g. for `DUPLICATE_REQUEST_ID`); absent for frame-level errors (e.g. unparseable JSON) where the server has no id to echo.

### Heartbeats

The heartbeat / connection-liveness mechanism is documented in detail on its own page — see [Heartbeats](/developers/websocket-api-reference/heartbeats). Short version: protocol-level pings handle liveness automatically, no application-level code is required on the client.

## Operations Reference

### `createOrder`

**Purpose**: Place a spot LIMIT GTC order, a perp IOC order, or a perp GTC/SL/TP conditional order. Identical body and semantics to REST `POST /v2/createOrder`.

**Request Envelope** (spot LIMIT GTC):

```json
{
  "type": "createOrder",
  "id": "req-7f3c1a",
  "payload": {
    "exchangeId": 2,
    "symbol": "WETHRUSD",
    "accountId": 10000000002,
    "isBuy": true,
    "limitPx": "1",
    "qty": "0.001",
    "orderType": "LIMIT",
    "timeInForce": "GTC",
    "signature": "0x...",
    "nonce": "1778601294274124",
    "signerWallet": "0x869d6494fe32B96F93F78F9c4B7aAf30eeC01C1F",
    "expiresAfter": 1747927089,
    "clientOrderId": 1778601294274124
  }
}
```

**Request Envelope** (perp IOC):

```json
{
  "type": "createOrder",
  "id": "req-7f3c1b",
  "payload": {
    "exchangeId": 2,
    "symbol": "ETHRUSDPERP",
    "accountId": 8017,
    "isBuy": true,
    "limitPx": "40000",
    "qty": "0.01",
    "orderType": "LIMIT",
    "timeInForce": "IOC",
    "reduceOnly": false,
    "signature": "0x...",
    "nonce": "...",
    "signerWallet": "0x869d6494fe32B96F93F78F9c4B7aAf30eeC01C1F",
    "expiresAfter": 1747927089
  }
}
```

**Success Response**:

```json
{
  "type": "createOrder",
  "id": "req-7f3c1a",
  "ok": true,
  "payload": {
    "status": "OPEN",
    "orderId": "1864998629727535104",
    "clientOrderId": 1778601294274124
  }
}
```

**Error Response**:

```json
{
  "type": "createOrder",
  "id": "req-7f3c1a",
  "ok": false,
  "error": {
    "error": "INPUT_VALIDATION_ERROR",
    "message": "limitPx is required"
  }
}
```

<details>

<summary><strong>Data Type — CreateOrderRequest payload</strong></summary>

* `exchangeId` (integer, required): Reya exchange identifier. Currently always `2`.
* `symbol` (string): Trading symbol (e.g. `WETHRUSD`, `ETHRUSDPERP`).
* `accountId` (integer, required): Reya account ID placing the order.
* `isBuy` (boolean, required): `true` for a buy, `false` for a sell.
* `limitPx` (string, required): Limit price as a decimal string.
* `qty` (string): Order quantity as a decimal string.
* `orderType` (string, required): `LIMIT`, `TP` (take-profit), or `SL` (stop-loss).
* `timeInForce` (string): `IOC` or `GTC`. Required for `LIMIT` orders.
* `triggerPx` (string): Trigger price. Required for `TP` / `SL` orders.
* `reduceOnly` (boolean): Whether the order is reduce-only. Required for perp IOC orders.
* `signature` (string, required): EIP-712 signature over the order. See [Signatures and Nonces](/developers/readme/signatures-and-nonces).
* `nonce` (string, required): Order nonce.
* `signerWallet` (string, required): Address that produced the signature.
* `expiresAfter` (integer): Expiration timestamp in seconds since epoch. Required for perp IOC orders and all spot orders.
* `clientOrderId` (integer, optional): Echoed back in the response; useful for client-side correlation independent of the server-issued `orderId`.

</details>

<details>

<summary><strong>Data Type — CreateOrderResponse payload</strong></summary>

* `status` (string, required): One of `OPEN`, `FILLED`, `CANCELLED`, `REJECTED`.
* `execQty` (string, optional): Executed quantity in this order update.
* `cumQty` (string, optional): Total executed quantity across all fills where the order is active.
* `orderId` (string, optional): Server-issued order ID. Present for all order types except perp IOC (which fills/voids on-chain in the same call and has no resting state).
* `clientOrderId` (integer, optional): Echoes the request's `clientOrderId`.

</details>

### `cancelOrder`

**Purpose**: Cancel a previously placed order by `orderId` (or `clientOrderId` for spot). Identical body and semantics to REST `POST /v2/cancelOrder`.

**Request Envelope**:

```json
{
  "type": "cancelOrder",
  "id": "req-7f3c1c",
  "payload": {
    "orderId": "1864998629727535104",
    "accountId": 10000000002,
    "symbol": "WETHRUSD",
    "signature": "0x...",
    "nonce": "1778601294356211",
    "expiresAfter": 1747927089
  }
}
```

**Success Response**:

```json
{
  "type": "cancelOrder",
  "id": "req-7f3c1c",
  "ok": true,
  "payload": {
    "status": "CANCELLED",
    "orderId": "1864998629727535104"
  }
}
```

<details>

<summary><strong>Data Type — CancelOrderRequest payload</strong></summary>

* `orderId` (string): Internal matching engine order ID to cancel. Provide either `orderId` or `clientOrderId`.
* `clientOrderId` (integer): Client-provided order ID to cancel. Provide either `orderId` or `clientOrderId`.
* `accountId` (integer): Account ID that owns the order. Required for spot markets.
* `symbol` (string): Market symbol for the order. Required for spot market orders.
* `signature` (string, required): EIP-712 signature over the cancellation.
* `nonce` (string): Cancel nonce. Required for spot.
* `expiresAfter` (integer): Expiration timestamp. Required for spot.

</details>

<details>

<summary><strong>Data Type — CancelOrderResponse payload</strong></summary>

* `status` (string, required): Always `CANCELLED` on success.
* `orderId` (string, required): The cancelled order ID.
* `clientOrderId` (integer, optional): Echoes the request's `clientOrderId`.

</details>

### `cancelAll`

**Purpose**: Mass-cancel all open orders for an account on a given (spot) market, or across all markets if `symbol` is omitted. Identical body and semantics to REST `POST /v2/cancelAll`. Perp mass-cancel is not supported and returns the same not-supported error REST returns.

**Request Envelope**:

```json
{
  "type": "cancelAll",
  "id": "req-7f3c1d",
  "payload": {
    "accountId": 10000000002,
    "symbol": "WETHRUSD",
    "signature": "0x...",
    "nonce": "1778601294501222",
    "expiresAfter": 1747927089
  }
}
```

**Success Response**:

```json
{
  "type": "cancelAll",
  "id": "req-7f3c1d",
  "ok": true,
  "payload": {
    "cancelledCount": 3
  }
}
```

<details>

<summary><strong>Data Type — MassCancelRequest payload</strong></summary>

* `accountId` (integer, required): Account ID to cancel orders for.
* `symbol` (string, optional): Symbol to cancel orders for. If omitted, cancels all orders for the account across all markets.
* `signature` (string, required): EIP-712 signature.
* `nonce` (string, required): Mass-cancel nonce.
* `expiresAfter` (integer, required): Expiration timestamp.

</details>

<details>

<summary><strong>Data Type — MassCancelResponse payload</strong></summary>

* `cancelledCount` (integer, required): Number of orders that were cancelled.

</details>

### `ping` / `pong`

**Purpose**: Optional client-initiated application-level liveness/RTT probe. The client sends `{type:"ping", id?}`; the server replies with `{type:"pong", id?}` echoing the optional `id`. See [Heartbeats](/developers/websocket-api-reference/heartbeats) for the full description — when to use it, when not to, and how it relates to the protocol-level liveness mechanism that keeps the connection alive automatically.

## Error Catalog

Every error envelope (both per-operation `{ok: false, error}` and top-level `error`) carries a `RequestError`-shaped object:

```json
{
  "error": "INPUT_VALIDATION_ERROR",
  "message": "qty is missing"
}
```

The `error` field is one of the codes below. Per-operation responses (`{ok: false, error}` on `createOrder` / `cancelOrder` / `cancelAll`) use codes from the **Trade Handler** group, shared 1:1 with REST. Top-level `error` envelopes use codes from the **Framing Layer** group exclusively; these only make sense for a streamed envelope protocol and never appear in REST responses.

### Trade Handler Codes (shared with REST)

| Code                                | When emitted                                                                                                              | Client action                                                                                                                                |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `SYMBOL_NOT_FOUND`                  | The `symbol` in the payload doesn't resolve to a known market.                                                            | Refresh market definitions via REST `GET /v2/marketDefinitions`.                                                                             |
| `NO_ACCOUNTS_FOUND`                 | The `accountId` doesn't exist or isn't owned by the signer.                                                               | Verify account configuration.                                                                                                                |
| `NO_PRICES_FOUND_FOR_SYMBOL`        | Stork oracle has no recent price for the symbol — usually transient at startup.                                           | Retry after a short backoff.                                                                                                                 |
| `INPUT_VALIDATION_ERROR`            | Generic body-validation failure (missing field, wrong type, illegal value).                                               | Fix the request body; consult the human-readable `message`.                                                                                  |
| `CREATE_ORDER_OTHER_ERROR`          | Generic createOrder failure not covered by a more specific code (includes on-chain reverts surfaced through the relayer). | Read `message` for the underlying reason; for perp IOC, also check that the limit price can be filled within the on-chain price-limit check. |
| `CANCEL_ORDER_OTHER_ERROR`          | Generic cancelOrder failure not covered by a more specific code.                                                          | Read `message`.                                                                                                                              |
| `ORDER_DEADLINE_PASSED_ERROR`       | `expiresAfter` is in the past.                                                                                            | Re-sign with a fresh deadline.                                                                                                               |
| `ORDER_DEADLINE_TOO_HIGH_ERROR`     | `expiresAfter` is too far in the future (anti-abuse cap).                                                                 | Use a shorter deadline (typically <= 24h for spot GTC, <= 60s for IOC).                                                                      |
| `INVALID_NONCE_ERROR`               | Nonce is not strictly monotonic for this signer, or was already used.                                                     | Re-sign with a fresh monotonic nonce.                                                                                                        |
| `UNAVAILABLE_MATCHING_ENGINE_ERROR` | The matching engine is unavailable (transient).                                                                           | Retry after a short backoff.                                                                                                                 |
| `UNAUTHORIZED_SIGNATURE_ERROR`      | The recovered signer is not authorized to act on the `accountId`.                                                         | Verify the signer wallet is in the account's permissioned-addresses list on-chain.                                                           |
| `NUMERIC_OVERFLOW_ERROR`            | A numeric field exceeds the allowed uint64 / int256 range.                                                                | Fix the request body.                                                                                                                        |

### Framing Layer Codes (top-level `error` envelope only)

These codes appear **only** in the top-level `error` envelope, never inside a per-operation `{ok: false}` response.

| Code                   | When emitted                                                                                                                                                                                                                        | Client action                                                  |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `MALFORMED_JSON`       | The frame body could not be parsed as JSON, or required envelope fields (`type`, `id`) are missing. Connection stays open.                                                                                                          | Fix the client serializer.                                     |
| `UNKNOWN_TYPE`         | The frame's `type` field is not one of the accepted values. Connection stays open.                                                                                                                                                  | Verify the request `type`.                                     |
| `DUPLICATE_REQUEST_ID` | The frame's `id` is already in-flight on this connection — i.e., the client sent a new request with an `id` whose response hasn't yet been emitted. Connection stays open; the new request is rejected, the original is unaffected. | Use a fresh `id` for each request (UUIDs work).                |
| `INTERNAL`             | The server hit an internal failure handling the frame. Connection stays open.                                                                                                                                                       | Retry; if the problem persists, contact support with the `id`. |

## Data Types & Schemas

### Enumeration Types

<details>

<summary><strong>OrderType</strong></summary>

* `LIMIT` — Limit order (with `timeInForce` = `IOC` or `GTC`).
* `TP` — Take-profit conditional order (perp).
* `SL` — Stop-loss conditional order (perp).

</details>

<details>

<summary><strong>TimeInForce</strong></summary>

* `IOC` — Immediate or Cancel. Required for perp IOC orders.
* `GTC` — Good Till Cancelled. Used for spot LIMIT orders.

</details>

<details>

<summary><strong>OrderStatus</strong></summary>

* `OPEN` — Order is resting in the book.
* `FILLED` — Order is fully filled.
* `CANCELLED` — Order is cancelled.
* `REJECTED` — Order was rejected by the matching engine.

</details>

For the complete enumeration of `RequestErrorCode` (per-operation errors) and `WsExecErrorCode` (top-level errors), see the [Error Catalog](#error-catalog) above.

## Connection Management

### Reconnection Pattern

Reconnect with the usual exponential-backoff-with-jitter pattern any robust WebSocket client should use. The Reya-specific bits are:

1. **No subscription state to replay.** There is no session-bound identity to restore — the next request authenticates itself via its EIP-712 signature just like the first one did.
2. **Verify in-flight requests via REST before resubmitting.** Closing the WebSocket has zero persistent side effects on the order book itself — an in-flight `createOrder` whose response cannot be delivered still settles on-chain (same as a REST timeout). For any request whose response was not received before disconnect, check `GET /v2/wallet/{address}/openOrders` and `GET /v2/wallet/{address}/perpExecutions` to confirm outcome before retrying — otherwise you risk a duplicate order. See [Idempotency (`clientOrderId`)](#idempotency-clientorderid) for safe retry correlation.

For the meaning of WS close codes you'll see on `onclose` (`1000`, `1001`, `1006`, etc.), see [What Happens When the Server Closes the Connection](/developers/websocket-api-reference/heartbeats#what-happens-when-the-server-closes-the-connection).

### Graceful Shutdown

The server's drain-and-close behavior on rolling deploys (10s drain, `/ready` returns `503`, idle connections closed first, `1001 SERVER_SHUTTING_DOWN` on close) is shared with the Info WebSocket and documented in [Server-Side Graceful Shutdown](/developers/websocket-api-reference/heartbeats#server-side-graceful-shutdown).

### In-Flight `id` Uniqueness

Each `id` must be unique across **in-flight** requests on the connection. Once the server has emitted the corresponding response envelope, the `id` is free to reuse. Sending a fresh request with the same `id` as an in-flight one triggers a top-level `DUPLICATE_REQUEST_ID` error envelope; the original in-flight request is unaffected.

In practice, clients should generate a fresh `id` for every request (e.g. UUIDv4 or a monotonic counter prefixed with a session token).

### Idempotency (`clientOrderId`)

For `createOrder`, the optional `clientOrderId` field is echoed back unchanged in the response and in any subsequent order-update events on the Info WebSocket. Use it for client-side correlation independent of the server-issued `orderId` — particularly useful when the response envelope is lost mid-flight and the client must reconcile state from Info-WebSocket updates after reconnect.

`clientOrderId` does not provide server-side deduplication: two requests with the same `clientOrderId` will be treated as two separate orders.

## Signatures and Nonces

All `createOrder`, `cancelOrder`, and `cancelAll` payloads carry an EIP-712 `signature` over the order contents. The shape of the signed message is identical to the REST `/v2` endpoints — see [Signatures and Nonces](/developers/readme/signatures-and-nonces) for the canonical reference. The Python SDK provides the helpers `sign_raw_order`, `sign_cancel_order_spot`, and `sign_mass_cancel` to produce these signatures correctly.

The WebSocket transport does **not** add or change any signing requirement. Frames are signed by your wallet (or a permissioned trading key) at the payload level; the WebSocket connection itself is unauthenticated.

## Differences vs REST

The WebSocket Order Entry surface is functionally equivalent to the corresponding REST endpoints, with transport-level differences:

| Concern           | REST                                                                 | WebSocket Order Entry                                                                        |
| ----------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| Request body      | `CreateOrderRequest` / `CancelOrderRequest` / `MassCancelRequest`    | Same — embedded as `payload`                                                                 |
| Response body     | `CreateOrderResponse` / `CancelOrderResponse` / `MassCancelResponse` | Same — embedded as `payload` on `ok: true`                                                   |
| Success / failure | HTTP `200` vs `400` / `500`                                          | `ok: true` vs `ok: false` inside the frame                                                   |
| Error body        | `RequestError`                                                       | Same — embedded as `error` on `ok: false`                                                    |
| Correlation       | HTTP request/response pairing                                        | Client-supplied `id` field                                                                   |
| Heartbeat         | n/a (stateless)                                                      | Protocol-level, automatic — see [Heartbeats](/developers/websocket-api-reference/heartbeats) |
| Auth              | EIP-712 signature in body                                            | Same EIP-712 signature in same body                                                          |
| Idempotency       | `clientOrderId` echoed                                               | Same                                                                                         |
| Connection        | Per-request                                                          | Persistent, multiplexed                                                                      |

**When to use which:**

* **REST** — One-off requests, low frequency, simpler client integration, no need to maintain a long-lived connection.
* **WebSocket Order Entry** — High-frequency order submission, lower per-request overhead (no TLS handshake per request), latency-sensitive integrations. Recommended for Market Makers running together with the [WebSocket Info API](/developers/websocket-api-reference/websocket-api-reference).

## Python SDK Example

A worked end-to-end example is included in the [Reya Python SDK](https://github.com/Reya-Labs/reya-python-sdk) at [`examples/ws_exec/mvp.py`](https://github.com/Reya-Labs/reya-python-sdk/blob/main/examples/ws_exec/mvp.py). It demonstrates:

1. Spot LIMIT GTC `createOrder` (resting in the book)
2. Spot `cancelOrder` (cancels the order from step 1)
3. Spot `cancelAll` (opens N orders then mass-cancels them)
4. Perp IOC `createOrder` (fills at the current mark with a loose limit)

Run with:

```bash
poetry shell
python -m examples.ws_exec.mvp
```

See the script's accompanying README for prerequisites (`.env` setup, funded test accounts on cronos).


# Rate Limits

Reya enforces rate limits at two layers. At the **application layer**, per-wallet limits cap how many trading operations a signing wallet can submit and how many resting orders it can keep on the book — these keep the matching engine and on-chain settlement layer responsive for everyone. At the **network edge**, a separate per-IP / per-API-key limit caps total REST traffic regardless of endpoint, applied at the infrastructure layer before traffic reaches the application. A request has to pass both layers to succeed. This page covers both, what the defaults are, and how to integrate cleanly against them.

The per-wallet limits apply uniformly across both transports — REST (`POST /v2/createOrder`, `POST /v2/cancelOrder`, `POST /v2/cancelAll`) and the corresponding WebSocket Order Entry messages. Switching transports does not bypass them; both feed the same per-wallet bucket. The network-edge limit applies to REST only, since it counts individual HTTP requests.

## How Rate Limits Are Applied

A few properties are important to understand before reading the numbers:

* **Per signer wallet.** Limits are keyed off the wallet that signs the request, not the source IP, not an API key, and not the `accountId`. All requests signed by the same wallet share one bucket regardless of which client or machine issued them.
* **Same bucket across REST and WebSocket.** Sending the same operation over the WebSocket Order Entry API counts the same as sending it over REST. The transport is irrelevant; the signer wallet is what matters.
* **Two distinct limit systems run side by side.** A request must clear **both** to succeed:
  1. **Request-rate limits** — a sliding window measuring how many operations you've sent in the last 60 seconds.
  2. **Open-order caps** — a state-based check on how many resting orders you currently have on the book, and their total notional value.

A request that's fine on one system but trips the other is rejected. You'll usually see whichever limit was hit named in the error message.

## The Three Tiers

Every wallet sits in one of three tiers. The tier determines both your request-rate limits and your open-order caps.

* **Tier 1 (default).** Every wallet starts here. No allowlisting needed.
* **Tier 2 (elevated).** Higher request-rate limits and higher open-order caps.
* **Tier 3 (highest).** Highest request-rate limits and no open-order caps.

**How to move tiers:** contact the Reya team to request an upgrade. The team reviews based on your integration profile, usage patterns, and business context. There is no self-service path to a higher tier.

Only Tier 1 limits are published below. Tier 2 and Tier 3 limits are higher, but the specifics are discussed case-by-case when a wallet is upgraded — the right limit depends on the integration. If you're hitting Tier 1 caps and your use case justifies more, talk to the team rather than designing around them.

## Request Rate Limits (Tier 1)

| Operation                                                               | Limit per 60 seconds |
| ----------------------------------------------------------------------- | -------------------- |
| Order placement and single cancellation (`createOrder` + `cancelOrder`) | **30**               |
| Mass cancellation (`cancelAll`)                                         | **10**               |

The two counters are independent — placements and single cancels share one bucket of 30; mass-cancels have their own bucket of 10.

**Algorithm: sliding window.** Each request is timestamped. The server counts how many of your requests have arrived in the **last 60 seconds** when a new request comes in. The window slides continuously — a request from 61 seconds ago has already aged out, so a steady cadence of one request per 2 seconds will never trip the limit.

This is different from a fixed-window rate limit. With a fixed window, a "30 per minute" limit would let you send 30 requests in the last second of one minute and another 30 in the first second of the next — 60 requests in 2 seconds. The sliding window prevents this burst.

## Open-Order Caps (Tier 1)

Independent of the request-rate limits, your wallet has a cap on how many open orders can be resting on the book at the same time, and on the total notional value of those orders.

| Limit                                     | Tier 1        |
| ----------------------------------------- | ------------- |
| Maximum open GTC orders                   | **100**       |
| Maximum total notional of open GTC orders | **5,000 USD** |

These apply to GTC (Good-Till-Cancelled) orders that are sitting in the order book waiting to match. IOC (Immediate-or-Cancel) orders do not count — they either fill at request time or are cancelled, so they never rest on the book.

The cap is checked at order placement. If a new GTC order would push either the count or the notional total over the limit, the placement is rejected. You can free up space under the cap by waiting for fills, cancelling existing orders, or letting orders expire.

## Network-Edge Rate Limit (Per IP / API Key)

Separate from the per-wallet limits above, Reya operates an additional rate limiter at the **network edge** — at the infrastructure layer, before traffic reaches the application. The edge limit is keyed off the source **IP address / API key** rather than the signing wallet, and it applies to **all REST endpoints collectively**, not just trading operations.

| Limit                         | Value                                           |
| ----------------------------- | ----------------------------------------------- |
| Requests per 60-second window | **1,000**                                       |
| Scope                         | Per IP / per API key, across all REST endpoints |

A few properties to know:

* **Fixed window.** The counter resets at the end of each 60-second window. You can consume the entire quota at any point inside the window — for example, all 1,000 requests in the first second — and additional requests are rejected until the window resets. This is different from the per-wallet request-rate limit above, which uses a sliding window.
* **All endpoints share one bucket.** Trading requests count against the same 1,000 as any other REST traffic you send (account lookups, market data polls, anything else). There is no per-endpoint sub-allocation.
* **REST only.** The edge limit counts HTTP requests. Messages sent over an established WebSocket connection don't tick the counter — so WebSocket Info subscriptions and WebSocket Order Entry operations sidestep this limit entirely.
* **Independent of the per-wallet limits.** A request must clear both the edge limit and the per-wallet limits to succeed. Upgrading your wallet's tier does not raise the edge limit, and vice versa.
* **Rejection.** Once the limit is reached, additional requests in the same window receive HTTP `429 Too Many Requests` until the window resets.

**Polling vs. WebSocket.** The edge limit is the strongest reason to prefer the [WebSocket Info API](/developers/websocket-api-reference/websocket-api-reference) over polling REST for any real-time data need. A polling client at one request per second already uses 60 of the 1,000 per minute on a single endpoint — before any other call your application makes. WebSocket subscriptions stream updates as they happen without consuming the per-window REST quota.

**Higher edge limits.** If your application's legitimate usage genuinely needs more than 1,000 REST requests per minute, contact the Reya team. The team reviews on a case-by-case basis depending on your integration profile and traffic patterns.

## When You Hit a Limit

For the **per-wallet limits**, the server rejects the request with a structured error response. The error message identifies which limit was hit (request rate vs. open-order count vs. notional). The connection stays open and other operations continue to work — only the offending request is rejected.

For the **network-edge limit**, the request is rejected at the infrastructure layer with an HTTP `429 Too Many Requests` response. Because this happens before the request reaches the application, there is no structured per-limit detail in the body — just the standard 429 status.

Recommended recovery:

* **Request-rate rejection (per-wallet).** Back off and retry. The simplest pattern is exponential backoff with jitter, starting at a few hundred milliseconds. Because the algorithm is a sliding window, waiting until the oldest counted request ages out (a few seconds, in most cases) is usually enough.
* **Open-order rejection (per-wallet).** Adjust your resting state before retrying. Cancel an older order, wait for fills, or send the new order at a price that crosses (so it fills as IOC instead of resting).
* **Edge `429` rejection.** Wait for the current 60-second window to expire before retrying. If you see these regularly, you're likely polling REST when a WebSocket subscription would serve the same need with no quota cost.

Don't retry tight loops against any rate-limit rejection — you'll keep tripping the same limit and burn server resources for no benefit. A back-off pause of one or two seconds is almost always enough to recover from a transient rejection.

## Best Practices for Integrators

* **Track your own request rate locally.** The server enforces a hard limit, but a well-behaved client paces itself client-side so it never gets close. A token-bucket-style throttle in your client is often the simplest way.
* **Prefer WebSocket Order Entry for high-frequency flow.** The rate limits are identical, but you save the per-request TLS handshake overhead. See the [WebSocket Order Entry API Reference](/developers/websocket-api-reference/ws-exec-api-reference).
* **Consolidate cancellations.** One `cancelAll` counts as a single mass-cancel request, regardless of how many orders it cancels. Calling `cancelAll` is far more efficient than firing 100 separate `cancelOrder` calls — which would also exhaust your single-cancel budget.
* **Keep an eye on notional, not just order count.** A wallet with 50 small orders is fine on count but may hit the notional cap. Either is a valid cap to hit.
* **Talk to the team if Tier 1 limits don't fit your workload.** Tiers exist precisely because integration profiles vary widely. Market makers, latency-sensitive bots, and high-volume integrations are common reasons for tier upgrades.


# Trade Busts

Reya is a hybrid system where the matching engine runs off-chain and the chain independently validates and settles each trade. If a trade that the matching engine matched fails on-chain validation, it results in a **trade bust** — the match is rolled back, both sides are released back to their previous state, and no trade occurred.

Busts are an expected but **uncommon** outcome of this architecture. The Reya team continuously works to minimize the edge cases that produce them — by tightening pre-match validation in the matching engine, narrowing the time window between match and settle, and reducing the conditions under which on-chain settlement can fail. Busts will never be zero in a hybrid system (the chain is always the ultimate source of truth), but they are designed to be rare given how disruptive they are to client workflows.

This page explains why busts happen, when in the trade lifecycle they happen, and how a client should handle them.

## The Two-Stage Trade Lifecycle

Every match on Reya goes through **two distinct stages**:

1. **Off-chain match.** The matching engine (ME) finds a counterparty and produces a fill record. This is fast and in-memory.
2. **On-chain settlement.** The executor submits the fill to the `OrdersGateway` smart contract. Each fill is validated on-chain (signatures, balances, margin requirements, oracle deviation, etc.) before being accepted.

These stages have independent outcomes. **A successful off-chain match does not guarantee on-chain settlement.** When settlement fails, the result is a bust.

Different WebSocket channels surface different stages of this lifecycle, which is what makes bust handling subtle — but also what makes it manageable, once you know which channel reflects which stage.

## Why Busts Happen

The matching engine and the on-chain settlement layer operate on slightly different snapshots of the world. The matching engine matches based on its in-memory view of orders, balances, and prices at the moment of the match. The on-chain settlement contract re-validates every fill against the **current** chain state when the settlement transaction lands — which may be a fraction of a second later, but enough time for some things to have changed.

These are two reasons for settlement fails:

* **Oracle price guard.** Each order signature commits to a price band (e.g. an IOC order's worst acceptable price). If the on-chain oracle has moved outside that band by settlement time, the contract refuses the fill rather than trade at an unacceptable price.
* **Order expired.** Orders carry an `expiresAfter` deadline as part of their signature. If on-chain settlement runs after that deadline (e.g. because of network congestion or executor backlog), the contract refuses the fill.

All of these share a common pattern: the matching engine and the chain disagreed about the state of the world at slightly different points in time, and the chain — being the source of truth — wins the disagreement. The team's work to minimize busts focuses on shortening the time window where this disagreement can develop, and on catching more of the conditions in pre-match validation so the ME never matches a trade that the chain would later reject.

## Timeline of a Trade

End-to-end for a single fill, in order:

1. A client submits an order via `POST /v2/createOrder` (or the equivalent WebSocket Order Entry call).
2. The matching engine finds a counterparty and generates the fill.
3. The ME publishes the order status change to Redis. This feeds the [`/v2/wallet/{address}/orderChanges`](/developers/websocket-api-reference/websocket-api-reference) WebSocket channel. At this point the maker side of the match surfaces — as `FILLED` if the maker order was fully consumed, or as `OPEN` with an updated cumulative-fill quantity if it was only partially consumed. **This is before on-chain settlement.**
4. The executor submits the fill to the `OrdersGateway` smart contract on Reya Network.
5. The contract validates the fill on-chain independently of the match — re-checking signatures, balances, margin, oracle staleness, market state, and so on.
6. The settlement outcome is published:
   * **Success.** The contract emits a successful-settlement event, which is indexed and published to [`/v2/wallet/{address}/spotExecutions`](/developers/websocket-api-reference/websocket-api-reference) (and the corresponding `/v2/market/{symbol}/spotExecutions` channel). This is the confirmed trade.
   * **Failure (bust).** The contract emits a settlement-failure event, which is indexed and published to [`/v2/wallet/{address}/spotExecutionBusts`](/developers/websocket-api-reference/websocket-api-reference) (and the corresponding `/v2/market/{symbol}/spotExecutionBusts` channel). The trade did not happen; both sides are released.

## The Three Channels — What Each One Tells You

| Channel                                   | What it shows                                                                                                    | Reflects on-chain settlement?                                      |
| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `/v2/wallet/{address}/orderChanges`       | ME-level order status changes (`OPEN`, `FILLED`, `CANCELLED`, `REJECTED`), plus updated cumulative-fill quantity | **No** — fires immediately after the ME matches, before settlement |
| `/v2/wallet/{address}/spotExecutions`     | Confirmed on-chain trades                                                                                        | **Yes** — only emitted after settlement succeeds                   |
| `/v2/wallet/{address}/spotExecutionBusts` | Failed on-chain settlements                                                                                      | **Yes** — only emitted after settlement fails                      |

The critical asymmetry: **`orderChanges` reports ME-level state and never retroactively corrects itself.** If a fill briefly appeared as `FILLED` on `orderChanges` and then the on-chain settlement attempt busted, no correction event is published on `orderChanges`. The order's state on that channel will reflect what the ME observed, not what happened on-chain.

## Recommended Pattern

For most clients, the cleanest model is to treat **`spotExecutions` as the single source of truth for confirmed trades.**

* If a trade appears on `spotExecutions`, it has settled on-chain and is final. It can never be busted after that.
* If a trade does not appear, either it never matched, or it matched but busted on settlement. Either way, your position state is unaffected and there is nothing to reconcile.

Under this model:

* **`spotExecutions`** drives your trade ledger and position accounting.
* **`orderChanges`** is useful for surfacing intent and ME-level workflow (e.g. "my order is now resting", "my order has been cancelled"), but its `FILLED` status (or any non-zero cumulative-fill quantity on an `OPEN` order) is not a trade confirmation — those signals fire before on-chain settlement.
* **`spotExecutionBusts`** is optional. You don't need to subscribe to it to be correct — busted trades simply never appear on `spotExecutions` in the first place. Subscribe only if you specifically need awareness of failed settlements, e.g. for monitoring, alerting on systematic failure rates, or surfacing diagnostic information to end users.

## What Not to Do

* **Don't treat the order-submission response as a trade confirmation.** The response from `POST /v2/createOrder` (REST) or `createOrder` over WebSocket Order Entry reports what the matching engine did with your order — it carries no information about whether any resulting fill settled on-chain. Treat it the same way you'd treat an `orderChanges` update. See the dedicated section below.
* **Don't treat `FILLED` on `orderChanges` as a trade confirmation.** It is an ME-level status that fires before on-chain settlement. A fill seen here may still be busted later, and you will not be notified of the bust on this channel.
* **Don't try to "match" `orderChanges` events against `spotExecutions` to detect busts.** It's possible to do, but it's strictly harder than just listening to `spotExecutionBusts` directly (or ignoring busts entirely and relying on `spotExecutions` as the source of truth).
* **Don't double-count.** A trade that settles on-chain produces exactly one event on `spotExecutions`. A trade that busts produces exactly one event on `spotExecutionBusts`. Never both.

## The Order-Submission Response Is an ME-Level Signal

When you submit an order — whether over REST (`POST /v2/createOrder`, `POST /v2/cancelOrder`, `POST /v2/cancelAll`) or the equivalent WebSocket Order Entry operations — the response you get back reports what the **matching engine** did with your order. It does **not** report on-chain settlement.

Treat the order-submission response the same way you'd treat an update on the `orderChanges` channel:

* **Success response with fills in the body.** The matching engine matched your order and produced fill records. Those fills are ME-level fills; they have not yet been settled on-chain and may still bust during settlement. The presence of fills in the response is not a guarantee that any of them settle.
* **Success response without fills.** The matching engine accepted your order — it rested on the book (GTC) or didn't find a match (IOC). No settlement is implied either way.
* **Failure response.** The matching engine rejected the order before any matching attempt (validation failure, signature error, insufficient permissions, rate-limit, etc.). No matches were attempted, so no fills exist anywhere.

In none of these cases does the response carry settlement information. To learn whether a specific fill settled, listen to [`/v2/wallet/{address}/spotExecutions`](/developers/websocket-api-reference/websocket-api-reference). That channel is the only authoritative source for confirmed trades — if a fill appears there, it has settled on-chain and is final; if it never appears, either it never matched or it busted.

This rule is the same regardless of which transport you use to submit the order. REST and WebSocket Order Entry affect latency and framing; they don't change the finality semantics. **Finality is on-chain, and finality is reported only on `spotExecutions`.**

The same applies in the partial-fill case. If you submit an aggressive order that produces ten fills, you will see references to those fills in the submission response (and on `orderChanges`), but each of the ten is independently subject to on-chain settlement. Some may settle, some may bust. The submission response and `orderChanges` will not reflect which is which — only `spotExecutions` (for the ones that settled) and `spotExecutionBusts` (for the ones that busted) will.

## Reading a Bust Event

A bust event on `spotExecutionBusts` carries enough information to identify which match failed and why. The wire shape and field semantics are documented in the channel reference under [`/v2/market/{symbol}/spotExecutionBusts`](/developers/websocket-api-reference/websocket-api-reference). Key fields:

* `symbol`, `accountId`, `makerAccountId`, `orderId`, `makerOrderId`, `qty`, `side`, `price` — identify the failed match
* `reason` — the hex-encoded revert reason bytes from the on-chain settlement attempt. Clients can ABI-decode this against the `OrdersGateway` error ABI to recover the specific revert (e.g. an `InsufficientBalance` or `UnauthorizedSigner` error).

For most monitoring needs, the high-level information (which order, which counterparty, why) is sufficient. Decoding the `reason` bytes is only necessary if you want to drive automated remediation based on the specific failure mode.


# Smart Contract Withdrawals

As shown in the dApp funds on Reya Network are non-custodial and available to withdraw at anytime. You may use the withdrawal buttons on the dApp, or alternative you can withdraw directly from the Reya Network smart contracts.

**Follow the guide below to withdraw from the smart contracts.**

***

1. Bridge ETH to Reya Network for gas fees and Socket bridge fees by using this bridge: <https://bridge.gelato.network/bridge/reya-network>. Note that:

   1. The bridge does not support ETH withdrawals for the time being, so make sure you don’t bridge too much ETH.
   2. Trading on Reya Network is made gas-free via a relayer architecture, if you’re interacting with the contracts directly you will need to pay a small amount of gas (hence the ETH needed).

   ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FaYn82zYOMm7iFAfnjhYp%252Fimage.png%3Falt%3Dmedia%26token%3D175dfb8f-b628-418b-8ed0-6874fd01cdbd\&width=768\&dpr=4\&quality=100\&sign=2bfc19e9\&sv=2)
2. Withdraw funds from the Passive Pool into your wallet on Reya Network by calling the removeLiquidity function here: <https://usecannon.com/packages/reya-omnibus/latest/1729-main/interact/reya-omnibus/PassivePoolProxy/0xB4B77d6180cc14472A9a7BDFF01cc2459368D413#selector-0x0b7c92f9>. To do this, you need to input the following parameters:

   1. poolId: 1
   2. sharesAmount: the amount you want to withdraw multiplied by 10^30 (10 to the power of 30).
   3. minAmount: the amount you want to withdraw multiplied by 10^6

   For example, if you want to withdraw 99.5 rUSD, the parameters will be:

   1. poolId: 1
   2. sharesAmount: 99500000000000000000000000000000
   3. minAmount: 99500000
3. Unwrap rUSD into USDC by calling the withdraw function here: <https://usecannon.com/packages/reya-omnibus/latest/1729-main/interact/reya-omnibus/RUSDProxy/0xa9F32a851B1800742e47725DA54a09A7Ef2556A3#selector-0x2e1a7d4d>. To do this, you need to input the following parameters:
   1. amount: the amount withdrawn at the previous step, same as minAmount (multiplied by 1000000). For example, if you withdrawn 99.5 rUSD, the parameters will be amount = 99500000
4. Confirm you have USDC in your Reya Wallet.
   1. Add the chain to your wallet. There is a link in the footer of: <https://explorer.reya.network/> ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FmQFS3KfuEx5eVQamrkW2%252Fimage.png%3Falt%3Dmedia%26token%3Db0825ced-080e-4ee0-9a0d-d9c8df6e03b3\&width=300\&dpr=4\&quality=100\&sign=aa83514e\&sv=2)
   2. Add the token at address: 0x3B860c0b53f2e8bd5264AA7c3451d41263C933F2 For example using Metamask: ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FlagVs3y8tJKlcI7VKyfG%252Fimage.png%3Falt%3Dmedia%26token%3D6513882f-6622-462f-b389-334a9149f93d\&width=300\&dpr=4\&quality=100\&sign=7f0b7758\&sv=2) Enter the contract address and the symbol and decimals should auto-populate. Press Next ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FDRHuHJdi2GeZp76DMDkc%252Fimage.png%3Falt%3Dmedia%26token%3D594bf99b-00ef-4112-8834-b278aa77be9e\&width=300\&dpr=4\&quality=100\&sign=d475d9df\&sv=2)
5. Once confirmed, you should bridge funds from Reya Network to a source chain (Ethereum Mainnet/Arbitrum/Optimism/Polygon). To do this, you have to call the bridge function on the Socket contract here: <https://explorer.reya.network/address/0x1d43076909Ca139BFaC4EbB7194518bE3638fc76?tab=write_contract#405e720a>.

   ![](https://docs.reya.network/~gitbook/image?url=https%3A%2F%2F4172979140-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FIHVxf7CaLQzjdZ5a8tyE%252Fuploads%252FIImwsvtmdBvDQQD9BG05%252Fimage.png%3Falt%3Dmedia%26token%3Dfd994820-d3b2-42ba-abca-d2ff0b66b4d3\&width=300\&dpr=4\&quality=100\&sign=c66e47c8\&sv=2) To do this, you have to provide the following parameters:

   1. receiver: your wallet address on the source chain (the chain you are withdrawing to)
   2. amount: the amount withdrawn at the previous steps, same as minAmount (still multiplied by 1000000).
      1. note: the pull down at the end of the row will help you multiply by 10^6 but this number should be the same as the one used in the previous steps
   3. msgGasLimit: 10000000
   4. connector: the socket connector address assigned to the source chain you want to withdraw to.

      NetworkConnector Address

      Ethereum Mainnet

      0x807B2e8724cDf346c87EEFF4E309bbFCb8681eC1

      Arbitrum

      0x663dc7E91157c58079f55C1BF5ee1BdB6401Ca7a

      Optimism

      0xe48AE3B68f0560d4aaA312E12fD687630C948561

      Polygon

      0x54CAA0946dA179425e1abB169C020004284d64D3
   5. execPayload: 0x
   6. options: 0x
   7. Send native ETH (uint256): the socket bridge fees. As these are dynamic, you can use 10000000000000000 to account for most cases (this is equivalent to 0.01 ETH). Note that you can use lower amount as well (e.g. 1000000000000000, which is equivalent to 0.001 ETH), but it might fail if Socket fees increase.

   Upon completion of these steps, funds should be in the destination wallet address entered, on the network corresponding to the network connecter address used, in 10-15min. If you have not received your funds after an hour, please open a support ticket in our Discord and we can try and help.


