Agent skill

deepbook-margin-trading-skill

Guides developers through using DeepBook V3 Margin Trading SDK for leverage trading, borrowing, lending, liquidation operations, and risk management on Sui blockchain. Use when working with DeepBook margin trading, margin pools, margin managers, take profit/stop loss orders, or liquidation functionality.

Stars 5
Forks 1

Install this agent skill to your Project

npx add-skill https://github.com/RandyPen/sui-eco-skills/tree/main/deepbook-margin-trading-skill

SKILL.md

DeepBook V3 Margin Trading

DeepBook V3 Margin Trading is a decentralized margin trading protocol built on Sui blockchain. It enables users to trade with leverage, lend assets to earn interest, and participate in liquidations.

Quick Start

typescript
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { deepbook } from '@mysten/deepbook-v3';

const client = new SuiGrpcClient({ network: 'mainnet', baseUrl: '...' })
  .$extend(deepbook({
    address: '0x...',
    marginManagers: {
      'myManager': { address: '0x...', poolKey: 'SUI_USDC' }
    }
  }));

// Deposit and trade with leverage
const tx = new Transaction();
tx.add(client.deepbook.marginManager.depositBase({ managerKey: 'myManager', amount: 1000 }));
tx.add(client.deepbook.marginManager.borrowQuote('myManager', 2000));
tx.add(client.deepbook.poolProxy.placeLimitOrder({
  poolKey: 'SUI_USDC',
  marginManagerKey: 'myManager',
  clientOrderId: '1',
  price: 2.5,
  quantity: 400,
  isBid: true,
  payWithDeep: true
}));

Core Concepts

Architecture

Component Purpose Documentation
MarginManager User's margin trading account User Operations
MarginPool Lending pool for specific assets Lending Operations
MarginRegistry Global configuration and risk parameters Admin Operations
PoolProxy Trading interface through margin Trading Operations

Risk Management

Margin trading involves several risk ratios (in 9 decimal precision):

  • minWithdrawRiskRatio: Minimum collateral ratio for withdrawals
  • minBorrowRiskRatio: Minimum collateral ratio for new borrows
  • liquidationRiskRatio: Ratio at which positions become liquidatable
  • targetLiquidationRiskRatio: Target ratio after liquidation

Key Features

For Traders

  • Margin Trading: Place limit and market orders with borrowed funds
  • Take Profit / Stop Loss: Automated conditional orders

For Lenders

  • Supply Assets: Deposit assets to margin pools and earn interest
  • Referral Program: Share fees by referring suppliers

For Liquidators

  • Liquidation: Earn rewards by liquidating undercollateralized positions

For Admins

  • Pool Management: Configure pools, risk parameters, and oracle settings

SDK Reference

Configuration

typescript
// Package IDs (auto-configured by SDK)
const MARGIN_PACKAGE_ID = {
  mainnet: '0xfbd322126f1452fd4c89aedbaeb9fd0c44df9b5cedbe70d76bf80dc086031377',
  testnet: '0xd6a42f4df4db73d68cbeb52be66698d2fe6a9464f45ad113ca52b0c6ebd918b6'
};

const MARGIN_REGISTRY_ID = {
  mainnet: '0x0e40998b359a9ccbab22a98ed21bd4346abf19158bc7980c8291908086b3a742',
  testnet: '0x48d7640dfae2c6e9ceeada197a7a1643984b5a24c55a0c6c023dac77e0339f75'
};

State Queries

typescript
// Get margin manager state
const state = await client.deepbook.getMarginManagerState('myManager');

// Get pool metrics
const interestRate = await client.deepbook.getMarginPoolInterestRate('SUI');

// Check risk parameters
const liquidationRatio = await client.deepbook.getLiquidationRiskRatio('SUI_USDC');

Examples

See the examples directory for complete working examples:

  • Basic Margin Trading
  • Lending and Earning Interest
  • Setting TP/SL Orders
  • Liquidation Bot

Error Handling

Common error codes:

Error Code Description
EInvalidDeposit 1 Invalid deposit parameters
EBorrowRiskRatioExceeded 7 Borrow would exceed risk ratio
EWithdrawRiskRatioExceeded 8 Withdrawal would exceed risk ratio
ECannotLiquidate 9 Position not eligible for liquidation
EPoolNotEnabledForMarginTrading 15 Pool not enabled for margin

Network Support

  • Mainnet: Full support with production pools
  • Testnet: Testing environment with test assets

Additional Resources


Note: This skill assumes familiarity with Sui blockchain, Move language, and basic DeFi concepts. For TypeScript SDK basics, see the Sui TypeScript SDK documentation.

Expand your agent's capabilities with these related and highly-rated skills.

RandyPen/sui-eco-skills

sui-transaction-building

Helps Claude Code understand Sui blockchain transaction building, providing guidelines and examples for Transaction class, commands, input types, gas configuration, and serialization. Use when building blockchain transactions on Sui or when the user mentions transaction building, Transaction class, or Move calls.

5 1
Explore
RandyPen/sui-eco-skills

sui-keypair-cryptography

Helps Claude Code understand Sui blockchain keypair and cryptography operations, providing guidelines and examples for key generation, signing, verification, address derivation, and multi-signature scheme support. Use when working with cryptography in Sui development or when the user mentions keypairs, cryptography, signing, or verification.

5 1
Explore
RandyPen/sui-eco-skills

deepbook-trading

Helps Claude Code understand DeepBook V3 SDK usage for order book trading, flash loans, fund management, and market data queries on Sui blockchain. Use when operating DeepBook DEX, executing trading strategies, or querying market data.

5 1
Explore
RandyPen/sui-eco-skills

working-with-ferra-dlmm

Helps developers work with the Ferra DLMM SDK for Discrete Liquidity Market Maker operations on Sui blockchain. Provides guidance on SDK initialization, pair creation, liquidity management, token swaps, and position handling. Use when working with DLMM pairs, adding/removing liquidity, creating trading pairs, or performing token swaps in the ferra-sdks monorepo.

5 1
Explore
RandyPen/sui-eco-skills

sui-client

Interact with Sui blockchain using @mysten/sui SDK. Use when building transactions, reading chain data, or managing staking positions on Sui.

5 1
Explore
RandyPen/sui-eco-skills

cetus-dlmm-interface

Enables Claude to effectively work with the Cetus Dynamic Liquidity Market Maker (DLMM) protocol on Sui blockchain. This skill provides comprehensive knowledge of the DLMM architecture, Move smart contracts, Rust SDK, and development workflows. Claude can assist with building, testing, and modifying DLMM contracts, creating swap simulations, implementing new features, and debugging protocol issues. The skill covers all 15 Move modules, multi-bin architecture, reward distribution, ACL system, and flash swap functionality. Trigger contexts include: working with Sui Move smart contracts for decentralized exchanges, implementing dynamic liquidity management, creating multi-bin AMM protocols, building swap simulations with Rust SDK, modifying DLMM protocol parameters, debugging pool operations, implementing reward systems, and working with Cetus DLMM interface codebase.

5 1
Explore

Didn't find tool you were looking for?

Be as detailed as possible for better results