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

# Close Position

> Close an existing position using a reduce-only order

Close an existing position using a reduce-only order. The router mirrors the behaviour of the open endpoint—scanning all supported venues for the best exit price unless you force a specific exchange.

## Features

* **Reduce-only safety**: Guarantees the API only decreases exposure
* **Smart venue selection**: Routes exits to the venue with the best available price
* **Partial or full closes**: Specify any size up to the total position
* **Consistent payloads**: Response structure matches the open position endpoint for easy reconciliation

## Use Cases

* Automate take-profit or stop-loss workflows across multiple exchanges
* Build UI flows for one-click position unwinds
* Implement partial de-risking strategies using precise quantities
* Maintain audit trails with routing and execution metadata in a single response

## Request

* **Method**: `POST`
* **Endpoint**: `/api/trade/position/close`
* **Authentication**: Required

## Request Fields

| Field               | Type   | Required | Description                                                          |
| ------------------- | ------ | -------- | -------------------------------------------------------------------- |
| `symbol`            | string | ✅        | Asset symbol being closed                                            |
| `direction`         | string | ✅        | Direction of the position you are closing (`LONG` or `SHORT`)        |
| `size`              | string | ✅        | Quantity to close (must not exceed open position size)               |
| `orderType`         | string | ❌        | `MARKET` by default; `LIMIT` supported when `limitPrice` is supplied |
| `limitPrice`        | string | ❌        | Required when `orderType` is `LIMIT`                                 |
| `preferredExchange` | string | ❌        | Force close on a specific venue                                      |
| `credentials`       | object | ✅        | Exchange credentials required for execution                          |

The response mirrors the **Open Position** endpoint, returning execution, routing, and position data so you can reconcile final fills.

## Usage Tips

* Reduce-only semantics ensure the API never increases exposure while closing.
* Provide credentials only for venues you wish to use; missing credentials remove that venue from routing consideration.
* For partial closes, set `size` to the exact quantity you want to reduce.

<Tip>
  Combine `/api/trade/position/open` and `/api/trade/position/close` in your workflow to ladder into and out of positions while keeping routing logic centralized.
</Tip>

***

## Hyperliquid - Close Single Position

Close a specific open position for a given symbol on Hyperliquid.

### Endpoint

`POST /api/hyperliquid/:walletId/positions/close/:symbol`

### Path Parameters

| Parameter  | Type   | Required | Description                |
| ---------- | ------ | -------- | -------------------------- |
| `walletId` | string | Yes      | Wallet ID (UUID)           |
| `symbol`   | string | Yes      | Asset symbol (e.g., "BTC") |

### Headers

| Header         | Value            | Required |
| -------------- | ---------------- | -------- |
| `x-wallet-id`  | Wallet ID (UUID) | Yes      |
| `Content-Type` | application/json | Yes      |

### Request Body

```json theme={null}
{
  "userId": "ee337309-3e77-4278-b21a-4681468168ba",
  "symbol": "BTC-PERP",
  "side": "BUY",
  "type": "MARKET",
  "quantity": "0.1",
  "price": "1",
  "reduceOnly": true
}
```

### Request Parameters

| Field        | Type    | Required | Description                            |
| ------------ | ------- | -------- | -------------------------------------- |
| `userId`     | string  | Yes      | User's wallet ID                       |
| `symbol`     | string  | Yes      | Trading pair (e.g., "BTC-PERP")        |
| `side`       | string  | Yes      | "BUY" or "SELL" (opposite of position) |
| `type`       | string  | Yes      | "MARKET" or "LIMIT"                    |
| `quantity`   | string  | Yes      | Quantity to close                      |
| `price`      | string  | Yes      | Price for the order                    |
| `reduceOnly` | boolean | Yes      | Must be `true` for closing positions   |

### Example Request

```bash theme={null}
curl -X POST https://api.tide.ag/api/hyperliquid/a1e82339-29f8-41a6-a468-ce8d268a3261/positions/close/BTC \
  -H "x-wallet-id: a1e82339-29f8-41a6-a468-ce8d268a3261" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "ee337309-3e77-4278-b21a-4681468168ba",
    "symbol": "BTC-PERP",
    "side": "BUY",
    "type": "MARKET",
    "quantity": "0.1",
    "price": "1",
    "reduceOnly": true
  }'
```

### Success Response

```json theme={null}
{
  "success": true,
  "data": {
    "closeId": "c2394ab3",
    "status": "submitted",
    "timestamp": 1698840000000
  }
}
```

***

## Hyperliquid - Close All Positions

