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

# V0.7.0

# Monaco Protocol SDK v0.7.0

## Perpetuals on Monaco

Monaco's first-class perp surface ships with v0.7.0. The SDK gains two new top-level modules — `sdk.marginAccounts` and `sdk.positions` — plus perp helpers on `sdk.market`, perp options on `sdk.trading`, a new `usePositions` React hook, and a `conditional_order_update` WebSocket event for TP/SL lifecycle.

Spot trading is unchanged. All existing spot endpoints, hooks, and patterns continue to work as in v0.6.x.

***

## New Features

### Margin Accounts

A margin account is the reusable parent collateral account that backs isolated perp buckets. Each parent holds a single collateral asset (USDC by default) and exposes equity, margin requirements, free collateral, and unrealized PnL.

**New module:** `sdk.marginAccounts`

```typescript theme={null}
import { MonacoSDK } from "@0xmonaco/core";

// Ensure the parent margin account exists (USDC by default)
const account = await sdk.marginAccounts.ensureParentMarginAccount({
  label: "perp-main",
  collateralAsset: "USDC",
});

// Read live state
const summary = await sdk.marginAccounts.getMarginAccountSummary(
  account.margin_account_id,
);
// summary.equity, summary.free_collateral,
// summary.maintenance_margin_required, summary.unrealized_pnl, …

// Move collateral in / out
await sdk.marginAccounts.transferCollateralToMarginAccount(
  account.margin_account_id,
  { asset: "USDC", amount: "1000" },
);

await sdk.marginAccounts.transferCollateralFromMarginAccount(
  account.margin_account_id,
  { asset: "USDC", amount: "250" },
);

// What's available in the wallet vs. transferable to margin
const collateral = await sdk.marginAccounts.getAvailableCollateral({
  asset: "USDC",
});

// Pre-flight: would this order be accepted?
const risk = await sdk.marginAccounts.simulateOrderRisk(
  account.margin_account_id,
  {
    tradingPairId,
    side: "BUY",
    positionSide: "LONG",
    orderType: "LIMIT",
    price: "2000",
    quantity: "1.5",
    leverage: "10",
    reduceOnly: false,
  },
);
// risk.accepted, risk.estimated_liquidation_price,
// risk.free_collateral_after, risk.estimated_fee, …

// Collateral transfers recorded against the margin account
const movements = await sdk.marginAccounts.getMarginAccountMovements(
  account.margin_account_id,
  { page: 1, page_size: 50 },
);
```

**Methods:**

| Method | Returns |
| - | - |
| `listMarginAccounts(params?)` | `ListMarginAccountsResponse` |
| `ensureParentMarginAccount(request?)` | `EnsureParentMarginAccountResponse` |
| `getMarginAccountSummary(id)` | `MarginAccountSummary` |
| `getAvailableCollateral(params?)` | `GetAvailableCollateralResponse` |
| `transferCollateralToMarginAccount(id, request)` | `TransferCollateralResponse` |
| `transferCollateralFromMarginAccount(id, request)` | `TransferCollateralResponse` |
| `getMarginAccountMovements(id, params?)` | `GetMarginAccountMovementsResponse` |
| `simulateOrderRisk(id, request)` | `SimulateOrderRiskResponse` |

**`MarginAccountSummary`:**

```typescript theme={null}
interface MarginAccountSummary {
  margin_account_id: string;
  label?: string;
  account_state: string;
  equity: string;
  initial_margin_required: string;
  maintenance_margin_required: string;
  free_collateral: string;            // available to open new positions
  withdrawable_collateral: string;    // can be transferred out
  total_position_notional: string;
  unrealized_pnl: string;
  realized_pnl: string;
  updated_at: string;
}
```

***

### Positions

A position is the open exposure on a perp pair backed by a margin account. The `sdk.positions` module covers the full lifecycle — open (via order placement), modify isolated margin, attach TP/SL, close (full or partial), inspect risk.

**New module:** `sdk.positions`

