> ## Documentation Index
> Fetch the complete documentation index at: https://docs.renesis.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# Execution API

> Unified order execution API with exchange-agnostic parameters

# Execution API

The Execution API provides a **unified interface** for order execution across all supported exchanges. Users specify standard parameters (order\_type, time\_in\_force, stop\_price, etc.) and the system automatically handles exchange-specific translation.

## Key Features

* **Unified Parameters**: Same API works across all exchanges
* **Clear Error Messages**: If an exchange doesn't support a feature, you get a specific error
* **Capability Discovery**: Query what each exchange supports before trading
* **Pre-validation**: Check if your order would be valid before submitting

***

## Unified Order Types

| Order Type          | Description                                            |
| ------------------- | ------------------------------------------------------ |
| `market`            | Execute immediately at best available price            |
| `limit`             | Execute at specified price or better                   |
| `stop_loss`         | Market order triggered when price falls to stop\_price |
| `stop_loss_limit`   | Limit order triggered when price falls to stop\_price  |
| `take_profit`       | Market order triggered when price rises to stop\_price |
| `take_profit_limit` | Limit order triggered when price rises to stop\_price  |
| `trailing_stop`     | Stop order that follows price with trailing\_delta     |
| `oco`               | One-Cancels-Other (limit + stop loss pair)             |

## Time-in-Force Options

| TIF         | Description                                    |
| ----------- | ---------------------------------------------- |
| `GTC`       | Good-Till-Cancelled                            |
| `IOC`       | Immediate-Or-Cancel                            |
| `FOK`       | Fill-Or-Kill                                   |
| `POST_ONLY` | Maker only (rejects if would immediately fill) |

***

## Exchange Capabilities Matrix

### Order Type Support

| Exchange           | market    | limit     | stop\_loss | take\_profit | stop\_limit | trailing\_stop | oco       |
| ------------------ | --------- | --------- | ---------- | ------------ | ----------- | -------------- | --------- |
| **Binance**        | Spot/Perp | Spot/Perp | Spot/Perp  | Spot/Perp    | Spot/Perp   | Perp only      | Spot only |
| **Bybit**          | Spot/Perp | Spot/Perp | Spot/Perp  | Spot/Perp    | Spot/Perp   | Perp only      | -         |
| **Gate.io**        | Spot/Perp | Spot/Perp | Spot/Perp  | Spot/Perp    | Spot/Perp   | -              | -         |
| **Kraken Spot**    | Yes       | Yes       | Yes        | Yes          | Yes         | -              | -         |
| **Kraken Futures** | Yes       | Yes       | Yes        | Yes          | Yes         | -              | -         |
| **Hyperliquid**    | Perp      | Perp      | Perp       | Perp         | Perp        | -              | -         |
| **OKX**            | Spot/Perp | Spot/Perp | Spot/Perp  | Spot/Perp    | Spot/Perp   | Perp only      | Spot only |

Kraken splits across two CCXT classes: spot at `api.kraken.com`
(`ccxt.kraken`) and futures at `futures.kraken.com`
(`ccxt.krakenfutures`). OEMS routes `(kraken, swap|future)` to the
futures class automatically; the caller uses the same unified API.
See [Trading on Kraken](/oems-api/guides/kraken).

### Feature Support

| Exchange           | reduce\_only | post\_only | hedge\_mode | Notes                                                  |
| ------------------ | ------------ | ---------- | ----------- | ------------------------------------------------------ |
| **Binance**        | Perp         | Both       | Perp        | Demo trading uses demo-api.binance.com                 |
| **Bybit**          | Perp         | Both       | Perp        | Uses category param (spot/linear/inverse)              |
| **Gate.io**        | Perp         | Perp       | -           | Spot stop orders use price-triggered endpoint          |
| **Kraken Spot**    | -            | Both       | -           | Uses oflags='post' for post-only                       |
| **Kraken Futures** | Yes          | Yes        | -           | Separate futures API key required (futures.kraken.com) |
| **Hyperliquid**    | Perp         | Perp       | -           | Perp only, requires slippage for market orders         |
| **OKX**            | Perp         | Both       | Perp        | -                                                      |

***

## POST /order-execution/execution/order

Execute an order using unified parameters. The system automatically translates to exchange-specific format.

### Authentication

Requires a valid API key whose user has the `trader` or `admin` role.

### Request Body (JSON)

* **exchange\_account\_id** (string, required): The exchange account UUID (e.g., "binance-sandbox-001")
* **symbol** (string, required): Trading pair in CCXT format (e.g., "BTC/USDT")
* **side** (string, required): Order side: `"buy"` or `"sell"`
* **order\_type** (string, required): Order type: `market`, `limit`, `stop_loss`, `stop_loss_limit`, `take_profit`, `take_profit_limit`, `trailing_stop`, `oco`
* **quantity** (number, required): Order quantity in base asset units
* **price** (number, optional): Limit price. Required for `limit`, `stop_loss_limit`, `take_profit_limit` orders.
* **stop\_price** (number, optional): Trigger price for stop orders. Required for `stop_loss`, `stop_loss_limit`, `take_profit`, `take_profit_limit` orders.
* **trailing\_delta** (number, optional): Trailing delta percentage. Required for `trailing_stop` orders.
* **time\_in\_force** (string, optional): Time-in-force: `GTC`, `IOC`, `FOK`, `POST_ONLY`. Default: `GTC`
* **reduce\_only** (boolean, optional): For perps: only reduce existing position, don't open new one. Default: false
* **post\_only** (boolean, optional): Maker only: reject if order would immediately fill. Default: false
* **client\_order\_id** (string, optional): Optional user-defined order ID for tracking.
* **market\_type** (string, optional): Market type: `spot`, `swap`, or `future`. Default: `spot`

