> For the complete documentation index, see [llms.txt](https://docs.flash.trade/flash-trade/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.flash.trade/flash-trade/flash-trade-protocol/build-on-flash/flash-trade-v2/reference/trading.md).

# Trading

Canonical request/response for every trading endpoint.

All trading transactions are built **unsigned** and submit to the **v2 RPC**. Quote builders carry the transaction under `transactionBase64` (`null` in preview-only mode); simple builders return `{ "transactionBase64": "…" }`. Compute failures come back `200` with `{ "err": "…" }`. Shared conventions: [Conventions](/flash-trade/flash-trade-protocol/build-on-flash/flash-trade-v2/reference/conventions.md).

| Method | Path                                                                                                                                         |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST` | `/transaction-builder/open-position`                                                                                                         |
| `POST` | `/transaction-builder/close-position`                                                                                                        |
| `POST` | `/transaction-builder/increase-position` · `/decrease-position`                                                                              |
| `POST` | `/transaction-builder/reverse-position`                                                                                                      |
| `POST` | `/transaction-builder/add-collateral` · `/remove-collateral`                                                                                 |
| `POST` | `/transaction-builder/place-trigger-order` · `/place-tp-sl` · `/edit-trigger-order` · `/cancel-trigger-order` · `/cancel-all-trigger-orders` |
| `POST` | `/transaction-builder/edit-limit-order` · `/cancel-limit-order`                                                                              |

***

## Open position

`POST /transaction-builder/open-position`

Opens a new position or increases an existing one. Supports market and limit orders and optional TP/SL. Omit `owner` for a preview-only quote.

| Field                | Type   | Req | Description                                |
| -------------------- | ------ | --- | ------------------------------------------ |
| `inputTokenSymbol`   | string | ✓   | Collateral token (e.g. `USDC`, `SOL`)      |
| `outputTokenSymbol`  | string | ✓   | Market token (e.g. `SOL`, `BTC`)           |
| `inputAmountUi`      | string | ✓   | Input amount, UI units                     |
| `leverage`           | number | ✓   | Leverage multiplier                        |
| `tradeType`          | enum   | ✓   | `LONG` or `SHORT`                          |
| `orderType`          | enum   | —   | `MARKET` (default) or `LIMIT`              |
| `limitPrice`         | string | —   | Trigger price for `LIMIT` (UI)             |
| `owner`              | string | —   | Wallet pubkey. Omit for preview only       |
| `slippagePercentage` | string | —   | Default `"0.5"`                            |
| `takeProfit`         | string | —   | TP trigger price (UI); appends a TP order  |
| `stopLoss`           | string | —   | SL trigger price (UI); appends an SL order |

**Response** — `OpenPositionResponseDto`

| Field                                                      | Description                               |
| ---------------------------------------------------------- | ----------------------------------------- |
| `newLeverage`, `newEntryPrice`, `newLiquidationPrice`      | Position after this trade                 |
| `entryFee`, `entryFeeBeforeDiscount`, `discountPercentage` | Entry-fee breakdown                       |
| `youPayUsdUi`, `youRecieveUsdUi`, `outputAmountUi`         | Collateral in / size out                  |
| `availableLiquidity`                                       | Market liquidity, USD                     |
| `takeProfitQuote`, `stopLossQuote`                         | Present when TP/SL supplied               |
| `oldLeverage`, `oldEntryPrice`, `oldLiquidationPrice`      | Present when increasing                   |
| `transactionBase64`                                        | Unsigned tx (`null` in preview-only mode) |
| `err`                                                      | Set when the computation failed           |

```bash
curl -X POST $FLASH_API_URL/transaction-builder/open-position -d '{
  "inputTokenSymbol": "USDC", "outputTokenSymbol": "SOL",
  "inputAmountUi": "100.0", "leverage": 5.0, "tradeType": "LONG",
  "owner": "bRXn4PPnUCLKP3kdHbX6FFQFpw2AhFzBVMgo4ZaWvtfb"
}'
```

***

## Close position

`POST /transaction-builder/close-position`

Closes a position fully or partially, identified by `(owner, marketSymbol, side)`.

| Field                 | Type    | Req | Description                                 |
| --------------------- | ------- | --- | ------------------------------------------- |
| `marketSymbol`        | string  | ✓   | Market token symbol                         |
| `side`                | enum    | ✓   | `LONG` or `SHORT`                           |
| `inputUsdUi`          | string  | ✓   | USD to close (full size = full close)       |
| `closeAll`            | boolean | —   | Force full close regardless of `inputUsdUi` |
| `withdrawTokenSymbol` | string  | ✓   | Token to withdraw into (display hint)       |
| `owner`               | string  | ✓   | Owner wallet pubkey                         |
| `slippagePercentage`  | string  | —   | Default `"0.5"`                             |

**Response** — `ClosePositionResponseDto`: `receiveTokenSymbol`, `receiveTokenAmountUi`, `receiveTokenAmountUsdUi`, `markPrice`, `settledPnl`, `fees`, `newLiquidationPrice`, `newSize`, `newLeverage`, `transactionBase64`.

***

## Increase / Decrease position <a href="#increase-decrease-position" id="increase-decrease-position"></a>

`POST /transaction-builder/increase-position` · `POST /transaction-builder/decrease-position`

Add or remove size on an open position. For a full exit use `close-position`.

| Field                           | increase | decrease | Description                                   |
| ------------------------------- | :------: | :------: | --------------------------------------------- |
| `marketSymbol`, `side`, `owner` |     ✓    |     ✓    | Identify the position                         |
| `sizeAmountUi`                  |     ✓    |     ✓    | Size delta, target token (UI)                 |
| `collateralAmountUi`            |     ✓    |     —    | Collateral to add (may be `"0"`)              |
| `collateralTokenSymbol`         |     —    |     —    | Increase only; defaults to collateral custody |
| `withdrawTokenSymbol`           |     —    |     —    | Decrease only; defaults to collateral custody |
| `slippagePercentage`            |     —    |     —    | Default `"0.5"`                               |

**Response:** `{ "transactionBase64": "…" }`.

***

## Reverse position

`POST /transaction-builder/reverse-position`

Atomically closes the current side and opens the opposite side at the given leverage. A 2% haircut on close proceeds absorbs price drift.

| Field                | Type   | Req | Description                                    |
| -------------------- | ------ | --- | ---------------------------------------------- |
| `marketSymbol`       | string | ✓   | Market token symbol                            |
| `side`               | enum   | ✓   | **Current** side; new position is the opposite |
| `leverage`           | number | ✓   | Leverage for the new position                  |
| `owner`              | string | ✓   | Owner wallet pubkey                            |
| `slippagePercentage` | string | —   | Default `"0.5"`                                |

**Response** — `ReversePositionResponseDto`: `closeReceiveUsd`, `closeFees`, `closeSettledPnl`, `newSide`, `newLeverage`, `newEntryPrice`, `newLiquidationPrice`, `newSizeUsd`, `newSizeAmountUi`, `newCollateralUsd`, `openEntryFee`, `transactionBase64`.

***

## Collateral

`POST /transaction-builder/add-collateral` · `POST /transaction-builder/remove-collateral`

Adjust margin on an open position to move its leverage and liquidation price.

| Field                                         | add | remove | Description           |
| --------------------------------------------- | :-: | :----: | --------------------- |
| `marketSymbol`, `side`, `owner`               |  ✓  |    ✓   | Identify the position |
| `depositAmountUi` + `depositTokenSymbol`      |  ✓  |    —   | Amount to add         |
| `withdrawAmountUsdUi` + `withdrawTokenSymbol` |  —  |    ✓   | USD to remove         |

**Response** — `AddCollateralResponseDto` / `RemoveCollateralResponseDto`: `existingCollateralUsd`, `newCollateralUsd`, `existingLeverage`, `newLeverage`, `existingLiquidationPrice`, `newLiquidationPrice`, `transactionBase64`. Add also returns `depositUsdValue` / `maxAddableUsd`; remove returns `receiveAmountUi` / `receiveAmountUsdUi` / `maxWithdrawableUsd`.

***

## Trigger orders

Return `{ "transactionBase64": "…" }` on success, `400 { "error": "…" }` on validation failure. Up to 5 TP + 5 SL per market + side. Task walkthrough: [Take-profit & stop-loss](/flash-trade/flash-trade-protocol/build-on-flash/flash-trade-v2/guides/take-profit-and-stop-loss.md).

### Place trigger order

`POST /transaction-builder/place-trigger-order`

| Field                           | Type    | Req | Description                       |
| ------------------------------- | ------- | --- | --------------------------------- |
| `marketSymbol`, `side`, `owner` |         | ✓   | Position identity                 |
| `triggerPriceUi`                | string  | ✓   | Trigger price (UI)                |
| `sizeAmountUi`                  | string  | ✓   | Size to close when triggered (UI) |
| `isStopLoss`                    | boolean | ✓   | `true` = SL, `false` = TP         |

### Place TP/SL (atomic)

`POST /transaction-builder/place-tp-sl` — `marketSymbol`, `side`, `owner`, `sizeAmountUi`, plus `takeProfitUi` and/or `stopLossUi` (each optional; supply one or both).

### Edit trigger order

`POST /transaction-builder/edit-trigger-order` — replaces **both** price and size (no keep-existing). Fields: `marketSymbol`, `side`, `owner`, `orderId` (0–4), `isStopLoss`, `triggerPriceUi`, `sizeAmountUi`.

### Cancel trigger order(s)

`POST /transaction-builder/cancel-trigger-order` — `marketSymbol`, `side`, `owner`, `orderId` (0–4; or `255` for all), `isStopLoss`.

`POST /transaction-builder/cancel-all-trigger-orders` — `marketSymbol`, `side`, `owner`.

***

## Limit orders

Placing a limit order goes through [open-position](#open-position) with `orderType: "LIMIT"`. The endpoints below edit and cancel. Up to 5 limit orders per market + side. Task walkthrough: [Limit orders](/flash-trade/flash-trade-protocol/build-on-flash/flash-trade-v2/guides/limit-orders.md).

### Edit limit order

`POST /transaction-builder/edit-limit-order`

For `limitPriceUi` / `sizeAmountUi`, omit (or `"0"`) to keep existing. TP/SL do **not** persist — re-send to keep, `"0"`/omit removes.

| Field                           | Type   | Req | Description                  |
| ------------------------------- | ------ | --- | ---------------------------- |
| `marketSymbol`, `side`, `owner` |        | ✓   | Position identity            |
| `orderId`                       | number | ✓   | Slot index (0–4)             |
| `limitPriceUi`                  | string | —   | New price (UI). Omit to keep |
| `sizeAmountUi`                  | string | —   | New size (UI). Omit to keep  |
| `takeProfitUi`                  | string | —   | Set TP; `"0"`/omit removes   |
| `stopLossUi`                    | string | —   | Set SL; `"0"`/omit removes   |

### Cancel limit order

`POST /transaction-builder/cancel-limit-order` — `marketSymbol`, `side`, `owner`, `orderId` (0–4). Returns reserved collateral and frees the slot.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.flash.trade/flash-trade/flash-trade-protocol/build-on-flash/flash-trade-v2/reference/trading.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
