CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-kucoin-python

A Python SDK for KuCoin cryptocurrency exchange API providing REST endpoints implementation, simple authentication handling, response exception handling, and websocket support for trading, market data, user account management, margin trading, lending, and earning features

Pending
Overview
Eval results
Files

margin-trading.mddocs/

Margin Trading

Cross and isolated margin trading operations with borrowing, repayment, and position management. Provides access to margin accounts, lending market, and risk management features for leveraged trading.

Capabilities

Margin Account Management

Access and manage margin account information.

def get_margin_account():
    """
    Get margin account information.
    
    Returns:
        dict: Margin account details with balances and risk metrics
    """

def query_margin_accounts():
    """
    Query margin account details.
    
    Returns:
        dict: Comprehensive margin account information
    """

def get_cross_isolated_margin_account():
    """
    Get cross and isolated margin account information.
    
    Returns:
        dict: Combined margin account details
    """

def get_isolated_margin_account(symbol: str):
    """
    Get isolated margin account for specific symbol.
    
    Args:
        symbol (str): Trading symbol (e.g., 'BTC-USDT')
    
    Returns:
        dict: Isolated margin account details
    """

def get_isolated_margin_accounts():
    """
    Get all isolated margin accounts.
    
    Returns:
        list: All isolated margin account information
    """

Isolated Margin Account Operations

Create and manage isolated margin accounts.

def create_isolated_margin_account(symbol: str):
    """
    Create isolated margin account for a symbol.
    
    Args:
        symbol (str): Trading symbol
    
    Returns:
        dict: Created account information
    """

def delete_isolated_margin_account(symbol: str):
    """
    Delete isolated margin account.
    
    Args:
        symbol (str): Trading symbol
    
    Returns:
        dict: Deletion confirmation
    """

Borrowing Operations

Borrow funds for margin trading.

def post_borrow_order(currency: str, size: str, maxRate: str = '', term: str = ''):
    """
    Place a borrow order.
    
    Args:
        currency (str): Currency to borrow
        size (str): Borrow amount
        maxRate (str, optional): Maximum interest rate
        term (str, optional): Borrow term
    
    Returns:
        dict: Borrow order information
    """

def get_borrow_order(orderId: str):
    """
    Query borrow order details.
    
    Args:
        orderId (str): Borrow order ID
    
    Returns:
        dict: Borrow order status and details
    """

def get_repay_record(currency: str):
    """
    Get repayment record for currency.
    
    Args:
        currency (str): Currency code
    
    Returns:
        list: Repayment history
    """

def get_repayment_record(currency: str, **kwargs):
    """
    Get detailed repayment records.
    
    Args:
        currency (str): Currency code
        currentPage (int, optional): Page number
        pageSize (int, optional): Page size
    
    Returns:
        dict: Paginated repayment records
    """

Repayment Operations

Repay borrowed funds.

def post_repay_all(currency: str, sequence: str, size: str):
    """
    Repay all borrowed funds for a currency.
    
    Args:
        currency (str): Currency to repay
        sequence (str): Repayment sequence
        size (str): Repayment amount
    
    Returns:
        dict: Repayment confirmation
    """

def post_repay_single(currency: str, tradeId: str, size: str):
    """
    Repay a single borrow order.
    
    Args:
        currency (str): Currency to repay
        tradeId (str): Trade ID to repay
        size (str): Repayment amount
    
    Returns:
        dict: Repayment confirmation
    """

Lending Operations

Lend funds to earn interest.

def post_lend_order(currency: str, size: str, dailyIntRate: str, term: int):
    """
    Place a lending order.
    
    Args:
        currency (str): Currency to lend
        size (str): Lending amount
        dailyIntRate (str): Daily interest rate
        term (int): Lending term in days
    
    Returns:
        dict: Lending order information
    """

def cancel_lend_order(orderId: str):
    """
    Cancel a lending order.
    
    Args:
        orderId (str): Lending order ID
    
    Returns:
        dict: Cancellation confirmation
    """

def set_auto_lend(currency: str, isEnable: bool, retainSize: str, dailyIntRate: str, term: int):
    """
    Set auto-lending configuration.
    
    Args:
        currency (str): Currency for auto-lending
        isEnable (bool): Enable/disable auto-lending
        retainSize (str): Amount to retain (not lend)
        dailyIntRate (str): Daily interest rate
        term (int): Lending term in days
    
    Returns:
        dict: Auto-lending configuration
    """

Lending History

Access lending and borrowing history.