### Request Examples

**Market Order**

```bash theme={null}
curl -X POST https://api.renesis.fi/order-execution/execution/order \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-sandbox-001",
    "symbol": "BTC/USDT",
    "side": "buy",
    "order_type": "market",
    "quantity": 0.001
  }'
```

**Limit Order with Post-Only**

```bash theme={null}
curl -X POST https://api.renesis.fi/order-execution/execution/order \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-sandbox-001",
    "symbol": "BTC/USDT",
    "side": "buy",
    "order_type": "limit",
    "quantity": 0.001,
    "price": 80000,
    "time_in_force": "POST_ONLY"
  }'
```

**Stop Loss Order**

```bash theme={null}
curl -X POST https://api.renesis.fi/order-execution/execution/order \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-sandbox-001",
    "symbol": "BTC/USDT",
    "side": "sell",
    "order_type": "stop_loss",
    "quantity": 0.001,
    "stop_price": 85000
  }'
```

**Stop Loss Limit Order**

```bash theme={null}
curl -X POST https://api.renesis.fi/order-execution/execution/order \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-sandbox-001",
    "symbol": "BTC/USDT",
    "side": "sell",
    "order_type": "stop_loss_limit",
    "quantity": 0.001,
    "price": 84000,
    "stop_price": 85000
  }'
```

**Trailing Stop Order** (Binance Futures)

```bash theme={null}
curl -X POST https://api.renesis.fi/order-execution/execution/order \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-sandbox-001",
    "symbol": "BTC/USDT:USDT",
    "side": "sell",
    "order_type": "trailing_stop",
    "quantity": 0.001,
    "trailing_delta": 1.0,
    "market_type": "swap"
  }'
```

**Perp Order with Reduce-Only**

```bash theme={null}
curl -X POST https://api.renesis.fi/order-execution/execution/order \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "bybit-001",
    "symbol": "BTC/USDT:USDT",
    "side": "sell",
    "order_type": "market",
    "quantity": 0.001,
    "reduce_only": true,
    "market_type": "swap"
  }'
```

### Response Examples

**Successful Order**

```json theme={null}
{
  "isError": false,
  "message": "Order executed successfully",
  "statusCode": 200,
  "data": {
    "order_id": "12345678",
    "exchange": "binance",
    "market": "BTC/USDT",
    "order_type": "market",
    "order_side": "buy",
    "order_status": "closed",
    "quantity": 0.001,
    "quantity_filled": 0.001,
    "avg_fill_price": 43250.50,
    "order_fee": 0.0432505,
    "fee_currency": "USDT",
    "execution_time": 0.342,
    "execution_date": "2025-01-15T10:30:00Z"
  }
}
```

**Unsupported Feature**

```json theme={null}
{
  "isError": true,
  "message": "Gate.io does not support trailing_stop orders",
  "statusCode": 400,
  "data": {
    "exchange": "gateio",
    "order_type": "trailing_stop",
    "market_type": "spot"
  }
}
```

**Daily Limit Exceeded**

```json theme={null}
{
  "isError": true,
  "message": "Order would exceed daily limit. Remaining: $23.50",
  "statusCode": 400,
  "data": {
    "error": "DAILY_LIMIT_EXCEEDED",
    "limit_check": {
      "allowed": false,
      "order_value_usd": 100.00,
      "remaining_usd": 23.50
    }
  }
}
```

***

## GET /order-execution/execution/capabilities

Query what order types, time-in-force options, and features each exchange supports.

### Query Parameters

* **exchange** (string, optional): Exchange name. If not provided, returns all exchanges.

### Request Example

```bash theme={null}
# Get Binance capabilities
curl "https://api.renesis.fi/order-execution/execution/capabilities?exchange=binance" \
  -H "X-API-Key: $API_KEY"

# Get all exchange capabilities
curl "https://api.renesis.fi/order-execution/execution/capabilities" \
  -H "X-API-Key: $API_KEY"
```

### Response Examples

**Single Exchange**

```json theme={null}
{
  "isError": false,
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "supports_spot": true,
    "supports_perp": true,
    "spot": {
      "order_types": ["limit", "market", "oco", "stop_loss", "stop_loss_limit", "take_profit", "take_profit_limit"],
      "time_in_force": ["FOK", "GTC", "IOC"],
      "features": ["post_only"]
    },
    "perp": {
      "order_types": ["limit", "market", "stop_loss", "stop_loss_limit", "take_profit", "take_profit_limit", "trailing_stop"],
      "time_in_force": ["FOK", "GTC", "IOC", "POST_ONLY"],
      "features": ["hedge_mode", "portfolio_margin", "post_only", "reduce_only"]
    },
    "notes": {
      "trailing_stop": "Only available on futures (TRAILING_STOP_MARKET)",
      "oco": "Only available on spot"
    }
  }
}
```

