# Transaction Builder

Transaction builder endpoints do two things:

1. **Preview** — Calculate fees, leverage, liquidation price, and other outputs before committing.
2. **Build** — Return a base64-encoded Solana transaction ready to be signed and sent.

**Preview only:** omit the `owner` field.\
**Preview + transaction:** include `owner` with the wallet pubkey.

All responses include an `err` field — `null` on success, or an error message if computation failed. Always check `err !== null` before using the response.

***

### Open Position

Open a new position or increase an existing one.

```
POST /transaction-builder/open-position
```

**Request body:**

json

```json
{
  "inputTokenSymbol": "USDC",
  "outputTokenSymbol": "SOL",
  "inputAmountUi": "100.0",
  "leverage": 5.0,
  "tradeType": "LONG",
  "owner": "YOUR_WALLET_PUBKEY"
}
```

| Field                       | Type    | Required | Description                                                            |
| --------------------------- | ------- | -------- | ---------------------------------------------------------------------- |
| `inputTokenSymbol`          | string  | yes      | Token you're paying with (e.g., `"USDC"`, `"SOL"`)                     |
| `outputTokenSymbol`         | string  | yes      | Market token (e.g., `"SOL"`, `"BTC"`)                                  |
| `inputAmountUi`             | string  | yes      | Amount to pay, human-readable                                          |
| `leverage`                  | number  | yes      | Leverage multiplier (e.g., `5.0` for 5x)                               |
| `tradeType`                 | string  | yes      | `"LONG"`, `"SHORT"`, or `"SWAP"`                                       |
| `orderType`                 | string  | no       | `"MARKET"` (default) or `"LIMIT"`                                      |
| `limitPrice`                | string  | no       | Trigger price for limit orders                                         |
| `degenMode`                 | boolean | no       | Enable high-leverage degen mode                                        |
| `tradingFeeDiscountPercent` | number  | no       | Fee discount from staking (0–100)                                      |
| `owner`                     | string  | no       | Wallet pubkey. Omit for preview-only; include to build the transaction |
| `slippagePercentage`        | string  | no       | Slippage tolerance (default `"0.5"`)                                   |
| `takeProfit`                | string  | no       | TP trigger price — creates TP order in the same transaction            |
| `stopLoss`                  | string  | no       | SL trigger price — creates SL order in the same transaction            |
| `tokenStakeFafAccount`      | string  | no       | FAF stake account (for fee discount)                                   |
| `userReferralAccount`       | string  | no       | Referral account                                                       |
| `privilege`                 | string  | no       | `"NONE"`, `"STAKE"`, or `"REFERRAL"` — overrides auto-inference        |

**Preview only (no transaction):**

bash

```bash
curl -X POST https://flashapi.trade/transaction-builder/open-position \
  -H "Content-Type: application/json" \
  -d '{
    "inputTokenSymbol": "USDC",
    "outputTokenSymbol": "SOL",
    "inputAmountUi": "100.0",
    "leverage": 5.0,
    "tradeType": "LONG"
  }'
```

**With transaction + TP/SL:**

bash

```bash
curl -X POST https://flashapi.trade/transaction-builder/open-position \
  -H "Content-Type: application/json" \
  -d '{
    "inputTokenSymbol": "USDC",
    "outputTokenSymbol": "SOL",
    "inputAmountUi": "100.0",
    "leverage": 5.0,
    "tradeType": "LONG",
    "owner": "YOUR_WALLET_PUBKEY",
    "takeProfit": "160.00",
    "stopLoss": "130.00"
  }'
```

**Response:**

json

```json
{
  "oldLeverage": null,
  "newLeverage": "5.00",
  "oldEntryPrice": null,
  "newEntryPrice": "148.52",
  "oldLiquidationPrice": null,
  "newLiquidationPrice": "120.30",
  "entryFee": "0.45",
  "entryFeeBeforeDiscount": "0.50",
  "openPositionFeePercent": "0.03600",
  "availableLiquidity": "1234567.89",
  "youPayUsdUi": "100.00",
  "youRecieveUsdUi": "500.00",
  "marginFeePercentage": "0.00800",
  "outputAmount": "3370000000",
  "outputAmountUi": "3.37",
  "transactionBase64": "AQAAAA...",
  "takeProfitQuote": {
    "exitPriceUi": "160.00",
    "profitUsdUi": "38.75",
    "lossUsdUi": "0",
    "exitFeeUsdUi": "0.45",
    "receiveUsdUi": "138.30",
    "pnlPercentage": "38.75"
  },
  "stopLossQuote": {
    "exitPriceUi": "130.00",
    "profitUsdUi": "0",
    "lossUsdUi": "62.33",
    "exitFeeUsdUi": "0.40",
    "receiveUsdUi": "37.27",
    "pnlPercentage": "-62.33"
  },
  "err": null
}
```

