# What is Monday Trade

Monday Trade is a all-in-one DEX for onchain trading on Monad that offers the best of CEX and DEX trading experience. Monad’s low latency enables Monday Trade to execute trades within milliseconds, ensuring traders can make the most of market moves, without giving up their asset ownership to centralized exchanges.

Monday Trade combines the precision of a fully on-chain order book with the simplicity of AMMs into one sleek UI, delivering gas-efficient, high-performance onchain trades with optional advanced trading tools.

### Core Offering

A highly efficient hybrid DEX suitable for beginner, pro, and institutional traders.

#### Perps

Monday Trade offers perpetuals trading for key pairs initially listed by the Monday Trade core contributors. The scope of the pairs offered will expand over time in line with community requirements.

#### RWA

Monday Trade offers RWA stock trading for its users through its partnership with [Anchored](https://anchored.finance). This facilitates trading of tokenized stocks backed 1:1 by the underlying asset, leveraging institutional-grade liquidity and 1-click trading. The initial pairs are tokenized versions of the top 10 US NASDAQ equities and the scope of assets will grow over time.

#### Spot

Users can seamlessly create liquidity pools or add to existing pools as well as provide liquidity directly in the order book through limit orders.

### Our Vision

To offer traders the same experience as trading on centralized exchanges in a fully onchain and decentralized ecosystem with complete control over their assets, enabled by Monad’s architecture.


# Key Features & Advantages

* **Lightning-Fast Execution:** Millisecond settlement times for capturing critical market opportunities
* **Hybrid Market Structure:** Seamlessly integrates AMM liquidity with a complete onchain order book. This is both for perps and spot, catering to deep liquidity on all markets.
* **Advanced Trading Tools:** Professional-grade interface for sophisticated market participants
* **Gas Efficiency:** Optimized transaction processing for cost-effective trading
* **Permissionless Listings:** Enable new token spot markets with minimal liquidity requirements
* **Proven Technology:** Built on SynFutures' battle-tested infrastructure—creators of Base's leading perpetual DEX with over $300B in trading volume.


# Why Monad

### Decentralization & Performance Without Compromise&#x20;

As a Monad-native DEX, our mission is to deliver the speed, interactivity, and cost-efficiency users expect from centralized platforms *without sacrificing the decentralization and transparency that define DeFi*. This is exactly why we chose Monad.

### Performance that unlocks new UX&#x20;

Traditional EVM chains are limited by single-threaded execution and consensus-execution coupling. This restricts throughput and drives up gas fees during peak demand. These become major UX killers for active trading environments.

Monad changes the game with:

* 10,000 tps throughput
* 500ms block times
* 1-second finality

This enables a CEX-like experience with instant trade confirmations, low latency, and negligible transaction costs, even for complex smart contract interactions. For a DEX, that means supporting **order books, real-time trading UIs**, and **power users** without breaking a sweat.

### Ethereum compatibility, no tradeoffs&#x20;

Monad is fully EVM-equivalent and bytecode-compatible, meaning:

* All existing Solidity contracts work out of the box
* No changes needed for address formats, signatures, or wallets

This lets us reuse the existing Ethereum DeFi stack while building something fundamentally more performant.

### Parallel & pipelined execution: a new architecture for scalable DeFi&#x20;

Monad introduces **parallel execution** and **superscalar pipelining** at the VM and consensus layers:

* **Parallel execution** means Monad can run multiple transactions across cores while preserving the exact same serial ordering which is essential for DEXs where execution determinism matters.
* **Pipelined consensus and execution** means validation doesn't block throughput, unlocking much higher gas limits and execution budgets per block.

This architectural shift allows us to build features like:

* Fully onchain **matching engines**
* **High-frequency strategies** or social trading without congestion
* **Granular analytics and audits**, thanks to faster state access and finality

### Decentralized, credibly neutral&#x20;

Most high-performance chains today cut corners: centralized sequencers, geographic constraints, or high hardware requirements. Monad, by contrast, is designed to **preserve decentralization:**

* Proof-of-Stake & pipelined BFT consensus (MonadBFT)
* Anyone can run a full node with commodity hardware
* Deterministic state transitions and re-execution guarantees

For a permissionless trading venue, this is non-negotiable. It ensures no one can censor transactions, manipulate ordering, or gain unfair advantages.


# Infrastructure Provider

Monday Trade is powered by SynFutures' white-label DEX infrastructure, allowing new exchanges to launch seamlessly on emerging chains while plugging into a shared backend and growth ecosystem. This modular model means SynFutures can rapidly replicate the Monday Trade blueprint across new networks, each with local branding and unique liquidity strategies.

As such, Monday Trade inherits battle-tested smart contracts, deep DeFi expertise, and a proven product stack, thus giving it the speed, scalability, and flexibility needed to thrive on Monad from day one.

## About SynFutures

[SynFutures](https://docs.monday.trade/introduction/www.synfutures.com) ($F) is a leading decentralized exchange and full-stack financial infrastructure provider deployed on Base. Utilizing its innovative Oyster AMM model and a fully onchain order-matching engine, SynFutures enables anyone to list and trade any asset with leverage. As the market leader for perps on Base, SynFutures has facilitated more than $270Bn in cumulative trading volume.

Backed by top-tier institutions like Pantera, Polychain, Dragonfly, Standard Crypto, Framework, and SIG, SynFutures streamlining DeFi for all market participants by building an all-in-one platform for spot, perpetuals, and wealth management.


# How to Start Trading on Monday Trade


# Add Monad Chain to Your Wallet

{% stepper %}
{% step %}
**EVM wallet**

To get started on Monday Trade, you'll first need to set up a Monad-compatible wallet e.g. OKX, Rabby, Backpack, and Phantom, HaHa.

If you don’t have a wallet, you can set one up easily [here](https://rabby.io/). After downloading a wallet extension for your browser, create a new wallet.

Your wallet has a secret recovery phrase, private key, and a password. Anyone with access to these can access and/or steal your funds. Ensure to write and store the phrase in a secure place.
{% endstep %}

{% step %}
**Add Monad Chain to your wallet.**

Step 1: Open your wallet and find where it shows the current network

{% hint style="info" %}
*The screenshots below are from Rabby Wallet, but you can follow similar steps for other wallets as well.*
{% endhint %}

<div align="left" data-full-width="true"><figure><img src="/files/1iF90eHxazK82ty8wLz9" alt="" width="375"><figcaption></figcaption></figure></div>

Step 2: Go to Custom Network → Add Custom Network

<div align="left"><figure><img src="/files/CjolGofGCkQv73egawfq" alt="" width="375"><figcaption></figcaption></figure></div>

Step 3: Either find and add the Monad Chain from the available Chainlist or manually add network details shared below:

<div align="left"><figure><img src="/files/V6LAgojqHybgdd4ypnQC" alt="" width="375"><figcaption></figcaption></figure></div>

For Mainnet:

<table><thead><tr><th width="230.6640625">Name</th><th>Value</th></tr></thead><tbody><tr><td>Network Name</td><td>Monad Mainnet</td></tr><tr><td>Chain ID</td><td>143</td></tr><tr><td>Currency Symbol</td><td>MON</td></tr><tr><td>RPC URL</td><td><a href="https://rpc-mainnet.monadinfra.com">https://rpc-mainnet.monadinfra.com</a></td></tr><tr><td>Block Explorer</td><td><a href="https://monadvision.com/">https://monadvision.com/</a></td></tr></tbody></table>

*Previously for Testnet:*

*Name: Monad Chain*&#x20;

*RPC URL: <https://testnet-rpc.monad.xyz>*

*Chain ID: 10143*

*Currency Symbol: MON*

*Block Explorer URL:* [*https://testnet.monadexplorer.com*](https://testnet.monadexplorer.com)

Once done, click Confirm.

You’ll now be able to see and use the Monad network in your wallet.

See Monad [documentation](https://docs.monad.xyz/guides/add-monad-to-wallet/metamask) for further information.
{% endstep %}

{% step %}
**Add gas for trading**

You will need MON to pay for gas and tokens to trade.<br>
{% endstep %}
{% endstepper %}


# Connect Your Wallet to Monday Trade

{% stepper %}
{% step %}
On the Monday Trade dapp, click “Connect Wallet” and choose a wallet from the pop up.&#x20;

\
![](https://images.gitbook.com/__img/dpr=2,width=760,onerror=redirect,format=auto,signature=-462412136/https%3A%2F%2Ffiles.gitbook.com%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fn4pTwA8lON53MAXxnP3m%252Fuploads%252FdSiktmCOzNheqAoIOvR1%252FScreenshot%25202025-12-12%2520at%25203.57.43%25E2%2580%25AFPM.png%3Falt%3Dmedia%26token%3D55db2eba-b7ef-41bc-b6cc-0cd096a9a4eb)<br>
{% endstep %}

{% step %}
A wallet extension pop-up will appear asking you to connect to Monday Trade. Press “Connect.”
{% endstep %}
{% endstepper %}

It's that simple. You're now ready to trade.


# RWA Overview

> Trade tokenized stocks, real-world equities represented as ERC-20 tokens on Monad, directly on Monday Trade's DEX.

Monday Trade's RWA Trading lets you buy and sell tokenized versions of US-listed stocks. Each tokenized stock is backed 1:1 by the underlying stock held in a regulated brokerage account, giving you direct economic exposure to traditional equities from your Web3 wallet.

RWA Trading is powered by [**Anchored**](https://anchored.finance), the global digital operating system for tokenized stocks. A dedicated market maker network acts as an intermediary between Monday Trade users and Anchored to fill orders, so you can trade tokenized stocks seamlessly through the same interface you already use for spot trading.

> **No KYC required.** RWA Trading on Monday Trade works the same way as spot and perpetuals. Connect your wallet and trade.&#x20;


# RWA Partner

RWA trading on Monday Trade is powered by Anchored: the global digital operating system for RWAs. Its first product issues tokenized stocks on the Monad blockchain in collaboration with Monday Trade. Each token represents direct economic exposure to the underlying stock, backed 1:1 by shares held through a regulated US broker.

Key highlights:

* **1:1 Backed** — Every tokenized stock is fully collateralized by the underlying stock held in a segregated brokerage account.
* **Proof of Reserves** — An independent auditor verifies the 1:1 backing, ensuring full transparency.
* **ERC-20 Standard** — All tokenized stocks are standard ERC-20 tokens, compatible with any Monad-compatible wallet (MetaMask, Rabby, Trust Wallet, OKX Wallet, Coinbase Wallet, Ledger, etc.).
* **Dividends** — Cash dividends are automatically distributed as USDC directly to your wallet. No action required.

Learn more at [anchored.finance](https://anchored.finance) or read the Anchored [Documentation](https://docs.anchored.finance/).

> You can independently verify Anchored's reserves through Accountable, an independent third party, [here](https://accountable.anchored.finance/).

***

### What You Own

When you hold a tokenized stock, you have **economic exposure** to the underlying stock. This means:

* You benefit from price movements of the underlying stock
* You receive cash dividends (as USDC) when the company pays them
* Your tokens are freely transferable to any wallet on Monad and can be used for DeFi-native use cases

**Note:** Tokenized stocks represent economic exposure only. They do not confer voting rights, shareholder reporting rights, or direct legal ownership of the underlying stock.


# How RWA Trading Works

When you place an order for a tokenized stock on Monday Trade, a market maker fills your order by sourcing liquidity through Anchored. This means:

1. **You place an order** on Monday Trade's DEX (market or limit order).
2. **A market maker in the Anchored Market Maker Network** receives your order and executes against Anchored's issuance/redemption system.
3. **You receive** the tokenized stock (when buying) or USDC (when selling) directly in your wallet.

This is not pool-based liquidity — the market maker acts as the intermediary to ensure your orders are filled against real, 1:1 backed tokenized stocks.

{% hint style="info" %}
Please note RWA trading of this nature is only available on the RWA tab of Monday Trade. Given that creation of liquidity pools is permissionless on Monday Trade, you may see tokenized stocks there. Please note that the execution for trades for tokenized stocks that is not in the RWA tab of Monday Trade will not have the same execution mechanism or liquidity depth.
{% endhint %}

### Trading Hours

Because tokenized stocks are tied to the underlying US stock market, RWA Trading follows a **24/5 schedule** (Monday through Friday) across four sessions:

| Session         | Hours (ET)        | Description                      |
| --------------- | ----------------- | -------------------------------- |
| **Overnight**   | 8:00 PM – 4:00 AM | Extended hours trading           |
| **Pre-Market**  | 4:00 AM – 9:30 AM | Early session before market open |
| **Regular**     | 9:30 AM – 4:00 PM | Standard US market hours         |
| **After-Hours** | 4:00 PM – 8:00 PM | Post-close trading               |

**Market closures:**

* All US federal holidays (New Year's Day, MLK Jr. Day, Presidents' Day, Good Friday, Memorial Day, Juneteenth, Independence Day, Labor Day, Thanksgiving, Christmas)
* Weekends (Saturday and Sunday)
* Early closures on the trading day before certain holidays

> Orders placed while the market is closed will not be filled until the next trading session opens.

The team is proactively working with the Anchored team and its market maker network to expand stock trading to 24/7.

### Order Types

RWA Trading supports the same order types available on Monday Trade's DEX:

* **Market Order** — Executes immediately at the best available price. Use when you want to buy or sell right away.
* **Limit Order** — Sets a specific price at which you want to buy or sell. The order only fills when the market reaches your price. Useful for targeting a specific entry or exit point.


# Getting Started with RWAs

1. **Connect your wallet** to Monday Trade (same wallet you use for spot/perps trading).
2. **Navigate to RWA Trading** in the Monday Trade navigation bar.
3. **Deposit USDC** into your RWA trading account and receive [mUSD](/rwa-trading/faqs-for-rwas#what-is-musd)
4. **Select a tokenized stock** from the available markets.
5. **Place your order.** Choose market enter the amount you want to purchase, and confirm. If it's a limit order, you will also need to include the price at which you want the order to be executed.
6. **Receive your tokens.** These will appear in your Monday Trade portfolio page.

To sell, simply place a sell order for your tokenized stock and receive USDC back to your wallet.


# FAQs for RWAs

<details>

<summary><strong>What tokenized stocks are available on Monday Trade?</strong> </summary>

Monday Trade currently offers 35 major US-listed tokenized stocks, each backed 1:1 by the underlying shares held in regulated custody. Additional assets will be added over time.

</details>

<details>

<summary><strong>Do I need to interact with Anchored directly?</strong></summary>

No. You trade entirely through Monday Trade's interface. The market maker network handles all interaction with Anchored.

</details>

<details>

<summary><strong>Are my tokenized stocks really backed 1:1?</strong></summary>

Yes. Every tokenized stock issued by Anchored is backed by the actual underlying stock, held in a segregated brokerage account and verified by [Accountable](https://accountable.capital/), an independent auditor, every 24 hours. Please check the proof of reserves data [here](https://accountable.anchored.finance/).

</details>

<details>

<summary><strong>What happens to my order if the market is closed?</strong> </summary>

Market orders placed during market closures (weekends, holidays) will not be filled until the next available trading session opens. \
\
A market order can only be placed and executed during market hours. Limit orders can be placed at anytime but can only be executed during market hours and extended trading hours.

</details>

<details>

<summary><strong>Can I transfer my tokenized stocks to another wallet?</strong></summary>

Yes. Tokenized stocks are standard ERC-20 tokens and can be freely transferred to any compatible wallet on the Monad network.

</details>

<details>

<summary><strong>How are dividends paid?</strong> </summary>

When the underlying company issues a cash dividend, the equivalent amount is distributed as USDC directly to your wallet. This happens automatically. No claim or action is required. Typically companies distribute dividends on a quarterly basis.

</details>

<details>

<summary><strong>Are there any fees?</strong></summary>

These are the fees associated with RWA trading:

Deposit fee: 0 bps\
Withdrawal fee: 21 bps\
Buy Order Third Party Fee: 10 bps\
Buy Order Protocol Fee: 1 bps\
Sell Order Protocol Fee: 1 bps

</details>

<details>

<summary><strong>Do I need to complete KYC?</strong></summary>

No. RWA Trading on Monday Trade does not require KYC, consistent with the rest of the platform.

</details>

<details>

<summary><strong>Where can I learn more about how tokenized stocks work?</strong></summary>

At the bottom of each tokenized stock on Monday Trade's trading portal, users can find additional information about the tokenized stock. Further details can be found at our partner's page, [anchored.finance](https://anchored.finance).

</details>

<details>

<summary><strong>Does Monday Trade custody my assets?</strong></summary>

Your assets are ERC-20 tokens that sit in your non-custodial wallet

</details>

<details>

<summary><strong>What is mUSD?</strong></summary>

mUSD is a 1:1 USD-backed accounting unit reflecting the real-time purchasing power. It is required to purchase and sell RWAs on Monday Trade. It is a digital representation of the credit you have exclusively for RWA trading on Monday Trade. mUSD is not a cryptocurrency, stablecoin, or transferable virtual asset.&#x20;

</details>

<details>

<summary><strong>Have RWAs on Monday Trade been audited?</strong></summary>

Yes, Anchored, our partner for RWA trading, has undergone a smart contract audit with [Sherlock](https://sherlock.xyz/). The report will be published when the RWA trading goes live.

</details>

<details>

<summary><strong>What are the trading hours for RWAs on Monday Trade?</strong></summary>

The trading sessions are structured as follows, from Sunday evening to Friday evening:

* **Overnight Session:** 8:00 PM - 4:00 AM ET (technically occurs on the evening before the trade date)
* **Pre-Market Session:** 4:00 AM – 9:30 AM ET
* **Regular Market Session:** 9:30 AM - 4:00 PM ET
* **After-Hours Session:** 4:00 PM - 8:00 PM ET

The overnight session follows the NYSE holiday calendar. If US markets are fully closed for a holiday, the overnight trading session immediately preceding that holiday will not run. ***For example, the overnight session will be closed on the Wednesday evening before US Thanksgiving (8:00 PM ET) and will resume on Thursday evening at 8:00 PM ET.*** On US market half-days, the overnight trading session runs as normal for the full eight hours (8:00 PM ET – 4:00 AM ET), even if regular or after-hours trading closes early. ***For example, on the Friday after US Thanksgiving, the overnight session runs as usual, but the after-hours session does not.***

</details>

<details>

<summary><strong>Can I redeem my tokenized stock for the underlying asset?</strong></summary>

You may only redeem tokenized stocks for USDC

</details>

<details>

<summary><strong>How is the price of the tokenized stock determined?</strong></summary>

Monday Trade's RWA trading benefits from institutional-grade liquidity and execution, meaning that the price and liquidity is sourced by Anchored's partner and market maker network, who in turn are partnered with brokerage firms to ensure top tier execution.

</details>

<details>

<summary><strong>Does RWA trading use a liquidity pool?</strong></summary>

No, it uses a market maker network that provides instant access to NASDAQ/ TradFi Markets & liquidity

</details>

<details>

<summary><strong>Are there any restricted regions for RWA trading?</strong></summary>

RWA trading is not available in the US or China

</details>

<details>

<summary><strong>How to add the tokenized stock to my wallet?</strong></summary>

1. Find the tokenized stock and select the add to wallet icon beside it—the token may import automatically.
2. When auto-import doesn’t work, hold the cursor over the icon to display the token’s on-chain address.
3. Paste or enter that address in your wallet’s “add custom token” (or equivalent) flow, following the wallet’s own guide.

</details>


# Spot Protocol Mechanics


# How the AMM + Order Book Model Works

### Hybrid AMM + Order Book Model

Monday Trade employs a hybrid model that seamlessly integrates an **Automated Market Maker (AMM)** with an **onchain order book**, delivering both **instant liquidity** and **precise trade execution** on a single platform.

#### Core Architecture

At the heart of the system is a **tick-based architecture**, where price levels are discretized into fixed intervals (“ticks”). This framework enables structured liquidity and granular order placement.

The protocol is composed of three main components:

* Liquidity Handler (AMM Management)
* Order Handler (Limit Order Management)
* Swap Handler (Trade Execution)

***

#### AMM Mechanics

The AMM serves as a **fallback liquidity source** when limit orders are unavailable or insufficient. Traders can always execute trades at the current AMM price.

* Inspired by **Uniswap V3**, liquidity is concentrated into **custom price ranges**.
* The **liquidity handler** calculates **active liquidity**, i.e., liquidity available in the current price range.
* Swaps are routed through a **swap router or custom aggregator**, ensuring optimal execution even for less liquid tokens.

***

#### Onchain Order Book

The **order book** is managed by the order handler and allows users to place **limit orders at specific ticks** (e.g., "buy ETH at $2000").

* Orders must be placed at ticks **above or below the current price**, depending on the token pair (e.g., token0 = ETH, token1 = USDC). This reduces arbitrage risks.
* **Orders on the same tick are merged** for efficiency and clarity.
* **Filled orders are automatically withdrawn** before new placements can occur at the same tick.

***

#### Swap Execution & Lazy Crossing

The **swap handler** introduces a novel **lazy crossing mechanism**, optimizing gas costs while maintaining order book precision.

* **Fine-grained ticks** are used for order placement, while **coarser ticks** are used for swap settlement.
* **Lazy crossing** updates only the necessary **swap ticks during trade execution** and delays order tick updates until the next relevant order placement.
* A **nonce system** ensures correctness and prevents desynchronization.

> ✅ This mechanism delivers up to 98% gas savings — for example, crossing 101 order ticks may only update 2 swap ticks.


# Spot Fees

Monday Trade features a transparent and efficient fee structure designed to ensure fairness for all participants. Below, we explain how fees are calculated based on the type of liquidity used during a trade.

### **Order Book Fees**

For trades executed against the order book liquidity:

* **Taker Fee**: **0.03% for all pools**
* **Maker Fee**: **0%**

### **AMM Fees**

For trades executed against AMM liquidity, fees vary by pool and are determined by the pool’s configuration. A list of AMM fees for specific pools is provided below:

<table><thead><tr><th width="132.58984375">Pool</th><th width="434.84375">Pool Address</th><th>AMM Fee</th></tr></thead><tbody><tr><td>MON/USDC</td><td>0x8f889ba499c0a176fb8f233d9d35b1c132eb868c</td><td>0.05%</td></tr><tr><td>gMON/MON</td><td>0x4e423abad0558c6d0635161ca1935d943a77b591</td><td>0.03%</td></tr><tr><td>wBTC/USDC</td><td>0xd70e977a5e07710084b04ac89ac7d3a28cb81417</td><td>0.3%</td></tr></tbody></table>

#### Hybrid Fee Calculation

Trades on Monday Trade can utilize both **order book liquidity** and **AMM liquidity** within the same transaction. In such cases, the fees are calculated independently for each part of the trade, based on the source of liquidity.

**Example**: Suppose you trade 100 MON in a pool where the AMM fee is 0.05% and the order taker fee is 0.03%. If 90 MON is filled by order book liquidity and 10 MON by AMM liquidity, the fee is calculated as:

* Order book portion: 90 MON × 0.03% = 0.027 MON
* AMM portion: 10 MON × 0.05% = 0.005 MON
* Total fee: 0.027 MON + 0.005 MON = **0.032 MON**


# How to Provide Liquidity on Monday Trade


# Provide Liquidity

Providing liquidity on Monday Trade allows you to contribute to trading pair liquidity pools, earn fees, and support the Monad ecosystem. This step-by-step guide explains how to add liquidity to a pool on Monday Trade.

### Before adding liquidity, ensure the following:

* A compatible wallet is connected to the Monad network and Monday Trade.
* Sufficient tokens for the chosen trading pair are available in your wallet.
* Enough MON to cover gas fees.

### Steps to Add Liquidity:

{% stepper %}
{% step %}
**Select an Asset Pool**

In the search bar on the dapp UI, select the asset pool you want to provide liquidity (e.g. MON/USDC).
{% endstep %}

{% step %}
**Access the Liquidity Panel**

On the right-hand side of the page, click the "**Liquidity**" panel to open the liquidity management interface for the selected pool.
{% endstep %}

{% step %}
**Set Your Price Range**

Choose the price range for your liquidity position. You can:

* Manually enter the minimum and maximum prices in the provided fields, or
* Drag the upper and lower boundary lines on the price range graph to adjust the range visually.

{% hint style="info" %}
If your selected range excludes the current market price (an out-of-range position), you will provide liquidity with only one token (e.g., MON or USDC, depending on the price range at which you are providing liquidity) and will not earn fees until the market price enters your range.
{% endhint %}

<div align="left"><figure><img src="/files/BcmnKeOX3MpozEarZc1h" alt="" width="363"><figcaption></figcaption></figure></div>

{% endstep %}

{% step %}
**Enter Deposit Amount**

Input the amount of one token (e.g., MON or USDC) you wish to deposit. The platform will automatically calculate the corresponding amount of the other token based on the current pool ratio and your selected price range.

* For in-range positions, you’ll provide both tokens proportionally.
* For out-of-range positions, you’ll provide only one token, as indicated by the interface.
  {% endstep %}

{% step %}
**Approve Token (First-Time Only)**

If this is your first time adding liquidity for a specific token, click the "Approve \[Token Symbol]" button (e.g., "Approve MON"). Confirm the approval transaction in your connected wallet. This step authorizes Monday Trade to access your tokens for the pool.
{% endstep %}

{% step %}
**Review and Confirm Transaction**

Review the liquidity details, including the token amounts and price range. Once satisfied, click "Add Liquidity" and approve the transaction in your wallet. Wait for the transaction to be confirmed on the Monad network.
{% endstep %}

{% step %}
Once confirmed, your liquidity position will appear in the "Liquidity" section at the bottom of dapp UI. You can monitor its status, collect fees, or manage your position as described [here](/spot-trading/how-to-provide-liquidity-on-monday-trade/manage-lp-positions).
{% endstep %}
{% endstepper %}


# Manage LP Positions

After adding liquidity, you can monitor, add to, remove, or claim fees from your liquidity positions (LP positions) on Monday Trade. This section provides clear steps to manage your positions effectively.

### Steps to Manage LP Positions:

{% stepper %}
{% step %}
**Access Your Liquidity Positions**

Navigate to the "Liquidity" panel on the Monday Trade interface. Select the "Liquidity" tab at the bottom of the panel to view all active LP positions associated with your connected wallet.

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

{% endstep %}

{% step %}
**Monitor Position Details**

Here you can view details of all your LP positions including:

* **Status**: Whether the position is in-range or out-of-range.
* **Current Price**: The market price of the trading pair.
* **Price Range**: The price range set for your position.
* **Liquidity**: The deposited token amounts.
* **Unclaimed Fees**: Accumulated fees earned from trading activity.
  {% endstep %}

{% step %}
**Collect Earned Fees**

To collect accumulated fees, click "Claim Fee". Confirm the transaction in your wallet. Fees are paid in the pool’s tokens and transferred to your wallet upon confirmation.

<figure><img src="/files/klPdXSE747YETg9x1T8Q" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}
**Add More Liquidity**

To increase liquidity in an existing position:

* Click "Add".
* The new liquidity will automatically use the same price range as the existing position.
* Enter the additional amounts for one token (e.g., MON or WETH); the platform will calculate the corresponding amount for the other token.
* Click "Add Liquidity" and confirm the transaction in your wallet.
  {% endstep %}

{% step %}
**Remove Liquidity**

To remove your liquidity:

* Click "Remove".
* Choose the percentage of the position to remove (e.g., 25%, 50%, 70%, or 100%) or manually enter a custom percentage.
* Review the token amounts to be returned and any unclaimed fees.
* Confirm the transaction in your wallet.&#x20;
* Removed tokens and any uncollected fees will be transferred to your wallet.
  {% endstep %}
  {% endstepper %}


# Understanding Impermanent Loss

#### What is Impermanent Loss (IL)? &#x20;

Impermanent Loss is a common concept in AMMs (Automated Market Makers) that affects liquidity providers (LPs). It happens when the prices of the tokens you've deposited into a liquidity pool change relative to each other after you’ve added them. This price divergence can cause you to earn less than if you had simply held the tokens in your wallet.

#### Why Does Impermanent Loss Happen?

In an AMM, you provide two tokens (e.g. USDC and MON) in equal value to a pool. The AMM keeps the ratio of these tokens in balance using a pricing formula like x \* y = k (in the case of constant product pools).

When the price of one token increases significantly relative to the other, the AMM automatically rebalances the pool. That means it sells the appreciating asset to maintain the ratio which in turn means that you end up holding more of the underperforming token and less of the outperforming one.

If you withdraw your liquidity after this shift, the total value of your position may be less than if you had just held the original tokens, even after earning trading fees. That difference is the impermanent loss.

#### Why Is It Called “Impermanent”?&#x20;

It’s considered “impermanent” because the loss only becomes real when you withdraw your liquidity. If prices return to the original ratio, the loss disappears. However, in volatile markets, that reversal doesn’t always happen.

#### IL on Monday Trade&#x20;

Monday Trade supports both AMM-based and orderbook-based liquidity. IL only affects AMM pools, not orderbook market makers. If you're an LP on an AMM pair, it's important to understand this risk and monitor token volatility.

That said, impermanent loss can often be offset by trading fees and incentives, depending on the pair’s activity and reward structure.<br>


# How to Trade Spot on Monday Trade

### Order Types

Monday Trade supports the following order types:<br>

* **Market Order**: Buy or sell an asset instantly at the best available market price. Ideal for quick trades when timing is key.<br>
* **Limit Order**: Set a specific price to buy or sell an asset. The order only executes if the market reaches your chosen price (or better). Note: The price is guaranteed, but the order may not fill if the market doesn’t hit your target.&#x20;

### Place a Market Trade

{% stepper %}
{% step %}
In the **search bar** on the dapp UI and select the trading pair you want to trade (e.g. MON/USDC).

<div align="left"><figure><img src="/files/X253OGxZu6AUj2brF1tc" alt="" width="338"><figcaption></figcaption></figure></div>

{% hint style="info" %}
*Your wallet must have enough tokens for the trade and MON for gas.*
{% endhint %}
{% endstep %}

{% step %}
On the **trading panel,** select either Buy or Sell direction.

<div align="left"><figure><img src="/files/3jR7XJyZAxWUgLMjZguV" alt="" width="364"><figcaption></figcaption></figure></div>

{% endstep %}

{% step %}
Select **Market**.

{% endstep %}

{% step %}
(Optional) Click the **settings icon** in the trading panel’s top-right corner to adjust:

1. **Slippage tolerance:** The maximum price change you’re willing to accept.
2. **Transaction deadline:** The time limit for the trade to execute.

<div align="left"><figure><img src="/files/Uolp7uRUA02XfdDR0Hk5" alt="" width="362"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
In the trading panel, enter Trade Value (the amount of tokens to **pay),** and **t**he amount of tokens to receive will automatically update.

<div align="left"><figure><img src="/files/7HJVEHq9Y67zU9Scz0dH" alt="" width="364"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
If trading a token for the first time, click **Approve \[Token Symbol]** **to continue**, then confirm in your wallet.

{% endstep %}

{% step %}
Review the trade details in the wallet pop-up. If correct, click **Confirm**.

{% endstep %}

{% step %}
Approve the transaction in your wallet when prompted.

{% endstep %}
{% endstepper %}

Done! Your trade is complete. To view the transaction, click the transaction hash to check it on the Monad Explorer.

### Limit Order

To place a limit trade on Monday Trade:

{% stepper %}
{% step %}
In the **search bar** on the dapp UI, select the trading pair you want to trade (e.g. WMON/USDC).

{% hint style="info" %}
*Ensure your wallet has enough tokens for the trade and MON for gas.*
{% endhint %}
{% endstep %}

{% step %}
On the **trading panel**, select either Buy or Sell direction.

{% endstep %}

{% step %}
(Optional) Click the **settings icon** in the trading panel’s top-right corner to adjust:

**a. Slippage tolerance**

**b. Transaction deadline**
{% endstep %}

{% step %}
In the trading panel:

a. Enter the **price** (in the quote asset) at which you want to buy or sell.

b. Enter the amount of tokens to **pay,** and **t**he amount of tokens to receive will automatically update.

<div align="left"><figure><img src="/files/9BuNqQYZGH3IspeGvioq" alt="" width="364"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
If trading a token for the first time, click **Approve \[Token Symbol]** to approve it, then confirm in your wallet.

{% endstep %}

{% step %}
Review the trade details in the pop-up window. If correct, click **Confirm.**

{% endstep %}

{% step %}
Approve the transaction in your wallet when prompted.

{% endstep %}

{% step %}
After the trade executes, go to the **Open Orders** section at the bottom of the page to **claim** your swapped tokens.
{% endstep %}
{% endstepper %}

Done! Your limit order is placed. To view the transaction, click the transaction hash to check it on the Monad Explorer.


# Spot Contract Pair Specifications

<table><thead><tr><th width="200.71484375">Periphery</th><th>Address</th></tr></thead><tbody><tr><td>Aggregator</td><td>0xAD8974D98f7fc386e396FFE826B886cf20AfE232</td></tr><tr><td>NFTPositionManager</td><td>0x68b507BF58ED32173f41FF20aa2494A569daeC44</td></tr><tr><td>QuoterV2</td><td>0xB97eCD41Aef0F842E773C8F9905919cDE49880C9</td></tr><tr><td>SwapRouter</td><td>0xFE951b693A2FE54BE5148614B109E316B567632F</td></tr></tbody></table>

<table><thead><tr><th width="201.56640625">Spot</th><th>Address</th></tr></thead><tbody><tr><td>Factory</td><td>0xC1e98D0A2a58fB8aBd10ccc30a58efff4080Aa21</td></tr><tr><td>Config</td><td>0xdc67221ea8D223E0A1D0948eDeCB634cAF190eC9</td></tr></tbody></table>

**Verified Pool Addresses are below:**

<table><thead><tr><th width="218.09857177734375">Pool</th><th>Address</th></tr></thead><tbody><tr><td>MON/USDC - 0.05%</td><td>0x8f889BA499C0A176Fb8F233D9D35b1c132eB868C</td></tr><tr><td>MON/USDC - 0.3%</td><td>0x0a439a3a809dcfa8565625839f74368b0e7d0e3c</td></tr><tr><td>gMON/MON - 0.03%</td><td>0x4e423abad0558c6d0635161ca1935d943a77b591</td></tr><tr><td>gMON/MON - 0.01%</td><td>0x327ebb1d4930262df6ad436b73805224caab4b71</td></tr><tr><td>AUSD/earAUSN - 0.03%</td><td>0x7362375b991a0a4500b7f97592369b6cccce034f</td></tr><tr><td>WBTC/USDC - 0.3%</td><td>0xd70e977a5e07710084b04ac89ac7d3a28cb81417</td></tr></tbody></table>


# How to Create a New Pool on Monday Trade

The pool creation function allows you to initialize a new liquidity pool for a trading pair that does not yet exist on the platform. By creating a pool, you enable trading for the selected pair and earn fees based on your chosen fee tier. This step-by-step guide explains how to create a new pool on Monday Trade.

<br>


# Create a New Pool

The pool creation function allows you to initialize a new liquidity pool for a trading pair that does not yet exist on the platform. By creating a pool, you enable trading for the selected pair and earn fees based on your chosen fee tier. This step-by-step guide explains how to create a new pool on Monday Trade.

### Steps to Create a Liquidity Pool (Add Liquidity to a New Pool)

{% stepper %}
{% step %}
**Select Tokens for the Pair**

On the Monday Trade interface, navigate to the Spot token list and select "New Pool." Choose two tokens to form the trading pair (e.g., MON and WETH). Use the token selector to search for and add the desired tokens.

<div align="left"><figure><img src="/files/qvjJbszCQMPeXh6bdOvy" alt="" width="375"><figcaption></figcaption></figure></div>

<div align="left"><figure><img src="/files/2UCfGQvqiQJcKL2OF2Yl" alt="" width="188"><figcaption></figcaption></figure></div>

{% endstep %}

{% step %}
**Choose the Fee Tier**

Select the fee tier for the new pool, which determines the trading fees you’ll earn as a liquidity provider. Available options are: 0.03%, 0.05%, 0.3%, and 1%.

{% hint style="info" %}
Note: Lower fee tiers are suitable for stable or less volatile pairs, while higher tiers are better returns for volatile pairs.
{% endhint %}

After selecting the token pair and fee tier, the platform will check if a pool already exists for the chosen pair and fee tier. If the pool exists, you will see an "Add Liquidity to an Existing Pool" option. You will then be redirected to the existing pool’s interface to add liquidity. Follow the steps in our How to Provide Liquidity guide to proceed. If no pool exists, continue to the next steps to create a new pool.
{% endstep %}

{% step %}
**Set the Initial Price**

Enter the initial price for the trading pair, which sets the starting price at which the pool will begin facilitating trades.

<div align="left"><figure><img src="/files/Urkl55BLzxdVkalt1ht2" alt="" width="188"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
**Adjust the Price Range**

Monday Trade shows you the current price that the token is trading at. Click on ‘Use market price’ to use the current market price for the token. It’s recommended to use the current market price to ensure efficient trading and minimize early imbalances in the pool.

<div align="left"><figure><img src="/files/MghsaxD0rbJPWz5ZKC2u" alt="" width="188"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
**Enter Deposit Amount**

Input the amount of one token (e.g., MON or WETH) to deposit into the pool. The platform will automatically calculate the corresponding amount of the other token based on the initial price and price range.

* For in-range positions, you’ll provide both tokens proportionally.
* For out-of-range positions, you’ll provide only one token, as indicated by the interface.

<div align="left"><figure><img src="/files/cEJD61VOQb5q95PbAyBa" alt="" width="188"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
**Approve Tokens (First-Time Only)**

If this is your first time using one or both tokens for liquidity on Monday Trade, click "Approve \[Token Symbol]" (e.g., "Approve MON" or "Approve WETH") for each token. Confirm the approval transactions in your wallet to authorize Monday Trade to access your tokens.
{% endstep %}

{% step %}
**Review and Create Pool**

Review the pool details, including the token pair, fee tier, initial price, price range, and token amounts. Click "Add Liquidity to a New Pool" and approve the transaction in your wallet. Wait for confirmation on the Monad network.
{% endstep %}
{% endstepper %}

Once confirmed, your new liquidity pool will be active, and your position will appear in the "Your Liquidity" tab under "Portfolio". You can monitor the pool’s performance, collect fees, or manage your position as described in our[ How to Manage LP Positions](/spot-trading/how-to-provide-liquidity-on-monday-trade/manage-lp-positions) guide.


# Pool Creation Tips

* Initial Price Accuracy: Setting the initial price close to the market price helps ensure efficient trading and minimizes early imbalances in the pool.
* Fee Tier Selection: Choose a fee tier based on the expected volatility of the pair.&#x20;
* Price Range Strategy: Narrow ranges may yield higher fees but require active management, while wider ranges are more stable but may earn lower fees.
* Gas Fees: Ensure sufficient MON for transaction costs, as creating a pool involves multiple onchain transactions.
* Risks: Pool creation involves risks like impermanent loss, especially for volatile pairs. Learn more in our[ Understanding Impermanent Loss](/spot-trading/how-to-provide-liquidity-on-monday-trade/understanding-impermanent-loss) section.


# Spot Audit Reports

The Monday Trade Spot contract has been audited by Quantstamp and Zenith.

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

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


# Perps Protocol Mechanics

{% hint style="info" %}

## Perps are currently unavailable **during** our transition to RWA trading. For timelines and details, please visit our [blog](https://monday.trade/post/perp-markets-are-transitioning).

{% endhint %}

## The Monday Trade Perps Engine

The **Monday Trade Perps Engine** represents a next-generation derivatives market infrastructure built around a **permissionless onchain orderbook**. Evolving beyond traditional AMM-based models, it enables **active market making** through deterministic, transparent, and fully on-chain mechanisms designed for perpetual futures and other derivative products—while maintaining the flexibility to support **passive liquidity provision** for long-tail assets.

### **Active Liquidity Through Orderbook Market Making**

At its core, the **Monday Trade Perps Engine** provides a framework for **professional-grade market making** directly on-chain. Instead of relying on algorithmic bonding curves or pooled liquidity, the system allows makers to place **native limit orders** at discrete price points, which execute atomically once matched—delivering the same precision and control as centralized exchange orderbooks.

This architecture empowers both algorithmic and manual market makers to actively manage exposure and deploy capital dynamically. By combining transparent settlement with composable smart contracts, the Monday Trade Perps Engine establishes a **trustless environment for sophisticated trading strategies**. Unlike hybrid or off-chain matching systems, all matching and settlement occur on-chain, eliminating centralized intermediaries and potential “backdoors.” The result is a **transparent, auditable, and censorship-resistant market layer** that combines the speed of modern matching engines with the integrity of decentralized execution.

### **Unified Liquidity Model**

The **Monday Trade Perps Engine** unifies concentrated liquidity and limit orders within a single on-chain framework. In smart contract terms, two primary entities—**Range** and **Order**—represent the liquidity and resting orders available at each price point.

* When multiple **Range** positions cover the same price, their liquidity (expressed as √k) is aggregated to define effective market depth.
* At that same price point, all **Orders**—discrete maker limit orders—are summed to accommodate taker demand.
* **Orders are always executed before any Range liquidity is consumed**, ensuring maker-defined pricing takes precedence in the trade-matching process.

Each price point is represented by a **Pearl**, a data structure that stores both Range and Order information. Pearls are indexed by price and together form the unified liquidity layer of the protocol. Conceptually, the Monday Trade Perps Engine can be viewed as a network of Pearls—each one a composable liquidity node—connected by a deterministic pricing function that governs market transitions.

This **Pearl-based design** also enables the protocol’s **asynchronous order logic**, which greatly simplifies the taker-side experience: takers can trade up to their desired size without managing multiple order books or liquidity pools. Gas costs scale linearly with price impact (i.e., the number of ticks crossed), ensuring cost-efficiency and predictable transaction behavior.

### Trade Execution Process

For a trade of size **S₀**, the unified liquidity consumption process proceeds as follows:

1. **Check active limit orders** within the Pearl at the current price **P₀**.
   * If unfilled orders exist, consume them until the trade is satisfied or the limit volume is exhausted.
   * If the trade size **S₀** is completely filled, terminate. *(The current price remains unchanged.)*
   * Otherwise, continue to step 2 with remaining size **S₁**.
2. **Locate the next Pearl** at the subsequent price **P₁**.
   * Execute the remaining trade size **S₁** across the liquidity connecting **P₀** and **P₁**.
   * If fully filled, terminate. *(The current price updates to reflect the impact.)*
   * If not, update the price to **P₁** and repeat from step 1 with residual size **S₂**.

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

This sequential logic ensures that **maker orders are prioritized**, **execution remains atomic**, and **pricing evolves continuously** across ticks, resulting in a predictable and gas-efficient trading process.

### Atomic Execution and Market Synchronization

The unified architecture guarantees **atomic trade settlement**—each transaction executes in full or not at all. By integrating both order placement and liquidity management within the same system, the Monday Trade Perps Engine eliminates the fragmentation and desynchronization issues common in hybrid or off-chain systems.

This model benefits all participants:

* **Takers** receive immediate and predictable fills.
* **Makers** maintain full transparency into their open interest, filled orders, and execution states.
* **The network** achieves deterministic consistency across every trade.


# Perps Order Types & Matching

### Market Orders

Trade with the Monday Trade perps engine directly. The counterparty can either limit orders or concentrated liquidity.

* **Price Impact:** The estimated change of price after this trade.
* **Limit Price:** The maximum price for a buy trade/The minimum price for a sell trade.
* **Trading Fee:** The fee paid for the trade. Please refer to the [Contract Specification](/perps-trading/perps-contract-specifications-and-fees) section.
* **Execution Fee:** A mechanism to protect liquidity providers. Please refer to the Security section.

### Limit Orders

Monday Trade Perps Engine enables **native limit orders** similar to those in centralized limit order book systems. These orders are defined at discrete price points and become irreversible once filled, providing makers with certainty regarding the status of their limit orders.

### Matching and Overall Pricing Mechanism

To circumvent current smart contract limitations, order matching in the **Monday Trade Perps Engine** does not follow the traditional centralized limit order book (CLOB) model based on the first-in, first-out (FIFO) principle. Instead, it employs a matching process optimized for onchain efficiency and fairness. The characteristics of this matching and pricing mechanism can be summarized as follows:

* At a price point where limit orders exist, those orders are filled before any concentrated liquidity is consumed. Concentrated liquidity becomes prominent for long-tail assets.
* Trade volume is allocated proportionally across multiple limit orders resting at the same price, supporting just-in-time limit order creation.
* Overall slippage is significantly reduced when limit orders exist along the engine’s price curve.

### Admissible Limit Order Price

The **Monday Trade Perps Engine** adopts a **tick-based pricing system**, where each tick corresponds to a price increment of 1.0001ⁿ.\
For limit orders, the price granularity is set to **1 tick**, meaning admissible limit order prices follow the structure:\
**1.0001¹ⁿ**, where *n* is an integer.

This design ensures precise, standardized price intervals that facilitate efficient on-chain order management and matching

### Execution Fees

Once an order is filled, the **Monday Trade Perps Engine** allows any address to submit a transaction on-chain to convert the filled order into a position, completing the settlement process. This mechanism does not alter ownership of the filled order or resulting position.

An **execution fee** is paid to the transaction sender as compensation for the associated gas cost. Please refer to the **Pair Specification** section for further details.


# One-Click Trading (1CT)

Perp **1‑Click Trading (1CT)** on Monday Trade lets you trade perps with near‑instant execution by reducing repeated wallet confirmations.&#x20;

***

#### Before you start

* Connect your wallet (top‑right)
* Make sure you’re on the correct network (Monad) in your wallet
* Have trading collateral ready (e.g., USDC) and be ready to fund a small amount of gas token for the 1CT wallet if prompted

***

{% stepper %}
{% step %}

#### Enable 1CT

Click the purple **Enable 1 click trading** button (top‑right).

<figure><img src="/files/u3Ewfb3MDfpuxW8YyUJG" alt="" width="358"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Complete the two setup steps

In the 1CT setup modal, follow the steps in order:

1. Under **SECURE 1CT WALLET**, click **Create**.
2. Under **ENABLE ACCOUNT DELEGATION**, click **Enable**.
3. Wait until it shows two green checks.

This delegates signatures to your 1CT wallet so perp actions can be executed with 1 click.

<figure><img src="/files/LlUCUazLO0bBJZvbPb0h" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Add Gas Token to the 1CT wallet

1. Choose how you want to fund gas:

* **MON** (direct top‑up), or
* **USDC** (it will be automatically swapped to MON via Monday Trade spot)

2. Enter an amount.
3. Click **Add Gas Token**.

If you choose **USDC**, you may see **Approve USDC to continue** first.

<figure><img src="/files/bWy9XgHbWfFfa7KDvXLy" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}
**1CT is now enabled!** Enjoy instantaneous trading!
{% endstep %}
{% endstepper %}


# Perps Funding Rate

As perpetual futures do not have a final settlement at maturity to guarantee convergence to the spot market index price, the **Monday Trade Perps Engine** employs **continuous funding** for its perpetual futures markets. The principle is to expect the deviation to converge in a specified cycle.

$$
FundingFeeRate = \frac{(P\_{\text{fair}} - P\_{\text{spot}})}{P\_{\text{spot}}} \cdot \frac{\Delta t}{Interval}
$$

**∆t** is the time difference in seconds between the current and last timestamp when the funding fee rate is calculated.

**Interval** can be set to different settings based on the trading pair, such as 1 hour (3,600 seconds), 8 hours (28,800 seconds), or 24 hours (86,400 seconds).

The Funding index of a pair is updated when anyone interacts with that pair.

**Unrealized funding payment/income of a position is realized or settled when the position is increased, reduced, or closed or its margin is adjusted.**

### Advanced <a href="#advanced" id="advanced"></a>

Due to limitations of smart contract implementations, the smart contracts only keep track of the total OI of long positions and total OI of short positions; liquidity added through AMM curves and not through limit orders are exempted from the funding income/fees.The actual funding payment amount calculation is as follows, let FundingFeeRate be the rate calculated above.

For the case long pays short：

* **FundingFeeRateForLong = -FundingFeeRate**
* **FundingFeeRateForShort = +FundingFeeRate \* totalLongPositionOI / totalShortPositionOI**

For the case short pays long：

* **FundingFeeRateForShort = FundingFeeRate**
* **FundingFeeRateForLong = -FundingFeeRate \* totalShortPositionOI / totalLongPositionOI**

**In other words, the side that pays funding always pays as is, but the side that receives funding may receive more or less funding depending on the position imbalance.**

### Implications <a href="#implications" id="implications"></a>

In a market scenario where **price rapidly goes up,** totalLongPositionOI is likely to be much larger than totalShortPositionOI as liquidity in Monday Trade Perps Engine is holding most of the short position until LP's remove those liquidity

* If the long positions need to pay funding, **short positions will receive much more fundings per unit of position**
* If the long positions are to receive funding, **long positions will receive less fundings per unit of position**

In a market scenario where **price rapidly goes down,** totalShortPositionOI is likely to be much larger than totalLongPositionOI as liquidity in Monday Trade Perps Engine is holding most of the long position until LP's remove those liquidity

* If the short positions need to pay funding, **long positions will receive more fundings per unit of position**
* If the short positions are to receive funding, **short positions will receive less fundings per unit of position**


# Perps Liquidation Engine

When the margin supports a trading position that falls below its **maintenance margin requirement,** that position is subject to **liquidation.**

Liquidation in Oyster AMM is performed primarily via the **taking-over approach,** where the liquidator takes over the target trading position along with the remaining margins and tops up the margin to meet the initial margin requirement. Effectively, the remaining margin of the trading position to be taken over is a potential profit for the liquidator—that is if the liquidator can adequately manage the risk.

In addition, Oyster AMM also allows a liquidation mechanism where trading positions failing the maintenance margin requirement are forced to trade against the Oyster AMM directly to close the position. In this approach, the trading fee is also charged. If the position has margin balanced remaining after the forced close, these margins **would go to the insurance fund of this pair.**

Both approaches support **partial liquidation,** where the initiator specifies the amount of position to be taken over or forcibly closed. In this way, a big bankrupted position can be taken over by multiple liquidators to improve the stability of the overall design.

In both approaches, there is chance that the target position is bankrupted. In that case, **insurance fund of this pair is firstly used to fill the gap if possible. If the insurance fund is not enough to cover the loss, the loss is socialized to all opposite positions, that is the profiting positions are taxed to cover the loss.** Social loss per LONG/SHORT is tracked by longSocialLossIndex and shortSocialLossIndex.


# Perps Contract Specifications & Fees

## Fees

Monday Trade currently supports perpetual futures markets for the following markets. Further pairs will continuously be added as the protocol grows.

IMR and MMR represent the Initial and Maintenance Margin Requirements, respectively.

<table><thead><tr><th width="119.4765625">Symbol</th><th width="109.484375">Leverage</th><th width="79.90625">IMR</th><th width="85.0703125">MMR</th><th width="142.859375">Execution Fee</th><th width="159.046875">Market Order Fee</th><th width="196.73828125">Limit Order Fee rebate</th></tr></thead><tbody><tr><td>BTC/USDC</td><td>10x</td><td>10%</td><td>5%</td><td>0.01 USDC</td><td>0.02%</td><td>0.00%</td></tr><tr><td>ETH/USDC</td><td>10x</td><td>10%</td><td>5%</td><td>0.01 USDC</td><td>0.02%</td><td>0.00%</td></tr><tr><td>MON/USDC</td><td>10x</td><td>10%</td><td>5%</td><td>0.01 USDC</td><td>0.02%</td><td>0.00%</td></tr></tbody></table>

## Perpetuals Contracts&#x20;

#### System Contracts

<table><thead><tr><th width="154.90625">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Config</td><td>0x15bC3C13cbf5903E78b97208ba1021E5dc1B4470</td></tr><tr><td>Gate</td><td>0x2E32345Bf0592bFf19313831B99900C530D37d90</td></tr><tr><td>Observer</td><td>0xdfBA572929De47838BdE12336dfE8842B06d9628</td></tr><tr><td>Guardian</td><td>0x5FE49fb8770A8009335B1d76496c3e07Ca04FC9F</td></tr></tbody></table>

For market configuration contracts related to oracles, please refer to the [Perps Oracle Sources](/perps-trading/perps-oracle-sources) section.


# Perps SDK & API

### SDK

The Monday Trade SDK provides a TypeScript interface for programmatically interacting with the Monday Trade Perps, allowing developers to integrate trading, query market data, and manage positions directly.

**TypeScript SDK:** <https://github.com/SynFutures/ts-sdk>

### API

The Monday Trade API offers RESTful endpoints for accessing real-time market data, historical trades, protocol metrics, and account information, enabling seamless integration with external applications and dashboards.

**API Documentation:** <https://docs.monday.trade/perp-trading-apis>

Should you have any inquiries during the integration process, please don’t hesitate to contact the Monday Trade team via [Discord](https://discord.com/invite/mondaytrade).

<br>


# Perps Oracle Sources

**Monday Trade** has partnered with [**Stork**](https://www.stork.network/) to provide oracle services for the first perpetual pairs, ensuring reliable and secure price feeds from day one. Stork is a decentralized oracle network designed to offer secure, reliable, and timely price feeds. As a leading provider in the oracles space with performant oracle and data infrastructure for onchain developers, Stork enables Monday Trade's perps to leverage Monad's latency unlocks.

Stork supplies the initial price feeds used for the initial perp deployments, with contract addresses for new markets added once they go live.

#### Stork Market Contracts

<table><thead><tr><th width="221.32421875">Field</th><th>Value</th></tr></thead><tbody><tr><td>beacon</td><td>0xcfb79469BDe45D6560f1D16965AB3b3895a85C5d</td></tr><tr><td>market</td><td>0x6E77d8eF45F572CE59b0D9b95Be5f12a5906bA65</td></tr></tbody></table>

#### **Stork Feeder Factory Contracts**

<table><thead><tr><th width="222.734375">Field</th><th>Value</th></tr></thead><tbody><tr><td>beacon</td><td>0xe6ED06331b0F81AC3FeD17A5963f723E53a35d9c</td></tr><tr><td>factory</td><td>0x6fDb78862C00F88930e4d758236907d39643aA75</td></tr></tbody></table>

#### **Stork Feeder Sources Contracts**

**BTCUSDC**

<table><thead><tr><th width="224.84375">Field</th><th>Value</th></tr></thead><tbody><tr><td>baseSymbol</td><td>BTC</td></tr><tr><td>quoteSymbol</td><td>USDC</td></tr><tr><td>Aggregator 0</td><td>0x52D0d18014689FA4Fdb062C11afD391D139011d5</td></tr><tr><td>Aggregator 1</td><td>0xD77286d433068Cd36fBD93FC45E6Dd36735cd09c</td></tr></tbody></table>

**ETHUSDC**

<table><thead><tr><th width="224.84375">Field</th><th>Value</th></tr></thead><tbody><tr><td>baseSymbol</td><td>ETH</td></tr><tr><td>quoteSymbol</td><td>USDC</td></tr><tr><td>Aggregator 0</td><td>0x67EBCDefd503fBBd8F014AfbD9f35D9c05e109b2</td></tr><tr><td>Aggregator 1</td><td>0xD77286d433068Cd36fBD93FC45E6Dd36735cd09c</td></tr></tbody></table>

**MONUSDC**

<table><thead><tr><th width="224.84375">Field</th><th>Value</th></tr></thead><tbody><tr><td>baseSymbol</td><td>MON</td></tr><tr><td>quoteSymbol</td><td>USDC</td></tr><tr><td>Aggregator 0</td><td>0x352C453501067FdD4b0Ae0789f7dB88cBD3897B4</td></tr><tr><td>Aggregator 1</td><td>0xD77286d433068Cd36fBD93FC45E6Dd36735cd09c</td></tr></tbody></table>


# How to Provide Liquidity

Providing liquidity on Monday Trade Perps allows you to contribute to trading pair liquidity pools, earn fees, and support the Monad ecosystem. This step-by-step guide explains how to add liquidity to a pool on Monday Trade Perps.

### Steps to Add Liquidity:

{% stepper %}
{% step %}
**Select an Asset Pool**

In the search bar on the dapp, select the asset pool you want to provide liquidity (e.g. BTC/USDC).
{% endstep %}

{% step %}
**Access the Liquidity Panel**

On the right-hand side of the page, click the "**Liquidity**" panel to open the liquidity management interface for the selected pool.
{% endstep %}

{% step %}
**Set Your Price Range**

Choose the price range for your liquidity position. You can drag the upper and lower boundary lines on the price range graph to adjust the range visually.

<div align="left"><figure><img src="/files/2MGD0KukqIGCWwjo3e3g" alt="" width="343"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
**Enter Deposit Amount (USDC)**

Input the amount of USDC you wish to deposit.&#x20;
{% endstep %}

{% step %}
**Review and Confirm Transaction**

Review the liquidity details, including the token amounts, price range, removal price, and liquidation price. Once satisfied, click "Confirm" and approve the transaction in your wallet. Wait for the transaction to be confirmed on the Monad network.
{% endstep %}

{% step %}
Once confirmed, your liquidity position will appear in the "Liquidity" section at the bottom of the dapp. Earned fee will be added to the Value Locked automatically.
{% endstep %}
{% endstepper %}

{% hint style="info" %}
When you remove the liquidity you provided, it is automatically converted into a net position. In order to retrieve the margin, it is advisable to close the position in trade immediately after the liquidity removal.
{% endhint %}


# Perps Audit Reports

Monday Trade Perps is powered by SynFutures' white-label DEX infrastructure. The Quantstamp audit reports for these core contracts, which underpin our protocol's security, are provided below:

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

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


# Integration Instructions

To integrate with Monday Trade Spot, please refer to [this document](https://mondaytrade.notion.site/Monday-Trade-Spot-Integration-Instructions-EN-2ae48d36614f8167bb6fdccc1859345d) for comprehensive information.


# Risks & Security

Monday Trade runs on smart contracts: automated code onchain that enables trading without intermediaries. While audited and tested, all smart contracts carry risk.

Bugs, exploits, or issues in third-party integrations could lead to loss of funds. By using Monday Trade, you acknowledge that:

* You are responsible for your own onchain activity
* Blockchain transactions are irreversible
* No system is immune to failure or attack

Always use trusted wallets and follow good security practices.


# FAQs


# General

#### <mark style="color:$primary;">**Which wallets are supported?**</mark>

You can connect with popular wallets like MetaMask, WalletConnect, Rabby, Phantom, Backpack, HaHa Wallet, or OKX Wallet.

#### <mark style="color:$primary;">Do I need to KYC?</mark>

No. Monday Trade is fully non-custodial and permissionless—no KYC needed.

#### <mark style="color:$primary;">Can I trade or LP on mobile?</mark>

Yes, as long as your mobile wallet supports dApp browsing (like Rabby Mobile, Phantom, or OKX wallet)

#### <mark style="color:$primary;">What do the "Verified Token" and "Pool with Verified Tokens" badges mean?</mark>

These badges are designed to help you quickly identify tokens and pools, reducing the chance of errors during trading.

* **Verified Token:** This badge is applied to a token that has been reviewed by our team and meets specific technical criteria (e.g., it has a verified contract). You will see a checkmark badge next to the token's name.
* **Pool with Verified Tokens:** This badge is applied to a pool where **both** tokens in the pair are verified. This pool will also display a checkmark badge.

**Important Disclaimer:** The "verified" badge **only** indicates that our interface correctly recognizes and displays the token's information. It is **not** an endorsement or guarantee of the token's value, the project's legitimacy, or its financial potential. You are always responsible for conducting your own research before making any trades.


# Trading

#### [**What do I need to start trading on Monday Trade?**](/introduction/how-to-start-trading-on-monday-trade/connect-your-wallet-to-monday-trade)

Just a supported crypto wallet, some assets (like ETH or USDC), and gas tokens (for Monad network). No sign-ups or emails required.

#### [How do I place a trade?](/spot-trading/how-to-trade-spot-on-monday-trade)

1. Connect your wallet.
2. Select the token you want to swap and the one you want to receive.
3. Enter the amount and confirm the transaction.
4. Approve the token (if it’s your first time) and submit the swap.

#### [What assets can I trade?](/spot-trading/spot-contract-pair-specifications)

You can trade any tokens supported by Monday Trade.&#x20;

#### <mark style="color:$primary;">How can I avoid high slippage and price impact?</mark>

To trade safely, especially in low-liquidity pools, follow these tips:

1. **Check Pool Liquidity Before Trading**:
   * Avoid large trades in pools with low liquidity, as they lead to high price impact.
2. **Use Limit Orders**:
   * Instead of market orders, place **limit orders** at your desired price. These execute only if the price matches, avoiding surprises.
3. **Set Realistic Slippage Tolerance**:
   * For low-liquidity pools, consider a higher slippage tolerance (e.g., 1-3%) to ensure your trade executes, but be aware of potential losses.
   * Monday Trade will warn you if your trade’s price impact exceeds 3% — pay attention to these alerts!
4. **Break Up Large Trades**:
   * Instead of one large trade, split it into smaller trades over time to reduce price impact per trade.


# Liquidity Provision

#### <mark style="color:$primary;">What happens when my spot liquidity goes out of range?</mark>

When your liquidity position goes out of range (i.e., the current market price of the trading pair moves outside your set price range), your position will no longer earn trading fees. This is because fees are only generated when trades occur within your set price range.

Additionally, the tokens in your liquidity position will consist of only one of the two tokens in the pair, depending on the direction of the price movement:

#### <mark style="color:$primary;">What can I do if my spot liquidity is out of range?</mark>

* Monitor: Check the "Liquidity" tab in the Liquidity panel to confirm your position’s status and token composition.
* Adjust: To resume earning fees, you can remove your current position and add liquidity again with a new price range that includes the current market price. Follow the steps in our[ How to Provide Liquidity](/perps-trading/how-to-provide-liquidity) guide.
* Wait: If you believe the market price may return to your range, you can leave the position as is, and it will start earning fees again when the price re-enters your range.

#### <mark style="color:$primary;">What is impermanent loss, and how does it affect my liquidity position?</mark>

Impermanent loss (IL) is a potential risk for liquidity providers in AMM-based pools on Monday Trade. It occurs when the relative prices of the tokens in a liquidity pool (e.g., MON and WETH) change after you deposit them, potentially resulting in a lower position value compared to holding the tokens outside the pool. For a detailed explanation, including why IL happens, its impermanent nature, and how it applies to Monday Trade’s AMM pools, refer to our [Understanding Impermanent Loss](/spot-trading/how-to-provide-liquidity-on-monday-trade/understanding-impermanent-loss) section.

#### <mark style="color:$primary;">Why can’t I create a pool with my selected fee tier?</mark>

If you’re unable to create a pool, it’s likely because a pool with the selected fee tier already exists for the chosen trading pair. Monday Trade allows only one pool per trading pair and fee tier. Instead of creating a new pool, you can add liquidity to the existing pool.&#x20;

#### <mark style="color:$primary;">Why can’t I create a pool with MON/WMON?</mark>

Instead of creating a pool with MON/WMON, you can wrap MON into WMON or unwrap WMON back to MON. On the spot trading interface for a MON pair, locate the balance of MON and click the wrap/unwrap icon next to it. Follow the prompts to convert your tokens, then proceed with adding liquidity or trading as needed.&#x20;

#### <mark style="color:$primary;">Where can I find the liquidity pool I created?</mark>

After creating a liquidity pool on Monday Trade, you can locate it in the following places:

* Pool List: Go to the "Pool" page to view the pool you created in the list of available pools.
* Pool > My Liquidity: Visit the "Pool" page and check the "My Liquidity" section to see your added liquidity to the new pool and its details.

Portfolio > Liquidity Tab: Navigate to the "Portfolio" section, select the "Liquidity" tab, and find your added liquidity to the new pool under the "Liquidity" tab to view details and manage your position. For more information on managing your liquidity, refer to our How to Manage LP Positions guide.


# Glossary

A quick reference for key trading and DeFi terms

## General Trading Terms

### Bid / Ask

* The bid is the highest price a buyer is willing to pay for an asset.
* The ask is the lowest price a seller is willing to accept.
* The difference between the two is the spread, which reflects market liquidity.

### Spread

* The gap between the bid and ask price.
* Tight spreads typically mean better liquidity and less slippage. Wider spreads can result in more expensive trades.

### Limit Order / Market Order

* A market order executes instantly at the best available price.
* A limit order lets you set the price you want to buy or sell at—but it may not fill if the market doesn’t hit your price.

***

## DeFi & Onchain Terms&#x20;

### AMM (Automated Market Maker)

* A smart contract-based system that allows users to swap tokens without relying on order books.
* Trades are executed against liquidity pools instead of individual buyers/sellers.

### LP (Liquidity Provider)

* A user who deposits tokens into an AMM pool to enable swaps.
* LPs earn a portion of the swap fees based on how much liquidity they contribute.

### Smart Contract

* Code deployed on-chain that runs automatically under specific conditions.
* Monday Trade uses smart contracts to handle swaps, liquidity provision, and more without intermediaries.

### Gas

* A small fee paid to execute transactions on the blockchain.
* On Monad, gas fees are lower and execution is faster than on Ethereum.

### Slippage

* The difference between the expected price of a trade and the price it actually executes at.
* More common in volatile markets or low-liquidity tokens.

### Price Impact

* The change in an asset’s price caused by your trade consuming available liquidity.
* Price impact is a key part of slippage.

### Wallet (e.g. Rabby)

* A browser extension or mobile app used to interact with DeFi protocols.
* Rabby, Phantom, and other wallets let you sign transactions, swap tokens, and manage funds on Monday Trade.


# Voyage Point Program

#### **Overview**

The Voyage Point Program is a 32-week campaign designed to reward users for providing deep, passive liquidity and trading on Monday Trade. A fixed pool of **2,000,000** **Voyage Points** is distributed each week, with each epoch running from Monday 00:00 UTC to Sunday 23:59 UTC.

***

#### **What are Voyage Points?**

Voyage Points are the measurement unit for your contribution to the Monday Trade ecosystem. Points are earned through a variety of trading and liquidity provision activities on Spot markets and holding RWA tokens. Your Voyage Points are calculated pro-rata based on your contribution to the total points pool each week.

**Note:**

* The total Voyage Points distributed each week is fixed at 2,000,000.
* Specific formulas and multipliers are proprietary and subject to adjustment.
* All point calculations are designed to ensure fair and balanced rewards.

***

#### Voyage Points Calculation Framework

Your Voyage Points are calculated using this multi-factor model:

1. **Trading & Liquidity Provision in Spot**&#x20;

   Earn points through three primary actions:

   * **Limit Orders (Maker):** Earn points when your spot limit orders are filled.
   * **Liquidity Provision:** Supply to Spot AMM pools to earn points from accumulated fees.
   * **Market Orders (Taker):** Execute spot market orders to accumulate points.
   * **Market Multipliers:** Selected markets offer boosted point earnings. (See details below)
2. **Holding RWA Tokens**\
   Earn points by holding RWA stock tokens in your Monday Trade account. The more you hold and the longer you hold, the more points you earn. Note: only tokens held in your Monday Trade account are eligible — tokens withdrawn to your wallet or added as spot AMM liquidity are not counted.
3. **Consistency**&#x20;

   Trade or provide liquidity or hold RWA tokens for 7 consecutive days in a week to activate a bonus on your total points. Any of these activities count:

   * Any filled spot order (limit or market)
   * Adding liquidity (LP)
   * Holding RWA tokens in your Monday Trade account
4. **Referral**\
   Earn 20% of the Voyage Points generated by users you directly refer to Monday Trade.\
   Example: If a user you refer earns 1,000 Voyage Points from their activities in a week, you will receive 200 Voyage Points as your referral reward.

***

#### Terms & Conditions

* The Voyage Point Program is open to users who complete registration. Participants in our dedicated Market Maker Program are ineligible.&#x20;
* The Voyage Point Program duration is tentatively set for 24 weeks, subject to change at Monday Trade's discretion.
* The weekly distribution of Voyage Points is capped. Your weekly Voyage Point is proportional to your contribution to the total points pool.
* All formulas and coefficients are proprietary and subject to change without notice.
* Only genuine trading and liquidity activities qualify; wash trading, market manipulation, and bulk-account registrations will be disqualified.
* Participants must comply with Monday Trade's Terms of Service.
* Monday Trade reserves the right to cancel, amend, or pause the program at any time.
* Monday Trade maintains final interpretation rights of these rules.

**Risk Warning:** Cryptocurrency trading involves substantial risk. All activities are undertaken at your own discretion. This information does not constitute financial advice. Monday Trade is not liable for any trading losses.


# FAQ

<details>

<summary>What is the Voyage Point Program?</summary>

The Voyage Point Program is a campaign designed to reward users for trading and providing liquidity on Monday Trade.

</details>

<details>

<summary>How are my weekly Voyage Points calculated?</summary>

A fixed pool of 2,000,000 Voyage Points is distributed each week. Your share is calculated pro-rata based on your contribution to the total points earned by all users during the weekly epoch, which concludes Monday at 00:00 UTC.

Points are allocated across the following categories:

• RWA Holding: Rewards for holding RWA tokens in your Monday Trade account\
• Spot Markets: Includes market orders, AMM LP, and limit orders (filled)\
• Consistency Bonus: Bonus for maintaining eligible activity for 7 consecutive days

Your Total Voyage Points:

Your Total Points = RWA Holding Points + Spot Points + Consistency Points

For example: If your contribution represents 0.01% of all users' total contributions for the week, you will receive 0.01% of the total point pool.

</details>

<details>

<summary>What activities earn points?</summary>

You earn points by contributing to the Monday Trade ecosystem through several key actions:

**Spot Trading**\
• Market Orders: Execute market orders on Spot markets. Rewards based on trading volume × market multiplier.\
• Limit Orders (Filled): Execute limit orders on Spot markets. Rewards based on filled volume × market multiplier.

**Liquidity Provision**\
Supply liquidity to Spot AMM pools.

**Holding RWA Tokens**\
Hold RWA tokens (e.g., aNVDA, aAAPL, aTSLA) in your Monday Trade account. Only tokens held in your account are eligible — tokens withdrawn to your wallet or added as spot AMM liquidity are not counted.

**Referring Users**\
Invite new users to the platform to earn 20% of their referral points.

Pro Tip: Maximize your earnings by maintaining consistent trading, holding RWA tokens, or providing spot liquidity throughout the week to unlock the consistency bonus.

</details>

<details>

<summary>How does RWA Holding Points work?</summary>

Hold RWA stock tokens in your Monday Trade account to earn Voyage points. The more you hold and the longer you hold, the more points you earn. Note: only tokens held in your Monday Trade account are eligible — tokens withdrawn to your wallet or added as spot liquidity are not counted.

</details>

<details>

<summary>What is the "Consistency" bonus?</summary>

The Consistency Bonus rewards sustained participation, distributed among users who maintain activity for 7 consecutive days.

Qualifying Activities (any one per day counts):

• Any filled spot order (limit or market)\
• Adding liquidity to spot AMM pools\
• Holding RWA tokens in your Monday Trade account (Note: tokens withdrawn to your wallet or added as spot liquidity are not counted.)

</details>

<details>

<summary>What is the "Market Multiplier"?</summary>

To encourage deep liquidity and active trading, your activities on selected markets will earn points at a boosted rate. Market multipliers are applied to all activity categories.

</details>

<details>

<summary>How does the Referral Bonus work?</summary>

You will earn 20% of the Voyage Points that your directly invited referrals generate from their activities. For more details on how to refer friends, please visit the [referral page](https://app.monday.trade/#/referral).

</details>

<details>

<summary>How often do my Voyage Points update?</summary>

Your Voyage Points are calculated and finalised weekly, distributed after each epoch concludes on Monday at 00:00 UTC.\
For live tracking, you can view your estimated share of the current week's point pool, which updates daily at 00:00 UTC. Please note this is an estimated calculation that fluctuates with ongoing activity and does not represent your final distribution.

\
Update Schedule:

* **Daily (00:00 UTC)**: Estimated shares recalculated for all categories, including resting orders
* **Epoch End (Monday 00:00 UTC)**: Final contributions calculated, points distributed, leaderboard updated

</details>

<details>

<summary>How long will the Voyage Point Program last?</summary>

The Voyage Point Program is planned to run for 32 weeks, with points distributed on a weekly basis. Monday Trade reserves the right to adjust the program duration if necessary.

</details>

<details>

<summary>Who is eligible for the Voyage Point Program?</summary>

The program is open to all users. However, market makers enrolled in our dedicated Market Maker Program are not eligible to earn points.

Monday Trade reserves the right to disqualify any accounts or trades identified as fraudulent, including wash trading, market manipulation, or bulk-account registrations used to farm points.

</details>

<details>

<summary>What's changing during the perp sunset period?</summary>

Perp markets are temporarily winding down as we transition to RWA-focused products. From May 4, 2026 (epoch 24), the weekly Voyage Points pool of 2,000,000 is distributed across RWA Holding, Spot Markets, and Consistency Bonus. Perp earning categories and OI Rewards are paused during this period. Your existing points remain unchanged. [Learn more](https://monday.trade/post/perp-markets-are-transitioning).

</details>


# MONDAY MOONSHOT CHALLENGE

Welcome to the Monday Moonshot Challenge! Trade and provide liquidity to earn MON rewards across three exciting prize pools: Trade & Spin Run, Moonshot Ladder Race - Top Traders, and Moonshot Ladder Race - Top LPs. Read on to learn how to join and maximize your rewards!

***

### Overview

**Duration**: Runs for 4 weekly cycles, starting 18 August at 08:00 UTC, resetting every Monday at 00:00 UTC.

**Eligibility**: Connect your X account on the campaign page to participate (mandatory).

**Total Rewards**: 50,000 MON across all pools.

**Reward Claim**: Claim rewards weekly after Monday at 00:00 UTC.

**Fair Play**:

* Manipulation (e.g. wash trading, Sybil attacks) leads to disqualification.
* Monday Trade reserves the right to verify and audit participant activity.

**Questions**? Please reach out on Discord if you have any questions.

***

### Trade & Spin Run

Earn daily spins by trading to win MON rewards and boost your earnings with a weekly streak!

#### How to Participate:

* Make at least one trade (any volume) on ANY pair on Monday Trade each day to unlock a spin.
* Each day starts at 00:00 UTC.
* Spins are valid only for the current week and expire after next Monday at 00:00 UTC.

#### Rewards:

* Each spin awards a random amount of MON.
* Trade for 7 consecutive days in a week to earn a 2x multiplier on your total weekly spin rewards (e.g., 5 MON becomes 10 MON).
* Missing a day resets the multiplier to 1x for that week.

***

### Moonshot Ladder Race

Climb the leaderboards by trading or providing liquidity on ELIGIBLE pairs to win weekly MON rewards!

#### 1. Top Traders

#### How to Participate:

* Trade on pairs containing MON, WMON, USDC, or USDT, either as the base or quote token (e.g., MON/USDC, WBTC/USDC, MON/WETH).

{% hint style="info" %}
Trading volume generated from market orders will be counted.
{% endhint %}

#### Ranking:

* Top 10 traders ranked by total trading volume (in MON equivalent) for the week.
* Leaderboard updates every 15 minutes.

#### Rewards (Weekly pool: 5,000 MON):

* 1st: 1,500 MON
* 2nd: 800 MON
* 3rd: 600 MON
* 4th–10th: 300 MON each

#### 2. Top LPs

#### How to Participate:

* Provide liquidity to pools with pairs containing MON, WMON, USDC, or USDT (e.g., MON/USDC, WBTC/USDC, MON/WETH).

#### Ranking:

* Top 10 liquidity providers ranked by accumulated fees (in MON equivalent) from LP activity during the week.
* Leaderboard updates every 15 minutes.

#### Rewards (Weekly pool: 2,500 MON):

* 1st: 500 MON
* 2nd: 350 MON
* 3rd: 250 MON
* 4th–10th: 200 MON each


# Terms of Service

Welcome to <https://monday.trade>, a website-hosted user interface (the “Site”) provided by Monday Trade (”we,” ”our,” or ”us”).  The Site provides access to a blockchain protocol that allows users to trade certain digital assets (the “Monday Trade” or “Protocol”).  The Site provides access to the Protocol and assists users in interacting with the Protocol, but is distinct from the Protocol itself.  We do not provide, manage, or control the Protocol itself.  The Site is one, but not the exclusive, means of accessing the Protocol.

This Terms of Service Agreement (the “Agreement”) explains the terms and conditions by which you may access and use the Site. You must read this Agreement carefully. By accessing or using the Site, you acknowledge that you have read, understand, and agree to be bound by this Agreement in its entirety. If you do not agree, you are not authorized to access or use the Site and must not use the Site.

Please read this Agreement carefully as it governs your use of the Site. The Agreement contains important information, including a binding arbitration provision and a class action waiver, both of which impact your rights as to how disputes are resolved. You should only access the Site if you agree completely with the Agreement

This Agreement may be amended, changed, or updated by us at any time and without prior notice to you. You should check back often on the Site to confirm that your copy and understanding of this Agreement is current and correct. Your non-termination or continued access or use of the Site or any Services after the effective date of any amendments, changes, or updates constitutes your acceptance of the Agreement, as modified by such amendments, changes, or updates.

The access or use of the Site and any of the Services is void where such access or use is prohibited by, would constitute a violation of, or would be subject to penalties under applicable Laws, and shall not be the basis for the assertion or recognition of any interest, right, remedy, power, or privilege.

#### 1. Definitions:

In these Terms of Service and all documents incorporated herein by reference, the following words have the following meanings unless otherwise indicated:

“Affiliate” means, in relation to SynFutures, a direct or indirect subsidiary of SynFutures, a direct or indirect parent of SynFutures, and any other entities owned by a direct or indirect parent of SynFutures.

“AML” means anti-money laundering, including all applicable Laws prohibiting money laundering or any acts or attempted acts to conceal or disguise the identity or origin of; change the form of; or move, transfer, or transport, illicit proceeds, property, funds, fiat currency, or Digital Tokens.

“Anti-Corruption” means all applicable Laws prohibiting corruption or bribery of government officials of any kind, including kickbacks, inducements, and any other forms of corruption or bribery.

“CFT” means countering the financing of terrorism.

“Digital Tokens” means a digital representation of value that functions as (i) a medium of exchange; (ii) a store of value, and/or (iii) other similar digital representations of rights or assets, which is neither issued nor guaranteed by any country or jurisdiction and does not have legal tender status in any country or jurisdiction.

“Digital Tokens Wallet” means a third party software application (or other mechanism) that provides a means for holding, storing, and transferring Digital Tokens. We do not provide users with Digital Tokens Wallets and users must obtain a Digital Tokens Wallet from a third party provider when accessing the Protocol through the Site.

“Government” means any national, federal, state, municipal, local, or foreign branch of government, including any department, agency, subdivision, bureau, commission, court, tribunal, arbitral body, or other governmental, government appointed, or quasi-governmental authority or component exercising executive, legislative, juridical, regulatory, or administrative powers, authority, or functions of or pertaining to a government instrumentality, including any parasternal company, or state-owned (majority or greater) or controlled business enterprise;

“Government Official” means an officer or employee of any Government, a director, officer, or employee of any instrumentality of any Government, a candidate for public office, a political party or political party official, an officer or employee of a public international organization, and any Person who is acting in an official capacity for any of the foregoing, even if such Person is acting in that capacity temporarily and without compensation;

“Laws” means all laws, statutes, orders, regulations, rules, treaties, and/or official obligations or requirements enacted, promulgated, issued, ratified, enforced, or administered by any Government that apply to you, to us, or to the Site.

“Person” includes an individual, association, partnership, corporation, company, other body corporate, trust, estate, and any form of organization, group, or entity (whether or not having separate legal personality).

“Prohibited Person” means the Government of Venezuela; any citizen or resident of, entity organized within, or Government or Government Official of, any Prohibited Jurisdiction; and any Sanctioned Person.

“Sanctions List” means the “Specially Designated Nationals and Blocked Persons” (“SDN”) List and the Non-SDN Lists, including the “Sectoral Sanctions Identifications List,” published by the U.S. Department of the Treasury’s Office of Foreign Assets Control (“OFAC”); the Section 311 Special Measures for Jurisdictions, Financial Institutions, or International Transactions of Primary Money Laundering Concern published by the U.S. Department of the Treasury’s Financial Crimes Enforcement Network (“FinCEN”); and, any other foreign terrorist organization or other sanctioned, restricted, or debarred party list published under Economic Sanctions, AML, or CFT Laws of or by Governments of the United States, European Union, United Kingdom, or the United Nations.

“Sanctioned Person” refers to any Person that is: (i) specifically listed in any Sanctions List; (ii) directly or indirectly owned 50 percent or more by any Person or group of Persons in the aggregate listed in any Sanctions List, (iii) Government or Government Official of any Prohibited Jurisdiction; or (iv) that is otherwise sanctioned, restricted, or penalized under applicable economic sanctions, AML, or CFT Laws.

“Services” means any and all services provided on or through the Site, including, but not limited to, assistance in accessing and using the Protocol.

#### 2. Right to Use the Site:

If you (i) are not a Prohibited Person, (ii) do not operate for the benefit of a Prohibited Person and (iii) otherwise fully comply with this Agreement, we grant you the limited right to use the Services.  The right to use the Services is a personal, restricted, non-exclusive, non-transferable, non-sublicensable, revocable, limited license, and it is subject to the limitations and obligations in this Agreement. Nothing in this Agreement gives you any license (other than as set out in this paragraph), right, title, or ownership of, in, or to the Site, any of the Services, the Copyrights, or the Marks. We may suspend or terminate the provision of Services to you at our sole discretion, as required by applicable Laws, where we determine that you have violated, breached, or acted inconsistent with any of this Agreement, or exposed us or any of our Affiliates to any liability under any applicable Laws.

Every Prohibited Person is strictly prohibited from using the Services or the Site.  No Account may be operated for the financial or other benefit of a Prohibited Person.

Every prohibited Person is strictly prohibited from directly or indirectly using the Services or the Site, and no one may use the Services or the Site for the financial or other benefit of a Prohibited Person.

#### 3. Proprietary Rights

The trademarks, service marks, and trade names, including both word marks and design marks (the “Mark(s)”) are used by us and our Affiliates under license. You agree not to appropriate, copy, display, reverse engineer, or use the Marks or other content without express, prior, written permission from us or the owner of the Marks, including as a domain name, as social media profile/handle, on a website, in an advertisement or other marketing, as or in connection with a phone number, as or in connection with an email address, in Internet search results, in meta data or code, or in any other manner.

Unless otherwise indicated, all materials on the Site are used by us under license (“Copyrights”). You agree not to appropriate, copy, display, or use the Copyrights or other content without express, prior, written permission from us or the third-party owner.

You may link to the Site’s homepage or other pages, provided you do so in a way that is fair and legal and does not damage our reputation or take advantage of it, but you must not establish a link in such a way as to suggest any form of association, approval, or endorsement on our part without prior, express, written consent.

The Site may provide certain social media features that enable you to link, send communications, or display certain content from the Site. You may use these features solely as they are provided by us. You may not establish a link from any website that is not owned by you, cause the Site or portions of it to be displayed on or by any other site (for example, by framing, deep linking, or in-line linking), or otherwise take any action with respect to the materials on the Site that is inconsistent with any other provision of this Agreement.

The Site and Services are protected by copyright, trademark, trade secret, and other intellectual property or proprietary rights laws in various jurisdictions. All rights not expressly granted to you in this Agreement are reserved by us or our licensor(s). Except as expressly authorized by us, you will not (i) license, sublicense, rent, sell, resell, transfer, assign, distribute, or otherwise commercially exploit or make available to any Person all or any part of the Site or Services in any way; (ii) copy, modify, republish, distribute, or make derivative works based upon all or any part of Site or Services; (iii) “frame” or “mirror” all or any part of the Site or Services on any other server or wireless or Internet-based device; or (iv) reverse engineer or access all or any part of Site or its Services in order to (a) build a competitive product or service, (b) build a product or service using similar ideas, features, functions, or graphics of all or any part of the Site or Services, or (c) copy any ideas, features, functions, or graphics of all or any part of the Site or Services.

#### **4. Additional Rights**

We reserve the following rights, which do not constitute obligations of ours: (a) with or without notice to you, to modify, substitute, eliminate or add to the Site; (b) to review, modify, filter, disable, delete and remove any and all content and information from the Site; and (c) to the extent permitted by law, to cooperate with any law enforcement, court or government investigation or order, or third party requesting or directing that we disclose information or content or information that you provide.

#### **5. Prohibited Uses**

You may not:

* use the Site or any Services in order to disguise the origin or nature of illicit proceeds of, or to further, any breach of applicable Laws, or to transact or deal in, any contraband Digital Tokens or other funds or property of any kind derived from illegal activity;
* use the Site or any Services if any applicable Laws would prohibit, penalize, sanction, or otherwise expose us to liability for any Services furnished or offered to you under this Agreement;
* use the Site or any Services to interfere with or subvert the rights or obligations of us or the rights or obligations of any other user of the Site or the Protocol or any other Person;
* use the Site or any Services to engage in conduct that is detrimental to us or any other user of the Site or the Protocol or any other Person;
* falsify or materially omit any information or provide misleading or inaccurate information requested by us or any of our Affiliates at any time;
* post, submit, publish, display, or transmit any advertising or promotional material without the prior written consent of us or our Affiliates;
* engage in activity that violates any applicable law, rule, or regulation concerning the integrity of trading markets, including, but not limited to, the manipulative tactics such as spoofing and wash trading;
* engage in activity that seeks to interfere with or compromise the integrity, security, or proper functioning of any computer, server, network, personal device, or other information technology system, including (but not limited to) the deployment of viruses and denial of service attacks;
* engage in activity that violates any applicable law, rule, or regulation concerning the trading of securities or derivative;
* utilize the Site or any Services for the financial or other benefit of a Prohibited Person; or
* violate, promote, cause a violation of, or conspire or attempt to violate this Agreement or applicable Laws.

Any use as described in this section shall constitute a “Prohibited Use.” If we determine or suspect that you have engaged in any Prohibited Use, we may address such Prohibited Use through appropriate action as determined by us in our sole and absolute discretion. Such action may include making a report to any Government, law enforcement, or other authorities, without providing any notice to you about any such report, and suspending or terminating your access to the Site or any Services. In addition, should your actions or inaction result in loss being suffered by us or any of our Affiliates, you shall pay an amount to us or the Affiliate so as to render us or the Affiliate whole, including the amount of taxes or penalties that might be imposed on us or the Affiliate.

#### **6. Non-Custodial and No Fiduciary Duties**

The Site is a purely non-custodial application, meaning we do not control, hold, or otherwise have access to your Digital Tokens or the Digital Tokens Wallet you use when accessing the Services.  You must use a third-party Digital Tokens Wallet to use the Services and we have no control over the use or security of any such Digital Tokens Wallet.  You are solely responsible for the custody of the cryptographic private keys to the Digital Tokens Wallet(s) you hold. This Agreement is not intended to, and does not, create or impose any fiduciary duties on us. To the fullest extent permitted by law, you acknowledge and agree that we owe no fiduciary duties or liabilities to you or any other party, and that to the extent any such duties or liabilities may exist at law or in equity, those duties and liabilities are hereby irrevocably disclaimed, waived, and eliminated. You further agree that the only duties and obligations that we owe you are those set out expressly in this Agreement.

#### 7. Non-Solicitation; No Investment Advice

You agree and understand that all trades you submit through the Site are considered unsolicited, which means that you have not received any investment advice from us in connection with any trades, and that we do not conduct a suitability review of any trades you submit.

All information provided by the Site is for informational purposes only and should not be construed as investment advice. You should not take, or refrain from taking, any action based on any information contained in the Site. We do not make any investment recommendations to you or opine on the merits of any investment transaction or opportunity. You alone are responsible for determining whether any investment, investment strategy or related transaction is appropriate for you based on your personal investment objectives, financial circumstances, and risk tolerance.

#### 8. No Warranties

The Site is provided on an “AS IS” and “AS AVAILABLE” basis. To the fullest extent permitted by law, we disclaim any representations and warranties of any kind, whether express, implied, or statutory, including (but not limited to) the warranties of merchantability and fitness for a particular purpose. To the extent permitted by law, you acknowledge and agree that your use of the Site is at your own risk; we do not represent or warrant that access to the Site will be continuous, uninterrupted, timely, or secure; that the information contained in the Site will be accurate, reliable, complete, or current; or that the Site will be free from errors, defects, viruses, or other harmful elements. No advice, information, or statement that we make should be treated as creating any warranty concerning the Site. We do not endorse, guarantee, or assume responsibility for any advertisements, offers, or statements made by third parties concerning the Site.

#### 9. Assumption of Risk

There is no guarantee against losses when interacting with the Protocol through the Site.  You should not trade in Digital Tokens unless you understand the associated risks.  You should never trade more than you are willing to lose.

By accessing and using the Site, you represent that you are financially and technically sophisticated enough to understand the inherent risks associated with using cryptographic and blockchain-based systems, and that you have a working knowledge of the usage and intricacies of Digital Tokens. In particular, you understand that blockchain-based transactions are irreversible.

You further understand that the markets for these digital assets are highly volatile due to factors including (but not limited to) adoption, speculation, technology, security, and regulation. You acknowledge and accept that the cost and speed of transacting with cryptographic and blockchain-based systems are variable and may increase dramatically at any time. You further acknowledge and accept the risk that your digital assets may lose some or all of their value while they are supplied to the Protocol through the Site. You understand that anyone can create a token, including fake versions of existing tokens and tokens that falsely claim to represent projects, and acknowledge and accept the risk that you may mistakenly trade those or other tokens. You further acknowledge that we are not responsible for any of these variables or risks, do not manage or control the Protocol, and cannot be held liable for any resulting losses that you experience while accessing or using the Protocol through the Site. Accordingly, to the extent permitted by law, you understand and agree to assume full responsibility for all of the risks of accessing and using the Site to interact with the Protocol.

#### 10. Third-Party Resources and Promotions

The Site may contain references or links to third-party resources, including (but not limited to) information, materials, products, or services, that we do not own or control. In addition, third parties may offer promotions related to your access and use of the Site. We do not endorse or assume any responsibility for any such resources or promotions. If you access any such resources or participate in any such promotions, you do so at your own risk, and you understand that this Agreement does not apply to your dealings or relationships with any third parties. To the extent permitted by law, you relieve us of any and all liability arising from your use of any such resources or participation in any such promotions.

#### 11. Release of Claims

To the extent permitted by law, you expressly agree that you assume all risks in connection with your access and use of the Site and your interaction with the Protocol. To the extent permitted by law, you further expressly waive and release us from any and all liability, claims, causes of action, or damages arising from or in any way relating to your use of the Site and your interaction with the Protocol.

#### 12. Indemnity

You agree to hold harmless, release, defend, and indemnify us and our officers, directors, employees, contractors, agents, and Affiliates from and against all claims, damages, obligations, losses, liabilities, costs, and expenses arising from: (a) your access and use of the Site; (b) your violation of any term or condition of this Agreement, the right of any third party, or any other applicable law, rule, or regulation; and (c) any other party’s access and use of the Site with your assistance or using any device that you own or control.

#### 13. Limitation of Liability

Under no circumstances shall we or any of our officers, directors, employees, contractors, agents, or Affiliates be liable to you for any indirect, punitive, incidental, special, consequential, or exemplary damages, including (but not limited to) damages for loss of profits, goodwill, use, data, or other intangible property, arising out of or relating to any access or use of the Site, nor will we be responsible for any damage, loss, or injury resulting from hacking, tampering, or other unauthorized access or use of the Site or the information contained within it. We assume no liability or responsibility for any: (a) errors, mistakes, or inaccuracies of content; (b) personal injury or property damage, of any nature whatsoever, resulting from any access or use of the Site; (c) unauthorized access or use of any secure server or database in our control, or the use of any information or data stored therein; (d) interruption or cessation of function related to the Site; (e) bugs, viruses, trojan horses, or the like that may be transmitted to or through the Site; (f) errors or omissions in, or loss or damage incurred as a result of the use of, any content made available through the Site; and (g) the defamatory, offensive, or illegal conduct of any third party. Under no circumstances shall we or any of our officers, directors, employees, contractors, agents, affiliates, or subsidiaries be liable to you for any claims, proceedings, liabilities, obligations, damages, losses, or costs in an amount exceeding the amount you paid to us in exchange for access to and use of the Site, or 100 euros, whichever is greater. This limitation of liability applies regardless of whether the alleged liability is based on contract, tort, negligence, strict liability, or any other basis, and even if we have been advised of the possibility of such liability. Some jurisdictions do not allow the exclusion of certain warranties or the limitation or exclusion of certain liabilities and damages. Accordingly, some of the disclaimers and limitations set forth in this Agreement may not apply to you. This limitation of liability shall apply to the fullest extent permitted by law.

#### 14. Resolution of Disputes

We will use our best efforts to resolve any potential disputes through informal, good faith negotiations. If a potential dispute arises, you must contact us by sending an email to <information@monday.trade> so that we can attempt to resolve it without resorting to formal dispute resolution. If we aren’t able to reach an informal resolution within ninety days of your email, then you and we both agree to resolve the potential dispute according to the process set forth below.

All disputes arising out of or in connection with this Agreement, or any other acts or omissions for which you may contend that we are liable, including (but not limited to) any claim or controversy as to arbitrability, shall be finally settled under the Rules of Arbitration (“Rules”) of the International Chamber of Commerce by a single arbitrator appointed in accordance with said Rules. No award or procedural order made in the arbitration shall be published. You understand that you are required to resolve all Disputes by final arbitration. The arbitration shall occur in English and will be held in Singapore, unless you and we both agree to hold it elsewhere. Unless we agree otherwise, the arbitrator may not consolidate your claims with those of any other party.

If you are a consumer in the European Union, the foregoing shall be without prejudice to any applicable provisions of mandatory consumer protection law under the laws of your country of residence, to the extent that these offer you more protection in the European Union.

#### 15. Class Action and Jury Trial Waiver

You must bring any and all Disputes against us in your individual capacity and not as a plaintiff in or member of any purported class action, collective action, private attorney general action, or other representative proceeding. This provision applies to class arbitration. You and we both agree to waive the right to demand a trial by jury.

If you are a consumer in the European Union, the foregoing shall be without prejudice to any applicable provisions of mandatory consumer protection law under the laws of your country of residence, to the extent that these offer you more protection in the European Union.

#### 16. Governing Law

You agree that the laws of Singapore, without regard to principles of conflict of laws, govern this Agreement and any Dispute between you and us. You further agree that the Site shall be deemed to be based solely in Singapore, and that although the Site may be available in other jurisdictions, its availability does not give rise to general or specific personal jurisdiction in any forum outside Singapore.

If you are a consumer in the European Union, the foregoing shall be without prejudice to any applicable provisions of mandatory consumer protection law under the laws of your country of residence, to the extent that these offer you more protection in the European Union.

#### 17. Language and Contact details

The Agreement and any information or notifications that you or we are to provide shall be in English. If you have any questions relating to these Agreement, your rights and obligations arising from these Terms and/or your use of the Site or any other matter, please, contact <information@monday.trade>

#### 18. Entire Agreement

These terms constitute the entire agreement between you and us with respect to the subject matter hereof. This Agreement supersedes any and all prior or contemporaneous written and oral agreements, communications and other understandings (if any) relating to the subject matter of this Agreement.


# Privacy Policy

Last Updated: April 21, 2025<br>

This Privacy Policy ("Policy") applies to any websites, applications, or services provided, owned, or operated by Monday Trade ("Monday Trade", "we", "our", or "us") (collectively, the "Services"), as applicable, that link to this Privacy Policy.

While we are committed to minimizing data collection and maximizing user privacy, certain information will be collected to maintain functionality, provide analytics, and for regulatory compliance. We aim to be transparent about our practices and continually review and improve our measures to protect your privacy.

By visiting our websites, you accept the practices described in this Policy, to the extent permitted by law. Please read this Policy carefully to understand our practices regarding your information and how we handle it. If you do not agree with this Policy, do not use, access, connect to, interact, download, or otherwise engage with our Services.

We encourage users to review this Policy periodically, as changes may be made to reflect updates in our practices, technology, or legal requirements.

#### **1. Information We Collect**

When you access, use, interact with, or connect to our Services, we may obtain certain types of information necessary to provide these Services in a secure and effective manner. This information enables us to maintain functionality and ensure a safe user experience.

Monday Trade primarily interacts with publicly available blockchain data, including but not limited to: transaction data, wallet addresses, order information, trading activity, and smart contracts. This data is recorded on the blockchain and is viewable via a blockchain explorer, and is collected when you transact through our interface.

Additionally, when you access our website or use our Services, our hosting provider automatically collects technical information necessary for operation and security. This may include your IP address, geolocation data inferred from network connections, browser and device types, operating system version, connection data such as timestamps and session identifiers, and usage patterns, such as pages viewed, time spent, and user interactions.

We do not and will never collect or sell user data outside what is publicly available on the blockchain.

#### 2. Purpose and Legal Basis for Processing

The legal bases for processing information collected through our Services include consent where applicable, fulfilling contracts, compliance with legal obligations, legitimate interests of ensuring security and operational efficiency, and activities in the public interest.

We ensure that all data processing activities align with relevant data protection regulations and uphold your rights. Your privacy and the proper handling of your information is a top priority in every aspect of our operations.

#### **3. User Rights and Control**

Under applicable data protection laws, you have several rights regarding your personal data. These include the right to access the information we hold about you, correct any inaccuracies in your personal data, and request the deletion of your data under certain conditions. You may also have the right to object to or restrict specific processing activities, request data portability to receive your data in a structured format, and withdraw consent where processing is based on your consent.

To exercise these rights, please contact us at <information@monday.trade>. We will take reasonable measures to verify your identity before processing your request to protect your privacy and security. We are committed to honoring your rights and will respond to requests in accordance with applicable laws.

As a user of a decentralized exchange, you maintain significant control over your blockchain interactions. You can manage multiple wallet addresses to enhance privacy, review your transaction history via blockchain explorers, and decide how and when to engage with the exchange.

#### **4. Security Measures and Data Minimization**

Protecting your data is a top priority at Monday Trade. We implement a range of technical and organizational measures to ensure the security and integrity of the information processed through our Services.

Some of the key security methods we employ include:

* Our smart contracts adhere to industry best practices to prevent vulnerabilities and optimize functionality
* We use industry-standard security protocols, to protect our websites and applications against unauthorized access or breaches
* We constantly monitor our systems for unauthorized access or anomalies, and implement patches, bug fixes, and updates as necessary to provide the best security features
* While we strive to protect your data with the highest standards, no security system is completely foolproof. We continually review and enhance our security practices to address emerging threats.

#### 5. Data Retention

We retain your data only for as long as necessary to fulfill the purposes for which it was collected. This includes complying with legal obligations, resolving disputes, and enforcing our agreements.

The retention period may vary depending on the type of data and its intended purpose. Once your data is no longer needed, we securely delete it, unless legal obligations require us to retain it for longer periods.

This approach ensures that personal data is not unnecessarily retained, thereby reducing the risk of misuse or unauthorized access.

#### **6. Updates to this Policy and Contact Information**

We may update this Policy periodically to reflect changes in our practices, technology, or legal obligations. We will notify you of any significant changes by updating the "Last Updated" date at the top of this Policy and, when appropriate, by providing direct notice on our websites or through community channels.

Your continued use of our Services following any changes to this Policy constitutes your acceptance of the revised terms.

For questions or concerns regarding this Privacy Policy or our data practices, please contact us at <information@monday.trade>. We value your privacy and will address your inquiries promptly.


# RWA API

Documentation for integrators using the **MondayTrade** RWA API to build stock trading, cash movement, and portfolio services.

Authenticate with API key + HMAC on every request. Choose **self-submit on-chain** or **One Click delegated** execution for orders, cash operations, and stock operations.

Current mainnet deployments are on Base, Monad, and Ethereum. Use `x-api-p: MondayTrade` for the MondayTrade product unless your API key is explicitly provisioned for another product context.

## Base URL

Production:

```
https://mainnet-api.monday.trade/rwa/trading
```

All paths start with `/api/v1`. Example:

```
GET https://mainnet-api.monday.trade/rwa/trading/api/v1/symbols
```

For HMAC authentication, the `URI` uses `/api/v1/...` only — no domain or `/rwa/trading` prefix.

## Live reference

| Resource         | URL                                                                |
| ---------------- | ------------------------------------------------------------------ |
| OpenAPI snapshot | `reference/openapi.snapshot.json` (refreshed 2026-07-03 from test) |
| Live OpenAPI     | `https://mainnet-api.monday.trade/rwa/trading/api-docs`            |

## Reader path

| Step | Topic                                          | Doc                                                                                                                                           |
| ---- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| 1    | Product and contract mental model              | [getting-started/product-and-contracts.md](/rwa-trading-apis/getting-started/product-and-contracts)                                           |
| 2    | API integration playbook                       | [getting-started/trader-questions.md](/rwa-trading-apis/getting-started/trader-questions)                                                     |
| 3    | Setup and response format                      | [getting-started/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/getting-started/README.md) |
| 4    | API key and HMAC authentication                | [authenticate/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/authenticate/README.md)       |
| 5    | Holdings and positions                         | [portfolio/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/portfolio/README.md)             |
| 6    | Symbols, quotes, history                       | [market/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/market/README.md)                   |
| 7    | Market and limit orders                        | [trading/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/trading/README.md)                 |
| 8    | Cash deposits and withdrawals                  | [cash/](/rwa-trading-apis/cash-operations/cash)                                                                                               |
| 9    | Stock deposits and withdrawals                 | [stock/](/rwa-trading-apis/stock-operations/stock)                                                                                            |
| 10   | First API trade quickstart                     | [guides/quickstart-first-trade.md](/rwa-trading-apis/guides/quickstart-first-trade)                                                           |
| 11   | End-to-end flows                               | [guides/](/rwa-trading-apis/guides/guides)                                                                                                    |
| 12   | Demo code (Node.js + viem)                     | [guides/demo-code.md](/rwa-trading-apis/guides/demo-code)                                                                                     |
| 13   | Status, troubleshooting, and production checks | [reference/](/rwa-trading-apis/reference/reference)                                                                                           |

## Execution modes

| Mode        | Who signs on-chain         | Use when                                              |
| ----------- | -------------------------- | ----------------------------------------------------- |
| Self-submit | Your wallet or custodian   | You control private keys; call `/calldata` then `/tx` |
| One Click   | Server via delegated proxy | User signs EIP-712 once; call `/send` endpoints       |

See [guides/self-submit-on-chain.md](/rwa-trading-apis/guides/self-submit-on-chain) and [guides/one-click-flow.md](/rwa-trading-apis/guides/one-click-flow).

## Production Helpers

| Need                           | Doc                                                                                               |
| ------------------------------ | ------------------------------------------------------------------------------------------------- |
| Debug stuck requests or txs    | [reference/troubleshooting.md](/rwa-trading-apis/reference/troubleshooting)                       |
| Interpret lifecycle states     | [reference/status-model.md](/rwa-trading-apis/reference/status-model)                             |
| Map API endpoints to contracts | [reference/api-contract-map.md](/rwa-trading-apis/reference/api-contract-map)                     |
| Choose chain/product context   | [reference/environments-and-chains.md](/rwa-trading-apis/reference/environments-and-chains)       |
| Review sample responses        | [reference/sample-responses.md](/rwa-trading-apis/reference/sample-responses)                     |
| Test before production         | [reference/integration-test-checklist.md](/rwa-trading-apis/reference/integration-test-checklist) |


# Introduction

The RWA API is a RESTful API for MondayTrade tokenized stock trading. It covers market data, portfolio, orders, cash deposits and withdrawals, and optional One Click delegated execution.

## Capabilities

* **43 endpoints** across market data, portfolio, orders, cash, stock, and One Click
* **Market and limit orders** with self-submit or delegated execution
* **Deposits and withdrawals** of cash tokens
* **Portfolio** balances and stock positions
* **Multi-chain mainnet**: Base, Monad, and Ethereum
* **Testnets**: Monad Testnet and Base Sepolia
* **HMAC-SHA256** request authentication

## Audience

Partner developers integrating RWA trading APIs for order submission, cash operations, and portfolio reconciliation.

Read [product-and-contracts.md](/rwa-trading-apis/getting-started/product-and-contracts) first for the on-chain model (`StockRouter`, `Cashier`, `Stock`, settlement, portfolio balances). Then use [trader-questions.md](/rwa-trading-apis/getting-started/trader-questions) as the practical API integration playbook.

## Before you begin

Obtain an API key and secret, configure IP whitelist, and confirm `chainId + productType + access` scopes. See [authenticate/headers-and-permissions.md](/rwa-trading-apis/authentication/headers-and-permissions).

## Document version

* Doc version: 1.0
* Last updated: 2026-07-03
* Derived from `mondaytrade-gitbook` with OpenAPI cross-check


# Conventions

## Base URL

Production environment:

```
https://mainnet-api.monday.trade/rwa/trading
```

All API paths start with `/api/v1`:

```
GET /api/v1/symbols
```

Full production URL:

```
https://mainnet-api.monday.trade/rwa/trading/api/v1/symbols
```

> **HMAC authentication note:** For HMAC calculation, the `URI` only uses `/api/v1/symbols` — not the domain or `/rwa/trading` prefix.

## Unified response structure

All endpoints return:

| Field    | Type                  | Description                       |
| -------- | --------------------- | --------------------------------- |
| `code`   | number                | Business status. `200` = success. |
| `errMsg` | string                | Error message. Empty on success.  |
| `data`   | object / array / null | Payload.                          |
| `uuid`   | string / null         | Request UUID.                     |
| `t`      | number / null         | Server timestamp.                 |

Success example:

```json
{
  "code": 200,
  "errMsg": "",
  "data": {
    "symbol": "AAPL"
  },
  "uuid": null,
  "t": null
}
```

### Pagination

Paginated `data`:

| Field   | Type   | Description             |
| ------- | ------ | ----------------------- |
| `total` | number | Total matching records. |
| `rows`  | array  | Current page.           |

Parameters:

| Parameter | Default | Constraints                        |
| --------- | ------- | ---------------------------------- |
| `page`    | `1`     | Treated as `1` if < 1.             |
| `limit`   | `10`    | Treated as `10` if < 1; max `100`. |

## Error handling

Business errors use HTTP `400` with `code` and `errMsg` in the body.

| code    | errMsg                  | Common cause                                                  |
| ------- | ----------------------- | ------------------------------------------------------------- |
| `401`   | `Unauthorized`          | Invalid key, signature, nonce, timestamp, IP, or permissions. |
| `500`   | `Server internal error` | Validation failure, missing config, downstream error.         |
| `10000` | `Unsupported chainId`   | `x-api-chain-id` not supported.                               |
| `10001` | `Unsupported product`   | `x-api-p` not in public list.                                 |
| `10002` | `ChainId is missing`    | Missing chain ID header.                                      |
| `10003` | `Product Id is missing` | Missing product type header.                                  |


# RWA Product Overview

This page explains the contract and accounting model behind the RWA API. The API does not replace on-chain rules. It helps you **build `StockRouter` calldata**, **submit or delegate transactions**, and **track state** across wallet balances, `Cashier`, `Stock`, and asynchronous settlement.

If you are debugging a concrete trade, start with [trader-questions.md](/rwa-trading-apis/getting-started/trader-questions). This page explains the system design; the playbook turns it into request, execution, and reconciliation checks.

## Overall Design

The RWA API supports funding, market and limit orders, cash and stock movement between wallet and contracts, and portfolio state queries. It behaves like a trading account at the API layer, but accounting and permissions are enforced by on-chain contracts. The API prepares the right transactions and tracks asynchronous results after those transactions are mined.

The system is built from on-chain contracts plus backend processing. The contracts hold accounting state and enforce the transaction path. Backend processing connects that on-chain state to market execution, final settlement, status updates, and API indexing.

Core on-chain contracts:

| Contract         | Role                                                                                                                                                                        |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `StockRouter`    | Public entrypoint. It receives transactions, uses ERC-20 allowance as spender when wallet tokens are needed, and calls `Cashier` or `Stock` with the original user address. |
| `Cashier`        | Tracks `mUSD`. The API surfaces this as `mUsdBalance`. Deposits increase it; withdrawals deduct it.                                                                         |
| `Stock`          | Tracks stock order state and stock tokens credited to users as `Stock.stockBalance`, surfaced by the API as `exchangeBalance`. Plain sells spend this balance.              |
| `OneClickRouter` | Optional delegated execution router. It forwards approved One Click actions to `StockRouter` while preserving the original user address.                                    |

With these contracts, a user can:

| User need       | What the product supports                                                                                                        |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Fund account    | Convert approved USDC into `mUSD`.                                                                                               |
| Buy stock       | Use `mUSD`, or use `/orders/with-deposit/*` to deposit cash and buy in one transaction.                                          |
| Sell stock      | Sell from `exchangeBalance`, or use `/orders/with-deposit/*` to deposit approved wallet stock and sell in one transaction.       |
| Withdraw cash   | Convert `mUSD` back to USDC.                                                                                                     |
| Move stock      | Use `/stock/deposits/*` to deposit wallet stock into `Stock`, or `/stock/withdrawals/*` to withdraw `exchangeBalance` to wallet. |
| Track portfolio | Read wallet balances, `mUsdBalance`, `exchangeBalance`, orders, and cash operation status.                                       |

The API prepares `StockRouter` transactions and indexes the lifecycle after submission. A mined transaction is not always the final business state; orders, cash operations, and portfolio balances can update after backend processing and settlement.

## Core Accounting Concepts

### mUSD

`mUSD` is a 1:1 USD-backed accounting unit reflecting real-time purchasing power. It is a digital representation of credit exclusively for MondayTrade RWA trading. `mUSD` is not a cryptocurrency, stablecoin, or transferable virtual asset. In this API guide, treat `mUSD` as the accounting balance a user can use to buy RWA stock or request a withdrawal.

| Concept              | Where it lives   | What it means                                                                                                                                                                         |
| -------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mUSD`               | `Cashier`        | Used for buys and withdrawals. The API surfaces this as `mUsdBalance`.                                                                                                                |
| USDC wallet balance  | User wallet      | ERC-20 cash token. Must be deposited before it becomes `mUSD`.                                                                                                                        |
| Stock wallet balance | User wallet      | ERC-20 stock token held directly by the user. `StockRouter` can pull it only after user approval.                                                                                     |
| `Stock.stockBalance` | `Stock` contract | Accounting record for ERC-20 stock tokens held by `Stock` and credited to the user. The API surfaces this as `exchangeBalance`. Bought stock lands here; plain sells spend from here. |
| `walletAllowance`    | ERC-20 allowance | Whether `StockRouter` can pull a wallet token for a deposit or other token-pulling flow.                                                                                              |

Stock `walletBalance` and `exchangeBalance` are different. `walletBalance` is the ERC-20 stock token in the user's wallet. `exchangeBalance` is the API view of `Stock.stockBalance`, where stock is held by `Stock` and credited to the user. Plain sells spend `exchangeBalance`; wallet-held stock must be approved before `StockRouter` can pull it into `Stock` for selling.

### Deposit and Withdrawal Conversion

Cash movement is not just an on-chain token transfer. Deposited USDC ultimately needs to become USD usable for trading and settlement, and withdrawals need cash to come back before USDC can be paid out. That final cash path can take time.

To reduce API-visible waiting time, `Cashier` uses pre-funded buffers. When a buffer can safely cover the request, `Cashier` can apply the result immediately while final cash settlement catches up later.

Deposits convert wallet cash tokens into `mUSD`. The user first approves `StockRouter` as the cash token spender, then submits a deposit; `StockRouter` transfers the token to `Cashier`. If the deposit is instant, `Cashier` credits `mUSD` immediately. If it is queued, `mUSD` is credited after final cash settlement.

Withdrawals convert `mUSD` back into wallet cash tokens. The user requests a withdrawal through `StockRouter`, and `Cashier` deducts `mUSD`. If the withdrawal is instant, USDC is sent to the wallet immediately. If it is queued, USDC is sent after final cash settlement.

A mined transaction means the request reached the contracts. For queued operations, the final `mUSD` credit or USDC payout can happen later. See [cash/buffer-mechanism.md](/rwa-trading-apis/cash-operations/buffer-mechanism) for buffer rules.

## Buy and Sell Paths

* **Plain buy:** spends existing `mUSD`.
* **Order-with-deposit buy:** uses approved cash token allowance, requires instant deposit, credits `mUSD`, then places the buy in one transaction.
* **Plain sell:** spends existing `exchangeBalance`, the API view of `Stock.stockBalance`.
* **Order-with-deposit sell:** transfers approved wallet stock into `Stock`, then places the sell in one transaction.

Buy paths lock `mUSD` before execution. A plain buy uses existing `mUSD`; an order-with-deposit buy first transfers approved cash token to `Cashier` and credits `mUSD`, but only when instant deposit is available and the buffer can cover the conversion.

```mermaid
sequenceDiagram
    participant U as User
    participant R as Contract: StockRouter
    participant C as Contract: Cashier
    participant S as Contract: Stock
    participant B as Backend bots

    alt Plain buy
        U->>R: place buy order
        R->>C: Lock existing mUSD
    else Order-with-deposit buy
        U->>R: deposit cash and place buy
        R->>C: Transfer cash token and credit mUSD
        R->>C: Lock mUSD
    end

    B->>B: Execute order
    B->>C: Apply mUSD spend or refund
    B->>S: Credit bought stock
    U->>U: Query API for order and balances
```

Sell paths lock stock before execution. A plain sell uses existing `exchangeBalance`; an order-with-deposit sell first transfers approved wallet stock into `Stock` and credits it there.

```mermaid
sequenceDiagram
    participant U as User
    participant R as Contract: StockRouter
    participant S as Contract: Stock
    participant C as Contract: Cashier
    participant B as Backend bots

    alt Plain sell
        U->>R: place sell order
        R->>S: Lock exchangeBalance
    else Order-with-deposit sell
        U->>R: deposit wallet stock and place sell
        R->>S: Transfer wallet stock and credit stockBalance
        R->>S: Lock stockBalance
    end

    B->>B: Execute order
    B->>S: Return unfilled stock if needed
    B->>C: Credit mUSD proceeds
    U->>U: Query API for order and balances
```

Market buys specify maximum `mUSD` to spend; market sells specify stock quantity. Limit orders specify quantity, limit price, and `timeInForce`; current production contracts accept only `DAY`. Limit orders can remain open and can be canceled while open. `txHash` is available as soon as the transaction is broadcast. `orderId` is created by the on-chain placement transaction and becomes available after the transaction is mined and indexed.

Cash endpoints are only for cash-token flows into or out of `Cashier`. Use `/stock/deposits/*` and `/stock/withdrawals/*` for stock token movement.

Any router flow that pulls wallet tokens requires ERC-20 **approve** first. Cash deposits require approval for the cash token; stock deposits require approval for the stock token. See [cash/deposits.md](/rwa-trading-apis/cash-operations/deposits).

## Fees

Fees can appear in both cash operations and order results. Do not hardcode fee assumptions; read the returned fields from operation and order responses.

| Area            | Common fields                                          | Meaning                                                              |
| --------------- | ------------------------------------------------------ | -------------------------------------------------------------------- |
| Cash operations | `amount`, `creditAmount`, `feeAmount`                  | Token amount, resulting `mUSD`, and cash operation fee when present. |
| Order history   | `mintFee`, `protocolFee`, `settlePay`, `settleReceive` | Trading/mint/protocol fees and final fill amounts when present.      |

For deposits, the credited `mUsdBalance` may differ from the token amount if a fee applies. For orders, final received stock or cash depends on traditional-market execution: orders can fill at the executed price, partially fill, or receive no fill. Use settlement fields such as `settlePay`, `settleReceive`, `mintFee`, and `protocolFee` as the authoritative final amounts, not only the original order input.

## Contract stack (integrator view)

State-changing transactions go through **`StockRouter`**. When wallet tokens are needed, `StockRouter` uses the user's ERC-20 allowance as spender and transfers the tokens to `Cashier` or `Stock`; it does not custody deposits as the final destination.

```mermaid
flowchart TB
    User[User wallet]
    OCR[OneClickRouter optional]
    Router["StockRouter<br/>API calldata target"]

    Cashier["Cashier<br/>mUSD"]
    Stock["Stock<br/>orders and stockBalance"]

    User -->|"direct tx"| Router
    User -.->|"EIP-712 delegate"| OCR
    OCR -->|"ERC-2771 forward"| Router

    Router --> Cashier
    Router --> Stock

    Cashier -.- C1["cash deposits and withdrawals<br/>change mUSD"]
    Stock -.- S1["orders<br/>stockBalance"]
```

Use `x-api-p: MondayTrade` for MondayTrade RWA trading. The active API docs do not require other product contexts.

## Router operations map to API flows

Calldata responses give `toAddress`, `value`, and `callData` for your wallet client. `toAddress` is the `StockRouter` address. See [guides/demo-code.md](/rwa-trading-apis/guides/demo-code).

| User action              | Router method      | Self-submit endpoint                         | One Click endpoint              |
| ------------------------ | ------------------ | -------------------------------------------- | ------------------------------- |
| Deposit cash             | `deposit`          | `POST /cash/deposits/calldata` then `/tx`    | `POST /cash/deposits/send`      |
| Withdraw cash            | `withdraw`         | `POST /cash/withdrawals/calldata` then `/tx` | `POST /cash/withdrawals/send`   |
| Market buy or plain sell | `placeMarketOrder` | `POST /orders/calldata` then `/tx`           | `POST /orders/send`             |
| Limit buy or plain sell  | `placeLimitOrder`  | `POST /orders/calldata` then `/tx`           | `POST /orders/send`             |
| Cancel limit             | `cancelLimitOrder` | `DELETE /orders/{orderId}/calldata`          | `DELETE /orders/{orderId}/send` |

Stock deposit and withdrawal are exposed through `/stock/deposits/*` and `/stock/withdrawals/*`.

## Portfolio API vs on-chain state

Use `GET /users/{userId}/balance` as the API view of wallet and exchange state.

| Field             | Meaning                                   | Integration note                                                         |
| ----------------- | ----------------------------------------- | ------------------------------------------------------------------------ |
| `mUsdBalance`     | `mUSD` tracked by `Cashier`               | Use for buy power and withdrawable credit                                |
| `walletBalance`   | ERC-20 tokens in wallet                   | Custody balance; `StockRouter` needs allowance before it can pull tokens |
| `exchangeBalance` | API name for `Stock.stockBalance`         | Use for plain sell availability                                          |
| `walletAllowance` | Token approval to spender / `StockRouter` | Check before token-pulling flows                                         |

Bought stock normally appears as `exchangeBalance` first because the ERC-20 stock tokens are held by `Stock` and credited to the user there. A user can withdraw stock from `Stock.stockBalance` to wallet custody. If wallet-held stock should be sold, the user must approve `StockRouter`; the selected flow can then deposit the stock into `Stock.stockBalance` separately or as part of the sell transaction. For API checks, use `mUsdBalance` for buy power and `exchangeBalance` for sell power.

## Two execution modes (same contracts)

| Mode        | How it works                                                                                                                |
| ----------- | --------------------------------------------------------------------------------------------------------------------------- |
| Self-submit | API returns calldata; the user wallet signs and broadcasts the `StockRouter` transaction; the integration records `txHash`. |
| One Click   | User signs delegation once; `/send` submits through `OneClickRouter` to the same `StockRouter` methods.                     |

One Click is scoped for safety: the delegate wallet is bound to one user wallet, limited to supported RWA router actions, cannot freely transfer user ERC-20 tokens, and can be disabled.

## Design principles

| Principle           | What it means for integrators                                                                                                                                               |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Router-only entry   | API calldata targets `StockRouter`; state-changing integrations should not call `Cashier` or `Stock` directly.                                                              |
| Lock then settle    | Open orders lock `mUSD` or `Stock.stockBalance`; final balances update asynchronously.                                                                                      |
| Off-chain execution | Quotes and fills come from trading services; chain state catches up asynchronously.                                                                                         |
| Wallet vs exchange  | Portfolio shows both wallet and exchange balances; plain sells use `exchangeBalance`, while wallet-held stock can be pulled into `Stock` by an approved `StockRouter` flow. |
| Cash timing         | Deposits/withdrawals can be instant or queued; watch `operationStatus`.                                                                                                     |

## Where to go next

| Step            | Doc                                                                                                                                        |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Authenticate    | [../authenticate/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/authenticate/README.md) |
| Trader playbook | [trader-questions.md](/rwa-trading-apis/getting-started/trader-questions)                                                                  |
| Portfolio       | [../portfolio/overview.md](/rwa-trading-apis/portfolio/overview)                                                                           |
| Trading         | [../trading/overview.md](/rwa-trading-apis/trading/overview)                                                                               |
| Cash            | [../cash/](/rwa-trading-apis/cash-operations/cash)                                                                                         |
| Demo code       | [../guides/demo-code.md](/rwa-trading-apis/guides/demo-code)                                                                               |
| Reference       | [../reference/](/rwa-trading-apis/reference/reference)                                                                                     |

Deep contract docs: [mondaytrade-contracts/docs/contract-architecture.md](https://github.com/MondayTradeLabs/mondaytrade-contracts/blob/main/docs/contract-architecture.md) · [mondaytrade-contracts/docs/flows/](https://github.com/MondayTradeLabs/mondaytrade-contracts/blob/main/docs/flows/README.md)


# API Integration Playbook

Use this page as the practical operating guide for an RWA API integration. Before submitting orders, moving cash, or reconciling portfolio state, verify these request and state checks.

The most important habit is to separate **wallet state**, **mUSD**, **exchangeBalance**, and **final settlement state**. The API connects these systems, but they do not update at the same time.

## Integration Mental Model

```mermaid
sequenceDiagram
    participant Client as Integrator client
    participant API as Trading API
    participant Wallet as User wallet
    participant OCR as OneClickRouter
    participant Router as StockRouter
    participant Cashier as Cashier
    participant Stock as Stock

    Client->>API: GET state
    API-->>Client: mUsdBalance, exchangeBalance, orders

    alt Self-submit
        rect rgb(232, 244, 255)
            Client->>API: POST /calldata
            API-->>Client: toAddress, value, callData
            Client->>Wallet: submit transaction
            Wallet->>Router: execute calldata
            Client->>API: POST /tx with txHash
        end
    else One Click
        rect rgb(246, 239, 255)
            Client->>API: POST /send
            API->>OCR: submit delegated tx
            OCR->>Router: forward as user
        end
    end

    Router->>Cashier: update mUSD
    Router->>Stock: update orders / stockBalance
    Cashier-->>API: indexed state
    Stock-->>API: indexed state
```

Diagram color key: blue is self-submit, purple is One Click.

For self-submit requests, call the API to build `StockRouter` calldata, submit the transaction with the user wallet, then record `txHash`. For One Click requests, call `/send`; the API submits through `OneClickRouter`. For state reads, the API indexes `Cashier` and `Stock` into fields such as `mUsdBalance`, orders, and `exchangeBalance`.

`StockRouter` enforces on-chain entry, `Cashier` accounts for `mUSD`, and `Stock` accounts for orders and `Stock.stockBalance`. Build integrations around the async lifecycle instead of assuming a trade is final when the transaction is mined.

## Discover Tradable Stocks

Start every trading flow from the symbol list. Treat a stock token as tradable only when the API marks it tradable for the current `chainId` and `x-api-p`.

1. Call `GET /api/v1/symbols`.
2. Keep only symbols where `tradable` is `true`.
3. Call `GET /api/v1/config` for fee rates, cashier buffer state, and per-token deposit/withdraw limits.
4. Use `contractAddress` as `stockAddress` when building orders.
5. Refresh quote context with `GET /api/v1/prices/{symbol}`.
6. Check `GET /api/v1/corporate-action?symbol=AAPL` when splits/dividends may affect downstream accounting.

Do not hardcode token addresses unless your release process also verifies they match the active API response.

## Check Buying Power

For plain buys, the important value is `mUsdBalance`, not the cash token `walletBalance`. A user can have USDC in their wallet and still have no `mUSD` until a deposit happens. If the cash token is approved and instant deposit is available, `/orders/with-deposit/*` can deposit and place the buy in one transaction.

| Field             | API meaning                                       |
| ----------------- | ------------------------------------------------- |
| `mUsdBalance`     | `mUSD` available for buys and withdrawals         |
| `walletBalance`   | ERC-20 tokens in wallet; not automatically `mUSD` |
| `walletAllowance` | Whether deposit can succeed on-chain              |

Use `mUsdBalance` for plain market buys and limit buys. If it is insufficient, deposit cash first. When cash token approval and instant deposit conditions are met, `/orders/with-deposit/*` can deposit and place the buy in one transaction.

## Check Stock Available To Sell

For plain sells, the important value is `exchangeBalance`. `walletBalance` means the user owns an ERC-20 stock token in their wallet, but it is not yet credited inside `Stock`.

Do not treat wallet stock as plain-sell balance. A plain sell uses `exchangeBalance`, the API view of `Stock.stockBalance`. To sell wallet-held stock with separate calls, approve the stock token and call `/stock/deposits/*` first. To deposit and sell in one transaction, use `/orders/with-deposit/*` after stock token approval.

## Prepare Deposits Correctly

Deposit means: **wallet cash token -> mUSD -> buy power**. Track the conversion so the integration does not treat wallet balance as spendable `mUSD`.

Before building deposit calldata:

1. Check wallet cash balance.
2. Check allowance with `GET /api/v1/users/{userId}/balance?spenderAddress={spender}`.
3. Request ERC-20 approval from the owner wallet if `walletAllowance` is too low.
4. For self-submit, build deposit calldata and submit the returned `StockRouter` transaction.
5. For One Click, call `/cash/deposits/send` after delegation is enabled.
6. Record `txHash` for self-submit flows and poll the deposit operation.

If allowance is too low, `/cash/deposits/calldata` can still return calldata, but the chain transaction will fail.

## Place A Market Buy

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant C as Cashier
    participant TS as Trading service

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST /orders/calldata
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST /orders/send
            API->>R: submit via OneClickRouter
        end
    end
    R->>R: placeMarketOrder buy notional
    R->>C: Lock max mUSD spend
    TS->>TS: Execute at best available price
    TS->>C: Apply mUSD spend or refund
```

Market buy input is `notional`: the maximum `mUSD` amount to spend. The final fill may spend less and refund the rest. The order is not economically final until settlement has credited stock and refunded unused `mUSD`.

## Place A Market Sell

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant Stock as Stock
    participant TS as Trading service
    participant C as Cashier

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST /orders/calldata
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST /orders/send
            API->>R: submit via OneClickRouter
        end
    end
    R->>R: placeMarketOrder sell quantity
    R->>Stock: Lock max stock quantity
    TS->>TS: Execute at best available price
    TS->>Stock: Apply filled and unfilled result
    TS->>C: Credit mUSD proceeds
```

Market sell input is `quantity`: the maximum stock quantity to sell. `Stock` locks that quantity first; settlement applies only the filled amount and returns any unfilled stock to `Stock.stockBalance`.

## Place A Limit Order

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant S as Stock
    participant C as Cashier
    participant B as Backend bots

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST /orders/calldata
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST /orders/send
            API->>R: submit via OneClickRouter
        end
    end
    R->>S: placeLimitOrder
    alt Buy
        S->>C: Lock mUSD
    else Sell
        S->>S: Lock stockBalance
    end
    B->>B: Execute when market conditions match
    alt Filled or partial
        B->>C: Apply mUSD spend/refund
        B->>S: Apply stock fill/remainder
    else Open
        B-->>API: Keep order in openOrder
    else Cancel
        T->>API: DELETE /orders/{orderId}/calldata or /send
        API->>R: cancelLimitOrder
        B->>C: Refund locked mUSD if needed
        B->>S: Return locked stock if needed
    end
```

Limit orders have a `price`, `quantity`, and `timeInForce`. Current production contracts accept only `DAY`; backend processing and settlement handle the practical lifecycle after placement.

Treat a limit order as an open commitment that locks `mUSD` or stock until fill, cancel, expiry, or settlement. Keep it separate from final portfolio balances.

## Reconcile Order Finality

A mined transaction means the order was accepted on-chain; it does not mean execution and settlement are final. Watch both mapping state and order detail:

1. `POST /api/v1/orders/tx` records a self-submitted tx.
2. `GET /api/v1/orders/tx/{txHash}` finds the tx mapping.
3. The indexer backfills `orderId`.
4. `GET /api/v1/orders/{orderId}` tracks open or historical state.
5. Portfolio balances update after settlement.

An order is economically final only after settlement updates `mUSD` and `exchangeBalance`.

## Understand Instant Vs Queued Cash

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant C as Cashier
    participant B as Backend bots

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST cash calldata endpoint
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST cash send endpoint
            API->>R: submit via OneClickRouter
        end
    end
    R->>C: Record cash operation
    alt Buffer can cover operation
        C->>C: Apply mUSD credit or token payout
        API-->>T: operationStatus settled
    else Buffer cannot cover operation
        C->>C: Mark processing
        B->>B: Complete final cash settlement
        B->>C: Settle operation
        API-->>T: operationStatus settled
    end
```

Cash can be instant when buffers are available. Otherwise it is queued until final settlement completes. Track status with:

* `GET /api/v1/cash/deposits/{operationId}`
* `GET /api/v1/cash/withdrawals/{operationId}`

Handle both instant and queued outcomes. A queued operation is not necessarily failed; it may be waiting for final cash settlement.

The underlying contracts use two buffers: a global `creditBuffer` for instant deposits and a per-token `withdrawalBuffer` for instant withdrawals. Deposits and withdrawals can replenish each other's buffers. See [cash/buffer-mechanism.md](/rwa-trading-apis/cash-operations/buffer-mechanism).

## Choose Execution Mode

Both modes call the same router methods. One Click only changes who submits the router transaction.

| Mode        | Use when                                           | Trade-off                                                |
| ----------- | -------------------------------------------------- | -------------------------------------------------------- |
| Self-submit | You manage wallets, custody, or transaction policy | More control; must record `txHash`                       |
| One Click   | You use delegated transaction submission           | Requires user delegation and API key bound `userAddress` |

Use Self-submit when your integration owns transaction policy or custody. Use One Click when the integration needs delegated submission after explicit authorization.

## Treat API Calldata As A Router Instruction

For self-submit, use `toAddress`, `value`, and `callData` exactly as returned by the API. Do not reconstruct calldata by hand unless you are deliberately bypassing the partner API. The API output is already shaped for the correct router method and product context.

## Pre-Trade Checklist

Before placing an order, confirm:

* Symbol is tradable for the selected chain/product.
* `x-api-chain-id`, wallet network, and `x-api-p` match.
* Portfolio has been refreshed.
* Plain buys use `mUsdBalance`; plain sells use `exchangeBalance`.
* Order-with-deposit flows require token allowance and, for buys, instant deposit availability.
* Deposit allowance is sufficient if funding is required.
* Execution mode is selected.
* Self-submit flows record `txHash`; One Click flows have `/1ct/status = enable`.

If a trade fails or appears stuck, check these in order: API response `code`, tx receipt, `/orders/tx/{txHash}`, `/orders/{orderId}`, then portfolio balances.

## Related Docs

| Need                             | Doc                                                                                                                                     |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| First API trade flow             | [../guides/quickstart-first-trade.md](/rwa-trading-apis/guides/quickstart-first-trade)                                                  |
| How do I authenticate?           | [authenticate/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/authenticate/README.md) |
| How do I read balances?          | [portfolio/overview.md](/rwa-trading-apis/portfolio/overview)                                                                           |
| How do I deposit?                | [cash/deposits.md](/rwa-trading-apis/cash-operations/deposits)                                                                          |
| How do I place or cancel orders? | [trading/place-and-cancel-orders.md](/rwa-trading-apis/trading/place-and-cancel-orders)                                                 |
| How do I track status?           | [trading/order-status-and-history.md](/rwa-trading-apis/trading/order-status-and-history)                                               |
| How do I submit with viem?       | [guides/demo-code.md](/rwa-trading-apis/guides/demo-code)                                                                               |
| How do I debug issues?           | [../reference/troubleshooting.md](/rwa-trading-apis/reference/troubleshooting)                                                          |


# Headers & Permissions

## Required headers

All `/api/v1/**` endpoints require:

| Header           | Required | Description                                             |
| ---------------- | -------- | ------------------------------------------------------- |
| `x-api-key`      | Yes      | Partner API key.                                        |
| `x-api-ts`       | Yes      | Unix ms timestamp. ≤ **45 seconds** drift from UTC.     |
| `x-api-nonce`    | Yes      | Unique per key within the 45s window. UUID recommended. |
| `x-api-sign`     | Yes      | HMAC-SHA256 authentication value. Case-insensitive hex. |
| `x-api-chain-id` | Yes      | Chain ID for this request.                              |
| `x-api-p`        | Yes      | Product type for this request.                          |

## Supported chain IDs

| Value      | Chain            |
| ---------- | ---------------- |
| `8453`     | Base Mainnet     |
| `1`        | Ethereum Mainnet |
| `143`      | Monad Mainnet    |
| `11155111` | Ethereum Sepolia |
| `10143`    | Monad Testnet    |
| `84532`    | Base Sepolia     |

## Supported product types

| Value         | Description          |
| ------------- | -------------------- |
| `MondayTrade` | MondayTrade product. |

> Enum values are case-sensitive. These docs focus the MondayTrade RWA API; use `x-api-p: MondayTrade`.

## API key validation

| Check        | Rule                                                                                                                               |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| API key      | Must exist and be `active`.                                                                                                        |
| Expiry       | `expires_at` null or in the future.                                                                                                |
| IP whitelist | **Required — an empty whitelist rejects every request (`401`); it does not mean "no restriction".** Exact IP match only (no CIDR). |
| Scope        | Must match `chainId + productType + access`.                                                                                       |

> **Before your first request, add your egress IP to the key's whitelist.** A key with an empty/unset whitelist rejects *all* requests with `401 Unauthorized` — the single most common first-integration failure. Behind a gateway/proxy the server matches the IP it resolves (see below, usually the `X-Forwarded-For` value), not your machine's local IP.

### Client IP resolution

1. First non-empty IP in `X-Forwarded-For`
2. `X-Real-IP`
3. TCP `remoteAddr`

## Permission levels

| access      | Allowed operations       |
| ----------- | ------------------------ |
| `READ_ONLY` | `GET` only.              |
| `WRITABLE`  | `GET`, `POST`, `DELETE`. |


# HMAC Authentication

This page describes API request authentication. It is not wallet signing. Every private endpoint request must include an HMAC value in `x-api-sign`.

## Authentication payload

Five lines joined by `\n`:

```
METHOD
URI
TIMESTAMP
NONCE
RAW_BODY
```

| Field       | Description                                               |
| ----------- | --------------------------------------------------------- |
| `METHOD`    | Uppercase HTTP method.                                    |
| `URI`       | Path with sorted query string. No domain or context path. |
| `TIMESTAMP` | Same as `x-api-ts` (ms).                                  |
| `NONCE`     | Same as `x-api-nonce`.                                    |
| `RAW_BODY`  | Raw body string, or empty if none.                        |

## Query string sorting

Parameters sorted by name ascending. Example request:

```
GET /api/v1/orders?page=1&limit=10
```

Authenticated `URI`:

```
/api/v1/orders?limit=10&page=1
```

> Avoid duplicate query parameter names when building the authentication payload.

## Body authentication

JSON requests use `Content-Type: application/json`. `RAW_BODY` must match the sent body exactly (spaces, field order).

`GET` and bodyless `POST` use empty `RAW_BODY`.

## HMAC-SHA256

```
x-api-sign = hex(HMAC_SHA256(authenticationPayload, apiSecret))
```

UTF-8 encoding throughout.

### Python

```python
import hmac
import hashlib
from urllib.parse import urlencode

def canonical_uri(path: str, query: dict = None) -> str:
    if not query:
        return path
    sorted_pairs = sorted(query.items(), key=lambda x: x[0])
    return f"{path}?{urlencode(sorted_pairs)}"

def sign_trading_api(
    method: str,
    path: str,
    query: dict = None,
    timestamp: int = None,
    nonce: str = None,
    raw_body: str = "",
    api_secret: str = "",
) -> str:
    import time
    import uuid
    timestamp = timestamp or int(time.time() * 1000)
    nonce = nonce or str(uuid.uuid4())
    uri = canonical_uri(path, query)
    payload = f"{method.upper()}\n{uri}\n{timestamp}\n{nonce}\n{raw_body}"
    return hmac.new(
        api_secret.encode("utf-8"),
        payload.encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()
```

### cURL

cURL + openssl works for a quick check, but shell HMAC has sharp edges (trailing-newline stripping by `$(...)`, secrets starting with `-`, `date +%s%3N` on macOS/BSD, `PATH` clobbering). For production, prefer the Python example above or the Node `crypto` version in [examples.md](/rwa-trading-apis/authentication/examples).

```bash
METHOD="GET"
URI="/api/v1/symbols"
# Unix milliseconds. GNU date works directly; BSD (macOS) date emits a literal "N",
# so fall back based on whether the output is all digits (do NOT rely on exit code —
# BSD date exits 0 even for %3N).
TIMESTAMP=$(date +%s%3N)
case "$TIMESTAMP" in
  ''|*[!0-9]*)
    if command -v gdate >/dev/null 2>&1; then TIMESTAMP=$(gdate +%s%3N)
    else TIMESTAMP=$(python3 -c 'import time; print(int(time.time()*1000))'); fi ;;
esac
NONCE=$(uuidgen | tr '[:upper:]' '[:lower:]')
RAW_BODY=""
# Pipe printf STRAIGHT into openssl. Three gotchas this avoids:
#  1) Join with REAL newlines (printf format), not the two-character "\n".
#  2) PAYLOAD=$(printf ...) would strip the trailing newline -> wrong sig for empty-body (GET/DELETE) requests.
#  3) -macopt "key:..." (not -hmac "...") so a secret starting with "-" isn't parsed as an openssl option.
HMAC_AUTH=$(printf '%s\n%s\n%s\n%s\n%s' "$METHOD" "$URI" "$TIMESTAMP" "$NONCE" "$RAW_BODY" \
  | openssl dgst -sha256 -mac HMAC -macopt "key:$API_SECRET" -hex | awk '{print $NF}')

curl -X GET "https://mainnet-api.monday.trade/rwa/trading/api/v1/symbols" \
  -H "x-api-key: ${API_KEY}" \
  -H "x-api-ts: ${TIMESTAMP}" \
  -H "x-api-nonce: ${NONCE}" \
  -H "x-api-sign: ${HMAC_AUTH}" \
  -H "x-api-chain-id: 8453" \
  -H "x-api-p: MondayTrade"
```


# Examples

Node.js HMAC authentication snippets. For a full integration sample with **viem** (self-submit tx, ERC-20 approve, One Click `signTypedData`), see [guides/demo-code.md](/rwa-trading-apis/guides/demo-code).

## HMAC helper

```js
import crypto from "node:crypto";

function canonicalUri(path, query = {}) {
  const pairs = [];
  for (const key of Object.keys(query).sort()) {
    const value = query[key];
    if (Array.isArray(value)) {
      for (const item of value) pairs.push(`${key}=${item}`);
    } else if (value !== undefined && value !== null) {
      pairs.push(`${key}=${value}`);
    }
  }
  return pairs.length === 0 ? path : `${path}?${pairs.join("&")}`;
}

function signTradingApi({ method, path, query, timestamp, nonce, rawBody, apiSecret }) {
  const uri = canonicalUri(path, query);
  const payload = [
    method.toUpperCase(),
    uri,
    String(timestamp),
    nonce,
    rawBody ?? ""
  ].join("\n");

  return crypto
    .createHmac("sha256", apiSecret)
    .update(payload, "utf8")
    .digest("hex");
}
```

## Signed POST example

```js
const body = JSON.stringify({
  stockAddress: "0x0000000000000000000000000000000000000001",
  side: "Buy",
  type: "Market",
  notional: "10",
  deadline: 1893456000
});

const timestamp = Date.now();
const nonce = crypto.randomUUID();
const hmacAuth = signTradingApi({
  method: "POST",
  path: "/api/v1/orders/calldata",
  query: {},
  timestamp,
  nonce,
  rawBody: body,
  apiSecret: process.env.TRADING_API_SECRET
});

const headers = {
  "content-type": "application/json",
  "x-api-key": process.env.TRADING_API_KEY,
  "x-api-ts": String(timestamp),
  "x-api-nonce": nonce,
  "x-api-sign": hmacAuth,
  "x-api-chain-id": "8453",
  "x-api-p": "MondayTrade"
};

const response = await fetch(
  "https://mainnet-api.monday.trade/rwa/trading/api/v1/orders/calldata",
  { method: "POST", headers, body }
);
```

## cURL with HMAC

```bash
API_KEY="your-api-key"
API_SECRET='your-api-secret'   # single-quote it: a secret containing shell metacharacters breaks when double-quoted or sourced
METHOD="POST"
URI="/api/v1/orders/calldata"   # do NOT name this variable PATH — it clobbers the shell's $PATH
# Unix milliseconds. GNU date works directly; BSD (macOS) date emits a literal "N",
# so fall back based on whether the output is all digits (do NOT rely on exit code —
# BSD date exits 0 even for %3N).
TIMESTAMP=$(date +%s%3N)
case "$TIMESTAMP" in
  ''|*[!0-9]*)
    if command -v gdate >/dev/null 2>&1; then TIMESTAMP=$(gdate +%s%3N)
    else TIMESTAMP=$(python3 -c 'import time; print(int(time.time()*1000))'); fi ;;
esac
NONCE=$(uuidgen | tr '[:upper:]' '[:lower:]')
BODY='{"stockAddress":"0x0000000000000000000000000000000000000001","side":"Buy","type":"Market","notional":"10","deadline":1893456000}'

# Pipe printf STRAIGHT into openssl. Gotchas this avoids:
#  1) Join with REAL newlines (printf format), not the two-character "\n".
#  2) PAYLOAD=$(printf ...) would strip the trailing newline (breaks empty-body GET/DELETE).
#  3) -macopt "key:..." (not -hmac "...") so a secret starting with "-" isn't parsed as an option.
HMAC_AUTH=$(printf '%s\n%s\n%s\n%s\n%s' "$METHOD" "$URI" "$TIMESTAMP" "$NONCE" "$BODY" \
  | openssl dgst -sha256 -mac HMAC -macopt "key:$API_SECRET" -hex | awk '{print $NF}')

curl -X ${METHOD} "https://mainnet-api.monday.trade/rwa/trading${URI}" \
  -H "Content-Type: application/json" \
  -H "x-api-key: ${API_KEY}" \
  -H "x-api-ts: ${TIMESTAMP}" \
  -H "x-api-nonce: ${NONCE}" \
  -H "x-api-sign: ${HMAC_AUTH}" \
  -H "x-api-chain-id: 143" \
  -H "x-api-p: MondayTrade" \
  -d "${BODY}"
```

See also [signature.md](/rwa-trading-apis/authentication/signature) for Python and HMAC authentication details, and [guides/demo-code.md](/rwa-trading-apis/guides/demo-code) for viem integration.


# Holdings & Positions

Use these endpoints to monitor a user's `mUSD`, wallet token balances, and `exchangeBalance`.

`userId` is currently the user's wallet address (trimmed, lowercased).

For API-level interpretation of `mUsdBalance`, `walletBalance`, and `exchangeBalance`, read [getting-started/trader-questions.md](/rwa-trading-apis/getting-started/trader-questions).

## Endpoints

| Method | Path                               | Description             |
| ------ | ---------------------------------- | ----------------------- |
| `GET`  | `/api/v1/users/{userId}`           | User info               |
| `GET`  | `/api/v1/users/{userId}/balance`   | Cash and token balances |
| `GET`  | `/api/v1/users/{userId}/positions` | Stock positions         |

## Query user info

```
GET /api/v1/users/{userId}
```

Response `data`:

| Field         | Type   | Description               |
| ------------- | ------ | ------------------------- |
| `userId`      | string | User ID (wallet address). |
| `userAddress` | string | Wallet address.           |

## Query balances

```
GET /api/v1/users/{userId}/balance
```

| Parameter        | Type   | Required | Default       | Description                  |
| ---------------- | ------ | -------- | ------------- | ---------------------------- |
| `spenderAddress` | string | No       | `0x000...000` | Spender for allowance query. |

Response `data`:

| Field           | Type   | Description   |
| --------------- | ------ | ------------- |
| `chainId`       | number | Chain ID.     |
| `productType`   | string | Product type. |
| `address`       | string | User wallet.  |
| `mUsdBalance`   | string | `mUSD`.       |
| `tokenBalances` | array  | Token list.   |

### tokenBalances item

| Field             | Type          | Description                                            |
| ----------------- | ------------- | ------------------------------------------------------ |
| `address`         | string        | Token address.                                         |
| `name`            | string        | Token name.                                            |
| `symbol`          | string        | Token symbol.                                          |
| `stockSymbol`     | string / null | Stock symbol (stock tokens).                           |
| `isStock`         | boolean       | Stock token flag.                                      |
| `decimals`        | number        | Decimals.                                              |
| `price`           | number / null | Price (stock tokens).                                  |
| `walletBalance`   | string        | Wallet balance (human-readable).                       |
| `walletAllowance` | string        | Allowance to spender.                                  |
| `exchangeBalance` | string        | API view of `Stock.stockBalance`; used by plain sells. |
| `logoUrl`         | string        | Logo URL.                                              |

## Query positions

```
GET /api/v1/users/{userId}/positions
```

Same query parameters as `/balance`. Returns `data` as a `tokenBalances` array.

Use `spenderAddress` when checking deposit allowance — see [cash/deposits.md](/rwa-trading-apis/cash-operations/deposits).


# On-Chain Market Config

## Get market config

```
GET /api/v1/config
```

Returns on-chain exchange configuration for the current `chainId + productType` scope: cashier buffers, exchange fee settings, and per-token cashier limits/rates.

Permission: `READ_ONLY`. No query parameters.

This endpoint is separate from direct on-chain stock reference-price reads. For the `StockOracle` contract interface, see [Stock Oracle](/rwa-trading-apis/market-data/stock-oracle).

## Response

Standard envelope. `data` contains:

| Field                | Type   | Description                                                    |
| -------------------- | ------ | -------------------------------------------------------------- |
| `cashierBuffer`      | object | Cashier-level buffer snapshot for instant deposit eligibility. |
| `exchangeFeeConfig`  | object | Exchange fee and minimum order settings.                       |
| `cashierTokenConfig` | object | Map of lowercase token address → per-token cashier config.     |

### Field naming note

`cashierBuffer` and each `cashierTokenConfig` entry use `chain`. `exchangeFeeConfig` uses `chainId`. Both represent the scoped chain ID.

### Value encoding

| Area                                                                 | Format                                | Example                                   |
| -------------------------------------------------------------------- | ------------------------------------- | ----------------------------------------- |
| `cashierBuffer.creditBuffer`, `creditBufferCapacity`, `totalBalance` | Raw WAD integer strings (18 decimals) | `"743810467000000000000"` ≈ 743.81 `mUSD` |
| `cashierTokenConfig.withdrawalBuffer`, `withdrawalBufferCapacity`    | Raw integer strings in token decimals | `"253689533"` with `decimals: 6`          |
| `exchangeFeeConfig.mintFeeRate`, `protocolFeeRate`, `minOrderValue`  | Human-readable decimal strings        | `"0"`, `"0.001"`                          |
| `cashierTokenConfig.depositRate`, `withdrawalRate`                   | Human-readable decimal strings        | `"1"`, `"0.9969"`                         |

Do not parse WAD or token-amount fields as human-readable decimals.

### `cashierBuffer`

| Field                     | Type   | Description                                                                                                                                                               |
| ------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `chain`                   | number | Chain ID for the scoped context.                                                                                                                                          |
| `productType`             | string | Product type, e.g. `MondayTrade`.                                                                                                                                         |
| `address`                 | string | Cashier contract address. Matches `cashierAddress` in `cashierTokenConfig` entries.                                                                                       |
| `instantThresholdDivisor` | string | Divisor used to cap instant operation size relative to buffer capacity. See [buffer mechanism — Instant Eligibility](/rwa-trading-apis/cash-operations/buffer-mechanism). |
| `creditBuffer`            | string | Current `mUSD` credit buffer balance (WAD).                                                                                                                               |
| `creditBufferCapacity`    | string | Maximum `mUSD` credit buffer capacity (WAD).                                                                                                                              |
| `totalBalance`            | string | Total cashier balance snapshot (WAD).                                                                                                                                     |

Per-token `withdrawalBuffer` values live under `cashierTokenConfig`, not in this object.

### `exchangeFeeConfig`

| Field             | Type   | Description                                                                                               |
| ----------------- | ------ | --------------------------------------------------------------------------------------------------------- |
| `chainId`         | number | Chain ID.                                                                                                 |
| `productType`     | string | Product type.                                                                                             |
| `mintFeeRate`     | string | Mint fee rate, human-readable (e.g. `0.001` = 0.1%). `"0"` means no mint fee.                             |
| `protocolFeeRate` | string | Protocol fee rate, human-readable. `"0"` means no protocol fee.                                           |
| `minOrderValue`   | string | Minimum order notional in USD, human-readable (e.g. `"1.00"`). `"0"` means no minimum enforced in config. |
| `txHash`          | string | Tx hash of the latest on-chain config update. May be empty when no update tx is recorded.                 |
| `updatedAt`       | number | Unix seconds when config was last updated.                                                                |

Use `minOrderValue`, `mintFeeRate`, and `protocolFeeRate` when validating or displaying order economics before calling order endpoints.

### `cashierTokenConfig` entries

Map keys are lowercase ERC-20 token addresses. Each value includes:

| Field                      | Type    | Description                                                             |
| -------------------------- | ------- | ----------------------------------------------------------------------- |
| `chain`                    | number  | Chain ID.                                                               |
| `productType`              | string  | Product type.                                                           |
| `cashierAddress`           | string  | Cashier contract address.                                               |
| `tokenAddress`             | string  | ERC-20 token address.                                                   |
| `minAmount`                | string  | Minimum deposit/withdraw amount in whole tokens.                        |
| `decimals`                 | number  | Token decimals.                                                         |
| `depositPaused`            | boolean | Deposit flow paused for this token.                                     |
| `withdrawPaused`           | boolean | Withdraw flow paused for this token.                                    |
| `depositRate`              | string  | Deposit rate, human-readable (e.g. `1` = no fee).                       |
| `withdrawalRate`           | string  | Withdrawal rate, human-readable (e.g. `0.9969`).                        |
| `withdrawalBuffer`         | string  | Current on-chain token buffer for instant withdrawals (token decimals). |
| `withdrawalBufferCapacity` | string  | Maximum token buffer capacity for instant withdrawals (token decimals). |

Check `depositPaused`, `withdrawPaused`, and buffer fields before building deposit or withdrawal calldata. See [cash deposits](/rwa-trading-apis/cash-operations/deposits) and [withdrawals](/rwa-trading-apis/cash-operations/withdrawals).

## Integration notes

* For instant vs queued cash behavior, pair buffer fields here with [buffer mechanism](/rwa-trading-apis/cash-operations/buffer-mechanism).

Example payload: [sample-responses.md — Market config](/rwa-trading-apis/reference/sample-responses).


# Stock Oracle

## Contract Overview

`StockOracle` stores one latest price payload per supported `bytes32 priceId`. The same oracle proxy can serve all stock symbols on a chain; it does not deploy one feed contract per symbol.

The oracle supports:

* single and batch price reads
* freshness-checked reads
* session-aware payloads
* bid and ask values alongside the main oracle price

All price fields use `8` decimals.

## Deployment and Backend Enablement

The integration draft records the intended mainnet proxy address as the same deterministic address on Ethereum, Monad, and Base:

| Network  | Chain ID | StockOracle proxy                            |
| -------- | -------: | -------------------------------------------- |
| Ethereum |      `1` | `0x037848af338c38e1e0ab722be80bf4c2e612a1f7` |
| Monad    |    `143` | `0x037848af338c38e1e0ab722be80bf4c2e612a1f7` |
| Base     |   `8453` | `0x037848af338c38e1e0ab722be80bf4c2e612a1f7` |

The draft also records implementation address `0x8745912828473e9bef9d843ce8629bee3dcb9fec` for reference only. Consumers should integrate with the proxy address, not the implementation address.

## Price IDs

Each supported asset is identified by `bytes32 priceId`.

The standard derived ID is:

```
priceId = keccak256(uppercase(trim(symbol)))
```

For example, the backend derives `AAPL` from the uppercase symbol bytes. Deployment scripts may also accept an explicit `bytes32 priceId`; if omitted, they use the same uppercase-symbol derivation.

Before reading a price, consumers can check:

```solidity
function isSupportedPriceId(bytes32 priceId) external view returns (bool);
function hasPrice(bytes32 priceId) external view returns (bool);
function description(bytes32 priceId) external view returns (string memory);
```

`isSupportedPriceId=true` means the ID is registered. `hasPrice=true` means at least one price has been published.

## Price Payload

Oracle reads return:

```solidity
enum Session {
    UNKNOWN,
    PRE_MARKET,
    REGULAR,
    POST_MARKET,
    OVERNIGHT,
    CLOSED
}

struct PricePayload {
    int128 price;
    int128 bestBid;
    int128 bestAsk;
    uint64 feedUpdateTimestamp;
    uint64 publishedAt;
    uint80 roundId;
    Session session;
}
```

| Field                 | Meaning                                                                 |
| --------------------- | ----------------------------------------------------------------------- |
| `price`               | Main oracle price, 8 decimals. Backend currently uses bid/ask midpoint. |
| `bestBid`             | Best bid price, 8 decimals.                                             |
| `bestAsk`             | Best ask price, 8 decimals.                                             |
| `feedUpdateTimestamp` | Source quote timestamp, in Unix seconds. Use this for freshness.        |
| `publishedAt`         | On-chain publish timestamp for this oracle round, in Unix seconds.      |
| `roundId`             | Monotonic oracle update round for this `priceId`.                       |
| `session`             | Market session associated with the source quote.                        |

Consumers should use `feedUpdateTimestamp` for staleness checks. `publishedAt` only says when the payload was written on-chain.

## Read APIs

Single-asset reads:

```solidity
function latestPrice(bytes32 priceId)
    external
    view
    returns (PricePayload memory);

function latestPriceNoOlderThan(bytes32 priceId, uint64 maxAge)
    external
    view
    returns (PricePayload memory);
```

Batch reads:

```solidity
function latestPrices(bytes32[] calldata priceIds)
    external
    view
    returns (PricePayload[] memory);

function latestPricesNoOlderThan(bytes32[] calldata priceIds, uint64 maxAge)
    external
    view
    returns (PricePayload[] memory);
```

Prefer `latestPriceNoOlderThan` or `latestPricesNoOlderThan` when the consuming contract must fail closed on stale source data. `maxAge` is denominated in seconds.

Current backend feeder comments note that the source quote can be about 15 minutes delayed. With the default 10-minute heartbeat, a consumer using `latestPriceNoOlderThan(maxAge)` should choose a `maxAge` that accounts for feed delay plus heartbeat and integration-specific risk tolerance; 25 minutes / 1500 seconds is a practical lower-bound example before adding any product-specific buffer.

## Read-Side Reverts

| Error               | Meaning                                                      |
| ------------------- | ------------------------------------------------------------ |
| `PriceIdNotFound`   | The `priceId` is not registered.                             |
| `PriceNotAvailable` | The `priceId` is registered but no price has been published. |
| `PriceTooOld`       | `block.timestamp - feedUpdateTimestamp > maxAge`.            |

## Write-Side Constraints

The backend feeder and deployment scripts are expected to satisfy these constraints before publishing:

| Constraint       | Contract behavior                                                                                                                                                    |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Registering IDs  | `registerPriceId` and `batchRegisterPriceIds` require `DEFAULT_ADMIN_ROLE`.                                                                                          |
| Updating prices  | `updatePrice` and `batchUpdatePrice` require `OPERATOR_ROLE`.                                                                                                        |
| Price validity   | `price`, `bestBid`, and `bestAsk` must be positive and fit into `int128`.                                                                                            |
| Spread validity  | `bestBid` cannot exceed `bestAsk`.                                                                                                                                   |
| Source timestamp | `feedUpdateTimestamp` cannot be in the future and cannot roll back below the current on-chain value.                                                                 |
| Same timestamp   | If `feedUpdateTimestamp` equals the current on-chain timestamp, the update is allowed only for a `CLOSED` carried-forward update with unchanged price, bid, and ask. |

These details are mainly useful for debugging feeder reverts and operational incidents. Normal readers do not need write permissions.

## Session Handling

Consumers should treat `session` as part of the risk model, not just display metadata.

Regular-session prices are generally the most liquid. Pre-market, post-market, and overnight prices may have wider spreads or lower coverage. `CLOSED` means the oracle carried forward the latest on-chain price into a closed-market state; it should not be treated the same as an active quote unless the integration explicitly supports that behavior.

For lending or risk-sensitive integrations, define per-asset and per-session controls for:

* maximum accepted age
* accepted spread or spread-derived haircut
* whether `CLOSED` prices are allowed
* fallback behavior when `PriceIdNotFound`, `PriceNotAvailable`, or `PriceTooOld` occurs


# Symbols & Tradability

## List tradable symbols

```
GET /api/v1/symbols
```

Returns `data` array items:

| Field                 | Type    | Description                          |
| --------------------- | ------- | ------------------------------------ |
| `symbol`              | string  | Stock symbol, e.g. `AAPL`.           |
| `contractAddress`     | string  | On-chain token address.              |
| `contractSymbol`      | string  | Contract symbol.                     |
| `contractName`        | string  | Contract name.                       |
| `decimals`            | number  | Contract decimals.                   |
| `onChainDecimals`     | number  | On-chain decimals.                   |
| `tradable`            | boolean | Tradable flag.                       |
| `fractionable`        | boolean | Fractional shares supported.         |
| `overnightTradable`   | boolean | Overnight session supported.         |
| `fractionalEhEnabled` | boolean | Fractional extended-hours supported. |
| `price`               | number  | Latest price.                        |
| `change24H`           | number  | 24h price change.                    |
| `change24HPercent`    | number  | 24h change percent.                  |
| `logoUrl`             | string  | Logo URL.                            |
| `lastUpdateTimestamp` | number  | Cache update (Unix seconds).         |
| `name`                | string  | Company name.                        |
| `pdfUrl`              | string  | Prospectus PDF URL.                  |
| `volume24H`           | number  | 24h volume.                          |

Use `contractAddress` as `stockAddress` when placing orders.

## Underlying stock quote

```
GET /api/v1/underlying/{symbol}/price
```

| Parameter | Type   | Description   |
| --------- | ------ | ------------- |
| `symbol`  | string | Stock symbol. |

Response fields (returned at the **top level** of `data`, not wrapped in a `basicInfo` object):

| Field                 | Type    | Description                  |
| --------------------- | ------- | ---------------------------- |
| `symbol`              | string  | Stock symbol.                |
| `contractAddress`     | string  | Token contract address.      |
| `contractSymbol`      | string  | Contract symbol.             |
| `onChainDecimals`     | number  | On-chain decimals.           |
| `name`                | string  | Company name.                |
| `exchange`            | string  | Exchange.                    |
| `status`              | string  | `active` or `inactive`.      |
| `price`               | number  | Latest price.                |
| `change24H`           | number  | 24h change.                  |
| `change24HPercent`    | number  | 24h change percent.          |
| `volume24H`           | number  | 24h volume.                  |
| `tradable`            | boolean | Tradable flag.               |
| `fractionable`        | boolean | Fractional shares.           |
| `lastUpdateTimestamp` | number  | Cache update (Unix seconds). |


# Quotes & History

## Real-time quote

```
GET /api/v1/prices/{symbol}
```

| Parameter | Type   | Description                                                         |
| --------- | ------ | ------------------------------------------------------------------- |
| `symbol`  | string | Stock symbol, token symbol, or token address. Uppercased by server. |

Response `data`:

| Field       | Type          | Description                                              |
| ----------- | ------------- | -------------------------------------------------------- |
| `basicInfo` | object        | Underlying quote (chain-agnostic).                       |
| `onChain`   | object / null | On-chain token info for current `chainId + productType`. |

For direct on-chain reference-price reads, see [Stock Oracle](/rwa-trading-apis/market-data/stock-oracle).

## Historical K-line

```
GET /api/v1/prices/{symbol}/history
```

| Parameter    | Type   | Required | Default | Description                                    |
| ------------ | ------ | -------- | ------- | ---------------------------------------------- |
| `startTime`  | number | No       | —       | Start (Unix seconds).                          |
| `endTime`    | number | Yes      | —       | End (Unix seconds).                            |
| `interval`   | string | Yes      | —       | `1m`, `3m`, `5m`, `15m`, `1h`, `1d`, `1w`.     |
| `adjustment` | string | No       | `all`   | `raw`, `split`, `dividend`, `spin-off`, `all`. |
| `limit`      | number | No       | `100`   | Max bars. Server max `5000`.                   |

Bar fields:

| Field       | Type   | Description              |
| ----------- | ------ | ------------------------ |
| `open`      | number | Open.                    |
| `high`      | number | High.                    |
| `low`       | number | Low.                     |
| `close`     | number | Close.                   |
| `volume`    | number | Volume.                  |
| `timestamp` | number | Bar time (Unix seconds). |

## Corporate actions

```
GET /api/v1/corporate-action
```

Query stock corporate actions (splits, dividends, etc.) for planning and display.

| Parameter   | Type   | Required | Description                                                                  |
| ----------- | ------ | -------- | ---------------------------------------------------------------------------- |
| `symbol`    | string | Yes      | Stock symbol without `a` prefix, e.g. `AAPL`.                                |
| `startTime` | number | No       | Start filter (Unix seconds). Filters on action `time`.                       |
| `endTime`   | number | No       | End filter (Unix seconds). Filters on action `time`.                         |
| `types`     | array  | No       | Filter by corporate action type. Repeat param or comma-separated per client. |

Allowed `types`:

| Value             | Description     |
| ----------------- | --------------- |
| `reverse_splits`  | Reverse split.  |
| `forward_splits`  | Forward split.  |
| `unit_splits`     | Unit split.     |
| `stock_dividends` | Stock dividend. |
| `cash_dividends`  | Cash dividend.  |

Example:

```
GET /api/v1/corporate-action?symbol=AAPL&types=cash_dividends&startTime=1704067200
```

### Response

Standard envelope. `data` is an array of `BrokerCorporateAction` objects, newest first when filtered by time.

| Field         | Type   | Description                                            |
| ------------- | ------ | ------------------------------------------------------ |
| `symbol`      | string | Stock symbol.                                          |
| `type`        | string | One of the `types` values above.                       |
| `time`        | string | Action timestamp (ISO-8601 date-time).                 |
| `exDate`      | string | Ex-dividend or ex-split date.                          |
| `recordDate`  | string | Record date.                                           |
| `payableDate` | string | Payable date.                                          |
| `processDate` | string | Processing date.                                       |
| `info`        | object | Type-specific broker metadata. Shape varies by `type`. |

### `info` object (varies by type)

| Field                 | Typical for | Description              |
| --------------------- | ----------- | ------------------------ |
| `rate`                | dividends   | Dividend rate per share. |
| `special`             | dividends   | Special dividend flag.   |
| `cusip`               | dividends   | CUSIP identifier.        |
| `oldRate` / `newRate` | splits      | Split ratio components.  |

Example response:

```json
{
  "code": 200,
  "errMsg": "",
  "data": [
    {
      "symbol": "AAPL",
      "type": "cash_dividends",
      "time": "2024-05-10T00:00:00Z",
      "exDate": "2024-05-10",
      "recordDate": "2024-05-13",
      "payableDate": "2024-05-16",
      "processDate": "2024-05-16",
      "info": {
        "rate": 0.25,
        "special": false,
        "cusip": "037833100"
      }
    }
  ],
  "uuid": null,
  "t": null
}
```

> Schema: `BrokerCorporateAction` in [openapi.snapshot.json](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/reference/openapi.snapshot.json).


# Overview

Before placing orders, review the trader integration playbook in [getting-started/trader-questions.md](/rwa-trading-apis/getting-started/trader-questions): tradable symbol, correct balance type, execution mode, and status tracking path.

## Order types

| Type        | Side            | Required fields                    |
| ----------- | --------------- | ---------------------------------- |
| Market buy  | `Buy`           | `notional`                         |
| Market sell | `Sell`          | `quantity`                         |
| Limit       | `Buy` or `Sell` | `quantity`, `price`, `timeInForce` |

All orders require `stockAddress` (from [symbols list](/rwa-trading-apis/market-data/symbols-and-tradability)) and `deadline` (Unix seconds, ≤ `4294967295`).

> Use **strings** for `quantity`, `notional`, and `price` to avoid JS precision loss.

## Execution modes

| Mode        | Place order             | Cancel limit                        | Record tx         |
| ----------- | ----------------------- | ----------------------------------- | ----------------- |
| Self-submit | `POST /orders/calldata` | `DELETE /orders/{orderId}/calldata` | `POST /orders/tx` |
| One Click   | `POST /orders/send`     | `DELETE /orders/{orderId}/send`     | Auto-recorded     |

One Click requires enabled delegation — see [one-click-delegated.md](/rwa-trading-apis/trading/one-click-delegated) and [guides/one-click-flow.md](/rwa-trading-apis/guides/one-click-flow).

## Typical flow

1. Check [portfolio](/rwa-trading-apis/portfolio/overview) for buying power and holdings.
2. Get quote from [market](/rwa-trading-apis/market-data/quotes-and-history) if needed.
3. Build or send order — [place-and-cancel-orders.md](/rwa-trading-apis/trading/place-and-cancel-orders).
4. Track status — [order-status-and-history.md](/rwa-trading-apis/trading/order-status-and-history).

Self-submit sequence: see [guides/self-submit-on-chain.md](/rwa-trading-apis/guides/self-submit-on-chain).


# Place & Cancel Orders

## Build order calldata

```
POST /api/v1/orders/calldata
```

| Field          | Type            | Required    | Description                                                   |
| -------------- | --------------- | ----------- | ------------------------------------------------------------- |
| `stockAddress` | string          | Yes         | Stock token address (EVM).                                    |
| `side`         | string          | Yes         | `Buy` or `Sell`.                                              |
| `type`         | string          | Yes         | `Market` or `Limit`.                                          |
| `quantity`     | string / number | Conditional | Limit orders; market sells.                                   |
| `notional`     | string / number | Conditional | Market buys.                                                  |
| `price`        | string / number | Conditional | Limit orders.                                                 |
| `timeInForce`  | string          | Conditional | Limit orders. See [enums](/rwa-trading-apis/reference/enums). |
| `deadline`     | number          | Yes         | Tx deadline (Unix seconds).                                   |

### Market buy

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Buy",
  "type": "Market",
  "notional": "10",
  "deadline": 1893456000
}
```

### Limit sell

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Sell",
  "type": "Limit",
  "quantity": "1.25",
  "price": "180.50",
  "timeInForce": "DAY",
  "deadline": 1893456000
}
```

### Limit buy

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Buy",
  "type": "Limit",
  "quantity": "0.05",
  "price": "180.50",
  "timeInForce": "DAY",
  "deadline": 1893456000
}
```

> Limit orders (**buy and sell**) use `quantity` + `price`; `notional` is only for **market buys**. Production limit orders accept only `timeInForce: "DAY"` — other values revert on-chain.

Response `data`:

| Field         | Type   | Description                              |
| ------------- | ------ | ---------------------------------------- |
| `chainId`     | number | Chain ID.                                |
| `productType` | string | Product type.                            |
| `toAddress`   | string | Router address.                          |
| `value`       | string | Native value (`"0"`).                    |
| `callData`    | string | Encoded calldata.                        |
| `method`      | string | `placeMarketOrder` or `placeLimitOrder`. |

Submit `toAddress` + `callData` on-chain, then record via [order-status-and-history.md](/rwa-trading-apis/trading/order-status-and-history).

## One Click place order

```
POST /api/v1/orders/send
```

Same body as `/calldata`, plus optional `gasLimit` (set a buffer — the API broadcasts through `OneClickRouter` and pays gas). Requires One Click enabled and API key `userAddress` configured.

The response is the **order-tx mapping**, not calldata: `{ id, chainId, productType, operationType, orderId, txHash, status, ... }`. `orderId` is `null` until the indexer backfills it — poll `GET /orders/tx/{txHash}` or `GET /orders/{orderId}` (once populated).

## Build Order-With-Deposit Calldata

```
POST /api/v1/orders/with-deposit/calldata
```

Use this endpoint when the order transaction should also use `StockRouter` as the approved spender before placing the order. For buys, `StockRouter` transfers the cash token to `Cashier`; for sells, it transfers the stock token to `Stock`.

| Field                 | Type            | Required    | Description                                                                                                |
| --------------------- | --------------- | ----------- | ---------------------------------------------------------------------------------------------------------- |
| `stockAddress`        | string          | Yes         | Stock token address.                                                                                       |
| `depositAmount`       | string / number | Yes         | Human-readable deposit amount. For buys, this is cash token amount. For sells, this is stock token amount. |
| `depositTokenAddress` | string          | Conditional | Cash token address. Required for buy orders.                                                               |
| `side`                | string          | Yes         | `Buy` or `Sell`.                                                                                           |
| `type`                | string          | Yes         | `Market` or `Limit`.                                                                                       |
| `quantity`            | string / number | Conditional | Limit orders; market sells.                                                                                |
| `notional`            | string / number | Conditional | Market buys.                                                                                               |
| `price`               | string / number | Conditional | Limit orders.                                                                                              |
| `timeInForce`         | string          | Conditional | Limit orders.                                                                                              |
| `deadline`            | number          | Yes         | Tx deadline (Unix seconds).                                                                                |

For buy orders, the cash token must be approved for `StockRouter`, and the cash deposit must be eligible for instant deposit; otherwise the combined transaction reverts. For sell orders, the wallet stock token must be approved for `StockRouter`.

### Market buy with deposit

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "depositTokenAddress": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  "depositAmount": "100",
  "side": "Buy",
  "type": "Market",
  "notional": "10",
  "deadline": 1893456000
}
```

### Market sell with stock deposit

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "depositAmount": "1.25",
  "side": "Sell",
  "type": "Market",
  "quantity": "1.25",
  "deadline": 1893456000
}
```

## One Click Order With Deposit

```
POST /api/v1/orders/with-deposit/send
```

Same body as `/with-deposit/calldata`, plus optional `gasLimit`. Requires One Click enabled and API key `userAddress` configured.

## Cancel limit order

### Self-submit cancel calldata

```
DELETE /api/v1/orders/{orderId}/calldata?deadline=1893456000
```

> Use the `orderId` **exactly as returned by the API** — a `0x`-prefixed 32-byte hex string (66 characters), e.g. `0x00000000000049fb0001000049d0d92daa26b7f121276e7034af17aed9e4c71e`. Put it in the path as-is: `DELETE /api/v1/orders/0x00000000000049fb0001000049d0d92daa26b7f121276e7034af17aed9e4c71e/calldata?deadline=1893456000`

### One Click cancel

```
DELETE /api/v1/orders/{orderId}/send?deadline=1893456000
```

Returns `uuid` and `txHash`.

### Cancel rules

* Order belongs to current API key
* Order is open
* Limit orders only
* No pending cancel in flight
* API key `userAddress` matches order user


# Order Status & History

## Record self-submitted order tx

```
POST /api/v1/orders/tx
```

| Field    | Type   | Required | Description                |
| -------- | ------ | -------- | -------------------------- |
| `txHash` | string | Yes      | On-chain transaction hash. |

Indexer backfills `orderId` from chain events.

> Same `txHash` from the same API key returns the existing mapping. A `txHash` already owned by another key returns an error.

## Query orders

### List mappings

```
GET /api/v1/orders?page=1&limit=10
```

### By tx hash

```
GET /api/v1/orders/tx/{txHash}
```

### By order ID

```
GET /api/v1/orders/{orderId}
```

`orderId` must belong to a mapping recorded by the current API key.

## Order detail fields

**openOrder:**

| Field           | Type   | Description                                                       |
| --------------- | ------ | ----------------------------------------------------------------- |
| `orderId`       | string | On-chain order ID.                                                |
| `userAddress`   | string | User address.                                                     |
| `side`          | string | `Buy` or `Sell`.                                                  |
| `type`          | string | `Market` or `Limit`.                                              |
| `tif`           | string | Time in force.                                                    |
| `symbol`        | string | Symbol.                                                           |
| `placeNotional` | string | Order notional (`0` for limit orders, which use `placeQuantity`). |
| `placeQuantity` | string | Order quantity.                                                   |
| `pay`           | string | Payment amount.                                                   |
| `placePrice`    | string | Order (limit) price.                                              |
| `status`        | string | `placing` or `canceling`.                                         |

**historyOrder** adds:

| Field           | Type          | Description      |
| --------------- | ------------- | ---------------- |
| `settleTxHash`  | string / null | Settlement tx.   |
| `settlePrice`   | string        | Execution price. |
| `settlePay`     | string / null | Actual payment.  |
| `settleReceive` | string / null | Actual received. |
| `mintFee`       | string        | Mint fee.        |
| `protocolFee`   | string        | Protocol fee.    |

See [reference/enums.md](/rwa-trading-apis/reference/enums) for status values.


# One Click Delegated

One Click lets the server submit transactions via an authorized proxy wallet. Required before calling any `/send` endpoint.

For user-facing safety copy, signer checks, and delegation UX, read [one-click-security-ux.md](/rwa-trading-apis/trading/one-click-security-ux).

## Query status

```
GET /api/v1/1ct/status
```

| Field       | Type   | Description                |
| ----------- | ------ | -------------------------- |
| `status`    | string | `/send` requires `enable`. |
| `delegatee` | string | Proxy wallet address.      |

## Prepare EIP-712 payload

```
POST /api/v1/1ct/prepare
```

| Field      | Type   | Required | Description                        |
| ---------- | ------ | -------- | ---------------------------------- |
| `deadline` | number | Yes      | Signature deadline (Unix seconds). |

Response `data`:

| Field         | Type   | Description         |
| ------------- | ------ | ------------------- |
| `delegatee`   | string | Proxy address.      |
| `signPayload` | object | EIP-712 typed data. |
| `nonce`       | number | Delegate nonce.     |
| `deadline`    | number | Same as request.    |

Example `signPayload`:

```json
{
  "domain": {
    "name": "OneClickRouter",
    "version": "1",
    "chainId": 10143,
    "verifyingContract": "0x..."
  },
  "types": {
    "Delegate": [
      { "name": "user", "type": "address" },
      { "name": "delegatee", "type": "address" },
      { "name": "nonce", "type": "uint64" },
      { "name": "deadline", "type": "uint32" }
    ]
  },
  "primaryType": "Delegate",
  "message": {
    "user": "0x...",
    "delegatee": "0x...",
    "nonce": 0,
    "deadline": 1893456000
  }
}
```

> The live `signPayload.types` also contains an `EIP712Domain` entry (omitted above for brevity). **ethers** ignores it — pass only `{ Delegate: ... }` as shown below. **viem** derives the domain itself and *throws* if `EIP712Domain` is present in `types`, so strip it first (see [guides/demo-code.md](/rwa-trading-apis/guides/demo-code)).

## Enable

```
POST /api/v1/1ct/enable
```

| Field       | Type   | Required | Description                                  |
| ----------- | ------ | -------- | -------------------------------------------- |
| `signature` | string | Yes      | 65-byte hex EIP-712 signature (`0x` prefix). |
| `deadline`  | number | Yes      | Must match `/prepare` response.              |

### ethers v6 signing

```js
import { Wallet } from "ethers";

const { signPayload, deadline } = prepareResponse.data;
const wallet = new Wallet(process.env.USER_PRIVATE_KEY);

if (wallet.address.toLowerCase() !== signPayload.message.user.toLowerCase()) {
  throw new Error("signer address must match signPayload.message.user");
}

const signature = await wallet.signTypedData(
  { ...signPayload.domain, chainId: BigInt(signPayload.domain.chainId) },
  { Delegate: signPayload.types.Delegate },
  {
    ...signPayload.message,
    nonce: BigInt(signPayload.message.nonce),
    deadline: BigInt(signPayload.message.deadline),
  }
);
```

## Disable

```
POST /api/v1/1ct/disable
```

No body. Use empty string for HMAC `RAW_BODY`.

## Send endpoints after enable

| Operation                | Endpoint                           | Method |
| ------------------------ | ---------------------------------- | ------ |
| Place order              | `/api/v1/orders/send`              | POST   |
| Place order with deposit | `/api/v1/orders/with-deposit/send` | POST   |
| Cancel order             | `/api/v1/orders/{orderId}/send`    | DELETE |
| Cash deposit             | `/api/v1/cash/deposits/send`       | POST   |
| Cash withdrawal          | `/api/v1/cash/withdrawals/send`    | POST   |
| Stock deposit            | `/api/v1/stock/deposits/send`      | POST   |
| Stock withdrawal         | `/api/v1/stock/withdrawals/send`   | POST   |

Flow: build calldata internally → submit via One Click → auto-record tx on success.

See [guides/one-click-flow.md](/rwa-trading-apis/guides/one-click-flow).


# One Click Security and API Semantics

One Click reduces repeated wallet prompts by letting a delegated service submit router transactions for a user. It does **not** change the underlying trading contracts: orders, deposits, withdrawals, and cancels still go through `StockRouter`.

## Mental Model

```mermaid
flowchart LR
    U[User wallet] -->|signs EIP-712 Delegate| API[Trading API]
    API -->|enable| OCR[OneClickRouter]
    D[Delegatee service] -->|execute as user| OCR
    OCR -->|ERC-2771 forward| R[StockRouter]
    R --> S[Cashier and Stock]
```

The user signs a typed delegation message. The delegatee service can then forward allowed router calls through `OneClickRouter`. The downstream router resolves the original user through ERC-2771 forwarding.

## Authorization Scope

Before enabling One Click, the integration should treat the delegation as a scoped transaction authorization:

* The delegatee can submit supported RWA trading router calls.
* The delegatee can place orders, cancel orders, deposit, and withdraw through allowed `/send` flows.
* The authorization is tied to the chain, OneClickRouter, delegatee, nonce, and deadline in the EIP-712 payload.
* Delegation can be disabled.

## API Flow

```mermaid
sequenceDiagram
    participant Client
    participant API as Trading API
    participant User
    participant OCR as OneClickRouter

    Client->>API: GET /1ct/status
    API-->>Client: status and delegatee
    Client->>API: POST /1ct/prepare
    API-->>Client: EIP-712 signPayload
    Client->>User: Request typed-data signature
    User-->>Client: signature
    Client->>API: POST /1ct/enable
    API->>OCR: delegateBySig
    API-->>Client: enabled
```

## Implementation Rules

| Rule                                            | Why                                                                      |
| ----------------------------------------------- | ------------------------------------------------------------------------ |
| Verify signer equals `signPayload.message.user` | Prevent enabling delegation for the wrong wallet                         |
| Use the returned `deadline` exactly             | It is part of the signed payload                                         |
| Treat nonce as single-use                       | Reusing old signatures should fail                                       |
| Check `/1ct/status` before `/send`              | Avoid avoidable send failures                                            |
| Keep `userAddress` binding explicit             | `/send` uses the API key bound user, not arbitrary request `userAddress` |
| Always support disable                          | Users need a clear recovery path                                         |

## API States

Treat One Click as a small API state machine: not enabled, preparing, signature requested, enabled, and disable pending. The only state that should allow `/send` endpoints is `Enabled`.

State mapping:

| State               | Integration handling                                       |
| ------------------- | ---------------------------------------------------------- |
| Not enabled         | Do not call `/send`; use `/calldata` or prepare delegation |
| Preparing           | Call `/1ct/prepare` and request typed-data signature       |
| Signature requested | Wait for a valid user signature                            |
| Enabled             | `/send` endpoints can be used                              |
| Disable pending     | Do not assume future `/send` requests will succeed         |

## Deposit Caveat

One Click does not remove ERC-20 approval requirements. For `/cash/deposits/send`, the API key bound `userAddress` must still approve the cash token spender.

## Risk Boundaries

One Click should be treated as a powerful trading authorization:

* Do not hide the delegatee address.
* Do not reuse signatures across chains or routers.
* Do not submit `/send` for a different user than the bound `userAddress`.
* Log `uuid`, `txHash`, and operation/order IDs for audit.

## Related Docs

| Need                   | Doc                                                                            |
| ---------------------- | ------------------------------------------------------------------------------ |
| Endpoint details       | [one-click-delegated.md](/rwa-trading-apis/trading/one-click-delegated)        |
| End-to-end flow        | [../guides/one-click-flow.md](/rwa-trading-apis/guides/one-click-flow)         |
| viem typed-data sample | [../guides/demo-code.md](/rwa-trading-apis/guides/demo-code)                   |
| Troubleshooting        | [../reference/troubleshooting.md](/rwa-trading-apis/reference/troubleshooting) |


# Overview

Docs for deposits, withdrawals, and cash operation status.

| Need                              | Doc                                                                       |
| --------------------------------- | ------------------------------------------------------------------------- |
| Understand instant vs queued cash | [buffer-mechanism.md](/rwa-trading-apis/cash-operations/buffer-mechanism) |
| Deposit cash into `mUSD`          | [deposits.md](/rwa-trading-apis/cash-operations/deposits)                 |
| Withdraw `mUSD` to tokens         | [withdrawals.md](/rwa-trading-apis/cash-operations/withdrawals)           |
| Track deposit/withdraw status     | [operation-status.md](/rwa-trading-apis/cash-operations/operation-status) |

API model: deposits turn wallet cash tokens into `mUsdBalance`; withdrawals turn `mUsdBalance` back into wallet cash tokens. Buffers only determine whether that happens instantly or after queued settlement.


# Deposits

Deposits turn wallet cash tokens into `mUSD` (`mUsdBalance`). See [getting-started/trader-questions.md](/rwa-trading-apis/getting-started/trader-questions) for the API flow and the distinction between wallet balance and `mUSD`.

Deposits may complete instantly if the Cashier `creditBuffer` can cover the `mUSD` credit and the token withdrawal buffer has room. Otherwise they are queued for final cash settlement. See [buffer-mechanism.md](/rwa-trading-apis/cash-operations/buffer-mechanism).

## Pre-authorization

Deposits transfer cash tokens from the user wallet to `Cashier` through `StockRouter`. The user must `approve` `StockRouter` as the spender before deposit:

```
ERC20(tokenAddress).approve(stockRouter, rawTokenAmount)
```

`rawTokenAmount = tokenAmount × 10^tokenDecimals`

### Mainnet cash token and approval spender addresses

| `x-api-chain-id` | Chain            | Cash token                                   | Approval spender (`StockRouter`)             |
| ---------------- | ---------------- | -------------------------------------------- | -------------------------------------------- |
| `8453`           | Base Mainnet     | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | `0x4f090d817fd83753988a7b0c1d76f170f8461be8` |
| `143`            | Monad Mainnet    | `0x754704Bc059F8C67012fEd69BC8A327a5aafb603` | `0x4f090d817fd83753988a7b0c1d76f170f8461be8` |
| `1`              | Ethereum Mainnet | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | `0x4f090d817fd83753988a7b0c1d76f170f8461be8` |

Check allowance:

```
GET /api/v1/users/{userId}/balance?spenderAddress={spender}
```

Use `tokenBalances[].walletAllowance`.

> Insufficient allowance: `/cash/deposits/calldata` still returns calldata, but the on-chain tx will fail.

Approval owner:

* `/cash/deposits/send` (One Click): API key bound `userAddress`
* `/cash/deposits/calldata` (self-submit): transaction sender wallet

## Build deposit calldata

```
POST /api/v1/cash/deposits/calldata
```

| Field          | Type            | Required | Description              |
| -------------- | --------------- | -------- | ------------------------ |
| `userAddress`  | string          | Yes      | User wallet.             |
| `tokenAddress` | string          | Yes      | Cash token address.      |
| `tokenAmount`  | string / number | Yes      | Amount (human-readable). |

Returns `method: deposit`, `value: "0"`.

## One Click deposit

```
POST /api/v1/cash/deposits/send
```

| Field          | Type            | Required | Description         |
| -------------- | --------------- | -------- | ------------------- |
| `tokenAddress` | string          | Yes      | Cash token address. |
| `tokenAmount`  | string / number | Yes      | Deposit amount.     |
| `gasLimit`     | number          | No       | Optional gas limit. |

Uses API key bound `userAddress` — not a request body field.

## Record deposit tx

```
POST /api/v1/cash/deposits/tx
```

| Field    | Type   | Required | Description      |
| -------- | ------ | -------- | ---------------- |
| `txHash` | string | Yes      | Deposit tx hash. |

## Query deposits

```
GET /api/v1/cash/deposits?page=1&limit=10
GET /api/v1/cash/deposits/{operationId}
```

`operationId` is backfilled by the indexer after parsing chain events.

See [operation-status.md](/rwa-trading-apis/cash-operations/operation-status) for response fields.


# Withdrawals

Withdrawals deduct `mUSD` (`mUsdBalance`) and return cash tokens to the user. They may complete instantly if the token withdrawal buffer has enough liquidity; otherwise they are queued for final cash settlement. See [buffer-mechanism.md](/rwa-trading-apis/cash-operations/buffer-mechanism).

## Build withdrawal calldata

```
POST /api/v1/cash/withdrawals/calldata
```

| Field          | Type            | Required | Description                          |
| -------------- | --------------- | -------- | ------------------------------------ |
| `userAddress`  | string          | Yes      | User wallet.                         |
| `tokenAddress` | string          | Yes      | Cash token address.                  |
| `creditAmount` | string / number | Yes      | Credit to withdraw (human-readable). |

Returns `method: withdraw`, `value: "0"`.

## One Click withdrawal

```
POST /api/v1/cash/withdrawals/send
```

Same body fields as calldata (no `userAddress` in body — uses API key bound address). Optional `gasLimit`.

Requires One Click enabled — see [trading/one-click-delegated.md](/rwa-trading-apis/trading/one-click-delegated).

## Record withdrawal tx

```
POST /api/v1/cash/withdrawals/tx
```

| Field    | Type   | Required | Description         |
| -------- | ------ | -------- | ------------------- |
| `txHash` | string | Yes      | Withdrawal tx hash. |

## Query withdrawals

```
GET /api/v1/cash/withdrawals?page=1&limit=10
GET /api/v1/cash/withdrawals/{operationId}
```

See [operation-status.md](/rwa-trading-apis/cash-operations/operation-status) for response fields.


# Operation Status

Shared fields for deposit and withdrawal detail responses.

Cash operations can be instant or queued depending on Cashier buffers. See [buffer-mechanism.md](/rwa-trading-apis/cash-operations/buffer-mechanism) for the buffer mechanism explanation.

## Response shape

`TradingCashOperationDetailRespDto`:

| Field                 | Type          | Description                |
| --------------------- | ------------- | -------------------------- |
| `mappingStatus`       | string / null | TX mapping status.         |
| `operationStatus`     | string / null | On-chain operation status. |
| `mapping`             | object        | Mapping record.            |
| `depositOperation`    | object / null | Deposit details.           |
| `withdrawalOperation` | object / null | Withdrawal details.        |

## depositOperation fields

| Field          | Type          | Description                                 |
| -------------- | ------------- | ------------------------------------------- |
| `operationId`  | string        | Deposit operation ID.                       |
| `userAddress`  | string        | User address.                               |
| `tokenAddress` | string        | Token address.                              |
| `status`       | string        | Operation status.                           |
| `isInstant`    | boolean       | Whether the operation used instant buffers. |
| `amount`       | number        | Token amount.                               |
| `creditAmount` | number        | `mUSD` amount.                              |
| `feeAmount`    | number        | Fee amount.                                 |
| `createTxHash` | string        | Creation tx.                                |
| `settleTxHash` | string / null | Settlement tx.                              |

## withdrawalOperation fields

| Field                | Type          | Description                                  |
| -------------------- | ------------- | -------------------------------------------- |
| `operationId`        | string        | Withdrawal operation ID.                     |
| `userAddress`        | string        | User address.                                |
| `tokenAddress`       | string        | Token address.                               |
| `status`             | string        | Operation status.                            |
| `isInstant`          | boolean       | Whether the operation used instant buffers.  |
| `creditAmount`       | number        | `mUSD` amount deducted.                      |
| `amount`             | number        | Token amount to pay out.                     |
| `feeAmount`          | number        | Fee amount.                                  |
| `failedPayoutAmount` | number / null | Token amount that failed to pay out, if any. |
| `createTxHash`       | string        | Creation tx.                                 |
| `settleTxHash`       | string / null | Settlement tx.                               |

`isInstant` indicates whether the operation used Cashier buffers. Queued operations can remain `processing` until final cash settlement completes.

## Status enums

| operationStatus | Description |
| --------------- | ----------- |
| `requested`     | Requested.  |
| `processing`    | Processing. |
| `settled`       | Settled.    |
| `closed`        | Closed.     |

`mappingStatus` reuses order mapping statuses — see [reference/enums.md](/rwa-trading-apis/reference/enums).

## Query endpoints

| Operation | List                           | Detail                                       |
| --------- | ------------------------------ | -------------------------------------------- |
| Deposit   | `GET /api/v1/cash/deposits`    | `GET /api/v1/cash/deposits/{operationId}`    |
| Withdraw  | `GET /api/v1/cash/withdrawals` | `GET /api/v1/cash/withdrawals/{operationId}` |

After self-submit, poll by `operationId` once the indexer backfills it from `txHash`.


# Buffer Mechanism

The stock contracts use a dual-buffer design so small deposits and withdrawals can settle instantly without waiting for the full asynchronous cash settlement path. This page explains the mechanism from an API integration perspective.

## Why Buffers Exist

Deposits and withdrawals may need asynchronous cash settlement. Waiting for that full path on every operation would add latency to every API flow, so `Cashier` can use pre-funded liquidity to apply the result first and let final settlement catch up later.

The Cashier therefore keeps pre-funded buffers:

| Buffer             | Unit                             | Used for            | API-visible result                |
| ------------------ | -------------------------------- | ------------------- | --------------------------------- |
| `creditBuffer`     | `mUSD`, 18-decimal WAD           | Instant deposits    | `mUsdBalance` updates immediately |
| `withdrawalBuffer` | Per-token amount, token decimals | Instant withdrawals | Cash token transfers immediately  |

If the relevant buffer can cover the operation safely, the operation is instant. Otherwise it is queued and settled later.

## Deposit Path

```mermaid
sequenceDiagram
    participant U as User
    participant R as StockRouter
    participant C as Cashier

    U->>R: deposit token
    R->>C: deposit(user, token, amount)
    alt creditBuffer available and withdrawalBuffer has room
        C->>C: reduce creditBuffer
        C->>C: increase withdrawalBuffer
        C->>U: credit mUsdBalance instantly
    else buffer criteria not met
        C->>C: record pending deposit
        Note over C: final settlement completes later
        C->>U: credit mUsdBalance later
    end
```

On an instant deposit:

* Cash token moves in from the wallet.
* Cashier consumes `creditBuffer`.
* `mUsdBalance` updates immediately.
* The token amount, net of fee, replenishes that token's `withdrawalBuffer` up to capacity.

On a queued deposit:

* Cashier records a pending deposit operation.
* `mUSD` is not credited immediately.
* Cashier credits `mUSD` after final settlement.

## Withdrawal Path

```mermaid
sequenceDiagram
    participant U as User
    participant R as StockRouter
    participant C as Cashier

    U->>R: withdraw credit
    R->>C: withdraw(user, token, creditAmount)
    C->>C: deduct mUsdBalance
    alt withdrawalBuffer available
        C->>C: reduce withdrawalBuffer
        C->>C: replenish creditBuffer
        C->>U: transfer token instantly
    else buffer criteria not met
        C->>C: record pending withdrawal
        Note over C: final settlement completes later
        C->>U: transfer token later
    end
```

On an instant withdrawal:

* `mUsdBalance` is deducted first.
* Cashier pays the token from `withdrawalBuffer`.
* The deducted credit replenishes `creditBuffer` up to capacity.

On a queued withdrawal:

* `mUsdBalance` is deducted when the withdrawal is requested.
* Cashier records a pending withdrawal operation.
* Cashier transfers tokens after final settlement.

## Instant Eligibility

The contracts intentionally avoid draining buffers in one operation. An operation must be small enough relative to the current buffer and the buffer must have enough available capacity.

| Operation  | Instant requirements, simplified                                                                                                               |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Deposit    | Deposit credit is no more than `creditBuffer / instantThresholdDivisor`, `creditBuffer` can cover it, and the token withdrawal buffer has room |
| Withdrawal | Withdrawal token value is no more than `withdrawalBuffer / instantThresholdDivisor`, and `withdrawalBuffer` can cover it                       |

MondayTrade production uses `instantThresholdDivisor = 5`, so an instant operation is normally limited to at most 20% of the relevant current buffer. Operators can configure this value.

## Cross-Buffer Replenishment

The two buffers feed each other:

| Operation          | Consumes                 | Replenishes              |
| ------------------ | ------------------------ | ------------------------ |
| Instant deposit    | `creditBuffer`           | Token `withdrawalBuffer` |
| Instant withdrawal | Token `withdrawalBuffer` | `creditBuffer`           |

This is why deposits help future withdrawals and withdrawals help future deposits. Buffer manager operations can also rebalance or bootstrap buffers without changing the API flow.

## API-Visible Results

| Result                         | Likely meaning                                          | Integration guidance                      |
| ------------------------------ | ------------------------------------------------------- | ----------------------------------------- |
| `isInstant = true`             | Operation used available buffer                         | Treat operation as instantly applied      |
| `operationStatus = processing` | Operation is queued or settlement path is still running | Continue polling; do not treat as failure |
| `operationStatus = settled`    | Cashier has applied final credit or payout              | Refresh portfolio state                   |

For deposits, track when `mUsdBalance` updates. For withdrawals, track when tokens arrive in the wallet. The buffer mechanism only changes timing, not the eventual accounting path.

## Integration Guidance

* Do not assume every deposit or withdrawal is instant.
* Treat queued cash operations as normal product behavior.
* Poll the operation detail endpoint and refresh portfolio after final status.
* If a large operation is queued, retrying the same amount does not make it instant; it is constrained by current buffer size and capacity.

Related docs:

| Need                       | Doc                                                                                                  |
| -------------------------- | ---------------------------------------------------------------------------------------------------- |
| Live buffer and fee config | [../market/on-chain-config.md](/rwa-trading-apis/market-data/on-chain-config) (`GET /api/v1/config`) |
| Deposit endpoints          | [deposits.md](/rwa-trading-apis/cash-operations/deposits)                                            |
| Withdrawal endpoints       | [withdrawals.md](/rwa-trading-apis/cash-operations/withdrawals)                                      |
| Cash status fields         | [operation-status.md](/rwa-trading-apis/cash-operations/operation-status)                            |
| Status model               | [../reference/status-model.md](/rwa-trading-apis/reference/status-model)                             |


# Overview

Docs for moving stock tokens between wallet balance and `Stock.stockBalance` (`exchangeBalance`).

| Need                             | Doc                                                                                        |
| -------------------------------- | ------------------------------------------------------------------------------------------ |
| Deposit stock token into `Stock` | [deposits-and-withdrawals.md](/rwa-trading-apis/stock-operations/deposits-and-withdrawals) |
| Withdraw stock token to wallet   | [deposits-and-withdrawals.md](/rwa-trading-apis/stock-operations/deposits-and-withdrawals) |


# Deposits & Withdrawals

Stock endpoints move ERC-20 stock tokens between wallet balance and `Stock.stockBalance`. The API surfaces `Stock.stockBalance` as `exchangeBalance`.

Cash endpoints are separate. Use `/cash/**` only for cash-token flows into or out of `Cashier`.

## Build Stock Deposit Calldata

```
POST /api/v1/stock/deposits/calldata
```

| Field          | Type            | Required | Description                        |
| -------------- | --------------- | -------- | ---------------------------------- |
| `userAddress`  | string          | Yes      | User wallet.                       |
| `tokenAddress` | string          | Yes      | Stock token contract address.      |
| `tokenAmount`  | string / number | Yes      | Human-readable stock token amount. |

The user wallet must approve `StockRouter` for the stock token before the transaction can move wallet stock into `Stock`.

## One Click Stock Deposit

```
POST /api/v1/stock/deposits/send
```

| Field          | Type            | Required | Description                        |
| -------------- | --------------- | -------- | ---------------------------------- |
| `tokenAddress` | string          | Yes      | Stock token contract address.      |
| `tokenAmount`  | string / number | Yes      | Human-readable stock token amount. |
| `gasLimit`     | number          | No       | Optional gas limit.                |

Uses API key bound `userAddress`; do not include `userAddress` in the request body.

## Record Stock Deposit Tx

```
POST /api/v1/stock/deposits/tx
```

| Field    | Type   | Required | Description            |
| -------- | ------ | -------- | ---------------------- |
| `txHash` | string | Yes      | Stock deposit tx hash. |

## Query Stock Deposits

```
GET /api/v1/stock/deposits?page=1&limit=10
GET /api/v1/stock/deposits/{operationId}
```

## Build Stock Withdrawal Calldata

```
POST /api/v1/stock/withdrawals/calldata
```

| Field          | Type            | Required | Description                        |
| -------------- | --------------- | -------- | ---------------------------------- |
| `userAddress`  | string          | Yes      | User wallet.                       |
| `tokenAddress` | string          | Yes      | Stock token contract address.      |
| `tokenAmount`  | string / number | Yes      | Human-readable stock token amount. |

Withdrawals deduct `Stock.stockBalance` and transfer ERC-20 stock tokens to the wallet.

## One Click Stock Withdrawal

```
POST /api/v1/stock/withdrawals/send
```

| Field          | Type            | Required | Description                        |
| -------------- | --------------- | -------- | ---------------------------------- |
| `tokenAddress` | string          | Yes      | Stock token contract address.      |
| `tokenAmount`  | string / number | Yes      | Human-readable stock token amount. |
| `gasLimit`     | number          | No       | Optional gas limit.                |

Uses API key bound `userAddress`; do not include `userAddress` in the request body.

## Record Stock Withdrawal Tx

```
POST /api/v1/stock/withdrawals/tx
```

| Field    | Type   | Required | Description               |
| -------- | ------ | -------- | ------------------------- |
| `txHash` | string | Yes      | Stock withdrawal tx hash. |

## Query Stock Withdrawals

```
GET /api/v1/stock/withdrawals?page=1&limit=10
GET /api/v1/stock/withdrawals/{operationId}
```

`operationId` is an API/indexer identifier for looking up the recorded stock operation. The `Stock` contract emits deposit and withdrawal events, but those events do not include a contract-native `operationId`.


# Overview

End-to-end guides for RWA API integrations.

| Need                       | Doc                                                                          |
| -------------------------- | ---------------------------------------------------------------------------- |
| First successful trade     | [quickstart-first-trade.md](/rwa-trading-apis/guides/quickstart-first-trade) |
| Self-submit flow           | [self-submit-on-chain.md](/rwa-trading-apis/guides/self-submit-on-chain)     |
| One Click flow             | [one-click-flow.md](/rwa-trading-apis/guides/one-click-flow)                 |
| TypeScript / viem examples | [demo-code.md](/rwa-trading-apis/guides/demo-code)                           |

Start with the quickstart, then use self-submit or One Click depending on who broadcasts router transactions.


# Quickstart: First API Trade

This guide walks through the smallest API flow for a partner integration:

1. Discover a tradable stock.
2. Confirm `mUSD`.
3. Deposit if needed.
4. Place a market buy.
5. Record and track the transaction.
6. Confirm the portfolio changed after settlement.

Use this as the smoke test before adding limit orders, withdrawals, or One Click.

## Flow

```mermaid
flowchart TB
    A[Configure API key] --> B[GET symbols]
    B --> C[Pick tradable symbol]
    C --> D[GET user balance]
    D --> E{Enough mUSD}
    E -->|no| F[Approve cash token]
    F --> G[Deposit cash]
    G --> H[Wait for mUSD]
    E -->|yes| I[Build market buy calldata]
    H --> I
    I --> J[Submit router transaction]
    J --> K[Record txHash]
    K --> L[Wait for orderId]
    L --> M[Poll order detail]
    M --> N[Confirm portfolio]
```

## 1. Configure Request Context

Every request must include:

| Header           | Example                               |
| ---------------- | ------------------------------------- |
| `x-api-key`      | Partner API key                       |
| `x-api-ts`       | Current Unix milliseconds             |
| `x-api-nonce`    | UUID                                  |
| `x-api-sign`     | HMAC-SHA256 authentication value      |
| `x-api-chain-id` | `8453`, `143`, `1`, or target chain   |
| `x-api-p`        | `MondayTrade` for the MondayTrade API |

Use the exact `/api/v1/...` path in the HMAC payload. Do not include the domain or `/rwa/trading`.

## 2. Discover a Tradable Stock

```
GET /api/v1/symbols
```

Pick an item where `tradable` is `true`. Relevant response fields:

| Field             | Use                               |
| ----------------- | --------------------------------- |
| `symbol`          | Symbol and quote lookup           |
| `contractAddress` | `stockAddress` for order requests |
| `price`           | Quote context                     |

Optional quote refresh:

```
GET /api/v1/prices/{symbol}
```

## 3. Check Portfolio

```
GET /api/v1/users/{userId}/balance
```

For a plain market buy, check `mUsdBalance`, the API field for `mUSD`. Wallet USDC is not buying power until it is deposited into `mUSD`. If the cash token is approved and instant deposit is available, `/api/v1/orders/with-deposit/calldata` can deposit and place the buy in one transaction.

## 4. Deposit Cash If Needed

First check allowance:

```
GET /api/v1/users/{userId}/balance?spenderAddress={spender}
```

If allowance is too low, have the user approve the spender from [cash/deposits.md](/rwa-trading-apis/cash-operations/deposits).

Then build deposit calldata:

```
POST /api/v1/cash/deposits/calldata
```

Example body:

```json
{
  "userAddress": "0x1111111111111111111111111111111111111111",
  "tokenAddress": "0x2222222222222222222222222222222222222222",
  "tokenAmount": "100"
}
```

Submit the returned `toAddress`, `value`, and `callData` on-chain. Then record:

```
POST /api/v1/cash/deposits/tx
```

Poll deposit detail until `operationStatus` is `settled` or `mUsdBalance` is updated.

## 5. Place a Market Buy

Build order calldata:

```
POST /api/v1/orders/calldata
```

Example body:

```json
{
  "stockAddress": "0x3333333333333333333333333333333333333333",
  "side": "Buy",
  "type": "Market",
  "notional": "10",
  "deadline": 1893456000
}
```

Submit the returned `StockRouter` transaction with your wallet client.

## 6. Record and Track the Order

Record the self-submitted tx:

```
POST /api/v1/orders/tx
```

Example:

```json
{
  "txHash": "0xabc..."
}
```

Then track:

```
GET /api/v1/orders/tx/{txHash}
GET /api/v1/orders/{orderId}
```

The transaction can be mined before execution and settlement are final. Treat the order as final only after it moves into history and portfolio balances reflect the settlement.

## 7. Confirm Portfolio

After settlement:

```
GET /api/v1/users/{userId}/balance
GET /api/v1/users/{userId}/positions
```

Expected result:

* `mUsdBalance` decreases by filled notional plus fees, with unspent `mUSD` refunded.
* The bought stock appears as `exchangeBalance`.
* Order detail shows settlement fields such as `settlePrice`, `settlePay`, and `settleReceive`.

## Next Steps

| Need                | Doc                                                                            |
| ------------------- | ------------------------------------------------------------------------------ |
| viem implementation | [demo-code.md](/rwa-trading-apis/guides/demo-code)                             |
| Debug failures      | [../reference/troubleshooting.md](/rwa-trading-apis/reference/troubleshooting) |
| Understand statuses | [../reference/status-model.md](/rwa-trading-apis/reference/status-model)       |
| Add One Click       | [one-click-flow.md](/rwa-trading-apis/guides/one-click-flow)                   |


# Self-Submit On-Chain

For integrators who sign and broadcast transactions with their own wallet or custodian.

## Workflow

```mermaid
sequenceDiagram
    participant Client
    participant API
    participant Chain
    participant Indexer

    Client->>API: POST /orders/calldata
    API-->>Client: calldata + toAddress
    Client->>Chain: Submit transaction
    Chain-->>Client: txHash
    Client->>API: POST /orders/tx { txHash }
    API-->>Client: Mapping record
    Indexer->>API: Parse on-chain events, backfill orderId
    Client->>API: GET /orders/{orderId}
    API-->>Client: Order status
```

## Steps

1. Call `/calldata` for the operation:
   * Orders: `POST /api/v1/orders/calldata`
   * Deposits: `POST /api/v1/cash/deposits/calldata`
   * Withdrawals: `POST /api/v1/cash/withdrawals/calldata`
2. Submit `toAddress`, `value`, and `callData` on-chain.
3. Call the matching `/tx` endpoint with `txHash`.
4. Indexer backfills `orderId` or `operationId`.
5. Poll status endpoints until settled.

> **Use a reliable RPC node.** `estimateGas`, `eth_call`, and `waitForTransactionReceipt` hit your RPC provider, not the MondayTrade API. Free/public endpoints (including viem's default `http()` transport and free-tier providers) may rate-limit or reject `eth_call` and gas estimation, failing *before* the API is involved. Pass your own node URL to `http("<url>")`.
>
> **Add a gas buffer.** Default `estimateGas` can under-estimate router calls on some chains (e.g. Monad) and the tx reverts out-of-gas. Multiply the estimate (e.g. `× 1.5–2`) before submitting.

## Record tx endpoints

| Operation   | Endpoint                           |
| ----------- | ---------------------------------- |
| Place order | `POST /api/v1/orders/tx`           |
| Deposit     | `POST /api/v1/cash/deposits/tx`    |
| Withdraw    | `POST /api/v1/cash/withdrawals/tx` |

## Status queries

| Operation | Endpoints                                                        |
| --------- | ---------------------------------------------------------------- |
| Order     | `GET /api/v1/orders/tx/{txHash}`, `GET /api/v1/orders/{orderId}` |
| Deposit   | `GET /api/v1/cash/deposits/{operationId}`                        |
| Withdraw  | `GET /api/v1/cash/withdrawals/{operationId}`                     |

> Same `txHash` from the same API key is idempotent. A `txHash` already recorded by another API key returns an error.

## Deposit prerequisite

Complete ERC-20 `approve` before deposit calldata execution. See [cash/deposits.md](/rwa-trading-apis/cash-operations/deposits) and [demo-code.md](/rwa-trading-apis/guides/demo-code).


# One Click Flow

For API keys with a bound user wallet address. The server submits transactions after the user delegates once.

## Authorization

```mermaid
sequenceDiagram
    participant User
    participant Client
    participant API
    participant Chain

    Client->>API: GET /1ct/status
    API-->>Client: { status: "disabled" }
    Client->>API: POST /1ct/prepare { deadline }
    API-->>Client: signPayload (EIP-712)
    Client->>User: Request signature
    User->>Client: signature (65 bytes)
    Client->>API: POST /1ct/enable { signature, deadline }
    API->>Chain: delegateBySig
    API-->>Client: { status: "enable" }
```

## Steps

1. `GET /api/v1/1ct/status` — check delegation.
2. If not enabled: `POST /api/v1/1ct/prepare` → user signs EIP-712 → `POST /api/v1/1ct/enable`.
3. Call `/send` endpoints for orders and cash.

Details: [trading/one-click-delegated.md](/rwa-trading-apis/trading/one-click-delegated). viem example: [demo-code.md](/rwa-trading-apis/guides/demo-code).

## Send endpoints

| Operation    | Endpoint                               |
| ------------ | -------------------------------------- |
| Place order  | `POST /api/v1/orders/send`             |
| Cancel order | `DELETE /api/v1/orders/{orderId}/send` |
| Deposit      | `POST /api/v1/cash/deposits/send`      |
| Withdraw     | `POST /api/v1/cash/withdrawals/send`   |

## Deposit prerequisite

User wallet must `approve` the cash token spender before `/cash/deposits/send`.

Approval owner is the API key bound `userAddress`. See [cash/deposits.md](/rwa-trading-apis/cash-operations/deposits) for spender addresses.


# Demo Code

TypeScript examples for RWA API integration. HMAC authentication uses Node `crypto`; on-chain actions use [viem](https://viem.sh).

```bash
npm install viem
```

Set environment variables:

```bash
export TRADING_API_KEY="your-api-key"
export TRADING_API_SECRET="your-api-secret"
export TRADING_USER_PRIVATE_KEY="0x..."   # self-submit / One Click user wallet
```

## API client with HMAC

```ts
import crypto from "node:crypto";

const BASE_URL = "https://mainnet-api.monday.trade/rwa/trading";

type HttpMethod = "GET" | "POST" | "DELETE";

interface TradingApiConfig {
    apiKey: string;
    apiSecret: string;
    chainId: number;
    productType: "MondayTrade";
}

function canonicalUri(path: string, query: Record<string, string | string[] | undefined> = {}): string {
    const pairs: string[] = [];
    for (const key of Object.keys(query).sort()) {
        const value = query[key];
        if (value === undefined || value === null) continue;
        if (Array.isArray(value)) {
            for (const item of value) pairs.push(`${key}=${item}`);
        } else {
            pairs.push(`${key}=${value}`);
        }
    }
    return pairs.length === 0 ? path : `${path}?${pairs.join("&")}`;
}

function signTradingApi(
    apiSecret: string,
    method: HttpMethod,
    path: string,
    query: Record<string, string | string[] | undefined>,
    timestamp: number,
    nonce: string,
    rawBody: string,
): string {
    const uri = canonicalUri(path, query);
    const payload = [method, uri, String(timestamp), nonce, rawBody].join("\n");
    return crypto.createHmac("sha256", apiSecret).update(payload, "utf8").digest("hex");
}

async function tradingApiRequest<T>(
    config: TradingApiConfig,
    method: HttpMethod,
    path: string,
    options: {
        query?: Record<string, string | string[] | undefined>;
        body?: unknown;
    } = {},
): Promise<T> {
    const query = options.query ?? {};
    const rawBody = options.body === undefined ? "" : JSON.stringify(options.body);
    const timestamp = Date.now();
    const nonce = crypto.randomUUID();
    const signature = signTradingApi(config.apiSecret, method, path, query, timestamp, nonce, rawBody);

    const url = new URL(`${BASE_URL}${canonicalUri(path, query)}`);
    const response = await fetch(url, {
        method,
        headers: {
            "content-type": "application/json",
            "x-api-key": config.apiKey,
            "x-api-ts": String(timestamp),
            "x-api-nonce": nonce,
            "x-api-sign": signature,
            "x-api-chain-id": String(config.chainId),
            "x-api-p": config.productType,
        },
        body: method === "GET" || method === "DELETE" ? undefined : rawBody,
    });

    const json = await response.json() as { code?: number; errMsg?: string; data?: T };
    if (json.code !== 200) {
        throw new Error(json.errMsg || `API error ${json.code}`);
    }
    return json.data as T;
}
```

## Self-submit market buy (viem)

Build calldata from the API, broadcast with viem, then record the tx hash.

```ts
import { createPublicClient, createWalletClient, http, type Address, type Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";

interface OrderCalldata {
    chainId: number;
    productType: string;
    toAddress: Address;
    value: string;
    callData: Hex;
    method: string;
}

const config: TradingApiConfig = {
    apiKey: process.env.TRADING_API_KEY!,
    apiSecret: process.env.TRADING_API_SECRET!,
    chainId: 8453,
    productType: "MondayTrade",
};

const account = privateKeyToAccount(process.env.TRADING_USER_PRIVATE_KEY as Hex);
const walletClient = createWalletClient({
    account,
    chain: base,
    transport: http(),
});
const publicClient = createPublicClient({ chain: base, transport: http() });

// Router calls under-estimate gas on some chains (e.g. Monad): the default
// estimate can leave the tx short and it reverts out-of-gas. Add a buffer.
async function submitTx(to: Address, callData: Hex, value: string): Promise<Hex> {
    const gas = (await publicClient.estimateGas({
        account: account.address,
        to,
        data: callData,
        value: BigInt(value),
    })) * 2n;
    return walletClient.sendTransaction({ to, data: callData, value: BigInt(value), gas });
}

async function placeMarketBuySelfSubmit(stockAddress: Address, notional: string): Promise<Hex> {
    const calldata = await tradingApiRequest<OrderCalldata>(config, "POST", "/api/v1/orders/calldata", {
        body: {
            stockAddress,
            side: "Buy",
            type: "Market",
            notional,
            deadline: Math.floor(Date.now() / 1000) + 3600,
        },
    });

    const txHash = await submitTx(calldata.toAddress, calldata.callData, calldata.value);

    await tradingApiRequest(config, "POST", "/api/v1/orders/tx", {
        body: { txHash },
    });

    return txHash;
}
```

## Deposit with ERC-20 approve (viem)

Approve the spender, then self-submit deposit calldata.

```ts
import { erc20Abi, maxUint256, type Address, type Hex } from "viem";

// Reuses the module-level `walletClient`, `publicClient`, `account`, `config`,
// and `submitTx` defined above.
const SPENDER: Address = "0x4f090d817fd83753988a7b0c1d76f170f8461be8"; // MondayTrade mainnet StockRouter

interface CashCalldata {
    chainId: number;
    productType: string;
    toAddress: Address;
    value: string;
    callData: Hex;
    method: string;
}

async function depositSelfSubmit(tokenAddress: Address, tokenAmount: string): Promise<Hex> {
    const approveHash = await walletClient.writeContract({
        address: tokenAddress,
        abi: erc20Abi,
        functionName: "approve",
        args: [SPENDER, maxUint256],
    });
    await publicClient.waitForTransactionReceipt({ hash: approveHash });

    const calldata = await tradingApiRequest<CashCalldata>(config, "POST", "/api/v1/cash/deposits/calldata", {
        body: {
            userAddress: account.address,
            tokenAddress,
            tokenAmount,
        },
    });

    const txHash = await submitTx(calldata.toAddress, calldata.callData, calldata.value);

    await tradingApiRequest(config, "POST", "/api/v1/cash/deposits/tx", {
        body: { txHash },
    });

    return txHash;
}
```

Spender addresses: [cash/deposits.md](/rwa-trading-apis/cash-operations/deposits).

## Order with deposit (self-submit)

Use `/orders/with-deposit/calldata` when the same transaction should deposit an approved token and place an order. For buy orders, the cash deposit must be eligible for instant deposit. The token must be approved before submitting the returned calldata.

```ts
async function placeMarketBuyWithDepositSelfSubmit(
    cashTokenAddress: Address,
    stockAddress: Address,
    depositAmount: string,
    notional: string,
): Promise<Hex> {
    const calldata = await tradingApiRequest<OrderCalldata>(config, "POST", "/api/v1/orders/with-deposit/calldata", {
        body: {
            stockAddress,
            depositTokenAddress: cashTokenAddress,
            depositAmount,
            side: "Buy",
            type: "Market",
            notional,
            deadline: Math.floor(Date.now() / 1000) + 3600,
        },
    });

    const txHash = await submitTx(calldata.toAddress, calldata.callData, calldata.value);

    await tradingApiRequest(config, "POST", "/api/v1/orders/tx", {
        body: { txHash },
    });

    return txHash;
}
```

## Stock deposit and withdrawal (self-submit)

Stock endpoints move ERC-20 stock tokens between wallet balance and `exchangeBalance`. Approve `StockRouter` for the stock token before calling stock deposit calldata.

```ts
async function depositStockSelfSubmit(stockTokenAddress: Address, tokenAmount: string): Promise<Hex> {
    const calldata = await tradingApiRequest<OrderCalldata>(config, "POST", "/api/v1/stock/deposits/calldata", {
        body: {
            userAddress: account.address,
            tokenAddress: stockTokenAddress,
            tokenAmount,
        },
    });

    const txHash = await submitTx(calldata.toAddress, calldata.callData, calldata.value);

    await tradingApiRequest(config, "POST", "/api/v1/stock/deposits/tx", {
        body: { txHash },
    });

    return txHash;
}

async function withdrawStockSelfSubmit(stockTokenAddress: Address, tokenAmount: string): Promise<Hex> {
    const calldata = await tradingApiRequest<OrderCalldata>(config, "POST", "/api/v1/stock/withdrawals/calldata", {
        body: {
            userAddress: account.address,
            tokenAddress: stockTokenAddress,
            tokenAmount,
        },
    });

    const txHash = await submitTx(calldata.toAddress, calldata.callData, calldata.value);

    await tradingApiRequest(config, "POST", "/api/v1/stock/withdrawals/tx", {
        body: { txHash },
    });

    return txHash;
}
```

## One Click enable (viem signTypedData)

User signs the EIP-712 payload from `/1ct/prepare`, then submits to `/1ct/enable`.

```ts
interface OneClickPrepare {
    delegatee: Address;
    signPayload: {
        domain: {
            name: string;
            version: string;
            chainId: number;
            verifyingContract: Address;
        };
        types: {
            // /1ct/prepare also returns EIP712Domain here; it must be stripped
            // before passing to viem signTypedData (viem derives it from `domain`).
            EIP712Domain?: Array<{ name: string; type: string }>;
            Delegate: Array<{ name: string; type: string }>;
        };
        primaryType: "Delegate";
        message: {
            user: Address;
            delegatee: Address;
            nonce: bigint | number;
            deadline: bigint | number;
        };
    };
    nonce: number;
    deadline: number;
}

async function enableOneClick(): Promise<void> {
    const deadline = Math.floor(Date.now() / 1000) + 3600;
    const prepared = await tradingApiRequest<OneClickPrepare>(config, "POST", "/api/v1/1ct/prepare", {
        body: { deadline },
    });

    const { signPayload } = prepared;
    if (account.address.toLowerCase() !== signPayload.message.user.toLowerCase()) {
        throw new Error("signer must match signPayload.message.user");
    }

    // viem derives EIP712Domain from `domain`; leaving it in `types` throws, so strip it.
    const types = { ...signPayload.types };
    delete types.EIP712Domain;
    const signature = await walletClient.signTypedData({
        domain: {
            ...signPayload.domain,
            chainId: BigInt(signPayload.domain.chainId),
        },
        types,
        primaryType: signPayload.primaryType,
        message: {
            ...signPayload.message,
            nonce: BigInt(signPayload.message.nonce),
            deadline: BigInt(signPayload.message.deadline),
        },
    });

    await tradingApiRequest(config, "POST", "/api/v1/1ct/enable", {
        body: { signature, deadline: prepared.deadline },
    });
}
```

After enable, use `/send` endpoints — see [one-click-flow.md](/rwa-trading-apis/guides/one-click-flow).

## One Click order (via `/send`)

Once One Click is enabled, place orders with `/orders/send`. The API builds the calldata and broadcasts it through `OneClickRouter`, paying gas on the user's behalf — no per-order wallet signature or self-broadcast. The body is the same as `/orders/calldata`, plus an optional `gasLimit` (set a buffer; router calls can under-estimate gas on some chains). The response is the order-tx mapping, not calldata: poll it (or `/orders/tx/{txHash}`) until `orderId` is populated.

```ts
interface OneClickOrderTx {
    id: string;
    chainId: number;
    productType: string;
    operationType: string;      // "trade"
    orderId: string | null;     // null until indexed, then the on-chain order id
    txHash: string;
    status: string;             // "pending" -> "new" -> ...
    createAt: string;
    updateAt: string;
}

async function placeLimitBuyOneClick(
    stockAddress: Address,
    quantity: string,
    price: string,
): Promise<OneClickOrderTx> {
    return tradingApiRequest<OneClickOrderTx>(config, "POST", "/api/v1/orders/send", {
        body: {
            stockAddress,
            side: "Buy",
            type: "Limit",
            quantity,
            price,
            timeInForce: "DAY", // production limit orders only accept DAY
            deadline: Math.floor(Date.now() / 1000) + 3600,
            gasLimit: 800000,   // gas buffer; API broadcasts via OneClickRouter
        },
    });
}
```

Cancel an open One Click order the same way — `DELETE /api/v1/orders/{orderId}/send` (query `deadline` required, `gasLimit` optional) — which also broadcasts through the router.

## Query portfolio

```ts
interface UserBalance {
    chainId: number;
    productType: string;
    address: Address;
    mUsdBalance: string;
    tokenBalances: Array<{
        symbol: string;
        stockSymbol?: string;
        isStock: boolean;
        walletBalance: string;
        exchangeBalance: string;
        price?: number;
    }>;
}

async function getPortfolio(userId: Address): Promise<UserBalance> {
    return tradingApiRequest<UserBalance>(
        config,
        "GET",
        `/api/v1/users/${userId.toLowerCase()}/balance`,
    );
}
```

## Query corporate actions

```ts
interface BrokerCorporateAction {
    symbol: string;
    type: "reverse_splits" | "forward_splits" | "unit_splits" | "stock_dividends" | "cash_dividends";
    time: string;
    exDate: string;
    recordDate: string;
    payableDate: string;
    processDate: string;
    info: Record<string, unknown>;
}

async function getCorporateActions(symbol: string): Promise<BrokerCorporateAction[]> {
    return tradingApiRequest<BrokerCorporateAction[]>(config, "GET", "/api/v1/corporate-action", {
        query: { symbol, types: ["cash_dividends"] },
    });
}
```

See also [authenticate/examples.md](/rwa-trading-apis/authentication/examples) for Node.js-only HMAC snippets.


# Overview

Reference docs for production RWA API integrations.

| Need                                | Doc                                                                                                                                                      |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| All endpoints                       | [endpoint-index.md](/rwa-trading-apis/reference/endpoint-index)                                                                                          |
| Enums and constraints               | [enums.md](/rwa-trading-apis/reference/enums)                                                                                                            |
| Status and UI state model           | [status-model.md](/rwa-trading-apis/reference/status-model)                                                                                              |
| Troubleshooting                     | [troubleshooting.md](/rwa-trading-apis/reference/troubleshooting)                                                                                        |
| API endpoint to contract effect     | [api-contract-map.md](/rwa-trading-apis/reference/api-contract-map)                                                                                      |
| Environments, chains, product types | [environments-and-chains.md](/rwa-trading-apis/reference/environments-and-chains)                                                                        |
| Sample responses                    | [sample-responses.md](/rwa-trading-apis/reference/sample-responses)                                                                                      |
| Production test checklist           | [integration-test-checklist.md](/rwa-trading-apis/reference/integration-test-checklist)                                                                  |
| Live OpenAPI snapshot               | [openapi.snapshot.json](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/reference/openapi.snapshot.json) |


# Endpoint Index

**43 endpoints** for RWA trading integrators. Permission: `READ_ONLY` or `WRITABLE` per API key scope.

Base path: `/api/v1`. Full URL prefix: `https://mainnet-api.monday.trade/rwa/trading`.

## Market data (6)

| Method | Path                                | Permission | Description            |
| ------ | ----------------------------------- | ---------- | ---------------------- |
| `GET`  | `/api/v1/config`                    | READ\_ONLY | On-chain market config |
| `GET`  | `/api/v1/symbols`                   | READ\_ONLY | Tradable symbols       |
| `GET`  | `/api/v1/prices/{symbol}`           | READ\_ONLY | Real-time quote        |
| `GET`  | `/api/v1/prices/{symbol}/history`   | READ\_ONLY | K-line history         |
| `GET`  | `/api/v1/underlying/{symbol}/price` | READ\_ONLY | Underlying quote       |
| `GET`  | `/api/v1/corporate-action`          | READ\_ONLY | Corporate actions      |

## Portfolio (3)

| Method | Path                               | Permission | Description |
| ------ | ---------------------------------- | ---------- | ----------- |
| `GET`  | `/api/v1/users/{userId}`           | READ\_ONLY | User info   |
| `GET`  | `/api/v1/users/{userId}/balance`   | READ\_ONLY | Balances    |
| `GET`  | `/api/v1/users/{userId}/positions` | READ\_ONLY | Positions   |

## Orders (10)

| Method   | Path                                   | Permission | Description                       |
| -------- | -------------------------------------- | ---------- | --------------------------------- |
| `GET`    | `/api/v1/orders`                       | READ\_ONLY | Order list                        |
| `POST`   | `/api/v1/orders/calldata`              | WRITABLE   | Build order calldata              |
| `POST`   | `/api/v1/orders/send`                  | WRITABLE   | One Click order                   |
| `POST`   | `/api/v1/orders/with-deposit/calldata` | WRITABLE   | Build order-with-deposit calldata |
| `POST`   | `/api/v1/orders/with-deposit/send`     | WRITABLE   | One Click order with deposit      |
| `POST`   | `/api/v1/orders/tx`                    | WRITABLE   | Record order tx                   |
| `GET`    | `/api/v1/orders/tx/{txHash}`           | READ\_ONLY | Order by tx                       |
| `GET`    | `/api/v1/orders/{orderId}`             | READ\_ONLY | Order detail                      |
| `DELETE` | `/api/v1/orders/{orderId}/calldata`    | WRITABLE   | Cancel calldata                   |
| `DELETE` | `/api/v1/orders/{orderId}/send`        | WRITABLE   | One Click cancel                  |

## Cash (10)

| Method | Path                                     | Permission | Description        |
| ------ | ---------------------------------------- | ---------- | ------------------ |
| `POST` | `/api/v1/cash/deposits/calldata`         | WRITABLE   | Deposit calldata   |
| `POST` | `/api/v1/cash/deposits/send`             | WRITABLE   | One Click deposit  |
| `POST` | `/api/v1/cash/deposits/tx`               | WRITABLE   | Record deposit tx  |
| `GET`  | `/api/v1/cash/deposits`                  | READ\_ONLY | Deposit list       |
| `GET`  | `/api/v1/cash/deposits/{operationId}`    | READ\_ONLY | Deposit detail     |
| `POST` | `/api/v1/cash/withdrawals/calldata`      | WRITABLE   | Withdraw calldata  |
| `POST` | `/api/v1/cash/withdrawals/send`          | WRITABLE   | One Click withdraw |
| `POST` | `/api/v1/cash/withdrawals/tx`            | WRITABLE   | Record withdraw tx |
| `GET`  | `/api/v1/cash/withdrawals`               | READ\_ONLY | Withdraw list      |
| `GET`  | `/api/v1/cash/withdrawals/{operationId}` | READ\_ONLY | Withdraw detail    |

## Stock (10)

| Method | Path                                      | Permission | Description                |
| ------ | ----------------------------------------- | ---------- | -------------------------- |
| `POST` | `/api/v1/stock/deposits/calldata`         | WRITABLE   | Stock deposit calldata     |
| `POST` | `/api/v1/stock/deposits/send`             | WRITABLE   | One Click stock deposit    |
| `POST` | `/api/v1/stock/deposits/tx`               | WRITABLE   | Record stock deposit tx    |
| `GET`  | `/api/v1/stock/deposits`                  | READ\_ONLY | Stock deposit list         |
| `GET`  | `/api/v1/stock/deposits/{operationId}`    | READ\_ONLY | Stock deposit detail       |
| `POST` | `/api/v1/stock/withdrawals/calldata`      | WRITABLE   | Stock withdrawal calldata  |
| `POST` | `/api/v1/stock/withdrawals/send`          | WRITABLE   | One Click stock withdrawal |
| `POST` | `/api/v1/stock/withdrawals/tx`            | WRITABLE   | Record stock withdrawal tx |
| `GET`  | `/api/v1/stock/withdrawals`               | READ\_ONLY | Stock withdrawal list      |
| `GET`  | `/api/v1/stock/withdrawals/{operationId}` | READ\_ONLY | Stock withdrawal detail    |

## One Click (4)

| Method | Path                  | Permission | Description        |
| ------ | --------------------- | ---------- | ------------------ |
| `GET`  | `/api/v1/1ct/status`  | READ\_ONLY | Delegation status  |
| `POST` | `/api/v1/1ct/prepare` | WRITABLE   | EIP-712 payload    |
| `POST` | `/api/v1/1ct/enable`  | WRITABLE   | Enable delegation  |
| `POST` | `/api/v1/1ct/disable` | WRITABLE   | Disable delegation |

## Doc map

| Module    | Doc                                                                                                                           |
| --------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Market    | [market/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/market/README.md)   |
| Portfolio | [portfolio/overview.md](/rwa-trading-apis/portfolio/overview)                                                                 |
| Orders    | [trading/](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/trading/README.md) |
| Cash      | [cash/](/rwa-trading-apis/cash-operations/cash)                                                                               |
| Stock     | [stock/](/rwa-trading-apis/stock-operations/stock)                                                                            |
| One Click | [trading/one-click-delegated.md](/rwa-trading-apis/trading/one-click-delegated)                                               |

## Related reference

| Need                          | Doc                                                                                     |
| ----------------------------- | --------------------------------------------------------------------------------------- |
| API to contract effects       | [api-contract-map.md](/rwa-trading-apis/reference/api-contract-map)                     |
| Environment and chain context | [environments-and-chains.md](/rwa-trading-apis/reference/environments-and-chains)       |
| Status model                  | [status-model.md](/rwa-trading-apis/reference/status-model)                             |
| Troubleshooting               | [troubleshooting.md](/rwa-trading-apis/reference/troubleshooting)                       |
| Sample responses              | [sample-responses.md](/rwa-trading-apis/reference/sample-responses)                     |
| Integration tests             | [integration-test-checklist.md](/rwa-trading-apis/reference/integration-test-checklist) |

OpenAPI snapshot: [openapi.snapshot.json](https://github.com/AnchoredLabs/anchored-knowledge/tree/api-doc/mondayTrade/02-products/rwa/api/reference/openapi.snapshot.json) (refreshed 2026-07-03 from live; server `https://mainnet-api.monday.trade/rwa/trading`)


# API ↔ Contract Map

This page maps partner API endpoints to the contract-level effect they prepare, submit, or query. Use it when debugging or explaining why an API call changes `mUSD`, `Stock.stockBalance`, or order state.

## Overview

```mermaid
flowchart TB
    API[Trading API] --> Router[StockRouter]
    Router --> Cashier[Cashier]
    Router --> Stock[Stock]
    Stock --> Cashier
```

## Market and Portfolio

| Endpoint                                | Contract relationship                        | Effect                                                                         |
| --------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------ |
| `GET /api/v1/config`                    | Reads on-chain Cashier/Exchange config cache | Returns fee rates, buffer state, and per-token cashier limits; no state change |
| `GET /api/v1/symbols`                   | Reads backend/token registry                 | Lists tradable stock tokens and contract addresses                             |
| `GET /api/v1/prices/{symbol}`           | Off-chain quote plus on-chain token context  | Quote display; no state change                                                 |
| `GET /api/v1/prices/{symbol}/history`   | Market data                                  | Historical display; no state change                                            |
| `GET /api/v1/underlying/{symbol}/price` | Market data                                  | Underlying quote; no state change                                              |
| `GET /api/v1/corporate-action`          | Corporate action data                        | Split/dividend data; no state change                                           |
| `GET /api/v1/users/{userId}/balance`    | Cashier + token balances + allowance         | Portfolio, buy power, deposit readiness                                        |
| `GET /api/v1/users/{userId}/positions`  | Indexed Stock state                          | Stock positions                                                                |

## Orders

| Endpoint                                    | Contract relationship                                                                                                       | Effect                                           |
| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| `POST /api/v1/orders/calldata`              | Encodes `StockRouter.placeMarketOrder` or `placeLimitOrder`                                                                 | Returns tx data; no state change until submitted |
| `POST /api/v1/orders/send`                  | OneClickRouter forwards to StockRouter                                                                                      | Places order and auto-records tx                 |
| `POST /api/v1/orders/with-deposit/calldata` | Encodes `StockRouter.depositAndMarketBuy`, `depositAndLimitBuy`, `depositStockAndMarketSell`, or `depositStockAndLimitSell` | Returns tx data for combined deposit + order     |
| `POST /api/v1/orders/with-deposit/send`     | OneClickRouter forwards combined deposit + order                                                                            | Submits combined flow and auto-records tx        |
| `POST /api/v1/orders/tx`                    | API/indexer mapping                                                                                                         | Links self-submitted tx to API key               |
| `GET /api/v1/orders`                        | API order mapping / indexed state                                                                                           | Lists mapped orders                              |
| `GET /api/v1/orders/tx/{txHash}`            | API tx mapping                                                                                                              | Finds order by tx                                |
| `GET /api/v1/orders/{orderId}`              | Indexed Stock state                                                                                                         | Shows open or historical order                   |
| `DELETE /api/v1/orders/{orderId}/calldata`  | Encodes `StockRouter.cancelLimitOrder`                                                                                      | Returns cancel tx data                           |
| `DELETE /api/v1/orders/{orderId}/send`      | OneClickRouter forwards cancel                                                                                              | Cancels via delegated execution                  |

## Cash

| Endpoint                                     | Contract relationship              | Effect                             |
| -------------------------------------------- | ---------------------------------- | ---------------------------------- |
| `POST /api/v1/cash/deposits/calldata`        | Encodes `StockRouter.deposit`      | Returns deposit tx data            |
| `POST /api/v1/cash/deposits/send`            | OneClickRouter forwards deposit    | Deposits from bound user           |
| `POST /api/v1/cash/deposits/tx`              | API/indexer mapping                | Links self-submitted deposit tx    |
| `GET /api/v1/cash/deposits`                  | Indexed Cashier state              | Lists deposits                     |
| `GET /api/v1/cash/deposits/{operationId}`    | Cash operation state               | Deposit detail and status          |
| `POST /api/v1/cash/withdrawals/calldata`     | Encodes `StockRouter.withdraw`     | Returns withdrawal tx data         |
| `POST /api/v1/cash/withdrawals/send`         | OneClickRouter forwards withdrawal | Withdraws from bound user          |
| `POST /api/v1/cash/withdrawals/tx`           | API/indexer mapping                | Links self-submitted withdrawal tx |
| `GET /api/v1/cash/withdrawals`               | Indexed Cashier state              | Lists withdrawals                  |
| `GET /api/v1/cash/withdrawals/{operationId}` | Cash operation state               | Withdrawal detail and status       |

## Stock

| Endpoint                                      | Contract relationship                    | Effect                                   |
| --------------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| `POST /api/v1/stock/deposits/calldata`        | Encodes `StockRouter.depositStock`       | Returns stock deposit tx data            |
| `POST /api/v1/stock/deposits/send`            | OneClickRouter forwards stock deposit    | Deposits stock from bound user           |
| `POST /api/v1/stock/deposits/tx`              | API/indexer mapping                      | Links self-submitted stock deposit tx    |
| `GET /api/v1/stock/deposits`                  | Indexed Stock state                      | Lists stock deposits                     |
| `GET /api/v1/stock/deposits/{operationId}`    | Stock operation state                    | Stock deposit detail                     |
| `POST /api/v1/stock/withdrawals/calldata`     | Encodes `StockRouter.withdrawStock`      | Returns stock withdrawal tx data         |
| `POST /api/v1/stock/withdrawals/send`         | OneClickRouter forwards stock withdrawal | Withdraws stock from bound user          |
| `POST /api/v1/stock/withdrawals/tx`           | API/indexer mapping                      | Links self-submitted stock withdrawal tx |
| `GET /api/v1/stock/withdrawals`               | Indexed Stock state                      | Lists stock withdrawals                  |
| `GET /api/v1/stock/withdrawals/{operationId}` | Stock operation state                    | Stock withdrawal detail                  |

For stock deposit and withdrawal detail endpoints, `operationId` is an API/indexer lookup identifier. It is not emitted as a native field by `Stock.depositStock` or `Stock.withdrawStock` events.

## One Click

| Endpoint                   | Contract relationship                  | Effect                 |
| -------------------------- | -------------------------------------- | ---------------------- |
| `GET /api/v1/1ct/status`   | Reads OneClickRouter delegate state    | Shows delegation state |
| `POST /api/v1/1ct/prepare` | Builds EIP-712 delegate payload        | No state change        |
| `POST /api/v1/1ct/enable`  | Calls `delegateBySig` through operator | Enables delegatee      |
| `POST /api/v1/1ct/disable` | Calls undelegate flow                  | Disables delegation    |

## Invariants for Integrators

* API calldata targets `StockRouter`; do not call Cashier or Stock directly.
* Buy orders lock `mUSD` in Cashier.
* Plain sell orders lock `Stock.stockBalance`, surfaced by the API as `exchangeBalance`.
* Order settlement updates `mUSD` and `exchangeBalance` asynchronously after execution.
* Cash operations can be instant or queued depending on Cashier buffers.


# Enums & Constraints

## Header enums

| Field            | Allowed values                                   |
| ---------------- | ------------------------------------------------ |
| `x-api-chain-id` | `8453`, `1`, `143`, `11155111`, `10143`, `84532` |
| `x-api-p`        | `MondayTrade`                                    |

## Permission enums

| Field    | Values      | Description        |
| -------- | ----------- | ------------------ |
| `access` | `READ_ONLY` | GET only.          |
| `access` | `WRITABLE`  | GET, POST, DELETE. |

## Order enums

| Field           | Values                         | Description                                                                                                                                                                    |
| --------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `side`          | `Buy`, `Sell`                  | Direction.                                                                                                                                                                     |
| `type`          | `Market`, `Limit`              | Order type.                                                                                                                                                                    |
| `timeInForce`   | `DAY`                          | Limit TIF. The contract enum includes `GTC`, `OPG`, `IOC`, `FOK`, `GTX`, `GTD`, and `CLS` for forward compatibility, but current production contracts reject non-`DAY` values. |
| `operationType` | `trade`, `deposit`, `withdraw` | Mapping type.                                                                                                                                                                  |

> Production limit orders currently only accept `DAY`; other `timeInForce` values will make the order transaction revert.

### Order status (mapped)

| Value            | Description             |
| ---------------- | ----------------------- |
| `Init`           | Initial.                |
| `Pending`        | Recorded or processing. |
| `New`            | New order identified.   |
| `Partial filled` | Partial fill.           |
| `Filled`         | Filled.                 |
| `Canceled`       | Canceled.               |
| `Expired`        | Expired.                |
| `Rejected`       | Rejected.               |
| `Failed`         | Failed.                 |

### On-chain status

| Value       | Description       |
| ----------- | ----------------- |
| `placing`   | Processing.       |
| `canceling` | Cancel in flight. |

### Broker raw status

```
init, pending, failed, new, partially_filled, filled, done_for_day,
canceled, expired, replaced, pending_cancel, pending_replace, accepted,
pending_new, accepted_for_bidding, stopped, rejected, suspended, calculated
```

## Cash status

### operationStatus

| Value        | Description |
| ------------ | ----------- |
| `requested`  | Requested.  |
| `processing` | Processing. |
| `settled`    | Settled.    |
| `closed`     | Closed.     |

### mappingStatus

Same as order mapping status enum above.

## Market data enums

### K-line interval

| Value | Description |
| ----- | ----------- |
| `1m`  | 1 minute    |
| `3m`  | 3 minutes   |
| `5m`  | 5 minutes   |
| `15m` | 15 minutes  |
| `1h`  | 1 hour      |
| `1d`  | 1 day       |
| `1w`  | 1 week      |

### Adjustment type

| Value      | Description    |
| ---------- | -------------- |
| `raw`      | No adjustment. |
| `split`    | Split.         |
| `dividend` | Dividend.      |
| `spin-off` | Spin-off.      |
| `all`      | All (default). |

### Corporate action types

| Value             | Description     |
| ----------------- | --------------- |
| `reverse_splits`  | Reverse split.  |
| `forward_splits`  | Forward split.  |
| `unit_splits`     | Unit split.     |
| `stock_dividends` | Stock dividend. |
| `cash_dividends`  | Cash dividend.  |

## Value constraints

| Field          | Constraint                                                                                                                       |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `stockAddress` | Valid EVM address. Lowercased by server.                                                                                         |
| `userAddress`  | Valid EVM address.                                                                                                               |
| `tokenAddress` | Valid EVM address.                                                                                                               |
| `quantity`     | > 0 in API input. Stock order quantities must encode to an 18-decimal WAD multiple of `1e9` (broker-facing 9-decimal precision). |
| `notional`     | > 0. Market-buy USD amount must use the production USD step: `0.01` when amount is `>= 1`, or `0.0001` when amount is `< 1`.     |
| `price`        | > 0. Limit price must use the production USD step: `0.01` when price is `>= 1`, or `0.0001` when price is `< 1`.                 |
| `tokenAmount`  | > 0, decimals ≤ token decimals, raw ≤ uint96.                                                                                    |
| `creditAmount` | > 0, up to 18 decimals, raw ≤ uint96.                                                                                            |
| `deadline`     | Unix seconds, > 0, ≤ `4294967295`.                                                                                               |
| `orderId`      | bytes32 hex (64 chars) for cancel.                                                                                               |
| `signature`    | 65-byte hex for One Click enable.                                                                                                |
| `gasLimit`     | Optional; server estimates if empty or ≤ 0.                                                                                      |


# Environments & Chains

Use this page to choose the correct base URL, chain ID, product type, and spender assumptions. These docs focus the MondayTrade RWA API.

## Base URL

Production Trading API:

```
https://mainnet-api.monday.trade/rwa/trading
```

All endpoint paths start with `/api/v1`.

HMAC authentication uses the path only:

```
/api/v1/symbols
```

Do not sign the domain or `/rwa/trading` prefix.

## Product Context

Every request must include both:

| Header           | Meaning                                                     |
| ---------------- | ----------------------------------------------------------- |
| `x-api-chain-id` | Chain context for the request                               |
| `x-api-p`        | Product context. Use `MondayTrade` for the MondayTrade API. |

The API key must have a matching `chainId + productType + access` permission.

## Supported Chain IDs

| Chain ID   | Chain            |
| ---------- | ---------------- |
| `8453`     | Base Mainnet     |
| `1`        | Ethereum Mainnet |
| `143`      | Monad Mainnet    |
| `11155111` | Ethereum Sepolia |
| `10143`    | Monad Testnet    |
| `84532`    | Base Sepolia     |

## Mainnet Contract Addresses

MondayTrade production uses the same deterministic proxy addresses on Base, Monad, and Ethereum:

| Contract         | Address                                      |
| ---------------- | -------------------------------------------- |
| `StockRouter`    | `0x4f090d817fd83753988a7b0c1d76f170f8461be8` |
| `Cashier`        | `0x8c1b182bb0fe4e8407404ffe37c974d6dacef3a9` |
| `Stock`          | `0x6d202d2f78aa26a7db51491416abf7f7a5003aac` |
| `OneClickRouter` | `0x102c30ac544aed8cbf838fdc1b1677ff16df0e65` |

## Mainnet Cash Tokens and Approval Spenders

| Chain ID | Chain            | Cash token                                   | Approval spender (`StockRouter`)             |
| -------- | ---------------- | -------------------------------------------- | -------------------------------------------- |
| `8453`   | Base Mainnet     | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | `0x4f090d817fd83753988a7b0c1d76f170f8461be8` |
| `143`    | Monad Mainnet    | `0x754704Bc059F8C67012fEd69BC8A327a5aafb603` | `0x4f090d817fd83753988a7b0c1d76f170f8461be8` |
| `1`      | Ethereum Mainnet | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | `0x4f090d817fd83753988a7b0c1d76f170f8461be8` |

Production cash config from `mondaytrade-contracts` `config/production`:

| Config                     | Value                    |
| -------------------------- | ------------------------ |
| Deposit rate               | `1`                      |
| Withdrawal rate            | `0.9979`                 |
| Minimum amount             | `90` cash-token units    |
| `creditBufferCapacity`     | `20000` `mUSD`           |
| `withdrawalBufferCapacity` | `10000` cash-token units |
| `instantThresholdDivisor`  | `5`                      |

## Request Context Checklist

Before sending state-changing requests, confirm:

| Item             | Expected                                       |
| ---------------- | ---------------------------------------------- |
| Base URL         | `https://mainnet-api.monday.trade/rwa/trading` |
| HMAC URI         | `/api/v1/...` only                             |
| `x-api-chain-id` | Matches wallet network                         |
| `x-api-p`        | Exact product value                            |
| API key scope    | Allows requested chain/product/access          |
| Deposit spender  | Matches chain/product                          |
| Wallet allowance | Sufficient before deposit                      |

## Common Mismatches

| Mismatch                    | Symptom                         | Fix                                        |
| --------------------------- | ------------------------------- | ------------------------------------------ |
| Wallet on wrong chain       | Tx fails or hits wrong contract | Switch wallet to `x-api-chain-id`          |
| API key lacks product scope | `Unauthorized`                  | Grant correct `chainId + x-api-p + access` |
| Wrong `x-api-p` casing      | `Unsupported product`           | Use exact `MondayTrade`                    |
| Wrong spender               | Deposit tx reverts              | Use spender for chain/product              |
| Wrong HMAC URI              | `Unauthorized`                  | Authenticate `/api/v1/...` only            |


# Status Model

This page explains how to interpret order and cash operation states.

## Order State Model

```mermaid
flowchart TB
    A[Build calldata or send] --> B[Tx submitted]
    B --> C[Tx mapping]
    C --> D[Order ID backfilled]
    D --> E{Order type}
    E -->|Market| F[placing]
    E -->|Limit| G[placing or open]
    F --> H[Execution result]
    G --> I{Fill or cancel}
    I -->|fill| H
    I -->|cancel| J[canceling]
    H --> K[historyOrder]
    J --> K
```

## API Objects

| Object         | Meaning                                               | Integration use                            |
| -------------- | ----------------------------------------------------- | ------------------------------------------ |
| `mapping`      | API key to tx/order linkage                           | Transaction accepted / waiting for indexer |
| `openOrder`    | On-chain order still active or canceling              | Open order or cancel in progress           |
| `historyOrder` | Settled, canceled, rejected, expired, or failed order | Final result                               |

## Order Statuses

| Status           | Meaning                             | Suggested handling |
| ---------------- | ----------------------------------- | ------------------ |
| `Init`           | Mapping or order initialized        | Pending            |
| `Pending`        | Processing                          | Pending            |
| `New`            | Order recognized                    | Open               |
| `Partial filled` | Some quantity filled                | Partially filled   |
| `Filled`         | Fully filled                        | Filled             |
| `Canceled`       | Canceled                            | Canceled           |
| `Expired`        | Expired by TIF/execution rules      | Expired            |
| `Rejected`       | Rejected by execution or validation | Failed / rejected  |
| `Failed`         | Processing failed                   | Failed             |

On-chain transient statuses:

| Status      | Meaning                   | Suggested handling |
| ----------- | ------------------------- | ------------------ |
| `placing`   | Order placement is active | Placing            |
| `canceling` | Cancel request is active  | Canceling          |

## Market Order Expectations

Market orders are intended for immediate execution, but settlement is still async.

```mermaid
flowchart LR
    A[Market order placed] --> B[Execution result]
    B --> C{Fill size}
    C -->|full| D[Filled]
    C -->|partial| E[Partial filled plus refund]
    C -->|zero| F[No fill plus refund]
```

Integration guidance:

* Do not show market order as final at tx mining time.
* Treat `placing` as pending until settlement appears.
* Refresh portfolio after final status.

## Limit Order Expectations

Limit orders can remain open.

```mermaid
flowchart TB
    A[Limit order placed] --> B[Open]
    B --> C{Execution event}
    C -->|fill| D[Filled or partial]
    C -->|cancel request| E[Canceling]
    C -->|expiry| F[Expired]
    E --> G[Canceled or partial cancel settlement]
```

Integration guidance:

* Show open limit orders separately from final history.
* Allow cancel only for open limit orders that are not already canceling.
* Current production contracts accept only `DAY` limit orders; treat expiry/fill/cancel transitions as asynchronous backend and settlement behavior after the order is placed.

## Cash Operation State Model

Cash operations use Cashier buffers for instant settlement when possible. If the relevant buffer cannot cover the operation safely, the operation follows the queued settlement path. See [../cash/buffer-mechanism.md](/rwa-trading-apis/cash-operations/buffer-mechanism).

```mermaid
flowchart TB
    A[Cash request tx] --> B[Mapping]
    B --> C[Operation created]
    C --> D{Instant buffer}
    D -->|available| E[settled]
    D -->|not available| F[processing]
    F --> G[Final cash settlement]
    G --> E
    E --> H[Portfolio updated]
```

## Cash Statuses

| `operationStatus` | Meaning                         | Suggested handling |
| ----------------- | ------------------------------- | ------------------ |
| `requested`       | Operation created               | Requested          |
| `processing`      | Waiting on settlement path      | Processing         |
| `settled`         | `mUSD` applied or cash paid out | Complete           |
| `closed`          | Closed lifecycle                | Closed             |

`mappingStatus` reuses the order mapping status enum. Use it to explain whether the tx was recorded and recognized.

## Portfolio Refresh Rules

Refresh portfolio after:

* Deposit operation reaches `settled`.
* Withdrawal operation reaches `settled` or `closed`.
* Order moves from `openOrder` to `historyOrder`.
* Cancel settlement completes.

Treat the status endpoint as authoritative for lifecycle and the portfolio endpoint as authoritative for balances.


# Sample Responses

These examples are representative. Use the live OpenAPI snapshot for exact schema names and the API response for production values.

## Unified Envelope

```json
{
  "code": 200,
  "errMsg": "",
  "data": {},
  "uuid": "b3d8d0b5-2f93-4f4e-bf06-2f0e5a9f6d1f",
  "t": 1782390000000
}
```

## Symbols

```json
{
  "code": 200,
  "errMsg": "",
  "data": [
    {
      "symbol": "AAPL",
      "contractAddress": "0x3333333333333333333333333333333333333333",
      "contractSymbol": "aAAPL",
      "contractName": "MondayTrade Apple Inc.",
      "decimals": 18,
      "onChainDecimals": 18,
      "tradable": true,
      "fractionable": true,
      "overnightTradable": false,
      "fractionalEhEnabled": false,
      "price": 180.5,
      "change24H": 1.2,
      "change24HPercent": 0.67,
      "logoUrl": "https://example.com/aapl.png",
      "lastUpdateTimestamp": 1782390000,
      "name": "Apple Inc.",
      "pdfUrl": "https://example.com/aapl.pdf",
      "volume24H": 1234567
    }
  ],
  "uuid": null,
  "t": null
}
```

## Portfolio Balance

```json
{
  "code": 200,
  "errMsg": "",
  "data": {
    "chainId": 143,
    "productType": "MondayTrade",
    "address": "0x1111111111111111111111111111111111111111",
    "mUsdBalance": "100.00",
    "tokenBalances": [
      {
        "address": "0x2222222222222222222222222222222222222222",
        "name": "USD Coin",
        "symbol": "USDC",
        "stockSymbol": null,
        "isStock": false,
        "decimals": 6,
        "price": null,
        "walletBalance": "250.00",
        "walletAllowance": "1000.00",
        "exchangeBalance": "0",
        "logoUrl": "https://example.com/usdc.png"
      },
      {
        "address": "0x3333333333333333333333333333333333333333",
        "name": "MondayTrade Apple Inc.",
        "symbol": "aAAPL",
        "stockSymbol": "AAPL",
        "isStock": true,
        "decimals": 18,
        "price": 180.5,
        "walletBalance": "0.25",
        "walletAllowance": "0",
        "exchangeBalance": "1.50",
        "logoUrl": "https://example.com/aapl.png"
      }
    ]
  },
  "uuid": null,
  "t": null
}
```

Interpretation:

* `mUsdBalance` is `mUSD` for buys and withdrawals.
* `walletBalance` is wallet-held ERC-20.
* `exchangeBalance` is the API view of `Stock.stockBalance`, used by plain sells.
* `walletAllowance` matters before deposits.

## Order Calldata

```json
{
  "code": 200,
  "errMsg": "",
  "data": {
    "chainId": 143,
    "productType": "MondayTrade",
    "toAddress": "0x4444444444444444444444444444444444444444",
    "value": "0",
    "callData": "0xabcdef...",
    "method": "placeMarketOrder"
  },
  "uuid": null,
  "t": null
}
```

Submit `toAddress`, `value`, and `callData` exactly as returned.

## Order Detail

```json
{
  "code": 200,
  "errMsg": "",
  "data": {
    "openOrder": null,
    "historyOrder": {
      "orderId": "0x0000000000000001000200001111111111111111111111111111111111111111",
      "userAddress": "0x1111111111111111111111111111111111111111",
      "side": "Buy",
      "type": "Market",
      "tif": null,
      "symbol": "AAPL",
      "placeNotional": "10.00",
      "placeQuantity": null,
      "pay": "10.00",
      "placePrice": null,
      "status": "Filled",
      "settleTxHash": "0xdef...",
      "settlePrice": "180.50",
      "settlePay": "9.95",
      "settleReceive": "0.0551",
      "mintFee": "0.01",
      "protocolFee": "0.01"
    }
  },
  "uuid": null,
  "t": null
}
```

## Deposit Detail

```json
{
  "code": 200,
  "errMsg": "",
  "data": {
    "mappingStatus": "Filled",
    "operationStatus": "settled",
    "mapping": {
      "txHash": "0xabc...",
      "operationType": "deposit"
    },
    "depositOperation": {
      "operationId": "0x1234...",
      "userAddress": "0x1111111111111111111111111111111111111111",
      "tokenAddress": "0x2222222222222222222222222222222222222222",
      "status": "settled",
      "isInstant": true,
      "amount": 100,
      "creditAmount": 100,
      "feeAmount": 0,
      "createTxHash": "0xabc...",
      "settleTxHash": "0xdef..."
    },
    "withdrawalOperation": null
  },
  "uuid": null,
  "t": null
}
```

## One Click Status

```json
{
  "code": 200,
  "errMsg": "",
  "data": {
    "status": "enable",
    "delegatee": "0x5555555555555555555555555555555555555555"
  },
  "uuid": null,
  "t": null
}
```

## Error Response

```json
{
  "code": 401,
  "errMsg": "Unauthorized",
  "data": null,
  "uuid": "b3d8d0b5-2f93-4f4e-bf06-2f0e5a9f6d1f",
  "t": 1782390000000
}
```

Use `uuid` when escalating issues.

## Market config

```json
{
  "code": 200,
  "data": {
    "cashierBuffer": {
      "chain": 10143,
      "productType": "MondayTrade",
      "address": "0x....",
      "instantThresholdDivisor": "1",
      "creditBuffer": "743810467000000000000",
      "creditBufferCapacity": "1000000000000000000000",
      "totalBalance": "156027003229608600000"
    },
    "exchangeFeeConfig": {
      "chainId": 10143,
      "productType": "MondayTrade",
      "mintFeeRate": "0",
      "protocolFeeRate": "0",
      "minOrderValue": "0",
      "txHash": "",
      "updatedAt": 1778477709
    },
    "cashierTokenConfig": {
      "0x534b2f3a21130d7a60830c2df862319e593943a3": {
        "chain": 10143,
        "productType": "MondayTrade",
        "cashierAddress": "0x....",
        "tokenAddress": "0x534b2f3a21130d7a60830c2df862319e593943a3",
        "minAmount": "1",
        "decimals": 6,
        "depositPaused": false,
        "withdrawPaused": false,
        "depositRate": "1",
        "withdrawalBuffer": "253689533",
        "withdrawalBufferCapacity": "1000000000",
        "withdrawalRate": "0.9969"
      }
    }
  },
  "errMsg": "",
  "t": null,
  "uuid": null
}

```

> Field names in `cashierBuffer` match the live OpenAPI schema (`CashierBufferRespDto`).


# Troubleshooting

Use this guide when an API request fails, a transaction reverts, or an order/cash operation appears stuck.

## First Triage

Start with the layer where the failure appears:

1. If API `code` is not `200`, fix request auth, scope, or parameters first.
2. If API succeeds but no transaction is submitted, inspect the calldata response and wallet client.
3. If the transaction is submitted but reverts, debug allowance, balance, deadline, chain, and router target.
4. If the transaction succeeds but the API cannot find it, record `txHash` or wait for indexer backfill.
5. If mapping exists but state is not final, poll order or cash detail endpoints.

## API Auth Fails

Symptoms:

* HTTP `400` with `code: 401`
* `Unauthorized`
* Signature, nonce, timestamp, IP, or permission errors

All of these return the **same** `401 Unauthorized` — the response body does **not** say which one failed. Rule them out one by one; for a new integration, check the IP whitelist and timestamp first.

| Check                                 | Fix                                                                                                                                                       |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| API key invalid, inactive, or expired | Confirm the key exists, is `active`, and `expires_at` is unset or future                                                                                  |
| Empty or mismatched IP whitelist      | Add your egress IP ([headers-and-permissions.md](/rwa-trading-apis/authentication/headers-and-permissions)); an empty whitelist rejects everything        |
| `x-api-ts` outside 45-second window   | Use current UTC milliseconds                                                                                                                              |
| Reused `x-api-nonce`                  | Use a unique UUID per request                                                                                                                             |
| Wrong HMAC URI                        | Authenticate `/api/v1/...`, not the full URL                                                                                                              |
| Literal `\n` in signed payload        | Join the 5 lines with **real newlines**, not the two-character `\n` (a common shell bug — see [signature.md](/rwa-trading-apis/authentication/signature)) |
| Query order mismatch                  | Sort query params by name before HMAC authentication                                                                                                      |
| Body mismatch                         | Sign the exact JSON string sent                                                                                                                           |
| Missing scope                         | Confirm `chainId + productType + access` permission                                                                                                       |

## Calldata Builds But Chain Transaction Reverts

Common causes:

| Symptom                                       | Likely cause                                                                                            | Fix                                                                                            |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| Deposit tx reverts                            | Insufficient ERC-20 allowance                                                                           | Check `walletAllowance`; approve spender                                                       |
| Deposit tx reverts                            | Wallet token balance too low                                                                            | Check `walletBalance`                                                                          |
| Order tx reverts                              | Plain buy has insufficient `mUsdBalance`                                                                | Deposit first, use `/orders/with-deposit/*` when eligible, or reduce `notional`                |
| Sell tx reverts                               | Plain sell has insufficient `exchangeBalance`, or order-with-deposit sell lacks stock allowance/balance | Approve stock, use `/orders/with-deposit/*`, or reduce quantity                                |
| Cancel tx reverts                             | Order not open or already canceling                                                                     | Query `/orders/{orderId}` first                                                                |
| Tx reverts out-of-gas (`gasUsed == gasLimit`) | Default `estimateGas` is too low on some chains (e.g. Monad) for router calls                           | Self-submit: add a gas buffer (`estimateGas × 1.5–2`). One Click: pass a sufficient `gasLimit` |
| Deadline error                                | `deadline` expired                                                                                      | Use a future Unix seconds value                                                                |
| Wrong chain                                   | Wallet on different chain than `x-api-chain-id`                                                         | Switch wallet network                                                                          |

## Deposit Not Credited Yet

A mined deposit transaction still needs API mapping and, for queued deposits, final cash settlement before `mUsdBalance` updates.

If the transaction succeeded:

1. Confirm `POST /api/v1/cash/deposits/tx` was called with the correct `txHash`.
2. Poll `GET /api/v1/cash/deposits/{operationId}`.
3. Check `operationStatus`.
4. Refresh `GET /api/v1/users/{userId}/balance`.

Queued deposits can remain `processing` while final cash settlement is still pending.

## Withdrawal Not Paid Out Yet

Withdrawals can be instant or queued. If queued:

1. `mUSD` is deducted first.
2. Final cash settlement completes later.
3. Cashier transfers tokens to the user when settlement completes.

Poll:

```
GET /api/v1/cash/withdrawals/{operationId}
```

Do not treat `processing` as failed unless the operation has an explicit failure status or support confirms an issue.

## Order Tx Mined But No Order ID

This usually means the indexer has not backfilled the mapping yet.

Check:

```
GET /api/v1/orders/tx/{txHash}
```

If missing:

1. Confirm the tx was sent to the returned `toAddress`.
2. Confirm the tx succeeded on the same chain as `x-api-chain-id`.
3. Confirm `POST /api/v1/orders/tx` was called by the same API key.
4. Wait for indexer backfill and retry.

## Order Open Too Long

For limit orders, open state can be normal. Practical lifecycle rules depend on `timeInForce` and backend execution.

> Production limit orders currently only accept `DAY`; other `timeInForce` values will make the order transaction revert.

For market orders, long open time usually means one of:

* Execution result not yet received.
* Final order result has not settled on-chain.
* Indexer/API has not refreshed status.

Use:

```
GET /api/v1/orders/{orderId}
```

Then inspect `openOrder.status` and history fields.

## One Click Send Fails

Check:

| Check                              | Fix                                                  |
| ---------------------------------- | ---------------------------------------------------- |
| `/1ct/status` is not `enable`      | Run prepare/sign/enable flow                         |
| API key has no bound `userAddress` | Configure API key user binding                       |
| Signer mismatch                    | EIP-712 signer must equal `signPayload.message.user` |
| Expired deadline                   | Prepare and sign a fresh payload                     |
| Deposit send fails                 | Bound user must approve cash token spender           |

## Escalation Data

When escalating to backend/support, include:

* Environment base URL
* `x-api-chain-id`
* `x-api-p`
* API response `code`, `errMsg`, `uuid`, `t`
* `txHash`
* `orderId` or `operationId`
* Wallet address / `userId`
* Request path and body (without API secret)


# Integration Test Checklist

Use this checklist before granting production access or enabling real user trading.

## Test Accounts and Scope

| Check                   | Expected                                |
| ----------------------- | --------------------------------------- |
| API key active          | Requests authenticate successfully      |
| IP whitelist configured | Requests only work from approved IPs    |
| `READ_ONLY` key         | GET works; POST/DELETE fails            |
| `WRITABLE` key          | GET/POST/DELETE work for approved scope |
| Product scope           | Only configured `x-api-p` works         |
| Chain scope             | Only configured `x-api-chain-id` works  |

## Authentication Tests

Required cases:

* Valid GET with sorted query params.
* Valid POST with exact raw body.
* Invalid timestamp older than 45 seconds.
* Duplicate nonce within the replay window.
* Body changed after signature.
* Missing `x-api-chain-id`.
* Wrong `x-api-p` casing.

Expected result: valid requests pass, and each invalid case fails with a clear auth or validation error.

## Market and Portfolio Tests

| Test                          | Expected                                                                                        |
| ----------------------------- | ----------------------------------------------------------------------------------------------- |
| `GET /config`                 | Returns `cashierBuffer`, `exchangeFeeConfig`, and `cashierTokenConfig` for scoped chain/product |
| `GET /symbols`                | Returns at least one known tradable stock                                                       |
| `GET /prices/{symbol}`        | Returns quote context                                                                           |
| `GET /corporate-action`       | Returns list or empty list without error                                                        |
| `GET /users/{userId}/balance` | Returns `mUsdBalance` and `tokenBalances`                                                       |
| `spenderAddress` query        | Returns `walletAllowance` for spender                                                           |

## Cash Tests

Required cases:

* Deposit calldata with valid `userAddress`, `tokenAddress`, `tokenAmount`.
* Deposit tx succeeds after approval.
* Deposit tx reverts or is blocked when allowance is missing.
* `POST /cash/deposits/tx` is idempotent for the same API key and tx.
* Deposit detail eventually reaches final status.
* Withdrawal calldata builds for available `mUsdBalance`.
* Withdrawal detail can be polled by `operationId`.

## Stock Movement Tests

Required cases:

* Stock deposit calldata builds for valid `userAddress`, `tokenAddress`, `tokenAmount`.
* Stock deposit tx succeeds after stock token approval.
* Stock withdrawal calldata builds for available `exchangeBalance`.
* Stock deposit and withdrawal details can be polled by `operationId`.

## Order Tests

| Test                             | Expected                                                                                                                                                                                                         |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Market buy calldata              | Returns router `toAddress`, `value`, `callData`                                                                                                                                                                  |
| Market sell calldata             | Plain sell requires sufficient `exchangeBalance`; wallet-held stock can be moved with `/stock/deposits/*` first                                                                                                  |
| Order-with-deposit buy calldata  | Requires cash token allowance and instant deposit eligibility                                                                                                                                                    |
| Order-with-deposit sell calldata | Requires stock token allowance and wallet stock balance                                                                                                                                                          |
| Limit buy calldata               | Requires `quantity`, `price`, and `timeInForce`; current production contracts accept only `DAY`                                                                                                                  |
| Limit sell calldata              | Requires `quantity`, `price`, and `timeInForce`; current production contracts accept only `DAY`. Plain sell requires sufficient `exchangeBalance`; wallet-held stock can be moved with `/stock/deposits/*` first |
| Cancel calldata                  | Works only for open limit orders                                                                                                                                                                                 |
| Record order tx                  | Backfills mapping/orderId                                                                                                                                                                                        |
| Order detail                     | Moves from open to history after settlement                                                                                                                                                                      |

Include negative tests:

* Missing `notional` for market buy.
* Missing `quantity` for market sell.
* Missing `price` for limit order.
* Non-`DAY` `timeInForce` for limit order.
* Expired `deadline`.
* Cancel market order.
* Cancel order owned by different API key.

## One Click Tests

Required cases:

* Status before enable.
* Prepare returns signer-matching `signPayload`.
* Signature by wrong wallet is rejected.
* Expired deadline is rejected.
* Enable succeeds with correct signature.
* `/send` order succeeds after enable.
* Deposit `/send` fails without token approval.
* Disable succeeds and blocks future `/send`.

## Reconciliation Tests

After each state-changing test, verify:

* API response `code` is `200`.
* Tx receipt succeeded.
* Mapping endpoint finds tx.
* Detail endpoint reaches expected state.
* Portfolio reflects final balances.
* Fees and partial fills are shown correctly when present.

## Production Readiness

Before go-live:

* Store API secrets securely.
* Log request path, response `uuid`, txHash, orderId, operationId.
* Never log API secret, wallet private key, or raw authorization material.
* Monitor delayed `processing` operations.
* Document queued cash behavior and async order settlement.
* Provide a manual support path for stuck tx/order/operation IDs.


# Introduction

Welcome to the Monday **Perpetual Trading** API documentation. This comprehensive guide will help you integrate with Monday's perpetual futures (perp) trading platform and access market data, trading functionality, and account management features.

> **Note:** This documentation covers the **Perpetual (Perp) API** only. It provides endpoints for perpetual futures trading, including order management, position handling, margin adjustments, and funding rate queries. Spot trading API documentation is maintained separately.

## What is Monday Perp API?

The Monday Perp API is a RESTful interface for perpetual futures trading that allows developers to:

* Access real-time and historical market data (instruments, orderbook, kline, tickers, funding)
* Manage API keys and One-Click Trade (1CT)
* Execute orders (market, limit, cancel, batch-cancel, fill) and close or adjust positions
* Prepare and submit approve transactions required before trading
* Query account balance, deposit/withdraw, and transaction history
* View open orders, order history, and trade (execution) history
* Manage liquidity positions and view liquidity history

## Key Features

### Real-time Market Data

* **Server Time**: Get synchronized server time
* **Instruments Info**: Retrieve trading instrument specifications
* **Kline Data**: Access candlestick chart data for technical analysis
* **Orderbook**: View real-time order book depth
* **Tickers**: Get 24-hour price statistics
* **Funding Rate History**: Track funding rate changes over time

### Account Management

* **Account Balance**: Check account balances and assets
* **Transaction History**: View deposit and withdrawal records
* **Position Management**: Monitor open positions and margin levels

### API Key Management

* **Create API Key**: Generate your first `apiKey` and `apiSecret` with wallet signature
* **List API Keys**: View existing API keys for the current wallet
* **Update API Key**: Adjust API key permissions and labels
* **Delete API Key**: Remove an API key you no longer need

### Trading Operations

* **Order Building**: Create market and limit orders with the required signing flow
* **Order Management**: Place, view, cancel, and batch-cancel orders
* **Order History**: Access historical order data
* **Trade Execution**: View detailed trade execution information
* **Margin Transfers**: Add or remove margin from positions
* **Approve Flow**: Prepare and submit approve transactions before trading

### Liquidity Provision

* **Liquidity Positions**: View active liquidity positions
* **Liquidity History**: Track liquidity addition and removal operations

## Getting Started

### 1. Create Your First API Key

To use the Monday API, you need to:

1. Create an account on the Monday platform
2. Call [Create API Key](/perp-trading-apis/api-keys/create_apikey) to generate your first `apiKey` and `apiSecret`
3. Store the returned `apiSecret` securely because it is shown only once
4. Use those credentials in the [Quick Start Guide](/perp-trading-apis/quick_start)

### 2. Read the Quick Start Guide

Before diving into the API, we recommend reading the [Quick Start Guide](/perp-trading-apis/quick_start) which covers:

* Authentication setup
* Generating signatures
* Making your first API call
* Error handling
* Best practices

### 3. Explore the API

* Review the [Summary](https://github.com/MondayTrade/monday-gitbook/blob/main/perp/SUMMARY.md) for a complete list of available endpoints
* Check [Error Codes](/perp-trading-apis/reference/error_codes) for error handling
* Reference [Enums](/perp-trading-apis/reference/enums) for available values and types

## Base URL

All API requests should be made to:

```
https://api.monday.trade
```

API endpoints use the path prefix `/v4/public/trader/`, so the full URL format is:

```
https://api.monday.trade/v4/public/trader/{endpoint}
```

## Authentication

All API endpoints require authentication using:

* **API Key** (`X-Api-Key`): Your public API key
* **Secret Key**: Your private secret key (used for signature generation)
* **Signature** (`X-Api-Sign`): HMAC-SHA256 signature with Base64 encoding
* **Timestamp** (`X-Api-Ts`): Request timestamp in milliseconds
* **Chain ID** (`X-Chain-Id`): Current chain identifier

The signature is generated using the format: `timestamp + method + request_path + body`

Detailed authentication instructions and code examples can be found in the [Quick Start Guide](/perp-trading-apis/quick_start).

## Response Format

All API responses follow a standard format:

```json
{
    "code": 200,
    "msg": "",
    "data": {},
    "requestId": "bbf4fa1a-0f41-449f-8d9c-44fdceae0bf7"
}
```

### Success Response

```json
{
    "code": 200,
    "msg": "",
    "data": {
        // Response data here
    },
    "requestId": "bbf4fa1a-0f41-449f-8d9c-44fdceae0bf7"
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Error message here",
    "data": {},
    "requestId": "bbf4fa1a-0f41-449f-8d9c-44fdceae0bf7"
}
```

## Rate Limits

* **Rate Limit**: 120 requests per minute per API key
* **Rate limit headers**: Monitor your rate limit status via response headers
* **Best Practice**: Implement exponential backoff for retry logic

## Error Handling

### HTTP Status Codes

* **200**: Success
* **400**: Bad Request - Invalid parameters
* **401**: Unauthorized - Invalid API credentials
* **403**: Forbidden - Insufficient permissions
* **429**: Too Many Requests - Rate limit exceeded
* **500**: Internal Server Error

For detailed error codes and handling strategies, refer to [Error Codes Documentation](/perp-trading-apis/reference/error_codes).

## Data Types

### String

Most text fields (symbols, addresses, etc.) are returned as strings.

### Number

Numeric values can be integers or decimals. Large numbers may be returned as strings to prevent precision loss.

### Timestamp

Timestamps are returned in milliseconds since Unix epoch.

### Address

Blockchain addresses (contract addresses, wallet addresses) are returned as hexadecimal strings.

## Security Best Practices

1. **Keep API Credentials Secure**
   * Never share your API Key or Secret Key
   * Don't commit API credentials to version control
   * Rotate API keys regularly
2. **Use HTTPS Only**
   * All API requests must use HTTPS
   * Never make API calls over HTTP
3. **Implement Proper Error Handling**
   * Handle all error responses gracefully
   * Implement retry logic with exponential backoff
   * Log errors for debugging
4. **Monitor Rate Limits**
   * Track your request rate
   * Implement rate limiting on your side
   * Avoid unnecessary API calls
5. **Validate Inputs**
   * Validate all parameters before making requests
   * Check data types and ranges
   * Use appropriate enums from the documentation

## Code Examples

The API documentation includes code examples in multiple languages:

* **cURL**: For command-line testing
* **JavaScript (Fetch)**: For web applications
* **Python (requests)**: For Python applications

You can find language-specific examples in each API endpoint documentation.

## Support and Resources

### Documentation

* [Quick Start Guide](/perp-trading-apis/quick_start) - Get started quickly
* [Summary](https://github.com/MondayTrade/monday-gitbook/blob/main/perp/SUMMARY.md) - Complete endpoint reference
* [Error Codes](/perp-trading-apis/reference/error_codes) - Error handling guide
* [Enums](/perp-trading-apis/reference/enums) - Available values and types

### Getting Help

For API support and questions, please contact:

* Email: \[support email]
* Documentation: \[documentation URL]
* Community: \[community forum URL]

## Version Information

* **Current Version**: v4
* **Base URL**: <https://api.monday.trade/v4/public>
* **API Format**: RESTful
* **Data Format**: JSON

## Next Steps

1. Read the [Quick Start Guide](/perp-trading-apis/quick_start)
2. Browse the [Summary](https://github.com/MondayTrade/monday-gitbook/blob/main/perp/SUMMARY.md)
3. Explore specific endpoint documentation
4. Implement error handling
5. Start building your integration

## Changelog

### Version 5

* Updated response format
* Added blockInfo to responses
* Improved error handling
* Enhanced documentation

***

Happy coding with Monday API!


# Quick Start

## Overview

This guide provides a comprehensive overview of how to use the Monday API endpoints. It covers the essential steps from authentication to making your first API call.

**Important**: All API endpoints require authentication.

## Prerequisites

Before you begin, ensure you have:

* A Monday account
* API credentials created by calling `/v4/public/trader/api-key/create`:
  * **API Key**: Your public API key
  * **Secret Key**: Your private secret key (keep this secure!)
* Basic understanding of REST APIs
* Your preferred programming language environment set up (Python recommended for API examples)

## Authentication

All API endpoints (prefixed with `/v4/public/trader/`) require authentication using API key headers and HMAC-SHA256 signature authentication.

### API Authentication

API endpoints (prefixed with `/v4/public/trader/`) use HMAC-SHA256 signature authentication.

#### Required Headers

```http
X-Api-Key: [your_api_key]
X-Api-Sign: [signature]
X-Api-Ts: [timestamp]
X-Chain-Id: [chain_id]
```

#### Signature Generation

The signature is generated using HMAC-SHA256 and Base64 encoding:

**Message Format:**

```
message = timestamp + method + request_path + body
```

**Signature Calculation:**

```
signature = base64(hmac_sha256(message, secret_key))
```

#### Python Implementation Example

```python
import hmac
import hashlib
import base64
import json
import time
from urllib.parse import urlencode, parse_qs

def compute_signature(message, secret_key):
    """Compute HMAC-SHA256 signature"""
    mac = hmac.new(
        secret_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    )
    return base64.b64encode(mac.digest()).decode('utf-8')

def sort_query_string(query_string):
    """Sort query parameters alphabetically (for GET requests)"""
    if not query_string:
        return ""
    params = parse_qs(query_string, keep_blank_values=True)
    sorted_params = []
    for key in sorted(params.keys()):
        for value in params[key]:
            sorted_params.append(f"{key}={value}")
    return "&".join(sorted_params)

def sort_json_keys(json_str):
    """Sort JSON keys alphabetically (for POST JSON requests)"""
    if not json_str:
        return ""
    try:
        data = json.loads(json_str)
        return json.dumps(data, sort_keys=True, separators=(',', ':'))
    except json.JSONDecodeError:
        return json_str

def build_message(timestamp, method, request_path, body="", content_type=""):
    """Build signature message"""
    method = method.upper()
    
    # Handle GET request query parameters
    if method == "GET" and "?" in request_path:
        path, query = request_path.split("?", 1)
        sorted_query = sort_query_string(query)
        request_path = f"{path}?{sorted_query}"
    
    # Handle POST request JSON body
    if method in ["POST", "PUT", "PATCH"] and body:
        if content_type and "application/json" in content_type.lower():
            body = sort_json_keys(body)
    
    return timestamp + method + request_path + body

def generate_trader_signature(secret_key, timestamp, method, request_path, body="", content_type=""):
    """Generate API signature"""
    message = build_message(timestamp, method, request_path, body, content_type)
    return compute_signature(message, secret_key)
```

#### Important Notes for API

1. **Timestamp Format**: Use milliseconds since Unix epoch

   ```python
   timestamp = str(int(time.time() * 1000))
   ```
2. **Time Window**: Requests are valid within 30 seconds of the timestamp
3. **GET Requests**: Query parameters must be sorted alphabetically by key
   * Example: `symbol=BTC/USDT&side=buy&amount=0.001` → `amount=0.001&side=buy&symbol=BTC/USDT`
4. **POST Requests**:
   * JSON body keys must be sorted alphabetically
   * Use compact JSON format (no spaces): `json.dumps(data, sort_keys=True, separators=(',', ':'))`
   * Form body: No sorting required, maintain original order

## Base URL

All API requests should be made to:

```
https://api.monday.trade
```

API endpoints use the path prefix `/v4/public/trader/`, so the full URL format is:

```
https://api.monday.trade/v4/public/trader/{endpoint}
```

**Important**: When generating signatures, use the full path including `/v4/public/trader/` (e.g., `/v4/public/trader/server/time`).

## Step-by-Step Examples

### API Examples

#### Step 1: Get Server Time (API)

First, synchronize with the server time:

```python
import hmac
import hashlib
import base64
import json
import requests
from datetime import datetime, timezone

def generate_trader_signature(secret_key, timestamp, method, request_path, body="", content_type=""):
    """Generate API signature"""
    # Build message: timestamp + method + request_path + body
    message = timestamp + method.upper() + request_path
    if body and method.upper() in ["POST", "PUT", "PATCH"]:
        if content_type and "application/json" in content_type.lower():
            # Sort JSON keys
            data = json.loads(body)
            body = json.dumps(data, sort_keys=True, separators=(',', ':'))
        message += body
    
    # Compute HMAC-SHA256 signature
    mac = hmac.new(
        secret_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    )
    return base64.b64encode(mac.digest()).decode('utf-8')

# Set your API credentials
api_key = "<your-api-key>"
secret_key = "<your-secret-key>"
chain_id = 143

# Generate timestamp in milliseconds
timestamp = str(int(time.time() * 1000))

# Generate signature
request_path = "/v4/public/trader/server/time"
signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)

# Make request
headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
}

response = requests.get("https://api.monday.trade/v4/public/trader/server/time", headers=headers)
data = response.json()
print("Server time:", data)
```

#### Step 2: Get Orderbook (API)

Retrieve orderbook data:

```python
# Generate timestamp
timestamp = str(int(time.time() * 1000))

# Build request path with sorted query parameters
# Note: Query parameters must be sorted alphabetically
request_path = "/v4/public/trader/market/orderbook?limit=100&symbol=BTC/USDT"  # limit comes before symbol alphabetically
signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)

headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
}

response = requests.get(
    "https://api.monday.trade/v4/public/trader/market/orderbook?symbol=BTC/USDT&limit=100",
    headers=headers
)
data = response.json()
print("Orderbook:", data)
```

#### Step 3: Get Account Balance (API)

Retrieve your account balance:

```python
# Generate timestamp
timestamp = str(int(time.time() * 1000))

# Build request path
request_path = "/v4/public/trader/account/balance"
signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)

headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
}

response = requests.get("https://api.monday.trade/v4/public/trader/account/balance", headers=headers)
data = response.json()
print("Account balance:", data)
```

#### Step 4: POST Request Example (API)

Example of a POST request with JSON body:

```python
# Generate timestamp
timestamp = str(int(time.time() * 1000))

# Build request path
request_path = "/v4/public/trader/order/market"

# Prepare body (will be sorted by keys)
body_data = {
    "symbol": "BTC/USDT",
    "side": "buy",
    "amount": "0.001",
    "price": "50000"
}
body = json.dumps(body_data, sort_keys=True, separators=(',', ':'))

# Generate signature (body will be sorted)
signature = generate_trader_signature(secret_key, timestamp, "POST", request_path, body, "application/json")

headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
    "Content-Type": "application/json",
}

response = requests.post("https://api.monday.trade/v4/public/trader/order/market", headers=headers, data=body)
data = response.json()
print("Order placed:", data)
```

## Error Handling

Always implement proper error handling:

```javascript
try {
    const response = await fetch(apiUrl, options);
    const data = await response.json();

    if (data.code !== 200) {
        console.error("API Error:", data.msg);
        return;
    }

    // Process successful response
    console.log("Success:", data.data);
} catch (error) {
    console.error("Request failed:", error);
}
```

## Rate Limits

Be aware of rate limits:

* **All Endpoints**: 120 requests per minute

Implement rate limiting in your application to avoid hitting these limits.

## Best Practices

### 1. Use HTTPS

Always use HTTPS for API requests to ensure data security.

### 2. Handle Timestamps

* Use server time for synchronization
* Include proper timestamp in requests
* Account for network latency

### 3. Implement Retry Logic

```javascript
async function apiCallWithRetry(url, options, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            const response = await fetch(url, options);
            if (response.ok) {
                return await response.json();
            }
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
        }
    }
}
```

### 4. Validate Responses

Always validate API responses before processing:

```javascript
function validateResponse(data) {
    if (!data || typeof data.code === "undefined") {
        throw new Error("Invalid response format");
    }

    if (data.code !== 200) {
        throw new Error(`API Error: ${data.msg}`);
    }

    return data.data;
}
```

### 5. Use Pagination

For endpoints that return large datasets, use pagination:

```javascript
async function getAllData(endpoint, params = {}) {
    let allData = [];
    let cursor = null;

    do {
        const response = await fetch(
            `${endpoint}?${new URLSearchParams({
                ...params,
                limit: 50,
                ...(cursor && { cursor }),
            })}`
        );

        const data = await response.json();
        allData = allData.concat(data.data);
        cursor = data.data.nextPageCursor;
    } while (cursor);

    return allData;
}
```

## Testing Your Setup

Test your API setup with this Python script:

```python
import hmac
import hashlib
import base64
import json
import requests
from datetime import datetime, timezone

def generate_trader_signature(secret_key, timestamp, method, request_path, body="", content_type=""):
    """Generate API signature"""
    message = timestamp + method.upper() + request_path
    if body and method.upper() in ["POST", "PUT", "PATCH"]:
        if content_type and "application/json" in content_type.lower():
            data = json.loads(body)
            body = json.dumps(data, sort_keys=True, separators=(',', ':'))
        message += body
    
    mac = hmac.new(
        secret_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    )
    return base64.b64encode(mac.digest()).decode('utf-8')

def test_trader_api_setup():
    """Test API setup"""
    try:
        # Test 1: Get server time
        timestamp = str(int(time.time() * 1000))
        request_path = "/v4/public/trader/server/time"
        signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)
        
        headers = {
            "X-Api-Key": api_key,
            "X-Api-Sign": signature,
            "X-Api-Ts": timestamp,
            "X-Chain-Id": str(chain_id),
        }
        
        response = requests.get("https://api.monday.trade/v4/public/trader/server/time", headers=headers)
        time_data = response.json()
        print("✓ Server time:", time_data)
        
        # Test 2: Get orderbook
        timestamp = str(int(time.time() * 1000))
        request_path = "/v4/public/trader/market/orderbook?limit=50&symbol=BTC/USDT"  # Sorted: limit before symbol
        signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)
        
        headers = {
            "X-Api-Key": api_key,
            "X-Api-Sign": signature,
            "X-Api-Ts": timestamp,
            "X-Chain-Id": str(chain_id),
        }
        
        response = requests.get(
            "https://api.monday.trade/v4/public/trader/market/orderbook?symbol=BTC/USDT&limit=50",
            headers=headers
        )
        orderbook_data = response.json()
        print("✓ Orderbook retrieved")
        
        # Test 3: Get account balance
        timestamp = str(int(time.time() * 1000))
        request_path = "/v4/public/trader/account/balance"
        signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)
        
        headers = {
            "X-Api-Key": api_key,
            "X-Api-Sign": signature,
            "X-Api-Ts": timestamp,
            "X-Chain-Id": str(chain_id),
        }
        
        response = requests.get("https://api.monday.trade/v4/public/trader/account/balance", headers=headers)
        balance_data = response.json()
        print("✓ Account balance retrieved")
        
        print("✓ All tests passed!")
    except Exception as e:
        print(f"✗ Test failed: {e}")

# Run tests
if __name__ == "__main__":
    # Use your own credentials
    api_key = "<your-api-key>"
    secret_key = "<your-secret-key>"
    chain_id = 143
    
    test_trader_api_setup()
```

## API Endpoints

The API provides the following endpoints (all prefixed with `/v4/public/trader/`):

* `/v4/public/trader/server/time` - Get server time
* `/v4/public/trader/market/kline` - Get kline/candlestick data
* `/v4/public/trader/market/instruments` - Get instrument information
* `/v4/public/trader/market/tickers` - Get ticker data
* `/v4/public/trader/market/funding/history` - Get funding rate history
* `/v4/public/trader/market/orderbook` - Get orderbook data
* `/v4/public/trader/order/list` - Get open orders
* `/v4/public/trader/order/history` - Get order history
* `/v4/public/trader/execution/history` - Get trade execution history
* `/v4/public/trader/position/list` - Get position information
* `/v4/public/trader/liquidity/list` - Get liquidity positions
* `/v4/public/trader/liquidity/history` - Get liquidity history
* `/v4/public/trader/account/balance` - Get account balance
* `/v4/public/trader/account/transactions` - Get transaction history
* `/v4/public/trader/api-key/list` - Get API key list
* `/v4/public/trader/api-key/create` - Create API key
* `/v4/public/trader/api-key/update` - Update API key
* `/v4/public/trader/api-key/delete` - Delete API key

## Next Steps

1. **Create API Credentials**: If you do not have credentials yet, call `/v4/public/trader/api-key/create` to generate your first `apiKey` and `apiSecret`
2. **Test Basic Endpoints**: Start with simple endpoints like `/v4/public/trader/server/time`
3. **Understand Signature Requirements**:
   * GET requests: Sort query parameters alphabetically
   * POST requests: Sort JSON keys alphabetically
   * Use milliseconds since Unix epoch
4. **Explore Market Data**: Access market data endpoints to understand available instruments
5. **Check Account Status**: Verify your account balance and permissions
6. **Monitor Positions**: Use position endpoints to track your current positions
7. **Review Order History**: Analyze your trading history and performance
8. **Implement Trading Logic**: Build your trading strategies using the API

## Support

For additional help:

* Check the individual API documentation files
* Review error codes and messages
* Ensure your API keys have the correct permissions
* Verify your request format matches the documentation

## Security Notes

* Never expose your API secret key or passphrase in client-side code
* Use environment variables for API credentials
* Implement proper access controls
* Monitor your API usage regularly
* Rotate your API keys periodically
* Keep your passphrase secure - it's required for API authentication
* Ensure timestamps are accurate - requests expire after 30 seconds for API

## Troubleshooting

### Common Issues with API

1. **Signature Mismatch**
   * Verify query parameters are sorted alphabetically for GET requests
   * Ensure JSON keys are sorted alphabetically for POST requests
   * Check timestamp format (must be milliseconds since Unix epoch)
   * Verify the message format: `timestamp + method + request_path + body`
2. **Invalid Timestamp**
   * Ensure your system clock is synchronized
   * Use UTC timezone for timestamps
   * Timestamp must be within 30 seconds of server time
   * Format: milliseconds since Unix epoch, for example `1700000000000`
3. **API Key Not Found**
   * Verify your API key is correct
   * Check if the API key is active
   * Ensure you're using the correct base URL


# Get Server Time

## API Description

Returns the current server time. Use for client time sync and aligning timestamps for Monday API signatures.

## HTTP Request

```
GET /v4/public/trader/server/time
```

## Request Parameters

No query parameters required.

## Response Parameters

Standard envelope. `data` is the server time as a Unix timestamp in milliseconds.

| Field     | Type   | Description          |
| --------- | ------ | -------------------- |
| code      | int    | Status code (0 = ok) |
| msg       | string | Error message        |
| data      | number | Server time in ms    |
| requestId | string | Request id           |

## Request Example

### Python (requests)

**Note:** Monday API authentication required. See [Quick Start](/perp-trading-apis/quick_start).

```python
import json
import time
import hmac
import hashlib
import base64
import requests

def generate_signature(ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

ts = str(int(time.time() * 1000))
path = "/v4/public/trader/server/time"
sig = generate_signature(ts, "GET", path)
headers = {"X-Chain-Id": str(CHAIN_ID), "X-Api-Key": API_KEY, "X-Api-Sign": sig, "X-Api-Ts": ts}
resp = requests.get(f"{BASE_URL}{path}", headers=headers)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

### Success Response

```json
{
    "code": 0,
    "msg": "",
    "data": 1768890735000,
    "requestId": "..."
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Request parameter error",
    "data": {},
    "requestId": "string"
}
```

## Notes

* Monday API authentication required (see [Quick Start](/perp-trading-apis/quick_start)).
* Use returned `data` to align client time for signature generation.
* Success response has `code: 0`.


# List API Keys

## API Description

Returns the list of API keys for the authenticated wallet address.

## HTTP Request

```
GET /v4/public/trader/api-key/list
```

## Request Parameters

No query parameters required.

## Response Parameters

Standard envelope. `data` is an array of API key objects:

| Field                | Type      | Description                      |
| -------------------- | --------- | -------------------------------- |
| id                   | int64     | API key id                       |
| address              | string    | Wallet address                   |
| label                | string    | API key label                    |
| productType          | string\[] | Enabled product types            |
| apiKey               | string    | Public API key                   |
| enableReading        | bool      | Read permission                  |
| enableTrading        | bool      | Trading permission               |
| enableWithdrawals    | bool      | Withdrawal permission            |
| restrictToTrustedIps | bool      | Whether trusted IPs are enforced |
| trustedIps           | string    | Trusted IPs list                 |
| createdAt            | int64     | Creation timestamp               |

## Request Example

### Python (requests)

**Note:** Monday API authentication required. See [Quick Start](/perp-trading-apis/quick_start).

```python
import json
import time
import hmac
import hashlib
import base64
import requests

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

def generate_signature(secret: str, ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(secret.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

ts = str(int(time.time() * 1000))
path = "/v4/public/trader/api-key/list"
sig = generate_signature(API_SECRET, ts, "GET", path)
headers = {"X-Chain-Id": str(CHAIN_ID), "X-Api-Key": API_KEY, "X-Api-Sign": sig, "X-Api-Ts": ts}

resp = requests.get(f"{BASE_URL}{path}", headers=headers)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

```json
{
  "code": 0,
  "msg": "",
  "data": [],
  "requestId": "..."
}
```

## Notes

* Monday API authentication required (see [Quick Start](/perp-trading-apis/quick_start)).
* Success response has `code: 0`.


# Create API Key

## API Description

Creates a new API key for the wallet address. This endpoint uses **wallet signature** (sign a message with your private key), not API key authentication. The response returns `apiKey` and `apiSecret` **once**; store the secret securely.

## HTTP Request

```
POST /v4/public/trader/api-key/create
```

## Request Headers

| Header       | Description      |
| ------------ | ---------------- |
| Content-Type | application/json |

No `X-Api-Key` / `X-Api-Sign` required; authentication is via the signed message in the body.

## Request Body

| Field                | Type    | Required | Description                                             |
| -------------------- | ------- | -------- | ------------------------------------------------------- |
| chainID              | int     | Yes      | Chain ID (e.g. 143 for Monad testnet)                   |
| address              | string  | Yes      | Wallet address (EVM, lowercase)                         |
| signature            | string  | Yes      | Signature of the auth message (from wallet signMessage) |
| nonce                | number  | Yes      | Nonce (e.g. current time in ms)                         |
| timestamp            | number  | Yes      | Unix timestamp in seconds                               |
| label                | string  | No       | Key label (e.g. "my-key")                               |
| productType          | array   | No       | Product types, e.g. \["perpetual"]                      |
| enableReading        | boolean | No       | Allow read operations (default true)                    |
| enableTrading        | boolean | No       | Allow trading (default true)                            |
| enableWithdrawals    | boolean | No       | Allow withdrawals (default false)                       |
| restrictToTrustedIps | boolean | No       | Restrict to trusted IPs (default false)                 |
| trustedIps           | string  | No       | Comma-separated trusted IPs                             |

**Auth message to sign** (format must match server expectation, e.g.):

```
Chain ID: {chainID}
Wallet Address: {address}
Nonce: {nonce}
Timestamp: {timestamp}
Sign this message to authenticate with Monday Trade API.
```

Sign this message with the wallet private key; put the resulting signature in `signature`.

## Request Example

### Python (requests + eth\_account)

**Note:** This endpoint does **not** use API key auth; it uses wallet signature.

```python
import json
import time
import requests
from eth_account import Account
from eth_account.messages import encode_defunct

BASE_URL = "https://api.monday.trade"
CHAIN_ID = 143
# Load wallet (never commit private key)
private_key = "0x..."  # your wallet private key
account = Account.from_key(private_key)
address = account.address.lower()

nonce = int(time.time() * 1000)
timestamp = int(time.time())
message_text = f"Chain ID: {CHAIN_ID}\nWallet Address: {address}\nNonce: {nonce}\nTimestamp: {timestamp}\nSign this message to authenticate with Monday Trade API."
message = encode_defunct(text=message_text)
signature = account.sign_message(message)
sig_hex = signature.signature.hex()

body = {
    "chainID": CHAIN_ID,
    "address": address,
    "signature": '0x' + sig_hex,
    "nonce": nonce,
    "timestamp": timestamp,
    "label": "my-key",
    "productType": ["perpetual"],
    "enableReading": True,
    "enableTrading": True,
    "enableWithdrawals": False,
    "restrictToTrustedIps": False,
    "trustedIps": "",
}

path = "/v4/public/trader/api-key/create"
resp = requests.post(
    f"{BASE_URL}{path}",
    headers={"Content-Type": "application/json"},
    json=body,
)
data = resp.json()
print(json.dumps(data, indent=2))
# Store data["data"]["apiKey"] and data["data"]["apiSecret"] securely; secret is only returned once.
```

## Response Parameters

Standard envelope. `data` contains the new API key info, including `apiKey` and `apiSecret`. The secret is returned only on create; store it securely.

## Response Example

```json
{
  "code": 0,
  "msg": "",
  "data": {
    "apiKey": "...",
    "apiSecret": "..."
  },
  "requestId": "..."
}
```

## Notes

* This endpoint uses **wallet signature**, not API key authentication.
* `apiSecret` is returned **only once**; store it securely and use it with [Quick Start](/perp-trading-apis/quick_start) for subsequent API calls.
* Success response has `code: 0`.


# Delete API Key

## API Description

Deletes the API key used for this request.

## HTTP Request

```
POST /v4/public/trader/api-key/delete
```

## Request Body

Empty JSON object:

```json
{}
```

## Request Example

### Python (requests)

**Note:** Monday API authentication required. See [Quick Start](/perp-trading-apis/quick_start).

```python
import json
import time
import hmac
import hashlib
import base64
import requests

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

def generate_signature(secret: str, ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(secret.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

ts = str(int(time.time() * 1000))
path = "/v4/public/trader/api-key/delete"
body = "{}"
sig = generate_signature(API_SECRET, ts, "POST", path, body)

headers = {
    "X-Chain-Id": str(CHAIN_ID),
    "X-Api-Key": API_KEY,
    "X-Api-Sign": sig,
    "X-Api-Ts": ts,
    "Content-Type": "application/json",
}

resp = requests.post(f"{BASE_URL}{path}", headers=headers, data=body)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

```json
{
  "code": 0,
  "msg": "",
  "data": {},
  "requestId": "..."
}
```

## Notes

* Monday API authentication required (see [Quick Start](/perp-trading-apis/quick_start)).
* Success response has `code: 0`.


# Get 1CT Status

## API Description

Returns the current account's One-Click Trade (1CT) switch status and configuration. Use before showing 1CT UI to confirm it is enabled/available.

## HTTP Request

```
GET /v4/public/trader/1ct/status
```

## Request Parameters

No query parameters required.

## Response Parameters

Standard envelope. `data` contains 1CT user info: userAddr, delegateAddr, delegateAddressBalance, status (`enable` or `disable`).

## Request Example

### Python (requests)

**Note:** This endpoint requires Monday API authentication. See [Trade Introduction](/perp-trading-apis/quick_start).

```python
import json
import time
import hmac
import hashlib
import base64
import requests

def generate_signature(secret: str, ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(secret.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

ts = str(int(time.time() * 1000))
path = "/v4/public/trader/1ct/status"
sig = generate_signature(API_SECRET, ts, "GET", path)
headers = {"X-Chain-Id": str(CHAIN_ID), "X-Api-Key": API_KEY, "X-Api-Sign": sig, "X-Api-Ts": ts}
resp = requests.get(f"{BASE_URL}{path}", headers=headers)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

### Success Response

```json
{
    "code": 0,
    "msg": "",
    "data": {
        "userAddr": "0x...",
        "delegateAddr": "0x...",
        "delegateAddressBalance": "0",
        "status": "enable"
    },
    "requestId": "..."
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Request parameter error",
    "data": {},
    "requestId": "string"
}
```

## Notes

* This endpoint requires Monday API authentication (see [Trade Introduction](/perp-trading-apis/quick_start)).
* Success response has `code: 0`.


# Prepare Approve

## API Description

Prepares an ERC20 EIP-712 permit payload for the authenticated trader. Call this endpoint first, sign the returned `signPayload` with the wallet that owns the trading account, then send the signature to Submit Approve.

## HTTP Request

```
POST /v4/public/trader/approve/prepare
```

## Request Headers

Monday API authentication required. See [Quick Start](/perp-trading-apis/quick_start).

## Request Body

Matches `dto.PrepareApproveRequest`:

| Field        | Type   | Required | Description                                                               |
| ------------ | ------ | -------- | ------------------------------------------------------------------------- |
| tokenAddress | string | Yes      | ERC20 token contract address.                                             |
| value        | string | No       | Human-readable decimal approve amount. Empty or `"0"` means max approval. |
| deadline     | int64  | No       | Unix timestamp in seconds. If `0`, server defaults to 1 hour from now.    |

## Request Example

### Python (requests)

```python
import json
import time
import hmac
import hashlib
import base64
import requests

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

def generate_signature(ts: str, method: str, path: str, body: str = "") -> str:
    payload = f"{ts}{method.upper()}{path}{body}"
    mac = hmac.new(API_SECRET.encode(), payload.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

ts = str(int(time.time() * 1000))
path = "/v4/public/trader/approve/prepare"
body_obj = {
    "tokenAddress": "0x...",
    "value": "10",
    "deadline": int(time.time()) + 3600
}
body = json.dumps(body_obj, separators=(",", ":"), sort_keys=True)
sig = generate_signature(ts, "POST", path, body)
headers = {
    "X-Chain-Id": str(CHAIN_ID),
    "X-Api-Key": API_KEY,
    "X-Api-Sign": sig,
    "X-Api-Ts": ts,
    "Content-Type": "application/json",
}
resp = requests.post(f"{BASE_URL}{path}", headers=headers, data=body)
print(json.dumps(resp.json(), indent=2))
```

## Response Parameters

Standard envelope. `data` matches `dto.PrepareApproveResponse`.

| Field           | Type   | Description                                                               |
| --------------- | ------ | ------------------------------------------------------------------------- |
| tokenAddress    | string | Normalized token address.                                                 |
| spenderAddress  | string | Gate / spender address resolved by the server.                            |
| value           | string | Raw integer permit amount. Use this exact value in Submit Approve.        |
| nonce           | string | ERC20 permit nonce.                                                       |
| deadline        | int64  | Unix timestamp in seconds.                                                |
| delegateAddress | string | Delegate address used for trader execution.                               |
| signPayload     | object | EIP-712 typed data payload to sign with the wallet that owns the account. |

## Response Example

### Success Response

```json
{
  "code": 0,
  "msg": "",
  "data": {
    "tokenAddress": "0x...",
    "spenderAddress": "0x...",
    "value": "10000000",
    "nonce": "7",
    "deadline": 1773891700,
    "delegateAddress": "0x...",
    "signPayload": {
      "types": {
        "EIP712Domain": [
          { "name": "name", "type": "string" },
          { "name": "version", "type": "string" },
          { "name": "chainId", "type": "uint256" },
          { "name": "verifyingContract", "type": "address" }
        ],
        "Permit": [
          { "name": "owner", "type": "address" },
          { "name": "spender", "type": "address" },
          { "name": "value", "type": "uint256" },
          { "name": "nonce", "type": "uint256" },
          { "name": "deadline", "type": "uint256" }
        ]
      },
      "primaryType": "Permit",
      "domain": {
        "name": "USDC",
        "version": "1",
        "chainId": "0x8f",
        "verifyingContract": "0x..."
      },
      "message": {
        "owner": "0x...",
        "spender": "0x...",
        "value": "10000000",
        "nonce": "7",
        "deadline": "1773891700"
      }
    }
  },
  "requestId": "..."
}
```

### Error Response

```json
{
  "code": 400,
  "msg": "Request parameter error",
  "data": null,
  "requestId": "..."
}
```

## Notes

* `spenderAddress` is resolved server-side; do not send it in the request body.
* `value` in the response is the raw on-chain integer amount, not the human-readable decimal amount you sent in the request.
* The next step is [Submit Approve](/perp-trading-apis/approve/submit_approve), using the signature produced from `data.signPayload`.


# Submit Approve

## API Description

Submits an ERC20 permit approval transaction through delegated trader execution. Use this after signing the EIP-712 payload returned by Prepare Approve.

## HTTP Request

```
POST /v4/public/trader/approve/submit
```

## Request Headers

Monday API authentication required. See [Quick Start](/perp-trading-apis/quick_start).

## Request Body

Matches `dto.SubmitApproveRequest`:

| Field        | Type   | Required | Description                                                                               |
| ------------ | ------ | -------- | ----------------------------------------------------------------------------------------- |
| tokenAddress | string | Yes      | ERC20 token contract address.                                                             |
| value        | string | No       | Raw integer permit amount returned by Prepare Approve. Empty or `"0"` means max approval. |
| deadline     | int64  | Yes      | Unix timestamp in seconds. Must match the signed permit deadline.                         |
| signature    | string | Yes      | 65-byte hex signature of the EIP-712 `signPayload` returned by Prepare Approve.           |
| gasLimit     | uint64 | No       | Optional gas limit (`0` = auto-estimate).                                                 |

## Request Example

### Python (requests)

```python
import json
import time
import hmac
import hashlib
import base64
import requests

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

def generate_signature(ts: str, method: str, path: str, body: str = "") -> str:
    payload = f"{ts}{method.upper()}{path}{body}"
    mac = hmac.new(API_SECRET.encode(), payload.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

ts = str(int(time.time() * 1000))
path = "/v4/public/trader/approve/submit"
body_obj = {
    "tokenAddress": "0x...",
    "value": "10000000",
    "deadline": 1773891700,
    "signature": "0x...",
    "gasLimit": 0
}
body = json.dumps(body_obj, separators=(",", ":"), sort_keys=True)
sig = generate_signature(ts, "POST", path, body)
headers = {
    "X-Chain-Id": str(CHAIN_ID),
    "X-Api-Key": API_KEY,
    "X-Api-Sign": sig,
    "X-Api-Ts": ts,
    "Content-Type": "application/json",
}
resp = requests.post(f"{BASE_URL}{path}", headers=headers, data=body)
print(json.dumps(resp.json(), indent=2))
```

## Response Parameters

Standard envelope; `data` matches `dto.TradeSubmitResponse` (only `txHash`).

## Response Example

### Success Response

```json
{
  "code": 0,
  "msg": "",
  "data": { "txHash": "0x..." },
  "requestId": "..."
}
```

### Error Response

```json
{
  "code": 400,
  "msg": "Request parameter error",
  "data": null,
  "requestId": "..."
}
```

## Notes

* `value` must be the exact raw integer string returned by Prepare Approve. Do not send the original human-readable amount again.
* `signature` must be generated from the `signPayload` returned by [Prepare Approve](/perp-trading-apis/approve/prepare_approve).
* `deadline` must match the deadline embedded in the signed permit.


# Get Instruments

## API Description

Returns basic info for all tradable instruments. Used for instrument list, symbol pickers, and config checks. Optional `symbol` filter.

## HTTP Request

```
GET /v4/public/trader/market/instruments
```

## Request Parameters

| Parameter | Type   | Required | Description                          |
| --------- | ------ | -------- | ------------------------------------ |
| symbol    | string | No       | Optional trading pair symbol filter. |

## Response Parameters

Standard envelope. `data` is an array of instrument objects. Each includes: instrumentAddress, symbol, base.symbol, quote.symbol, quote.address, quote.decimals, market.address, market.type, initialMarginRatio, maintenanceMarginRatio (basis points, e.g. 5000 = 50%, 500 = 5%), minMarginAmount, tradingFeeRatio, protocolFeeRatio, tip, quoteType, minTradeValue, minOrderValue, minRangeValue, fundingIntervalHour, minRangeTickDelta, instrumentCondition, placeLimitOrderPaused, disableMakerOrderRebate, **amms** (array of AMM state snapshots per expiry).

### `amms` (per instrument)

Each element describes AMM pool state for one expiry on that instrument. Fields are sent as strings where noted to preserve precision.

| Field                  | Type   | Description                                     |
| ---------------------- | ------ | ----------------------------------------------- |
| `blockInfo.height`     | number | Block height associated with this snapshot      |
| `blockInfo.timestamp`  | number | Block timestamp                                 |
| `expiry`               | number | Expiry identifier for this AMM row              |
| `fairPrice`            | string | Fair price                                      |
| `feeIndex`             | string | Cumulative fee index                            |
| `instrumentAddr`       | string | Instrument contract address                     |
| `insuranceFund`        | string | Insurance fund balance / index                  |
| `involvedFund`         | string | Involved fund amount                            |
| `liquidity`            | string | Active liquidity                                |
| `longFundingIndex`     | string | Long-side funding index                         |
| `longSocialLossIndex`  | string | Long-side social loss index                     |
| `markPrice`            | string | Mark price                                      |
| `openInterests`        | string | Open interest                                   |
| `protocolFee`          | string | Protocol fee accrual                            |
| `settlementPrice`      | string | Settlement price (when applicable)              |
| `shortFundingIndex`    | string | Short-side funding index                        |
| `shortSocialLossIndex` | string | Short-side social loss index                    |
| `sqrtPX96`             | string | Uniswap V3–style sqrt price (Q64.96), as string |
| `status`               | number | AMM row status code                             |
| `tick`                 | number | Current tick                                    |
| `timestamp`            | number | Snapshot or update time                         |
| `totalLiquidity`       | string | Total liquidity                                 |
| `totalLong`            | string | Total long notional / size                      |
| `totalShort`           | string | Total short notional / size                     |

## Request Example

### Python (requests)

**Note:** This endpoint requires Monday API authentication. See [Trade Introduction](/perp-trading-apis/quick_start).

```python
import json
import time
import hmac
import hashlib
import base64
import requests
from urllib.parse import urlencode

def generate_signature(secret: str, ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(secret.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

ts = str(int(time.time() * 1000))
params = {}  # optional: params["symbol"] = "ETH/USDC"
query = urlencode(sorted(params.items())) if params else ""
path = f"/v4/public/trader/market/instruments?{query}" if query else "/v4/public/trader/market/instruments"
sig = generate_signature(API_SECRET, ts, "GET", path)
headers = {"X-Chain-Id": str(CHAIN_ID), "X-Api-Key": API_KEY, "X-Api-Sign": sig, "X-Api-Ts": ts}
resp = requests.get(f"{BASE_URL}{path}", headers=headers)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

### Success Response

```json
{
    "code": 0,
    "msg": "",
    "data": [
        {
            "instrumentAddress": "0x...",
            "symbol": "ETH/USDC",
            "base": { "symbol": "ETH" },
            "quote": { "symbol": "USDC", "address": "0x...", "decimals": 6 },
            "market": { "address": "0x...", "type": "QUOTE_STABLE" },
            "initialMarginRatio": 50000,
            "maintenanceMarginRatio": 5000,
            "instrumentCondition": "NORMAL",
            "amms": [
                {
                    "blockInfo": { "height": 0, "timestamp": 0 },
                    "expiry": 0,
                    "fairPrice": "2000.5",
                    "feeIndex": "0",
                    "instrumentAddr": "0x...",
                    "insuranceFund": "0",
                    "involvedFund": "0",
                    "liquidity": "0",
                    "longFundingIndex": "0",
                    "longSocialLossIndex": "0",
                    "markPrice": "2000.4",
                    "openInterests": "0",
                    "protocolFee": "0",
                    "settlementPrice": "0",
                    "shortFundingIndex": "0",
                    "shortSocialLossIndex": "0",
                    "sqrtPX96": "0",
                    "status": 0,
                    "tick": 0,
                    "timestamp": 0,
                    "totalLiquidity": "0",
                    "totalLong": "0",
                    "totalShort": "0"
                }
            ]
        }
    ],
    "requestId": "..."
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Request parameter error",
    "data": {},
    "requestId": "string"
}
```

## Notes

* This endpoint requires Monday API authentication (see [Trade Introduction](/perp-trading-apis/quick_start)).
* Margin and fee ratios are in basis points (e.g. 5000 = 50%, 500 = 5%).
* Success response has `code: 0`.
* `amms` is an array of per-expiry AMM snapshots; large numeric values use string encoding.


# Get Orderbook

## API Description

Returns the order book (bid/ask depth) for a given instrument/symbol. Used for order book UI and quantitative strategies.

## HTTP Request

```
GET /v4/public/trader/market/orderbook
```

## Request Parameters

| Parameter | Type   | Required | Description                          |
| --------- | ------ | -------- | ------------------------------------ |
| symbol    | string | Yes      | Trading pair symbol (e.g. ETH/USDC). |

## Response Parameters

Standard envelope. `data` contains:

| Field     | Type   | Description                  |
| --------- | ------ | ---------------------------- |
| blockInfo | object | Optional; height, timestamp  |
| bids      | array  | Array of price level objects |
| asks      | array  | Array of price level objects |

Each price level: tick, price, baseSize, quoteSize, baseSum, quoteSum.

## Request Example

### Python (requests)

**Note:** This endpoint requires Monday API authentication. See [Trade Introduction](/perp-trading-apis/quick_start).

```python
import json
import time
import hmac
import hashlib
import base64
import requests
from urllib.parse import urlencode

def generate_signature(secret: str, ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(secret.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

ts = str(int(time.time() * 1000))
params = {"symbol": "ETH/USDC"}
query = urlencode(sorted(params.items()))
path = f"/v4/public/trader/market/orderbook?{query}"
sig = generate_signature(API_SECRET, ts, "GET", path)
headers = {"X-Chain-Id": str(CHAIN_ID), "X-Api-Key": API_KEY, "X-Api-Sign": sig, "X-Api-Ts": ts}
resp = requests.get(f"{BASE_URL}{path}", headers=headers)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

### Success Response

```json
{
    "code": 0,
    "msg": "",
    "data": {
        "blockInfo": { "height": 12345, "timestamp": 1768890735 },
        "bids": [
            { "tick": 80000, "price": "3100.5", "baseSize": "1.0", "quoteSize": "3100.5", "baseSum": "1.0", "quoteSum": "3100.5" }
        ],
        "asks": [
            { "tick": 80001, "price": "3101", "baseSize": "0.5", "quoteSize": "1550.5", "baseSum": "0.5", "quoteSum": "1550.5" }
        ]
    },
    "requestId": "..."
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Request parameter error",
    "data": {},
    "requestId": "string"
}
```

## Notes

* This endpoint requires Monday API authentication (see [Trade Introduction](/perp-trading-apis/quick_start)).
* Success response has `code: 0`.


# Get Kline

## API Description

Retrieves kline (candlestick) data for a specific trading pair. This endpoint provides historical price data including open, high, low, close prices and volume for specified time intervals. Monday API injects `chainId` and `address` from authentication; you do not need to send them.

## HTTP Request

```
GET /v4/public/trader/market/kline
```

## Request Parameters

| Parameter | Type   | Required | Description                                                          |
| --------- | ------ | -------- | -------------------------------------------------------------------- |
| symbol    | string | Yes      | Trading pair symbol (e.g., BTC/USDC)                                 |
| interval  | string | Yes      | Kline interval (e.g., 1m, 5m, 15m, 30m, 1h, 4h, 8h, 12h, 1d, 1w, 1M) |
| start     | uint64 | No       | Start time in Unix timestamp (seconds). Default: 0                   |
| end       | uint64 | No       | End time in Unix timestamp (seconds). Default: current time          |
| limit     | uint64 | No       | Number of kline data points to retrieve. Default: 1000, max: 1000    |

**Note:** `chainId` and `address` are injected by the Monday API middleware and do not need to be sent.

## Response Parameters

| Parameter   | Type    | Description                                        |
| ----------- | ------- | -------------------------------------------------- |
| symbol      | string  | Trading pair symbol                                |
| openTime    | uint64  | Opening time timestamp (Unix timestamp in seconds) |
| open        | float32 | Opening price                                      |
| high        | float32 | Highest price in the period                        |
| low         | float32 | Lowest price in the period                         |
| close       | float32 | Closing price                                      |
| closeTime   | uint64  | Closing time timestamp (Unix timestamp in seconds) |
| baseVolume  | float32 | Base asset volume                                  |
| quoteVolume | float32 | Quote asset volume                                 |

The response is the standard envelope: `code`, `msg`, `data` (array of kline objects above), `requestId`.

## Request Example

### Python (requests)

**Note:** This endpoint requires Monday API authentication. See [Quick Start](/perp-trading-apis/quick_start) for signature generation.

```python
import json
import time
import hmac
import hashlib
import base64
import requests
from urllib.parse import urlencode

def generate_signature(secret: str, ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(secret.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

ts = str(int(time.time() * 1000))
params = {"symbol": "BTC/USDC", "interval": "1m", "limit": 100}
query = urlencode(sorted(params.items()))
path = f"/v4/public/trader/market/kline?{query}"
sig = generate_signature(API_SECRET, ts, "GET", path)

headers = {
    "X-Chain-Id": str(CHAIN_ID),
    "X-Api-Key": API_KEY,
    "X-Api-Sign": sig,
    "X-Api-Ts": ts,
}
url = f"{BASE_URL}{path}"
resp = requests.get(url, headers=headers)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

### Success Response

```json
{
    "data": [
        {
            "symbol": "BTC/USDC",
            "openTime": 1765728240,
            "open": 89032.47,
            "high": 89032.47,
            "low": 89032.47,
            "close": 89032.47,
            "closeTime": 1765728299,
            "baseVolume": 0,
            "quoteVolume": 0
        }
    ],
    "msg": "",
    "code": 0,
    "requestId": "d55bb2e2-cca0-4de7-a99a-681d479042a9"
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Request parameter error",
    "data": {},
    "requestId": "string"
}
```

## Notes

* This endpoint requires Monday API authentication (see [Quick Start](/perp-trading-apis/quick_start)).
* **Required parameters:** `symbol`, `interval`. `chainId` and `address` are taken from auth.
* **Optional parameters:** `start`, `end`, `limit`.
* **Time format:** `start` and `end` are Unix timestamps in **seconds**.
* **Interval format:** Use strings such as "1m", "5m", "15m", "30m", "1h", "4h", "8h", "12h", "1d", "1w", "1M".
* Success response has `code: 0`.


# Get Tickers

## API Description

Returns latest ticker info for one or more instruments/symbols (e.g. price, change, 24h volume). Used for ticker lists and market overview dashboards. Omit `symbol` to get all tickers.

## HTTP Request

```
GET /v4/public/trader/market/tickers
```

## Request Parameters

| Parameter | Type   | Required | Description                                 |
| --------- | ------ | -------- | ------------------------------------------- |
| symbol    | string | No       | Trading pair symbol filter (e.g. ETH/USDC). |

## Response Parameters

Standard envelope. `data` is an array of ticker objects. Each object includes: instrumentAddress, symbol, expiry, lastPrice, priceChange24H, priceChangePercent24h, openPrice24h, highPrice24h, lowPrice24h, volume24h, quoteVolume24h, openTime24h, closeTime24h, markPrice, spotPrice.

## Request Example

### Python (requests)

**Note:** This endpoint requires Monday API authentication. See [Trade Introduction](/perp-trading-apis/quick_start).

```python
import json
import time
import hmac
import hashlib
import base64
import requests
from urllib.parse import urlencode

def generate_signature(secret: str, ts: str, method: str, path: str, body: str = "") -> str:
    message = ts + method.upper() + path + body
    mac = hmac.new(secret.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

BASE_URL = "https://api.monday.trade"
API_KEY = "<your-api-key>"
API_SECRET = "<your-api-secret>"
CHAIN_ID = 143

ts = str(int(time.time() * 1000))
params = {"symbol": "BTC/USDC"}  # omit for all tickers
query = urlencode(sorted(params.items())) if params else ""
path = f"/v4/public/trader/market/tickers?{query}" if query else "/v4/public/trader/market/tickers"
sig = generate_signature(API_SECRET, ts, "GET", path)
headers = {"X-Chain-Id": str(CHAIN_ID), "X-Api-Key": API_KEY, "X-Api-Sign": sig, "X-Api-Ts": ts}
url = f"{BASE_URL}{path}"
resp = requests.get(url, headers=headers)
print(json.dumps(resp.json(), indent=2))
```

## Response Example

### Success Response

```json
{
    "data": [
        {
            "instrumentAddress": "0x...",
            "symbol": "BTC/USDC",
            "expiry": 4294967295,
            "lastPrice": "89000.28",
            "priceChange24H": "-1104.74",
            "priceChangePercent24h": "-1.24",
            "openPrice24h": 90105.02,
            "highPrice24h": 91000,
            "lowPrice24h": 88500,
            "volume24h": "10.5",
            "quoteVolume24h": "920000",
            "openTime24h": 1765642705,
            "closeTime24h": 1765729105,
            "markPrice": "88990",
            "spotPrice": "88990"
        }
    ],
    "msg": "",
    "code": 0,
    "requestId": "..."
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Request parameter error",
    "data": {},
    "requestId": "string"
}
```

## Notes

* This endpoint requires Monday API authentication (see [Trade Introduction](/perp-trading-apis/quick_start)).
* Omit `symbol` to return tickers for all instruments.
* Success response has `code: 0`.


# Get Funding History

## API Description

Retrieves historical funding rate data for perpetual contracts. This endpoint provides funding rate information including long and short funding rates at different timestamps, which is crucial for understanding the cost of holding positions in perpetual futures.

## HTTP Request

```
GET /v4/public/trader/market/funding/history
```

## Request Parameters

| Parameter | Type   | Required | Description                                            |
| --------- | ------ | -------- | ------------------------------------------------------ |
| chainId   | uint64 | Yes      | Chain ID (e.g., 143 for Monad mainnet)                 |
| symbol    | string | Yes      | Trading pair symbol (e.g., BTC/USDC)                   |
| startTime | uint64 | No       | Start time in Unix timestamp (seconds)                 |
| endTime   | uint64 | No       | End time in Unix timestamp (seconds)                   |
| limit     | uint32 | No       | Number of records to retrieve (default: 200, max: 200) |

**Important**: Use `symbol` (singular) as the parameter name. `startTime`, `endTime`, and `limit` are optional.

## Response Parameters

| Parameter | Type   | Description                                        |
| --------- | ------ | -------------------------------------------------- |
| timestamp | uint64 | Funding rate timestamp (Unix timestamp in seconds) |
| long      | string | Long position funding rate                         |
| short     | string | Short position funding rate                        |

## Request Example

### Python (requests)

**Note**: This endpoint requires Monday API authentication. See [Quick Start](/perp-trading-apis/quick_start) for signature generation.

```python
import hmac
import hashlib
import base64
import json
import time
import requests
from urllib.parse import urlencode

def generate_signature(secret_key, timestamp, method, request_path, body=""):
    """Monday API signature: timestamp (ms) + method + path + body"""
    message = timestamp + method.upper() + request_path + (body or "")
    mac = hmac.new(secret_key.encode("utf-8"), message.encode("utf-8"), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode("utf-8")

api_key = "<your-api-key>"
secret_key = "<your-api-secret>"
chain_id = 143

# Generate timestamp (milliseconds for Monday API)
timestamp = str(int(time.time() * 1000))

# Build request path with sorted query parameters
# Note: Use 'symbol' (singular) as the parameter name
params = {
    'chainId': 143,
    'symbol': 'BTC/USDC',  # Use 'symbol' (singular)
    'startTime': 1764603778,  # Optional
    'endTime': 1765726982,    # Optional
    'limit': 200              # Optional, default is 200
}
# Sort parameters alphabetically for signature
sorted_params = sorted(params.items())
query_string = urlencode(sorted_params)
request_path = f"/v4/public/trader/market/funding/history?{query_string}"

# Generate signature
signature = generate_signature(secret_key, timestamp, "GET", request_path)

# Make request (Monday API headers)
headers = {
    "X-Chain-Id": str(chain_id),
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
}

url = f"https://api.monday.trade/v4/public/trader/market/funding/history?{urlencode(params)}"
response = requests.get(url, headers=headers)
result = response.json()
print(json.dumps(result, indent=2))
```

## Response Example

### Success Response

```json
{
    "data": [
        {
            "timestamp": 1764603778,
            "long": "0.0001",
            "short": "-0.0001"
        },
        {
            "timestamp": 1764607378,
            "long": "0.00015",
            "short": "-0.00015"
        }
    ],
    "msg": "",
    "code": 0,
    "requestId": "bbf4fa1a-0f41-449f-8d9c-44fdceae0bf7"
}
```

### Error Response

```json
{
    "code": 400,
    "msg": "Request parameter error",
    "data": {},
    "requestId": "bbf4fa1a-0f41-449f-8d9c-44fdceae0bf7"
}
```

## Notes

* This endpoint requires API authentication (see [Quick Start Guide](/perp-trading-apis/quick_start))
* **Important**: Use `symbol` (singular) as the parameter name
* Only `chainId` and `symbol` are required; `startTime`, `endTime`, and `limit` are optional
* If `limit` is not provided, it defaults to 200
* `startTime` and `endTime` are in Unix timestamp format (seconds, not milliseconds)
* Maximum `limit` is 200
* Returns funding rates at 1-hour intervals
* `long`: Funding rate for long positions (positive means longs pay shorts)
* `short`: Funding rate for short positions (negative means shorts pay longs)
* `timestamp`: Unix timestamp in seconds when the funding rate was applied
* Funding rates are typically applied every 8 hours (00:00, 08:00, 16:00 UTC), but this endpoint returns hourly data
* Rate limit: 120 requests per minute
* Success response has `code: 0` (not 200)

## Common Errors

### "invalid request parameters"

* Ensure you're using `symbol` (singular) as the parameter name
* `chainId` and `symbol` are required; other parameters are optional
* `startTime` and `endTime` must be Unix timestamps in seconds (not milliseconds) if provided




---

[Next Page](/llms-full.txt/1)