**All Exchanges**

```json theme={null}
{
  "isError": false,
  "statusCode": 200,
  "data": {
    "exchanges": {
      "binance": { "..." },
      "bybit": { "..." },
      "gateio": { "..." },
      "kraken": { "..." },
      "hyperliquid": { "..." },
      "okx": { "..." }
    }
  }
}
```

***

## POST /order-execution/execution/validate

Check if an order would be valid for a specific exchange before submitting.

### Request Body (JSON)

* **exchange** (string, required): Exchange name (e.g., "binance", "gateio")
* **order\_type** (string, required): Order type to validate
* **market\_type** (string, optional): Market type: `spot`, `swap`, or `future`. Default: `spot`
* **time\_in\_force** (string, optional): Time-in-force option to validate
* **reduce\_only** (boolean, optional): Check if reduce\_only is supported. Default: false
* **post\_only** (boolean, optional): Check if post\_only is supported. Default: false
* **stop\_price** (number, optional): Include to validate stop order requirements
* **trailing\_delta** (number, optional): Include to validate trailing stop requirements

### Request Example

```bash theme={null}
# Check if trailing_stop is supported on Gate.io spot
curl -X POST https://api.renesis.fi/order-execution/execution/validate \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange": "gateio",
    "order_type": "trailing_stop",
    "market_type": "spot"
  }'
# Returns: "Gate.io does not support trailing_stop orders"
```

### Response Examples

**Valid**

```json theme={null}
{
  "isError": false,
  "message": "Order parameters are valid",
  "statusCode": 200,
  "data": {
    "valid": true,
    "error": null,
    "warnings": []
  }
}
```

**Invalid**

```json theme={null}
{
  "isError": true,
  "message": "Hyperliquid does not support spot trading",
  "statusCode": 400,
  "data": {
    "valid": false,
    "error": "Hyperliquid does not support spot trading",
    "warnings": []
  }
}
```

***

## GET /order-execution/execution/order/{order_id}

Fetch the current status of an order from the exchange.

A successful fetch also writes the live status back to the order's
`meta_orders` record (`order_status`, `quantity_filled`, `avg_fill_price`,
fee, `last_traded_timestamp`), so a resting order that filled after
submission stops showing a stale `open` in order listings. Error results
(e.g. ORDER\_NOT\_FOUND) never modify the record.

### Path Parameters

* **order\_id** (string, required): The exchange order ID

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, optional): Trading symbol (required by some exchanges)
* **market\_type** (string, optional): Market type: `spot`, `swap`, or `future`. Default: `spot`. If the symbol is a derivative (contains `:`, e.g. `BTC/USD:USD`) and `market_type` is omitted, it is derived as `swap` automatically. On Kraken this routes to the futures instance (`ccxt.krakenfutures`) instead of spot. Pass `future` explicitly for dated futures if needed.

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/order/12345678?exchange_account_id=binance-sandbox-001&symbol=BTC/USDT" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "order_id": "12345678",
    "symbol": "BTC/USDT",
    "status": "closed",
    "type": "market",
    "side": "buy",
    "price": null,
    "amount": 0.001,
    "filled": 0.001,
    "remaining": 0,
    "average": 43250.50,
    "cost": 43.25,
    "fee": { "cost": 0.04325, "currency": "USDT" },
    "timestamp": 1705315800000,
    "datetime": "2025-01-15T10:30:00Z"
  }
}
```

***

## DELETE /order-execution/execution/order/{order_id}

Cancel an open order on the exchange.

### Path Parameters

* **order\_id** (string, required): The exchange order ID to cancel

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, optional): Trading symbol (required by some exchanges)
* **market\_type** (string, optional): Market type: `spot`, `swap`, or `future`. Default: `spot`

### Request Example

```bash theme={null}
curl -X DELETE "https://api.renesis.fi/order-execution/execution/order/12345678?exchange_account_id=binance-sandbox-001&symbol=BTC/USDT" \
  -H "X-API-Key: $API_KEY"
```

***

## GET /order-execution/execution/balance

Fetch account balance from the exchange.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **market\_type** (string, optional): Market type: `spot`, `swap`, or `future`. Default: `spot`

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/balance?exchange_account_id=gateio-001" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "exchange": "gateio",
    "exchange_account_id": "gateio-001",
    "free": { "BTC": 0.00033967, "USDT": 0.30120829 },
    "used": { "BTC": 0.0001 },
    "total": { "BTC": 0.00043967, "USDT": 0.30120829 }
  }
}
```

***

## GET /order-execution/execution/orders/open

Fetch all open orders from the exchange.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, optional): Filter by trading symbol
* **market\_type** (string, optional): Market type: `spot`, `swap`, or `future`. Default: `spot`

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/orders/open?exchange_account_id=binance-sandbox-001" \
  -H "X-API-Key: $API_KEY"
