Lighter Python SDK

repository·main·Indexed 43 days ago

https://github.com/elliottech/lighter-python

A Python client (version 1.1.4) for interacting with Lighter, a zkLighter perpetuals exchange. The SDK provides an asynchronous API for managing account information, executing limit, market, and batch orders via HTTP or WebSocket, and configuring stop-loss and take-profit orders. It includes support for spot markets, public pools, collateral management, and fund transfers between perp and spot accounts.

Tokens
114.4K
Snippets
280
Records
370
Agent score
55%

What's inside Lighter

  1. Understand the RespPublicPoolsMetadata model

    main

    The RespPublicPoolsMetadata model is a data structure used to represent metadata for public pools. It contains a status code, an optional message, and a list of PublicPoolMetadata objects.

    Properties

    NameTypeDescription
    codeintThe response status code.
    messagestrAn optional descriptive message.
    public_poolsList[PublicPoolMetadata]A list of metadata objects for individual public pools.
  2. How Read-Only Token Expiry and Alignment Works

    main

    The read-only token system relies on strict time alignment to ensure predictable lookups across different systems.

    Time Alignment

    All timestamps are aligned to 6-hour boundaries (21,600 seconds). The calculation used is: unix_timestamp // (6 * 3600) * (6 * 3600)

    Expiry and Overlap

    • Token Validity: Each token is valid for 8 hours from its aligned timestamp.
    • Overlap: Because tokens are generated every 6 hours but last for 8 hours, there is a 2-hour overlap period where two different tokens might be valid, ensuring no service interruption during transitions.

    Token Lookup

    To retrieve the token valid for the current moment, use the get_auth_token.py script provided in the example directory.

  3. Use the TokenList model

    main

    The TokenList model is used to represent a collection of tokens associated with a specific status code and message. It provides methods for serialization and deserialization between JSON strings, Python dictionaries, and class instances.

    from lighter.models.token_list import TokenList
    
    # Example usage
    json_data = '{"code": 200, "message": "success", "tokens": []}'
    token_list_instance = TokenList.from_json(json_data)
    
    # Convert to dict
    data_dict = token_list_instance.to_dict()
    
    # Convert back to instance
    new_instance = TokenList.from_dict(data_dict)
  4. Use the ReferralProgramKickback model

    main

    The ReferralProgramKickback model represents the data structure for referral program kickbacks. It contains the following properties:

    NameTypeDescription
    var_dateint
    percentagestr

    You can instantiate this model from JSON strings or dictionaries, and convert instances back into JSON or dictionaries for serialization.

    from lighter.models.referral_program_kickback import ReferralProgramKickback
    
    # Create an instance from a JSON string
    json_data = '{"var_date": 12345, "percentage": "10.5"}'
    instance = ReferralProgramKickback.from_json(json_data)
    
    # Convert to a dictionary
    instance_dict = instance.to_dict()
    
    # Convert back to JSON
    instance_json = instance.to_json()
  5. Serialize and deserialize RespWithdrawalDelay

    main

    You can move RespWithdrawalDelay instances between different formats using these methods:

    • from_json(json_string): Creates an instance from a JSON-formatted string.
    • to_json(): Returns the JSON string representation of the object.
    • to_dict(): Converts the object into a standard Python dictionary.
    • from_dict(dictionary): Creates an instance from a Python dictionary.
    from lighter.models.resp_withdrawal_delay import RespWithdrawalDelay
    
    # Example workflow
    json_str = '{"seconds": 60}'
    
    # 1. JSON -> Object
    obj = RespWithdrawalDelay.from_json(json_str)
    
    # 2. Object -> JSON
    print(obj.to_json())
    
    # 3. Object -> Dict
    obj_dict = obj.to_dict()
    
    # 4. Dict -> Object
    new_obj = RespWithdrawalDelay.from_dict(obj_dict)
  6. Use the SlippageResult model

    main

    The SlippageResult model represents slippage data for a specific market and exchange. It can be instantiated from JSON strings or dictionaries and supports conversion back to both formats.

    from lighter.models.slippage_result import SlippageResult
    
    # Create an instance from a JSON string
    json_data = '{"exchange": "example", "market": "BTC-USD", "size_usd": 1000, "avg_slippage": 0.01, "data_count": 10}'
    slippage_result_instance = SlippageResult.from_json(json_data)
    
    # Convert to a dictionary
    slippage_dict = slippage_result_instance.to_dict()
    
    # Convert back to JSON
    json_output = slippage_result_instance.to_json()
  7. Use the SharePrice model

    main

    The SharePrice model represents a snapshot of a share price at a specific point in time. It contains two primary properties:

    • timestamp (int): The time associated with the price.
    • share_price (float): The value of the share.

    You can instantiate SharePrice from JSON strings or dictionaries, and convert instances back into JSON or dictionaries for serialization.

    from lighter.models.share_price import SharePrice
    
    # Example: Creating from JSON and converting to dict
    json_data = '{"timestamp": 1672531200, "share_price": 150.5}'
    share_price_instance = SharePrice.from_json(json_data)
    
    share_price_dict = share_price_instance.to_dict()
    print(share_price_dict)
  8. Use the DetailedAccounts model

    main

    The DetailedAccounts model represents a paginated collection of detailed account information. It includes status information (code, message), the total count of accounts, a list of accounts (of type DetailedAccount), and a next_cursor for pagination.

    Properties

    NameTypeDescription
    codeintStatus code
    messagestr[optional] Status message
    totalintTotal number of accounts
    accountsList[DetailedAccount]List of detailed account objects
    next_cursorstrCursor for the next page of results
  9. Configure Stop Loss (SL) and Take Profit (TP) orders

    main

    SL and TP orders are triggered when a specific price is reached. When triggered, they execute as a standard order (Market, Limit IOC, or Limit GTC).

    Important Configuration Rules:

    • Direction: To close a long position, the SL/TP order must be an ask (sell) order.
    • Slippage Protection: Because a triggered order is just a normal order, you must configure execution price limits (e.g., lowest acceptable price for a sell) to prevent excessive slippage during volatility.
    • Automated SL/TP:
      • Using create_grouped_ioc_with_attached_sl_tp.py, you can attach SL/TP orders to an IoC order. The SL/TP size will match the executed size of the parent order, and they are canceled when your position sign changes.
      • Using create_position_tied_sl_tp.py, SL/TP orders can be tied to your entire position size (using BaseAmount=0), allowing them to grow or shrink as you accumulate more position.
  10. Use the RespListRFQs model

    main

    The RespListRFQs model represents a list of Request for Quotation (RFQ) entries returned by the API. It includes a status code, an optional message, a list of RFQEntry objects, and an optional next_cursor for pagination.

    Properties

    NameTypeDescription
    codeintThe response status code.
    messagestrAn optional status or error message.
    rfqsList[RFQEntry]A list of RFQ entries (see RFQEntry documentation).
    next_cursorstrAn optional cursor used for paginating through results.
  11. Use the AccountMetadatas model

    main

    The AccountMetadatas model is a container for a list of AccountMetadata objects, typically used for paginated responses. It includes properties for the response status (code, message), the list of metadata items (account_metadatas), and a pagination cursor (next_cursor).

    Properties

    NameTypeDescription
    codeintThe response status code.
    messagestr (optional)An optional status message.
    account_metadatasList[AccountMetadata]A list of individual account metadata objects.
    next_cursorstr (optional)An optional string used for pagination to fetch the next set of results.
  12. Use the LiquidationInfos model

    main

    The LiquidationInfos model is used to represent liquidation information, typically returned from API responses. It contains a list of Liquidation objects and pagination metadata.

    Properties

    NameTypeDescription
    codeintStatus code
    messagestr[optional] Status message
    liquidationsList[Liquidation]A list of liquidation details (see Liquidation.md)
    next_cursorstr[optional] Pagination cursor for fetching the next page