def get_active_order(currency: str, **kwargs):
    """
    Get active lending orders.
    
    Args:
        currency (str): Currency code
        currentPage (int, optional): Page number
        pageSize (int, optional): Page size
    
    Returns:
        dict: Active lending orders
    """

def get_lent_history(currency: str, **kwargs):
    """
    Get lending history.
    
    Args:
        currency (str): Currency code
        currentPage (int, optional): Page number
        pageSize (int, optional): Page size
    
    Returns:
        dict: Lending transaction history
    """

def get_active_lent_history(currency: str, **kwargs):
    """
    Get active lending history.
    
    Args:
        currency (str): Currency code
        currentPage (int, optional): Page number
        pageSize (int, optional): Page size
    
    Returns:
        dict: Active lending positions
    """

def get_settled_lent_history(currency: str, **kwargs):
    """
    Get settled lending history.
    
    Args:
        currency (str): Currency code
        currentPage (int, optional): Page number  
        pageSize (int, optional): Page size
    
    Returns:
        dict: Settled lending transactions
    """

def get_account_lend_record(currency: str, **kwargs):
    """
    Get account lending record.
    
    Args:
        currency (str): Currency code
        currentPage (int, optional): Page number
        pageSize (int, optional): Page size
    
    Returns:
        dict: Account lending records
    """

Market Information

Access margin trading market data.

def get_market_interestRate(currency: str):
    """
    Get market interest rates for a currency.
    
    Args:
        currency (str): Currency code
    
    Returns:
        list: Market interest rate information
    """

def get_lend_record(currency: str):
    """
    Get lending record for market analysis.
    
    Args:
        currency (str): Currency code
    
    Returns:
        list: Market lending records
    """

def get_margin_currencies():
    """
    Get currencies available for margin trading.
    
    Returns:
        dict: Margin-enabled currencies with parameters
    """

def get_isolated_margin_symbols():
    """
    Get symbols available for isolated margin trading.
    
    Returns:
        dict: Isolated margin trading pairs
    """

Risk Management

Risk limits and ETF information.

def get_risk_limit(marginModel: str):
    """
    Get risk limits for margin model.
    
    Args:
        marginModel (str): Margin model type
    
    Returns:
        list: Risk limit information
    """

def get_etf_info():
    """
    Get ETF information for margin trading.
    
    Returns:
        dict: ETF details and parameters
    """

Margin Orders

Place margin trading orders (inherits from TradeData).

def create_limit_margin_order(symbol: str, side: str, size: str, price: str, clientOid: str = '', **kwargs):
    """
    Place a margin limit order.
    
    Args:
        symbol (str): Trading symbol
        side (str): Order side ('buy' or 'sell')
        size (str): Order size
        price (str): Order price
        clientOid (str, optional): Client order ID
        **kwargs: Additional margin order parameters
    
    Returns:
        dict: Margin order response with borrow information
    """

def create_market_margin_order(symbol: str, side: str, clientOid: str = '', **kwargs):
    """
    Place a margin market order.
    
    Args:
        symbol (str): Trading symbol
        side (str): Order side
        clientOid (str, optional): Client order ID
        size (str, optional): Order size (for sell orders)
        funds (str, optional): Order funds (for buy orders)
        **kwargs: Additional parameters
    
    Returns:
        dict: Margin order response with borrow information
    """

def place_margin_order_test(symbol: str, side: str, type: str, clientOid: str = '', **kwargs):
    """
    Test margin order placement.
    
    Args:
        symbol (str): Trading symbol
        side (str): Order side
        type (str): Order type
        clientOid (str, optional): Client order ID
        **kwargs: Additional parameters
    
    Returns:
        dict: Test order response
    """

Usage Examples

Basic Margin Trading

from kucoin.client import Margin, Trade

# Initialize margin client
margin = Margin(api_key, api_secret, api_passphrase, is_sandbox=False)
trade = Trade(api_key, api_secret, api_passphrase, is_sandbox=False)

# Check margin account
account = margin.get_margin_account()
print(f"Margin level: {account.get('marginLevel')}")
print(f"Total liability: {account.get('totalLiabilityOfQuoteCurrency')}")

# Borrow USDT for trading
borrow_order = margin.post_borrow_order(
    currency='USDT',
    size='1000',
    maxRate='0.001'  # 0.1% daily rate
)
print(f"Borrow order: {borrow_order}")

Isolated Margin Trading

# Create isolated margin account for BTC-USDT
isolated_account = margin.create_isolated_margin_account('BTC-USDT')
print(f"Created isolated account: {isolated_account}")

# Get isolated margin account details
account_details = margin.get_isolated_margin_account('BTC-USDT')
print(f"Available balance: {account_details}")