```

***

## GET /order-execution/execution/daily-limit

Get the daily trading limit status for an exchange account.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/daily-limit?exchange_account_id=gateio-001" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "date": "2025-01-15",
    "exchange_account_id": "gateio-001",
    "limit_usd": 100.00,
    "used_usd": 76.50,
    "remaining_usd": 23.50,
    "pct_used": 76.5,
    "order_count": 3
  }
}
```

***

## Error Codes

| Error Code                | Status | Description                                 |
| ------------------------- | ------ | ------------------------------------------- |
| `DAILY_LIMIT_EXCEEDED`    | 400    | Order would exceed daily trading limit      |
| `DEV_MODE_LIMIT_EXCEEDED` | 400    | Order exceeds DEV\_MODE safety limit (\$50) |
| `INSUFFICIENT_BALANCE`    | 400    | Not enough balance for order                |
| `INSUFFICIENT_MARGIN`     | 400    | Not enough margin (futures)                 |
| `EXCHANGE_ERROR`          | 500    | Exchange returned an error                  |
| `NETWORK_ERROR`           | 500    | Network error after max retries             |
| `ORDER_NOT_FOUND`         | 404    | Order not found on exchange                 |

***

## Migration from Legacy API

If you were using the old `params` object for exchange-specific parameters, here's how to migrate:

**Before (Legacy)**

```json theme={null}
{
  "order_type": "stop_loss_limit",
  "price": 84000,
  "params": {
    "stopPrice": 85000,
    "timeInForce": "GTC"
  }
}
```

**After (Unified)**

```json theme={null}
{
  "order_type": "stop_loss_limit",
  "price": 84000,
  "stop_price": 85000,
  "time_in_force": "GTC"
}
```

The unified API handles all exchange-specific translation automatically. If you try to use a feature that an exchange doesn't support, you'll get a clear error message like "Gate.io does not support trailing\_stop orders" instead of a cryptic exchange error.

***

# Futures/Perpetuals Endpoints

The following endpoints are specific to futures and perpetual trading.

***

## POST /order-execution/execution/leverage

Set leverage for a symbol on futures/perp markets.

### Request Body (JSON)

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, required): Trading pair in perp format (e.g., "BTC/USDT:USDT")
* **leverage** (number, required): Leverage value (e.g., 1, 5, 10, 20, 50, 100)
* **market\_type** (string, optional): `swap` or `future`. Default: `swap`

### Request Example

```bash theme={null}
curl -X POST "https://api.renesis.fi/order-execution/execution/leverage" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-perp-001",
    "symbol": "BTC/USDT:USDT",
    "leverage": 10
  }'
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Leverage set to 10x for BTC/USDT:USDT",
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "exchange_account_id": "binance-perp-001",
    "symbol": "BTC/USDT:USDT",
    "leverage": 10,
    "result": { "leverage": 10, "symbol": "BTCUSDT" }
  }
}
```

***

## GET /order-execution/execution/leverage

Get current leverage and margin mode for a symbol.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, required): Trading pair (e.g., "BTC/USDT:USDT")
* **market\_type** (string, optional): `swap` or `future`. Default: `swap`

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/leverage?exchange_account_id=binance-perp-001&symbol=BTC/USDT:USDT" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "exchange_account_id": "binance-perp-001",
    "symbol": "BTC/USDT:USDT",
    "leverage": 10,
    "margin_mode": "cross",
    "position_side": "long",
    "position_size": 0.05,
    "notional": 4925.25,
    "unrealized_pnl": 125.50
  }
}
```

***

## POST /order-execution/execution/margin-mode

Set margin mode (cross or isolated) for a symbol.

### Request Body (JSON)

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, required): Trading pair (e.g., "BTC/USDT:USDT")
* **margin\_mode** (string, required): `cross` or `isolated`
* **market\_type** (string, optional): `swap` or `future`. Default: `swap`

### Request Example

```bash theme={null}
curl -X POST "https://api.renesis.fi/order-execution/execution/margin-mode" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-perp-001",
    "symbol": "BTC/USDT:USDT",
    "margin_mode": "isolated"
  }'
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Margin mode set to isolated for BTC/USDT:USDT",
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "exchange_account_id": "binance-perp-001",
    "symbol": "BTC/USDT:USDT",
    "margin_mode": "isolated",
    "result": {}
  }
}
```

***

## GET /order-execution/execution/positions

Fetch open positions from exchange (futures/perp only).

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, optional): Filter by symbol
* **market\_type** (string, optional): `swap` or `future`. Default: `swap`

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/positions?exchange_account_id=binance-perp-001" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "positions": [
      {
        "symbol": "BTC/USDT:USDT",
        "side": "long",
        "contracts": 0.05,
        "contract_size": 1,
        "entry_price": 98000.00,
        "mark_price": 98505.00,
        "notional": 4925.25,
        "leverage": 10,
        "unrealized_pnl": 25.25,
        "percentage": 0.51,
        "margin_mode": "cross",
        "liquidation_price": 88200.00,
        "collateral": 492.52,
        "timestamp": 1706745600000,
        "datetime": "2025-01-31T12:00:00Z",
        "exchange": "binance",
        "exchange_account_id": "binance-perp-001"
      }
    ],
    "count": 1
  }
}
```

