К основному содержанию
скилл CX Codex

deepbook-margin — скилл для Claude Code: маржинальная торговля

Скилл deepbook-margin для Claude Code объясняет маржинальную торговлю в DeepBook на Sui. Подключается к задачам с заёмными позициями, залогом, рисками и ликвидацией.

Apache-2.0 181 установок ★ 25 обновлён 2026-11-12

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add MystenLabs/skills --skill deepbook-margin -a claude-code
Открыть на GitHub

Что делает deepbook-margin

Скилл помогает разбирать устройство DeepBook Margin и создавать приложения для маржинальной торговли на Sui. Он объясняет работу залога и заимствований, расчёт risk ratio, начисление процентов и ликвидацию позиций.

Материалы разделены на справки о рисках, торговом цикле и параметрах контрактов. Для ордеров нужны функции с суффиксом _v2, а операции с маржой требуют аргументы Pyth PriceInfoObject. Параметры риска задаются управлением протокола и могут меняться.

Скилл также описывает создание и повторное использование MarginManager: каждый менеджер привязан к одному пулу DeepBook. При разработке интеграции он направляет к разным справочным файлам в зависимости от задачи.

Какие задачи решает

  • рассчитать risk ratio и допустимый размер займа
  • разобрать условия ликвидации маржинальной позиции
  • спроектировать открытие и закрытие позиции через MarginManager
  • сравнить маржинальную торговлю со спотовой в DeepBook

Примеры запросов агенту

  • Объясни, как рассчитать риск позиции в DeepBook Margin и когда её могут ликвидировать.
  • Покажи порядок открытия маржинальной позиции с залогом и заимствованием.
  • Сравни спотовую и маржинальную торговлю в DeepBook.

Как установить deepbook-margin

1Через Skills CLI (Vercel)

npx skills add MystenLabs/skills --skill deepbook-margin -a claude-code

2Вручную: положить файлы

~/.claude/skills/deepbook-margin/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/deepbook-margin/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о deepbook-margin

Как установить deepbook-margin в Claude Code?

Выполни npx skills add MystenLabs/skills --skill deepbook-margin -a claude-code. Файл скилла находится по пути ~/.claude/skills/deepbook-margin/SKILL.md.

Что делает deepbook-margin?

Скилл объясняет маржинальную торговлю в DeepBook на Sui: залог, займы, риск позиции, проценты и ликвидацию. Он также охватывает интеграцию и жизненный цикл MarginManager.

Что нужно для работы deepbook-margin?

Для операций с маржой требуются аргументы Pyth PriceInfoObject. Скилл описывает интеграцию с DeepBook Margin на Sui.

Исходный текст

SKILL.md · Apache-2.0
---
name: deepbook-margin
description: >
  DeepBook Margin leveraged trading on Sui. Use when building margin trading
  applications, understanding leveraged positions, risk ratios, liquidation
  mechanics, interest rate models, MarginManager lifecycle, or integrating
  margin trading into a protocol. Also use when the user asks about borrowing
  against collateral on DeepBook, margin pool parameters, or the differences
  between spot and margin trading.

  For spot trading and the DeepBook SDK, see the `deepbook-sdk` skill.
  For DeepBook architecture and contract addresses, see the `deepbook-overview` skill.
  For Move smart contract integration, see the `deepbook-move` skill.
---

# DeepBook Margin

> **MCP tool:** When available in your environment, also query the Sui documentation MCP server (`https://sui.mcp.kapa.ai`) for up-to-date answers. Use it for verification and for details not covered by these reference files.