# Place margin order for isolated account
margin_order = trade.create_limit_margin_order(
    symbol='BTC-USDT',
    side='buy',
    size='0.001',
    price='30000',
    marginModel='isolated'  # Specify isolated margin
)
print(f"Margin order: {margin_order}")

Lending Operations

# Place a lending order to earn interest
lend_order = margin.post_lend_order(
    currency='USDT',
    size='1000',
    dailyIntRate='0.0001',  # 0.01% daily
    term=7  # 7 days
)
print(f"Lending order: {lend_order}")

# Set up auto-lending
auto_lend = margin.set_auto_lend(
    currency='USDT',
    isEnable=True,
    retainSize='100',  # Keep 100 USDT unlent
    dailyIntRate='0.0001',
    term=7
)
print(f"Auto-lending configured: {auto_lend}")

# Check active lending orders
active_orders = margin.get_active_order('USDT')
for order in active_orders['items']:
    print(f"Lending: {order['size']} USDT at {order['dailyIntRate']} daily rate")

Repayment Operations

# Get repayment records
repay_records = margin.get_repayment_record('USDT')
total_owed = sum(float(record['principal']) for record in repay_records['items'])
print(f"Total owed: {total_owed} USDT")

# Repay all outstanding for a currency
if total_owed > 0:
    repay_result = margin.post_repay_all(
        currency='USDT',
        sequence='RECENTLY_EXPIRE_FIRST',
        size=str(total_owed)
    )
    print(f"Repayment completed: {repay_result}")

Risk Monitoring

# Check margin currencies and their parameters
margin_currencies = margin.get_margin_currencies()
for currency_info in margin_currencies['data']:
    print(f"{currency_info['currency']}: Max leverage {currency_info['maxLeverage']}")

# Monitor risk limits
risk_limits = margin.get_risk_limit('cross')
for limit in risk_limits:
    print(f"Risk level {limit['level']}: Max borrowable {limit['maxBorrowableAmount']}")

# Check market interest rates
interest_rates = margin.get_market_interestRate('USDT')
for rate in interest_rates:
    print(f"Term {rate['term']} days: {rate['dailyIntRate']} daily rate")

Types

MarginAccountInfo = dict
# {
#   "debtRatio": str,                    # Debt ratio
#   "totalDebtOfBaseCurrency": str,      # Total debt in base currency
#   "totalLiabilityOfQuoteCurrency": str, # Total liability in quote currency
#   "marginLevel": str,                  # Margin level
#   "totalAssetOfQuoteCurrency": str,    # Total assets in quote currency
#   "accounts": list                     # Account details
# }

BorrowOrderInfo = dict
# {
#   "orderId": str,        # Borrow order ID
#   "currency": str,       # Borrowed currency
#   "size": str,           # Borrow amount
#   "filled": str,         # Filled amount
#   "matchList": list,     # Match details
#   "status": str          # Order status
# }

LendOrderInfo = dict
# {
#   "orderId": str,        # Lending order ID
#   "currency": str,       # Lending currency
#   "size": str,           # Lending amount
#   "filledSize": str,     # Filled amount
#   "dailyIntRate": str,   # Daily interest rate
#   "term": int,           # Lending term in days
#   "createdAt": int       # Creation timestamp
# }

RepaymentRecord = dict
# {
#   "tradeId": str,        # Trade ID
#   "currency": str,       # Currency
#   "principal": str,      # Principal amount
#   "interest": str,       # Interest amount
#   "createdAt": int,      # Creation time
#   "repaidSize": str,     # Repaid amount
#   "dailyIntRate": str,   # Daily interest rate
#   "term": int            # Term in days
# }

IsolatedMarginAccountInfo = dict
# {
#   "totalConversionBalance": str,   # Total conversion balance
#   "liabilityConversionBalance": str, # Liability conversion balance
#   "assets": list,                  # Asset details
#   "symbol": str,                   # Trading symbol
#   "isolatedMarginLevel": str,      # Isolated margin level
#   "debtRatio": str,                # Debt ratio
#   "status": str                    # Account status
# }

MarginOrderResponse = dict
# {
#   "orderId": str,        # Order ID
#   "borrowSize": float,   # Borrowed size for the order
#   "loanApplyId": str     # Loan application ID (if applicable)
# }

Install with Tessl CLI

npx tessl i tessl/pypi-kucoin-python

docs

account-management.md

earn-products.md

index.md

lending.md

margin-trading.md

market-data.md

spot-trading.md

websocket.md

tile.json