***

## GET /order-execution/execution/funding-history

Fetch funding rate payments for perpetual futures.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, optional): Filter by symbol
* **since** (number, optional): Start timestamp in milliseconds
* **limit** (number, optional): Max number of records
* **market\_type** (string, optional): `swap` or `future`. Default: `swap`

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/funding-history?exchange_account_id=binance-perp-001&symbol=BTC/USDT:USDT&limit=10" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "exchange_account_id": "binance-perp-001",
    "symbol": "BTC/USDT:USDT",
    "payments": [
      {
        "id": "123456789",
        "symbol": "BTC/USDT:USDT",
        "amount": -0.15,
        "code": "USDT",
        "timestamp": 1706745600000,
        "datetime": "2025-01-31T12:00:00Z",
        "info": {}
      }
    ],
    "count": 1
  }
}
```

***

## GET /order-execution/execution/funding-rate

Fetch the current and predicted funding rate for a perpetual symbol, with the annualized APR precomputed. The predicted rate is the venue's own live estimate of the next print.

Responses are served through a server-side cache (about 30 seconds), so this endpoint is safe to poll.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, required): Perp symbol, e.g. `BTC/USD:USD`
* **market\_type** (string, optional): `swap` or `future`. Default: `swap`; derived from the symbol's `:` convention when omitted

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/funding-rate?exchange_account_id=kraken-001&symbol=BTC/USD:USD" \
  -H "Authorization: Bearer $TOKEN"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "exchange": "krakenfutures",
    "exchange_account_id": "kraken-001",
    "symbol": "BTC/USD:USD",
    "funding_rate": 0.0001,
    "predicted_rate": 0.00012,
    "predicted_rate_source": "next",
    "funding_interval_hours": 8.0,
    "windows_per_year": 1095.0,
    "predicted_apr_pct": 13.14,
    "mark_price": 100250.0,
    "index_price": 100240.0,
    "next_funding_timestamp": null,
    "timestamp": 1765400000000
  }
}
```

Field notes:

* **funding\_rate / predicted\_rate**: relative rates per funding window, as normalized by ccxt. For Kraken Futures, ccxt converts the venue's hourly absolute rate to an 8h-equivalent relative rate, so values are on the same scale as Binance/Bybit.
* **predicted\_rate\_source**: `next` when the venue publishes a next-window estimate, `current` when the current rate is used as the fallback.
* **predicted\_apr\_pct**: `predicted_rate x windows_per_year x 100`. Positive APR means shorts collect.
* Venues without a funding-rate endpoint return a `NOT_SUPPORTED` error.

***

## GET /order-execution/execution/realized-pnl

Fetch realized PnL for perpetual futures positions.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **symbol** (string, optional): Filter by symbol
* **since** (number, optional): Start timestamp in milliseconds
* **limit** (number, optional): Max number of records
* **market\_type** (string, optional): `swap` or `future`. Default: `swap`

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/realized-pnl?exchange_account_id=binance-perp-001&limit=10" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "exchange_account_id": "binance-perp-001",
    "symbol": null,
    "entries": [
      {
        "id": "987654321",
        "symbol": "BTC/USDT:USDT",
        "amount": 125.50,
        "code": "USDT",
        "timestamp": 1706745600000,
        "datetime": "2025-01-31T12:00:00Z",
        "info": {}
      }
    ],
    "count": 1
  }
}
```

***

# Inter-Wallet Transfer

## Transfer Funds

<Api method="POST" path="/order-execution/execution/transfer" />

Move balance between two wallets on the **same** exchange account.
Used primarily for Kraken (spot ↔ futures, since they're separate
products at `api.kraken.com` vs `futures.kraken.com`), but the unified
shape works on any exchange whose CCXT class exposes `exchange.transfer(...)` ,
Binance (spot ↔ usdm/coinm), OKX (funding ↔ trading), Gate.io.

Bybit UTA and Hyperliquid have a single wallet and return
`NOT_SUPPORTED`.

### Authentication

Requires a valid API key whose user has the `trader` or `admin` role.

### Request Body

<ParamField body="exchange_account_id" type="string" required>
  The exchange account UUID
</ParamField>

<ParamField body="asset" type="string" required>
  Asset code, e.g. `"USD"`, `"USDT"`, `"BTC"`
</ParamField>

<ParamField body="amount" type="number" required>
  Positive amount to move
</ParamField>

<ParamField body="from_account" type="string" required>
  Source wallet: `spot`, `swap`, `future`, `margin`, `funding`, `main`, `savings`
</ParamField>

<ParamField body="to_account" type="string" required>
  Destination wallet (same vocabulary as `from_account`, must differ)
</ParamField>

### Response

<ResponseExample>
  ```json 200 theme={null}
  {
    "isError": false,
    "message": "Transfer successful",
    "statusCode": 200,
    "data": {
      "exchange": "krakenfutures",
      "exchange_account_id": "exchange_my_kraken",
      "asset": "USD",
      "amount": 100.0,
      "from": "spot",
      "to": "swap",
      "response": { ... }
    }
  }
  ```

  ```json 400 Single-wallet exchange theme={null}
  {
    "isError": true,
    "message": "bybit does not support inter-wallet transfers (unified-account or single-wallet exchange)",
    "statusCode": 400,
    "data": { "error": "NOT_SUPPORTED" }
  }
  ```
</ResponseExample>

### Example, Kraken spot → futures

```bash theme={null}
curl -X POST "https://api.renesis.fi/order-execution/execution/transfer" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "exchange_my_kraken",
    "asset": "USD",
    "amount": 100,
    "from_account": "spot",
    "to_account": "swap"
  }'