```typescript theme={null}
// List open positions in a margin account
const open = await sdk.positions.listPositions({
  margin_account_id,
  status: "OPEN",
});

// Inspect a single position
const position = await sdk.positions.getPosition(positionId);
// position.side ("LONG"|"SHORT"), position.size, position.entry_price,
// position.mark_price, position.liquidation_price, position.unrealized_pnl,
// position.leverage, position.isolated_margin, position.status, …

// Live risk snapshot — useful for a continuously-updating UI
const risk = await sdk.positions.getPositionRisk(positionId);
// risk.mark_price, risk.liquidation_price, risk.margin_ratio, …

// Close: full market close, partial market close, limit close, or IOC
await sdk.positions.closePosition(positionId, { closeType: "MARKET" });

await sdk.positions.closePosition(positionId, {
  closeType: "LIMIT",
  limitPrice: "2050.00",
  quantity: "0.5",
});

// Adjust isolated margin on an open position
await sdk.positions.addPositionMargin(positionId, {
  amount: "200",
  asset: "USDC",
});
await sdk.positions.reducePositionMargin(positionId, { amount: "100" });

// Attach TP and/or SL — both legs are optional
await sdk.positions.attachPositionTpSl(positionId, {
  takeProfit: { triggerPrice: "2200", orderType: "MARKET" },
  stopLoss: {
    triggerPrice: "1900",
    orderType: "LIMIT",
    limitPrice: "1895",
  },
});

// Position lifecycle events (open, fills, funding, liquidations, close)
const history = await sdk.positions.listPositionHistory({
  position_id: positionId,
});
```

**Methods:**

| Method | Returns |
| - | - |
| `listPositions(params?)` | `ListPositionsResponse` |
| `getPosition(id)` | `Position` |
| `closePosition(id, request)` | `ClosePositionResponse` |
| `getPositionRisk(id)` | `PositionRisk` |
| `addPositionMargin(id, request)` | `PositionMarginResponse` |
| `reducePositionMargin(id, request)` | `PositionMarginResponse` |
| `attachPositionTpSl(id, request)` | `AttachPositionTpSlResponse` |
| `listPositionHistory(params?)` | `ListPositionHistoryResponse` |

**`Position`:**

```typescript theme={null}
interface Position {
  position_id: string;
  margin_account_id: string;
  trading_pair_id: string;
  side: "LONG" | "SHORT" | "NONE";
  size: string;
  entry_price: string;
  mark_price: string;
  index_price?: string;
  unrealized_pnl: string;
  realized_pnl: string;
  isolated_margin: string;
  leverage?: string;
  maintenance_margin_required: string;
  initial_margin_required?: string;
  liquidation_price: string;
  status: "OPEN" | "CLOSED" | "LIQUIDATING";
  updated_at: string;
}
```

`closePosition` accepts `{ closeType: "MARKET" | "LIMIT" | "IOC" }` plus optional `limitPrice`, `quantity` (for partial close), and `slippageToleranceBps`.

***

### Perp options on `placeLimitOrder` / `placeMarketOrder`

Existing order placement methods now accept perp options. Spot order placement continues to work unchanged — the new options are additive.

```typescript theme={null}
// Open a 10x long via limit order
await sdk.trading.placeLimitOrder(tradingPairId, "BUY", "1.5", "2000", {
  marginAccountId,
  positionSide: "LONG",
  leverage: "10",
});

// Reduce-only market close of a short
await sdk.trading.placeMarketOrder(tradingPairId, "BUY", "0.5", {
  marginAccountId,
  positionSide: "SHORT",
  reduceOnly: true,
});
```

**New options on both methods:**

| Option | Type | Notes |
| - | - | - |
| `marginAccountId` | `string` | Required for perp orders |
| `positionSide` | `"LONG" \| "SHORT" \| "NONE"` | Required for perp orders |
| `leverage` | `string` | Decimal string, e.g. `"10"` |
| `reduceOnly` | `boolean` | Order can only reduce existing exposure |

***

### Perp market data on `sdk.market`

Real-time perp metrics are available through the existing `sdk.market` module.

```typescript theme={null}
// Static perp config: tick/lot size, leverage tiers, margin ratios, funding interval
const config = await sdk.market.getPerpMarketConfig(tradingPairId);

// Aggregate market snapshot
const summary = await sdk.market.getPerpMarketSummary(tradingPairId);
// summary.mark_price, summary.index_price, summary.open_interest,
// summary.current_funding_rate, summary.next_funding_time, …

// Individual metrics
const mark = await sdk.market.getMarkPrice(tradingPairId);
const index = await sdk.market.getIndexPrice(tradingPairId);
const funding = await sdk.market.getFundingState(tradingPairId);
const oi = await sdk.market.getOpenInterest(tradingPairId);

// Historical funding payments
const records = await sdk.market.listFundingHistory(tradingPairId, {
  page: 1,
  page_size: 100,
});
```