Close all open positions for the wallet on Hyperliquid.

### Endpoint

`POST /api/hyperliquid/:walletId/positions/close-all`

### Path Parameters

| Parameter  | Type   | Required | Description      |
| ---------- | ------ | -------- | ---------------- |
| `walletId` | string | Yes      | Wallet ID (UUID) |

### Headers

| Header         | Value            | Required |
| -------------- | ---------------- | -------- |
| `x-wallet-id`  | Wallet ID (UUID) | Yes      |
| `Content-Type` | application/json | Yes      |

### Request Body

Same schema as close-single-symbol.

### Example Request

```bash theme={null}
curl -X POST https://api.tide.ag/api/hyperliquid/a1e82339-29f8-41a6-a468-ce8d268a3261/positions/close-all \
  -H "x-wallet-id: a1e82339-29f8-41a6-a468-ce8d268a3261" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "a1e82339-29f8-41a6-a468-ce8d268a3261",
    "symbol": "BTC-PERP",
    "side": "BUY",
    "type": "MARKET",
    "quantity": "0.1",
    "price": "1",
    "reduceOnly": true
  }'
```

### Success Response

```json theme={null}
{
  "success": true,
  "data": {
    "success": true,
    "closedCount": 1,
    "totalPositions": 1,
    "results": [
      {
        "symbol": "BTC",
        "status": "CLOSED",
        "orderId": "255732635491"
      }
    ],
    "message": "Successfully closed 1/1 positions"
  }
}
```

***

## Aster - Close Position

Close positions on Aster exchange with a single API call.

### Endpoint

`POST /api/aster/perp/:walletId/close-position`

### Path Parameters

| Parameter  | Type   | Required | Description      |
| ---------- | ------ | -------- | ---------------- |
| `walletId` | string | Yes      | Wallet ID (UUID) |

### Request Body

```json theme={null}
{
  "symbol": "BTCUSDT"
}
```

**Optional - Close specific side:**

```json theme={null}
{
  "symbol": "BTCUSDT",
  "positionSide": "LONG"
}
```

### Request Parameters

| Field          | Type   | Required | Description                                                                    |
| -------------- | ------ | -------- | ------------------------------------------------------------------------------ |
| `symbol`       | string | Yes      | Trading pair (e.g., "BTCUSDT")                                                 |
| `positionSide` | string | No       | "LONG" or "SHORT" (for hedge mode). Omit to close all positions for the symbol |

### Example Request

```bash theme={null}
curl -X POST https://api.tide.ag/api/aster/perp/ee337309-3e77-4278-b21a-4681468168ba/close-position \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "BTCUSDT"
  }'
```

### Success Response

```json theme={null}
{
  "success": true,
  "data": {
    "orderId": 9884649221,
    "symbol": "BTCUSDT",
    "status": "NEW",
    "clientOrderId": "6D52PQwRlg0PcdHz5ttkgN",
    "price": "0",
    "avgPrice": "0.0000",
    "origQty": "0.001",
    "executedQty": "0",
    "cumQty": "0",
    "cumQuote": "0",
    "timeInForce": "GTC",
    "type": "MARKET",
    "reduceOnly": true,
    "closePosition": false,
    "side": "SELL",
    "positionSide": "BOTH",
    "stopPrice": "0",
    "workingType": "CONTRACT_PRICE",
    "priceProtect": false,
    "origType": "MARKET",
    "updateTime": 1764640797006
  }
}
```

***

## Avantis - Close Position (Client-Side Execution)

Avantis positions are closed **client-side** via on-chain transactions on the Base network. Like opening, closing is not routed through the Tide backend.

<Warning>
  Avantis close execution uses client-side wallet signing via the `useAvantisTrade` React hook. Supports both full and partial closes.
</Warning>

### Close by Pair and Trade Index

```typescript theme={null}
useAvantisTrade().closePosition({
  pairIndex: 0,              // From PAIR_INDEX_MAP (e.g., 0 = ETH)
  tradeIndex: 0,             // On-chain trade index
  closeAmountUsdc: "50.00"   // Partial close amount (optional)
})
// Returns: txHash
```

### Close by Symbol and Direction

```typescript theme={null}
// Convenience method — finds and closes the matching open trade
useAvantisTrade().closeBySymbol("ETH", "LONG")
// Returns: txHash
```

### Request Parameters

| Field             | Type   | Required | Description                                       |
| ----------------- | ------ | -------- | ------------------------------------------------- |
| `pairIndex`       | number | Yes      | Pair index from PAIR\_INDEX\_MAP                  |
| `tradeIndex`      | number | Yes      | On-chain trade index                              |
| `closeAmountUsdc` | string | No       | Partial close amount in USDC. Omit for full close |