```

### Example, Binance spot → USDⓈ-M futures

```bash theme={null}
curl -X POST "https://api.renesis.fi/order-execution/execution/transfer" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-001",
    "asset": "USDT",
    "amount": 500,
    "from_account": "spot",
    "to_account": "swap"
  }'
```

***

# Portfolio Margin Endpoints (Binance)

The following endpoints are specific to Binance Portfolio Margin accounts. Portfolio Margin is a unified margin account that combines cross margin, USDⓈ-M Futures, and COIN-M Futures.

***

## GET /order-execution/execution/portfolio-margin/balance

Get Portfolio Margin balance from Binance PAPI.

Returns detailed breakdown of:

* **Cross Margin**: Total, free, locked, borrowed, interest
* **USDⓈ-M Futures**: Wallet balance, unrealized PnL
* **COIN-M Futures**: Wallet balance, unrealized PnL

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID (must be a Binance PM account)

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/portfolio-margin/balance?exchange_account_id=binance-pm-001" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "exchange_account_id": "binance-pm-001",
    "assets": {
      "USDT": {
        "cross_margin": {
          "total": 10000.00,
          "free": 8500.00,
          "locked": 1500.00,
          "borrowed": 0,
          "interest": 0
        },
        "um_futures": {
          "wallet": 2500.00,
          "unrealized_pnl": 125.50
        },
        "cm_futures": {
          "wallet": 0,
          "unrealized_pnl": 0
        },
        "total_wallet_balance": 12500.00,
        "negative_balance": 0
      },
      "BTC": {
        "cross_margin": {
          "total": 0.5,
          "free": 0.45,
          "locked": 0.05,
          "borrowed": 0,
          "interest": 0
        },
        "um_futures": {
          "wallet": 0,
          "unrealized_pnl": 0
        },
        "cm_futures": {
          "wallet": 0.1,
          "unrealized_pnl": 0.005
        },
        "total_wallet_balance": 0.6,
        "negative_balance": 0
      }
    }
  }
}
```

***

## GET /order-execution/execution/portfolio-margin/account

Get Portfolio Margin account info from Binance PAPI.

Returns raw PAPI balance and UM account data.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID (must be a Binance PM account)

### Request Example

```bash theme={null}
curl "https://api.renesis.fi/order-execution/execution/portfolio-margin/account?exchange_account_id=binance-pm-001" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "exchange": "binance",
    "exchange_account_id": "binance-pm-001",
    "papi_balance": [
      {
        "asset": "USDT",
        "crossMarginAsset": "10000.00",
        "crossMarginFree": "8500.00",
        "crossMarginLocked": "1500.00",
        "umWalletBalance": "2500.00",
        "umUnrealizedPNL": "125.50",
        "cmWalletBalance": "0",
        "cmUnrealizedPNL": "0",
        "totalWalletBalance": "12500.00"
      }
    ],
    "papi_um_account": {
      "totalInitialMargin": "1000.00",
      "totalMaintMargin": "200.00",
      "totalWalletBalance": "12500.00",
      "totalUnrealizedProfit": "125.50",
      "totalMarginBalance": "12625.50",
      "availableBalance": "11500.00",
      "maxWithdrawAmount": "11500.00"
    }
  }
}
```

***

## POST /order-execution/execution/portfolio-margin/auto-collection

Trigger auto-collection for Portfolio Margin account.

Transfers **all positive balances** from USDⓈ-M and COIN-M Futures Wallets to Cross Margin Wallet.

<Warning>
  BNB in USDⓈ-M Futures Wallet will NOT be transferred.
</Warning>

### Request Body (JSON)

* **exchange\_account\_id** (string, required): The exchange account UUID (must be a Binance PM account)

### Request Example

```bash theme={null}
curl -X POST "https://api.renesis.fi/order-execution/execution/portfolio-margin/auto-collection" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-pm-001"
  }'
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Auto-collection triggered successfully",
  "statusCode": 200,
  "data": {
    "success": true,
    "exchange": "binance",
    "exchange_account_id": "binance-pm-001",
    "response": {}
  }
}
```

***

## POST /order-execution/execution/portfolio-margin/asset-collection

Trigger asset-specific collection for Portfolio Margin account.

Transfers a **specific asset** from Futures Account to Margin account.

<Warning>
  BNB transfer is NOT supported.
</Warning>

### Request Body (JSON)