**New methods:** `getPerpMarketConfig`, `getPerpMarketSummary`, `getMarkPrice`, `getIndexPrice`, `getFundingState`, `getOpenInterest`, `listFundingHistory`.

***

### Standalone conditional orders

In addition to attaching TP/SL through `attachPositionTpSl`, conditional orders can be created standalone via `sdk.trading`:

```typescript theme={null}
const conditional = await sdk.trading.createConditionalOrder({
  tradingPairId,
  marginAccountId,
  conditionType: "STOP_LOSS",
  triggerPrice: "1900",
  triggerSource: "MARK_PRICE",
  side: "SELL",
  positionSide: "LONG",
  orderType: "MARKET",
  reduceOnly: true,
});

await sdk.trading.cancelConditionalOrder(conditional.conditional_order_id);

const open = await sdk.trading.listConditionalOrders({
  margin_account_id,
  state: "ACTIVE",
});
```

States: `"ACTIVE" | "TRIGGERING" | "TRIGGERED" | "CANCELLED" | "EXPIRED" | "FAILED"`.

***

### `conditional_order_update` WebSocket event

TP/SL lifecycle updates stream over the existing authenticated websocket.

```typescript theme={null}
const unsubscribe = sdk.ws.conditionalOrders((evt) => {
  // evt.eventType === "conditional_order_update"
  // evt.data.conditionalOrderId, evt.data.state, evt.data.reason,
  // evt.data.triggeredOrderId, evt.data.triggerPrice, …
}, tradingPairId /* optional — omit for all pairs */);

// Later
unsubscribe();
```

`reason` is one of `"created" | "cancelled" | "triggered" | "failed" | "oco_cancelled"`.

***

### React: `usePositions` hook

```tsx theme={null}
import { usePositions } from "@0xmonaco/react";

function PositionsPanel({ marginAccountId }: { marginAccountId: string }) {
  const {
    listPositions,
    getPosition,
    getPositionRisk,
    closePosition,
    addPositionMargin,
    reducePositionMargin,
    attachPositionTpSl,
    listPositionHistory,
  } = usePositions();

  // …
}
```

`useMarket` is extended with `getPerpMarketConfig`, `getPerpMarketSummary`, `getMarkPrice`, `getIndexPrice`, `getFundingState`, `listFundingHistory`, `getOpenInterest`.

`useTrade`'s `placeLimitOrder` and `placeMarketOrder` accept the same perp options shown above. `useTrade` also exposes `createConditionalOrder`, `cancelConditionalOrder`, `listConditionalOrders`.

***

## Breaking Changes

### Pagination standardized to `page` / `page_size`

`limit`, `offset`, and `skip` query parameters have been removed across all paginated endpoints in favor of `page` / `page_size`. `total_count` was renamed to `total`. `total_pages` was added to `GetUserBalancesResponse`.

```typescript theme={null}
// Before
const trades = await sdk.profile.getUserTrades({ limit: 20, offset: 0 });
const balances = await sdk.profile.getUserBalances({ limit: 50, offset: 0 });

// After
const trades = await sdk.profile.getUserTrades({ page: 1, page_size: 20 });
const balances = await sdk.profile.getUserBalances({ page: 1, page_size: 50 });
```

`@0xmonaco/mcp-server`: the `get-trades` MCP tool parameters changed from `skip`/`limit` to `page`/`page_size`.

***

### `Order.trading_pair` → `Order.trading_pair_id`

Trading-pair identifier fields have been standardized across the API.

```typescript theme={null}
// Before
order.trading_pair          // pair UUID
profileOrder.trading_pair   // pair string like "ETH-USD"

// After
order.trading_pair_id       // pair UUID
profileOrder.symbol         // pair string like "ETH-USD"
```

Same change applies to `GetPaginatedOrdersParams.trading_pair` → `.trading_pair_id`. WebSocket events: `tradingPair` → `symbol` on order events.

***

### Flattened response shapes (trades & market)

The `data` wrapper has been removed from trades and market responses.

```typescript theme={null}
// Before
const response = await sdk.market.getPaginatedTradingPairs();
const pairs = response.data.data; // TradingPair[]

// After
const response = await sdk.market.getPaginatedTradingPairs();
const pairs = response.trading_pairs; // TradingPair[]
```

The `PaginatedTradingPairs` interface has been removed; pagination fields (`page`, `page_size`, `total`, `total_pages`) now live directly on the response.