| Field                                                   | Description                                                                              |
| ------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `oldLeverage` / `oldEntryPrice` / `oldLiquidationPrice` | Previous values — present when increasing an existing position, `null` for new positions |
| `newLeverage` / `newEntryPrice` / `newLiquidationPrice` | Values after this trade                                                                  |
| `entryFee`                                              | Entry fee after discount                                                                 |
| `entryFeeBeforeDiscount`                                | Entry fee before discount                                                                |
| `openPositionFeePercent`                                | Fee rate as a percentage string (e.g., `"0.03600"` = 0.036%)                             |
| `availableLiquidity`                                    | Available liquidity for this market                                                      |
| `youPayUsdUi`                                           | Total USD collateral you're paying                                                       |
| `youRecieveUsdUi`                                       | Total USD position size after leverage                                                   |
| `marginFeePercentage`                                   | Hourly borrow rate (e.g., `"0.00800"` = 0.008%/hr)                                       |
| `outputAmount`                                          | Size in native token units (raw u64)                                                     |
| `outputAmountUi`                                        | Size in human-readable token amount                                                      |
| `transactionBase64`                                     | Ready-to-sign Solana transaction (`null` if `owner` not provided)                        |
| `takeProfitQuote` / `stopLossQuote`                     | Projected PnL at TP/SL prices (present when `takeProfit` / `stopLoss` provided)          |
| `swapInPriceUi` / `swapOutPriceUi` / `swapFeeUsdUi`     | Present for `SWAP` trade type only                                                       |
| `err`                                                   | Error message or `null`                                                                  |

***

### Close Position

Close all or part of an existing position.

```
POST /transaction-builder/close-position
```

**Request body:**

json

```json
{
  "positionKey": "POSITION_ACCOUNT_PUBKEY",
  "inputUsdUi": "500.00",
  "withdrawTokenSymbol": "USDC"
}
```

| Field                       | Type    | Required | Description                                                   |
| --------------------------- | ------- | -------- | ------------------------------------------------------------- |
| `positionKey`               | string  | yes      | Position account pubkey to close                              |
| `inputUsdUi`                | string  | yes      | USD amount to close — use full position size for a full close |
| `withdrawTokenSymbol`       | string  | yes      | Token to receive proceeds in                                  |
| `keepLeverageSame`          | boolean | no       | Keep leverage constant during partial close                   |
| `slippagePercentage`        | string  | no       | Slippage tolerance (default `"0.5"`)                          |
| `tradingFeeDiscountPercent` | number  | no       | Fee discount from staking (0–100)                             |
| `tokenStakeFafAccount`      | string  | no       | FAF stake account                                             |
| `userReferralAccount`       | string  | no       | Referral account                                              |
| `privilege`                 | string  | no       | `"NONE"`, `"STAKE"`, or `"REFERRAL"`                          |

**Response:**

json

```json
{
  "receiveTokenSymbol": "USDC",
  "receiveTokenAmountUi": "105.23",
  "receiveTokenAmountUsdUi": "105.23",
  "markPrice": "148.52",
  "entryPrice": "145.00",
  "existingLiquidationPrice": "120.30",
  "newLiquidationPrice": "0.00",
  "existingSize": "500.00",
  "newSize": "0.00",
  "existingCollateral": "100.00",
  "newCollateral": "0.00",
  "existingLeverage": "5.00",
  "newLeverage": "0.00",
  "settledPnl": "5.23",
  "fees": "0.36",
  "feesBeforeDiscount": "0.40",
  "lockAndUnsettledFeeUsd": null,
  "transactionBase64": "AQAAAA...",
  "err": null
}
```

| Field                      | Description                                                        |
| -------------------------- | ------------------------------------------------------------------ |
| `receiveTokenAmountUi`     | Amount of the receive token you'll get                             |
| `markPrice`                | Current market price — what you're closing at                      |
| `entryPrice`               | Your original entry price                                          |
| `existingSize` → `newSize` | Position size before and after the close (`"0.00"` for full close) |
| `settledPnl`               | Realized PnL in USD (negative for a loss)                          |
| `fees`                     | Total fees (exit + borrow) after discount                          |
| `lockAndUnsettledFeeUsd`   | Present for partial closes only — fee on locked collateral         |