* **exchange\_account\_id** (string, required): The exchange account UUID (must be a Binance PM account)
* **asset** (string, required): Asset to transfer (e.g., "USDT", "BTC")

### Request Example

```bash theme={null}
curl -X POST "https://api.renesis.fi/order-execution/execution/portfolio-margin/asset-collection" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange_account_id": "binance-pm-001",
    "asset": "USDT"
  }'
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Asset-collection triggered for USDT",
  "statusCode": 200,
  "data": {
    "success": true,
    "exchange": "binance",
    "exchange_account_id": "binance-pm-001",
    "asset": "USDT",
    "response": {}
  }
}
```

***

## Portfolio Margin Notes

### What is Portfolio Margin?

Portfolio Margin is a margin system that calculates margin requirements based on the overall risk of your portfolio, rather than individual positions. This typically results in **lower margin requirements** compared to traditional isolated margin.

### Key Concepts

| Concept             | Description                                            |
| ------------------- | ------------------------------------------------------ |
| **Cross Margin**    | Shared margin pool across all positions                |
| **USDⓈ-M Futures**  | USD-margined perpetual/delivery contracts              |
| **COIN-M Futures**  | Coin-margined perpetual/delivery contracts             |
| **Auto-Collection** | Moves funds from Futures to Cross Margin automatically |
| **uniMMR**          | Unified Maintenance Margin Ratio across all accounts   |

### Setting Up Portfolio Margin

To use Portfolio Margin endpoints, your Binance account must:

1. Have Portfolio Margin enabled on Binance (requires manual application)
2. Be registered in Renesis with `portfolio_margin: true`
3. Meet Binance's minimum equity requirements (\$100,000+ in some regions)

### PAPI Endpoints Used

These endpoints call Binance's Portfolio Margin API (PAPI):

| Endpoint                             | PAPI Endpoint                  | Description             |
| ------------------------------------ | ------------------------------ | ----------------------- |
| `/portfolio-margin/balance`          | GET /papi/v1/balance           | Full balance breakdown  |
| `/portfolio-margin/account`          | GET /papi/v1/um/account        | UM account info         |
| `/portfolio-margin/auto-collection`  | POST /papi/v1/auto-collection  | Transfer all assets     |
| `/portfolio-margin/asset-collection` | POST /papi/v1/asset-collection | Transfer specific asset |

***

## GET /oems/tca/report

Account-wide Transaction Cost Analysis over a lookback window: slippage vs mark, maker/taker capture, effective fee rate vs the account's tier, cost drag as bps of turnover and % of NAV, post-fill markout (adverse-selection signal), a detailed `adverse_selection` block (markout term structure, spread decomposition, per-fill distribution), a per-symbol breakdown, and a daily time-series for trend charts. Covers all fills (manual, algo, SOR), not just algo runs. Complements the per-algo TCA (which benchmarks a single algo run against its arrival price).

Slippage is benchmarked against the mark price at fill time; positive = cost. Maker fills that rest and fill better than mark show negative slippage (price improvement).

Slippage and markout require a mark price, which exists only on perps, so the report is perp-first (`market_type=swap`). On `market_type=spot` those blocks are null and only fees are reported; spot fees are charged in the base asset and are converted to USD so cost bps is not inflated by `1/price`.

Markout is the price drift in the minutes after each fill (default horizon 5m), signed so positive = favourable to the position and negative = adverse. A persistently negative *maker* markout means passive orders were getting run over: `maker_net_edge_bps` (fee saved by resting + maker markout) below zero flags fills where crossing (taker) would have been cheaper.

### Query Parameters

* **exchange\_account\_id** (string, required): The exchange account UUID
* **market\_type** (string, optional): `swap` or `spot`. Default: `swap`. Slippage/markout are perp-only.
* **symbol** (string, optional): Restrict to one symbol
* **start** / **end** (int ms, optional): Window bounds. Default: last 30 days

### Request Example

```bash theme={null}
curl "http://localhost:8082/oems/tca/report?exchange_account_id=bybit-001&market_type=swap" \
  -H "X-API-Key: $API_KEY"
```

### Response Example