***

### Removed `success` field from response types

HTTP status codes already convey success/failure. The redundant `success` boolean has been dropped from:

* `BatchCancelOrdersResponse`, `BatchCancelResult`
* `BatchCreateOrdersResponse`, `BatchCreateResult`
* `BatchReplaceOrdersResponse`, `BatchReplaceResult`
* `GetTradingPairsResponse`, `GetTradingPairResponse`
* `GetCandlestickResponse`

For batch operations, check `total_failed === 0` or inspect individual result `error` fields.

***

### Close-position requests

`position_id` is now only accepted in the URL path, not the request body.

```typescript theme={null}
// Before — would also accept position_id in body
await sdk.positions.closePosition(positionId, { closeType: "MARKET", position_id: positionId });

// After
await sdk.positions.closePosition(positionId, { closeType: "MARKET" });
```

***

## New Types

The following types are now exported from `@0xmonaco/types`:

**Margin Accounts** — `MarginAccountSummary`, `ListMarginAccountsParams`, `ListMarginAccountsResponse`, `EnsureParentMarginAccountRequest`, `EnsureParentMarginAccountResponse`, `GetAvailableCollateralParams`, `GetAvailableCollateralResponse`, `TransferCollateralRequest`, `TransferCollateralResponse`, `GetMarginAccountMovementsParams`, `GetMarginAccountMovementsResponse`, `MarginAccountMovement`, `SimulateOrderRiskRequest`, `SimulateOrderRiskResponse`, `MarginAccountsAPI`.

**Positions** — `Position`, `PositionStatus`, `ClosePositionType`, `ListPositionsParams`, `ListPositionsResponse`, `GetPositionResponse`, `ClosePositionRequest`, `ClosePositionResponse`, `PositionRisk`, `AddPositionMarginRequest`, `ReducePositionMarginRequest`, `PositionMarginResponse`, `TpSlLeg`, `AttachPositionTpSlRequest`, `AttachPositionTpSlResponse`, `ListPositionHistoryParams`, `ListPositionHistoryResponse`, `PositionHistoryEvent`, `PositionsAPI`.

**Market (perp)** — `PerpMarketConfig`, `PerpMarketSummary`, `MarkPrice`, `IndexPrice`, `IndexComponent`, `FundingState`, `FundingRecord`, `ListFundingHistoryParams`, `ListFundingHistoryResponse`, `OpenInterest`, `RiskTier`.

**Conditional orders** — `ConditionalOrderConditionType`, `ConditionalOrderTriggerSource`, `ConditionalOrderState`, `CreateConditionalOrderParams`, `CreateConditionalOrderResponse`, `CancelConditionalOrderResponse`, `ListConditionalOrdersParams`, `ListConditionalOrdersResponse`, `ConditionalOrderEvent`, `ConditionalOrderEventData`, `ConditionalOrderEventReason`.

**Trading** — `PositionSide`, `TradingMode`. `Order` gains `margin_account_id`, `position_side`, `leverage`, `reduce_only`, `position_id` fields.

***

## Upgrade Instructions

```bash theme={null}
# NPM
npm install @0xmonaco/core@0.7.0 @0xmonaco/types@0.7.0 @0xmonaco/react@0.7.0

# Bun
bun add @0xmonaco/core@0.7.0 @0xmonaco/types@0.7.0 @0xmonaco/react@0.7.0
```

**Migration checklist:**

1. Replace `limit`/`offset`/`skip` with `page`/`page_size` in any paginated calls.
2. Update field reads: `Order.trading_pair` → `.trading_pair_id`, `ProfileOrder.trading_pair` → `.symbol`.
3. Update WebSocket order-event handlers reading `tradingPair` → `symbol`.
4. Unwrap `data` from market and trades responses (`response.data.data` → `response.trading_pairs`).
5. Drop reads of `success` on batch / trading-pair / candlestick responses; check `total_failed` or HTTP status instead.

***

*For complete documentation, see [Perpetuals (perps)](https://docs.0xmonaco.com/trading-mechanics/perps.md), [Perps Accounts](https://docs.0xmonaco.com/developers/perps-accounts), [Positions](https://docs.0xmonaco.com/developers/positions.md), [Margin Accounts SDK reference](https://docs.0xmonaco.com/sdk/typescript/margin-accounts.md), and [Positions SDK reference](https://docs.0xmonaco.com/sdk/typescript/positions.md).*


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.