### Close by Symbol Parameters

| Field       | Type   | Required | Description                |
| ----------- | ------ | -------- | -------------------------- |
| `symbol`    | string | Yes      | Asset symbol (e.g., "ETH") |
| `direction` | string | Yes      | `"LONG"` or `"SHORT"`      |

<Note>
  The close operation uses `initialPosToken` (not `positionSizeUSDC`) for the collateral amount, read from `TradingStorage.openTrades()` on-chain.
</Note>


## OpenAPI

````yaml POST /api/trade/position/close
openapi: 3.1.0
info:
  title: Tide API
  description: >-
    Decentralized Perpetual Aggregator API for multi-exchange trading across
    Hyperliquid, Aster, Lighter, and Pacifica
  version: 1.0.0
  contact:
    name: Tide Support
    email: support@tide.ag
    url: https://tide.ag
  license:
    name: MIT
servers:
  - url: https://api.tide.ag
    description: Production server
security:
  - ApiKeyAuth: []
tags:
  - name: Market Data
    description: Public market data endpoints
  - name: Trading
    description: Order placement and management
  - name: Positions
    description: Position management and history
  - name: Account
    description: Account and balance management
  - name: System
    description: System status and health
paths:
  /api/trade/position/close:
    post:
      tags:
        - Trading
      summary: Close Position
      description: Close an existing position using a reduce-only order
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - symbol
                - direction
                - size
                - credentials
              properties:
                symbol:
                  type: string
                  description: Asset symbol being closed
                direction:
                  $ref: '#/components/schemas/PositionSide'
                size:
                  type: string
                  description: Quantity to close
                orderType:
                  $ref: '#/components/schemas/OrderType'
                limitPrice:
                  type: string
                  description: Required when orderType is LIMIT
                preferredExchange:
                  $ref: '#/components/schemas/ExchangeName'
                credentials:
                  $ref: '#/components/schemas/ExchangeCredentials'
      responses:
        '200':
          description: Position closed successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      executedOn:
                        $ref: '#/components/schemas/ExchangeName'
                      order:
                        $ref: '#/components/schemas/Order'
                      routing:
                        type: object
                      execution:
                        type: object
components:
  schemas:
    PositionSide:
      type: string
      enum:
        - LONG
        - SHORT
    OrderType:
      type: string
      enum:
        - LIMIT
        - MARKET
        - STOP_MARKET
        - STOP_LIMIT
    ExchangeName:
      type: string
      enum:
        - hyperliquid
        - aster
        - lighter
        - pacifica
    ExchangeCredentials:
      type: object
      properties:
        lighter:
          type: object
          properties:
            apiKeyPrivateKey:
              type: string
            accountIndex:
              type: integer
        aster:
          type: object
          properties:
            apiKey:
              type: string
            apiSecret:
              type: string
            walletAddress:
              type: string
        hyperliquid:
          type: object
          properties:
            privateKey:
              type: string
        pacifica:
          type: object
          properties:
            apiKey:
              type: string
            apiSecret:
              type: string
            walletAddress:
              type: string
    Order:
      type: object
      properties:
        orderId:
          type: string
          description: Unique order identifier
        symbol:
          type: string
          description: Trading pair symbol
        side:
          $ref: '#/components/schemas/OrderSide'
        type:
          $ref: '#/components/schemas/OrderType'
        status:
          $ref: '#/components/schemas/OrderStatus'
        price:
          type: string
          description: Order price
        quantity:
          type: string
          description: Order quantity
        filledQuantity:
          type: string
          description: Filled quantity
        averagePrice:
          type: string
          description: Average fill price
        timestamp:
          type: integer
          description: Order timestamp in milliseconds
        exchange:
          $ref: '#/components/schemas/ExchangeName'
        clientOrderId:
          type: string
          description: Client-provided order ID
        reduceOnly:
          type: boolean
          description: Whether this is a reduce-only order
        triggerPrice:
          type: string
          description: Trigger price for stop orders
    OrderSide:
      type: string
      enum:
        - BUY
        - SELL
    OrderStatus:
      type: string
      enum:
        - OPEN
        - FILLED
        - PARTIALLY_FILLED
        - CANCELED
        - REJECTED
        - UNKNOWN
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-KEY
      description: >-
        API key for authentication. Also requires X-API-SECRET, X-API-TIMESTAMP,
        and X-API-SIGNATURE headers for private endpoints.

````