***

### Add Collateral

Deposit more collateral to reduce leverage and move your liquidation price further away.

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

**Request body:**

json

```json
{
  "positionKey": "POSITION_ACCOUNT_PUBKEY",
  "depositAmountUi": "50.0",
  "depositTokenSymbol": "USDC",
  "owner": "YOUR_WALLET_PUBKEY"
}
```

| Field                | Type   | Required | Description                                            |
| -------------------- | ------ | -------- | ------------------------------------------------------ |
| `positionKey`        | string | yes      | Position account pubkey                                |
| `depositAmountUi`    | string | yes      | Amount to deposit (in deposit token units)             |
| `depositTokenSymbol` | string | yes      | Token to deposit                                       |
| `owner`              | string | yes      | Wallet pubkey — always required for collateral changes |
| `slippagePercentage` | string | no       | Slippage tolerance                                     |

**Response:**

json

```json
{
  "existingCollateralUsd": "100.00",
  "newCollateralUsd": "150.00",
  "existingLeverage": "5.00",
  "newLeverage": "3.33",
  "existingLiquidationPrice": "120.30",
  "newLiquidationPrice": "105.00",
  "depositUsdValue": "50.00",
  "maxAddableUsd": "10000.00",
  "transactionBase64": "AQAAAA...",
  "err": null
}
```

***

### Remove Collateral

Withdraw collateral from a position. Increases leverage and moves the liquidation price closer.

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

**Request body:**

json

```json
{
  "positionKey": "POSITION_ACCOUNT_PUBKEY",
  "withdrawAmountUsdUi": "25.00",
  "withdrawTokenSymbol": "USDC",
  "owner": "YOUR_WALLET_PUBKEY"
}
```

| Field                 | Type   | Required | Description             |
| --------------------- | ------ | -------- | ----------------------- |
| `positionKey`         | string | yes      | Position account pubkey |
| `withdrawAmountUsdUi` | string | yes      | USD amount to withdraw  |
| `withdrawTokenSymbol` | string | yes      | Token to receive        |
| `owner`               | string | yes      | Wallet pubkey           |
| `slippagePercentage`  | string | no       | Slippage tolerance      |

**Response:**

json

```json
{
  "existingCollateralUsd": "100.00",
  "newCollateralUsd": "75.00",
  "existingLeverage": "5.00",
  "newLeverage": "6.67",
  "existingLiquidationPrice": "120.30",
  "newLiquidationPrice": "130.00",
  "receiveAmountUi": "25.00",
  "receiveAmountUsdUi": "25.00",
  "maxWithdrawableUsd": "80.00",
  "transactionBase64": "AQAAAA...",
  "err": null
}
```

***

### Reverse Position

Flip a position from Long to Short (or vice versa) in a single atomic transaction. Closes the existing position and opens a new one in the opposite direction.

```
POST /transaction-builder/reverse-position
```

**Request body:**

json

```json
{
  "positionKey": "POSITION_ACCOUNT_PUBKEY",
  "owner": "YOUR_WALLET_PUBKEY"
}
```

| Field                       | Type    | Required | Description                            |
| --------------------------- | ------- | -------- | -------------------------------------- |
| `positionKey`               | string  | yes      | Position account pubkey to reverse     |
| `owner`                     | string  | yes      | Wallet pubkey                          |
| `slippagePercentage`        | string  | no       | Slippage tolerance                     |
| `tradingFeeDiscountPercent` | number  | no       | Fee discount (0–100)                   |
| `tokenStakeFafAccount`      | string  | no       | FAF stake account                      |
| `userReferralAccount`       | string  | no       | Referral account                       |
| `privilege`                 | string  | no       | `"NONE"`, `"STAKE"`, or `"REFERRAL"`   |
| `degenMode`                 | boolean | no       | Enable degen mode for the new position |

**Response:**

json

```json
{
  "closeReceiveUsd": "105.23",
  "closeFees": "0.36",
  "closeSettledPnl": "5.23",
  "newSide": "Short",
  "newLeverage": "5.00",
  "newEntryPrice": "148.52",
  "newLiquidationPrice": "175.00",
  "newSizeUsd": "500.00",
  "newSizeAmountUi": "3.37",
  "newCollateralUsd": "98.00",
  "openEntryFee": "0.45",
  "transactionBase64": "AQAAAA...",
  "err": null
}
```

{% hint style="info" %}
**Note:** `newCollateralUsd` reflects a 2% haircut applied during the reversal.
{% endhint %}