```json theme={null}
{
  "isError": false,
  "message": "Success",
  "statusCode": 200,
  "data": {
    "window": { "start": 1704067200000, "end": 1706745600000 },
    "turnover": 1250000.0,
    "turnover_pct_nav": 480.0,
    "nav": 260000.0,
    "fill_count": 842,
    "cost": {
      "total_cost_usd": 400.0,
      "cost_drag_bps": 3.2,
      "cost_drag_pct_nav": 0.154,
      "slippage_bps": 1.1,
      "fee_bps": 2.1,
      "maker_slippage_bps": -0.3,
      "taker_slippage_bps": 2.4
    },
    "fills": { "maker_pct": 41.0, "taker_pct": 59.0 },
    "fees": {
      "total": 262.5,
      "effective_bps": 2.1,
      "tier_maker_bps": 0.2,
      "tier_taker_bps": 0.55,
      "taker_flow_pct": 59.0,
      "rebate_gap_bps": 0.2,
      "estimated": false
    },
    "markout": {
      "horizon_min": 5,
      "markout_bps": -0.4,
      "maker_markout_bps": -1.2,
      "taker_markout_bps": 0.3,
      "fee_saved_bps": 0.35,
      "maker_net_edge_bps": -0.85
    },
    "by_symbol": [
      { "symbol": "SOL/USDT:USDT", "notional": 500000.0, "cost_bps": 5.1, "slippage_bps": 3.2, "fee_bps": 1.9, "markout_bps": -0.6, "maker_pct": 30.0, "fill_count": 210 }
    ],
    "by_day": [
      { "date": 1704067200000, "maker_pct": 38.0, "taker_pct": 62.0, "cost_bps": 3.5, "slippage_bps": 1.3, "fee_bps": 2.2, "markout_bps": -0.5, "turnover": 42000.0, "fill_count": 31 }
    ],
    "adverse_selection": {
      "horizons_min": [1, 2, 5, 15, 30],
      "primary_horizon_min": 5,
      "markout_curve_bps": [
        { "horizon_min": 1, "markout_bps": -2.1 },
        { "horizon_min": 2, "markout_bps": -0.8 },
        { "horizon_min": 5, "markout_bps": 0.3 },
        { "horizon_min": 15, "markout_bps": 1.4 },
        { "horizon_min": 30, "markout_bps": 1.9 }
      ],
      "maker_markout_curve_bps": [],
      "taker_markout_curve_bps": [
        { "horizon_min": 1, "markout_bps": -2.1 },
        { "horizon_min": 5, "markout_bps": 0.3 }
      ],
      "spread_decomposition": {
        "effective_spread_bps": 0.7,
        "price_impact_bps": 0.3,
        "realized_spread_bps": 0.4
      },
      "distribution": {
        "fills": 210,
        "median_bps": 0.2,
        "p25_bps": -1.1,
        "p75_bps": 1.8,
        "worst_bps": -14.3,
        "best_bps": 22.6,
        "adverse_fill_pct": 41.0,
        "low_sample": false
      },
      "by_symbol": [
        {
          "symbol": "SOL/USDT:USDT",
          "notional": 500000.0,
          "markout_curve_bps": [ { "horizon_min": 5, "markout_bps": -0.6 } ],
          "spread_decomposition": { "effective_spread_bps": 3.2, "price_impact_bps": -0.6, "realized_spread_bps": 3.8 },
          "distribution": { "fills": 210, "median_bps": -0.4, "p25_bps": -2.0, "p75_bps": 1.1, "worst_bps": -18.0, "best_bps": 12.0, "adverse_fill_pct": 55.0, "low_sample": false },
          "fill_count": 210
        }
      ]
    },
    "meta": { "exchange": "bybit", "market_type": "swap", "markout_horizon_min": 5, "markout_horizons_min": [1, 2, 5, 15, 30] }
  }
}
```

`rebate_gap_bps` = bps of turnover you would save by shifting the taker portion of flow to maker (at your tier's maker/taker rates). Fills without a mark price are excluded from slippage but still counted in fees and turnover. `by_day.date` is the day-start epoch ms (UTC); rows are sorted ascending for trend charts. `fees.estimated` is true when a venue omits per-fill fees (e.g. Kraken Futures `/fills`) and the fee was computed from your deterministic tier rate (`notional x rate`) rather than reported per fill.

### Adverse selection (`adverse_selection`)

The detailed post-fill analysis, one level below the scalar `markout` block. The scalar `markout` is a single point at the primary horizon (5m); this block adds the shape, the microstructure decomposition, and the distribution.

* **`markout_curve_bps`** (and `maker_`/`taker_` splits): the markout **term structure**, i.e. volume-weighted signed drift measured at each horizon in `horizons_min` (`[1, 2, 5, 15, 30]` minutes). The shape is the read: an early dip that recovers means you crossed into momentum or got picked off at entry; a rise that fades means your resting flow gets faded. Horizons vary per fill (recent fills have not reached the longer ones yet), so each horizon is aggregated over the fills that have it. Horizons below 1m are not available (1m is the OHLCV floor).
* **`spread_decomposition`**: the identity `effective_spread = realized_spread + price_impact`, from the liquidity taker's side. `effective_spread_bps` is the concession paid vs mark at the fill (the slippage). `price_impact_bps` is the post-fill drift in the trade's favour (the markout) and is the information / adverse-selection component the resting counterparty bore. `realized_spread_bps = effective - impact` is what a maker on the other side actually kept; negative means the makers who filled you lost money after the drift, i.e. your flow was informed ("toxic").
* **`distribution`**: the spread of per-fill markout at the primary horizon (median, quartiles, best/worst, and `adverse_fill_pct` = share of fills with negative markout). A mean hides that a couple of toxic fills can dominate. `low_sample` is true when the fill count is too small (\< 5) to read as stable.
* **`by_symbol`**: the same curve, decomposition, and distribution per symbol.

***

## GET /oems/tca/metrics

Headline-only variant of `/tca/report` (the `cost`, `fills`, `fees`, `markout`, and `adverse_selection` blocks, without the per-symbol or daily breakdown) for compact widgets and alerts. Same query parameters.