> **Source constraint:** All information in this skill is sourced exclusively from [docs.sui.io](https://docs.sui.io/onchain-finance/deepbook/deepbook-margin) and the [deepbookv3 repository](https://github.com/MystenLabs/deepbookv3). When extending or updating this skill, only pull from these sources. Do not use third-party blogs, tutorials, or unofficial documentation.

DeepBook Margin enables leveraged trading by allowing users to post collateral, borrow from lending pools, and trade borrowed funds on spot order books. This skill covers the margin system architecture, risk model, and SDK integration. Common mistakes include ignoring continuous interest accrual on borrowed positions, not monitoring risk ratios for liquidation proximity, and creating new MarginManagers per session instead of reusing existing ones.

This skill routes to focused reference files. Load only the ones relevant to the current task.

All patterns in this skill are derived from:
  https://docs.sui.io/onchain-finance/deepbook/deepbook-margin
  https://docs.sui.io/onchain-finance/deepbook/deepbook-margin/design
  https://docs.sui.io/onchain-finance/deepbook/deepbook-margin/leveraged-workflow
  https://docs.sui.io/onchain-finance/deepbook/deepbook-margin/margin-integration
  https://docs.sui.io/onchain-finance/deepbook/deepbook-margin/margin-risks
  https://github.com/MystenLabs/deepbookv3/tree/main/packages/deepbook_margin

If unsure about any API or parameter, fetch the relevant page before answering.
Do not guess or extrapolate from other leverage protocols.

---

## Reference files

### risk-model — Risk Ratio, Interest Rates, and Liquidation
**Path:** `risk-model.md`
**Load when:** the user asks about risk ratios, leverage calculations, liquidation thresholds, interest rate formulas, the kinked utilization model, or margin risks.
**Covers:** risk ratio formula, four risk thresholds, leverage calculation table, interest rate kinked model with formulas and per-pool parameters, liquidation mechanics and rewards, oracle considerations, comprehensive risk categories.

### trading-workflow — Leveraged Position Lifecycle
**Path:** `trading-workflow.md`
**Load when:** the user wants to open, monitor, or close a leveraged position, create a MarginManager, deposit collateral, borrow funds, place margin orders, or withdraw.
**Covers:** SDK setup, MarginManager creation and reuse, reading risk parameters, checking borrow liquidity, depositing collateral, borrowing, placing margin orders, monitoring risk status, closing positions (reduce-only + repay), withdrawing collateral, troubleshooting.

### contract-info — Contract Addresses and Pool Parameters
**Path:** `contract-info.md`
**Load when:** the user needs margin package IDs, supported assets, margin pool IDs and supply caps, trading pair risk parameters, or the spot-vs-margin comparison matrix.
**Covers:** current package version, registry ID, supported tokens, margin pool configurations, trading pair risk parameters and leverage levels, spot-vs-margin structural comparison.

---

## Routing guide

| Task | Load |
|------|------|
| Understanding margin risk and liquidation | risk-model |
| Calculating leverage or risk ratio | risk-model |
| Understanding interest rates | risk-model |
| Opening a leveraged position | trading-workflow |
| Creating or reusing a MarginManager | trading-workflow |
| Depositing collateral and borrowing | trading-workflow |
| Monitoring position health | trading-workflow |
| Closing a position and withdrawing | trading-workflow |
| Looking up margin contract addresses | contract-info |
| Comparing spot vs margin integration | contract-info |
| Building a margin trading application | **all reference files** |
| Integrating margin into a protocol | **all reference files** |

---

## Skill Content

### Key concepts

- **MarginManager.** A shared object that wraps a DeepBook BalanceManager, holds collateral, and tracks borrowing. Each MarginManager is bound to exactly one DeepBook pool (isolated margin, not cross-pool).

- **Risk ratio.** The central metric: `total_assets / total_debt`. This single number controls what operations are allowed. It changes with market price movements and interest accrual.

- **Four risk thresholds.** All stored per-pool in the MarginRegistry and set by governance:
  - **Min withdraw risk ratio** — withdrawal blocked below this (typically 2.0)
  - **Min borrow risk ratio** — borrowing blocked below this; sets max leverage
  - **Target liquidation risk ratio** — liquidation restores position to this level
  - **Liquidation risk ratio** — permissionless liquidation triggered at or below this

- **Kinked interest model.** Borrow rates rise gently below optimal utilization (typically 80%), then spike sharply above it. Interest accrues at event-driven intervals (whenever pool state changes), not continuously — but the effect is that debt grows over time even when prices are stable.

- **Permissionless liquidation.** Once risk ratio reaches the liquidation threshold, anyone can liquidate the position. There is no grace period. Liquidators receive collateral rewards (typically 2%) and the pool takes additional rewards (typically 3%).

### Rules

1. **Read risk parameters on-chain.** All thresholds are governance-set and can change. Never hardcode them.
2. **Use `_v2` functions for margin orders** (`place_limit_order_v2`, `place_market_order_v2`). The unsuffixed originals are deprecated.
3. **Every margin operation requires Pyth `PriceInfoObject` arguments.** Unlike spot trading, margin has an oracle dependency for all operations (borrow, withdraw, risk reads, trading).
4. **Reuse MarginManagers.** Creating a new one per session fragments collateral across orphaned shared objects. Discover existing managers via the registry.
5. **Size borrows from risk parameters, not trial and error.** The min borrow risk ratio defines your maximum leverage per unit of collateral.
6. **`clientOrderId` must be a numeric string** (encoded as u64), same as spot.

### Common mistakes

- **Ignoring interest accrual.** Debt grows at event-driven intervals (whenever pool state changes — borrows, repays, liquidations). A position can drift toward liquidation purely from accumulated interest, even with stable prices.
- **Not monitoring risk ratio.** There is no grace period before liquidation. Integrators must surface the risk ratio and its distance to the liquidation threshold to users.
- **Creating new MarginManagers per run.** This fragments collateral. Use `findMarginManagerId` to discover existing managers before creating new ones.
- **Borrowing and trading in the same pool without oracle freshness checks.** If the Pyth price exceeds the pool's maximum age, the operation reverts.
- **Confusing margin order entry with spot.** Margin orders route through a pool proxy with risk checks, not the direct spot order entry.

© MystenLabs · Apache-2.0 · MystenLabs/skills

Похожие скиллы

Все скиллы по теме «Финансы и бизнес» →
margin-operations JoelLewis Скилл margin-operations помогает рассчитывать маржинальные требования брокерских счетов по правилам Reg T, FINRA 4210 и OCC TIMS. Пригодится при проверке маржин-коллов, лимитов SMA и плеча для дейтрейдинга. CX Codex +1 726установок margin-analyzer ilyautov Скилл margin-analyzer для Claude Code и Codex разбирает выручку и затраты по товарам и услугам, учитывает НДС и показывает сценарии изменения цены. Считает, какие позиции приносят прибыль. CX Codex +1 ★ 38звёзд репо The Margin themarginapp Удалённый MCP-сервер связывает ИИ с личным пространством The Margin: задачами, привычками, семейными расходами и заметками. Помогает поручать агенту бытовые и рабочие дела. CX Codex +1 thinking-margin-of-safety tjboudreaux Скилл thinking-margin-of-safety заставляет агента закладывать буфер в ёмкость, таймауты и оценки сроков, считая его от остаточной неопределённости и цены сбоя, а не от оптимистичного края. CX Codex +1 649установок blockchain-developer sickn33 Скилл blockchain-developer для Claude Code направляет разработку смарт-контрактов, Web3-приложений и децентрализованных систем. Помогает проектировать, проводить ревью и проверять риски до действий в сети. CX Codex +1 1 300установок coingecko coingecko Подключает живые данные крипторынка через CoinGecko и GeckoTerminal: цены токенов, пулы DEX, балансы кошельков и документацию API. CX Codex +1 1 200установок

Из того же набора30

Весь набор →
move-security Скилл move-security для Claude Code проверяет безопасность смарт-контрактов на Move в Sui. Подключается при аудите пакета, настройке прав доступа или проверке работы с ключами и случайностью. CX Codex +1 381установок sui-networks-gas Скилл sui-networks-gas для Claude Code объясняет сети Sui и расчёт газа. Включается на вопросы о Mainnet, Testnet, Devnet, Localnet, бюджетах газа и эпохах. CX Codex +1 184установок deepbook-overview Скилл deepbook-overview для Claude Code объясняет устройство DeepBook V3 на Sui и варианты интеграции. Запускается на вопросах о CLOB, пулах, токене DEEP и адресах mainnet. CX Codex +1 183установок deepbook-sdk Скилл deepbook-sdk для Claude Code помогает подключить TypeScript-приложение к пулам DeepBook V3. Включается при разработке торговых приложений, ботов и скриптов на @mysten/deepbook-v3. CX Codex +1 183установок deepbook-move Скилл deepbook-move для Claude Code помогает писать и отлаживать Move-контракты с DeepBook V3. Он подключается к вопросам о пулах, ордерах, обменах, флеш-займах и правах BalanceManager. CX Codex +1 181установок deepbook-predict Объясняет интеграцию DeepBook Predict с рынками прогнозов на Sui. Помогает создавать и закрывать позиции, разбирать расчёт и работу пула ликвидности. CX Codex +1 181установок sui-ts-sdk-backend Скилл sui-ts-sdk-backend для Claude Code помогает писать серверный код и агентов, которые работают с Sui через TypeScript SDK. Подключается для настройки клиента, подписания транзакций и запуска их сериями. CX Codex +1 167установок zklogin Объясняет устройство zkLogin и помогает интегрировать вход через OAuth в приложения на Sui. Подключается к вопросам о провайдерах OpenID, адресах, сроке сессии и безопасности. CX Codex +1 164установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой