quantpylib.wrappers.lighter
quantpylib.wrappers.lighter module is our official Lighter wrapper SDK implementing the endpoints for Lighter's perpetuals zk-rollup. The library supports a fully asynchronous endpoint for efficiency and lightweight concurrency. The websocket manager handles reconnections and resubscriptions under network errors and upgrades, and a ctypes-based Signer wraps Lighter's official Go signer binary for L2 transaction signing.
We will demonstrate usage of the library. On top of the endpoints exposed by the exchange, we have added a variety of utility functions.
Examples
We would demonstrate some endpoints. Refer to full documentation for details. Let us first make some imports we would like to use:
import os
import asyncio
from pprint import pprint
from datetime import datetime, timedelta
from dotenv import load_dotenv
load_dotenv()
from quantpylib.standards import Period
from quantpylib.wrappers.lighter import Lighter
async def print_handler(msg): print(msg)
async def main():
lighter = Lighter(
key=os.getenv("LIT_KEY"), # L1 ETH address (master)
secret=os.getenv("LIT_SECRET"), # L1 ETH private key
cache_stream=True, # subscribe to market_stats/all and maintain mids/marks/indexes,
reserve_from=123,
)
await lighter.init_client()
# ...examples go here
await lighter.cleanup()
if __name__ == "__main__":
asyncio.run(main())
Bootstrap
Lighter is a zk-rollup. The L1 ETH key only ever signs ChangePubKey transactions — actual trading uses an L2 key registered at an api_key_index slot on the account. The connector handles the bootstrap automatically:
- On
init_client, if no L2 secret forreserve_fromis found in the env (LIT_<reserve_from>_SECRET) or passed viaall_secret=, a fresh L2 keypair is generated and the new private key is appended to your.env. - The same flow runs once for
reserve_from + 1(themaker_key), which Lighter's exchange registers as a maker-only slot with a 0ms speed bump for optimized execution paths (the maker key signs ALO/post-only orders and cancels) for performant trading. - A 1-hour
auth_tokenis created via the L2 key and refreshed every 30 minutes by a background task.
Navigating Assets
Lighter identifies markets by a numeric market_id. The connector resolves human-readable tickers (e.g. "LIT", "BTC", "ETH") automatically. If you'd rather pass the raw integer index, every gateway method takes is_index=True:
await lighter.limit_order(ticker="BTC", amount=20, price=0.5, tif='ALO')
await lighter.limit_order(ticker=120, amount=20, price=0.5, tif='ALO', is_index=True)
Precision helpers are also available:
lighter.get_price_precision("LIT")
lighter.get_lot_precision("BTC")
lighter.get_min_base("ETH")
lighter.get_min_quote("BTC")
Account
We may get account balances, subscribe to fill events easily
Standardized fills come through as(ts, ticker, amount, price, is_maker) where amount is signed (+ buy / − sell) from the account's perspective.
We can get perpetuals and spot contract specs:
specs = await lighter.contract_specifications(is_perpetuals=True)
specs = await lighter.contract_specifications(is_perpetuals=False)
Positions
We can get account perp-positions from a HTTP-request
or keep a local copy of the position state using: theon_update is optional, and the alive, local copy of positions can be retrieved here:
This is handled internally by the websocket subscriptions made available. All get-mirror-peek trio's work similarly. get is the HTTP request-response,
mirror is the mirror-copy maintained using socket subscriptions and peek requires a mirror request and just echoes the internal copy.
Orders
Of course you can make orders:
ord = await lighter.limit_order(ticker="LIT", amount=20, price=0.5, tif='GTC')
ord = await lighter.limit_order(ticker="LIT", amount=20, price=0.5, tif='ALO') # post-only routes via maker_key
ord = await lighter.market_order(ticker="LIT", amount=20) # IOC + slippage tolerance
submit=False and ship the signed tuples via send_tx_batch:
signed = [
await lighter.limit_order(ticker="LIT", amount=20, price=0.5, submit=False),
await lighter.limit_order(ticker="LIT", amount=20, price=0.6, submit=False),
]
await lighter.send_tx_batch(*zip(*signed))
Order states can be get-mirror-peek-ed:
print(await lighter.orders_get())
await lighter.orders_mirror(on_update=print_handler)
lighter.orders_peek()
Of course you can cancel the orders (by ticker and id, all for some ticker, or all tickers):
await lighter.cancel_order("LIT", oid='333444555666777')
await lighter.cancel_order("LIT", cloid=12345)
await lighter.cancel_open_orders() # everything
await lighter.cancel_open_orders(ticker="LIT") # one market
Single-order lookup (walks active + the 100 most recent inactive orders for the market):
await lighter.order_query(ticker="LIT", oid='<oid>')
await lighter.order_query(ticker="LIT", cloid=12345)
Data
Snapshot or stream the L2 book:
book = await lighter.l2_book_get(ticker="BTC", depth=5)
ob = await lighter.l2_book_mirror(ticker="BTC", as_dict=False)
print(ob.get_mid())
await lighter.l2_book_subscribe(ticker="BTC", handler=print_handler)
await asyncio.sleep(5)
await lighter.l2_book_unsubscribe(ticker="BTC")
subscribe handler receives {ts, b, a, is_snapshot} with is_snapshot=True on the first message and False on subsequent deltas. l2_book_mirror returns a quantpylib.hft.lob.LOB when as_dict=False.
Public trades:
Standardized trades come through as(ts, price, size, dir) where dir = 1 if the maker was on the ask side (taker bought), −1 otherwise.
Mid prices across all markets:
Historical OHLCV candles and funding rates:
df = await lighter.get_trade_bars(
ticker="BTC",
start=datetime.utcnow() - timedelta(days=1),
end=datetime.utcnow(),
granularity=Period.HOURLY,
granularity_multiplier=1,
)
print(df)
rates = await lighter.get_funding_rates(
ticker="BTC",
start=datetime.utcnow() - timedelta(days=7),
end=datetime.utcnow(),
)
print(rates)
Endpoints
The full Lighter REST API is exposed as direct method calls on the client. Here's an enumeration:
'''root'''
await lighter.system_config()
await lighter.status()
await lighter.info()
await lighter.layer1_basic_info()
'''account'''
await lighter.account()
await lighter.accounts_by_l1_address()
await lighter.account_limits()
await lighter.account_metadata()
await lighter.pnl()
await lighter.l1_metadata()
await lighter.change_account_tier(new_tier='premium')
await lighter.liquidations()
await lighter.position_funding()
await lighter.public_pools_metadata()
'''order / market'''
await lighter.account_active_orders()
await lighter.account_inactive_orders()
await lighter.export(dtype='trade')
await lighter.asset_details()
await lighter.exchange_stats()
await lighter.orderbook_details()
await lighter.orderbook_orders(market_id=0)
await lighter.orderbooks()
await lighter.recent_trades(market_id=0)
await lighter.trades()
'''transaction'''
await lighter.tx(value='<tx_hash>')
await lighter.tx_from_l1_txhash(hash='<l1_tx_hash>')
await lighter.deposit_history()
await lighter.transfer_history()
await lighter.withdraw_history()
'''apikeys'''
await lighter.apikeys()
await lighter.next_nonce()
await lighter.tokens_create(name='example', sub_account_access=False)
await lighter.tokens()
await lighter.tokens_revoke(token_id=0)
await lighter.set_maker_only_apikeys([124, 157])
await lighter.get_maker_only_apikeys()
'''candles / funding'''
await lighter.candles(market_id=0)
await lighter.fundings(market_id=0)
await lighter.funding_rates()
'''bridge'''
await lighter.create_intent_address(chain_id='1', from_addr='0x...', amount='100')
await lighter.fastbridge_info()
await lighter.deposit_latest()
await lighter.deposit_networks()
await lighter.fast_withdraw(tx_info='<signed_tx>', to_address='0x...')
await lighter.fast_withdraw_info()
'''info'''
await lighter.exchange_metrics(period='all', kind='volume')
await lighter.partner_stats()
await lighter.execute_stats(period='d')
await lighter.transfer_fee_info()
await lighter.withdrawal_delay()
await lighter.token_list()
'''referral'''
await lighter.user_referrals()
await lighter.referral_create()
await lighter.referral_get()
await lighter.referral_kickback_update(kickback_percentage=10)
await lighter.referral_update(new_referral_code='MYCODE')
await lighter.referral_use(referral_code='quantpylib', x='<x>', signature='<sig>')
'''fee credits'''
await lighter.lease_options()
await lighter.leases()
await lighter.lit_lease(tx_info='<signed_tx>', lease_amount='1000000', duration_days=30)
The Lighter Explorer API is also wrapped:
await lighter.account_logs()
await lighter.account_positions()
await lighter.account_assets()
await lighter.batches()
await lighter.batch_id(batch_id=164607)
await lighter.blocks()
await lighter.block_id(block_id=222526303)
await lighter.log_hash(hash='<hash>')
await lighter.markets()
await lighter.markets_log(symbol='ETH')
await lighter.search(q='0x...')
await lighter.stats_tx(aggregation_period='1h')
await lighter.stats_total()
Websockets
The websocket manager supports all documented channels (per the Lighter websocket reference). You can use the gateway-level subscribe/unsubscribe methods on the Lighter instance, or access the aws_manager member object directly for the full channel set.
Gateway-level websocket methods (with optional schema standardization):
await lighter.l2_book_subscribe(ticker="BTC", handler=print_handler)
await lighter.l2_book_unsubscribe(ticker="BTC")
await lighter.trades_subscribe(ticker="BTC", handler=print_handler)
await lighter.trades_unsubscribe(ticker="BTC")
await lighter.all_mids_subscribe(handler=print_handler)
await lighter.all_mids_unsubscribe()
await lighter.order_updates_subscribe(handler=print_handler)
await lighter.order_updates_unsubscribe()
await lighter.account_fill_subscribe(handler=print_handler)
await lighter.account_fill_unsubscribe()
For the full set of channels, use aws_manager directly:
aws = lighter.aws_manager
await aws.order_book_subscribe(market_id=0, handler=print_handler)
await aws.ticker_subscribe(market_id=0, handler=print_handler)
await aws.market_stats_subscribe(market_id=0, handler=print_handler)
await aws.trade_subscribe(market_id=0, handler=print_handler)
await aws.account_all_subscribe(handler=print_handler)
await aws.account_market_subscribe(market_id=0, handler=print_handler)
await aws.user_stats_subscribe(handler=print_handler)
await aws.account_tx_subscribe(handler=print_handler)
await aws.account_all_orders_subscribe(handler=print_handler)
await aws.height_subscribe(handler=print_handler)
await aws.pool_data_subscribe(handler=print_handler)
await aws.pool_info_subscribe(handler=print_handler)
await aws.notification_subscribe(handler=print_handler)
await aws.account_orders_subscribe(market_id=0, handler=print_handler)
await aws.account_all_trades_subscribe(handler=print_handler)
await aws.account_all_positions_subscribe(handler=print_handler)
await aws.spot_market_stats_subscribe(market_id=0, handler=print_handler)
await aws.account_all_assets_subscribe(handler=print_handler)
await aws.account_spot_avg_entry_prices_subscribe(handler=print_handler)
auth_token from the closure passed at construction.
More Examples
example_lighter.py:
import os
import time
import asyncio
import logging
from pprint import pprint
from functools import partial
from datetime import datetime, timedelta
from dotenv import load_dotenv
load_dotenv()
from quantpylib.standards import Period
from quantpylib.wrappers.lighter import Lighter
async def print_handler(msg):
print(msg)
lighter = Lighter(
key=os.getenv("LIT_KEY"),
secret=os.getenv("LIT_SECRET"),
cache_stream=True
)
async def endpoint_examples():
'''root'''
pprint(await lighter.system_config())
pprint(await lighter.status())
pprint(await lighter.info())
pprint(await lighter.layer1_basic_info())
'''account'''
pprint(await lighter.account())
pprint(await lighter.accounts_by_l1_address())
pprint(await lighter.account_limits())
pprint(await lighter.account_metadata())
pprint(await lighter.pnl())
pprint(await lighter.l1_metadata())
pprint(await lighter.change_account_tier(new_tier='premium'))
pprint(await lighter.liquidations())
pprint(await lighter.position_funding())
pprint(await lighter.public_pools_metadata())
'''order'''
pprint(await lighter.account_active_orders())
pprint(await lighter.account_inactive_orders())
pprint(await lighter.export(dtype='trade'))
pprint(await lighter.asset_details())
pprint(await lighter.exchange_stats())
pprint(await lighter.orderbook_details())
pprint(await lighter.orderbook_orders(market_id=0))
pprint(await lighter.orderbooks())
pprint(await lighter.recent_trades(market_id=0))
pprint(await lighter.trades())
'''transaction'''
## send_tx / send_tx_batch — write paths, exercised via order/cancel methods
# pprint(await lighter.tx(value='<tx_hash>'))
# pprint(await lighter.tx_from_l1_txhash(hash='<l1_tx_hash>'))
pprint(await lighter.deposit_history())
pprint(await lighter.transfer_history())
pprint(await lighter.withdraw_history())
'''announcement'''
pprint(await lighter.announcement())
'''apikeys'''
pprint(await lighter.apikeys())
pprint(await lighter.next_nonce())
# pprint(await lighter.tokens_create(name='example', sub_account_access=False))
# pprint(await lighter.tokens_revoke(token_id=0))
# pprint(await lighter.tokens())
# pprint(await lighter.set_maker_only_apikeys([124]))
pprint(await lighter.get_maker_only_apikeys())
'''candles'''
pprint(await lighter.candles(market_id=0))
'''bridge'''
# pprint(await lighter.create_intent_address(chain_id='1', from_addr='0x...', amount='100'))
pprint(await lighter.fastbridge_info())
pprint(await lighter.deposit_latest())
pprint(await lighter.deposit_networks())
'''funding'''
pprint(await lighter.fundings(market_id=0))
pprint(await lighter.funding_rates())
'''notification'''
pprint(await lighter.notification_ack(notif_id='<id>'))
'''info'''
pprint(await lighter.exchange_metrics(period='all', kind='volume'))
pprint(await lighter.partner_stats())
pprint(await lighter.execute_stats(period='d'))
pprint(await lighter.transfer_fee_info())
pprint(await lighter.withdrawal_delay())
# pprint(await lighter.fast_withdraw(tx_info='<signed_tx>', to_address='0x...'))
pprint(await lighter.fast_withdraw_info())
pprint(await lighter.token_list())
'''referral'''
pprint(await lighter.user_referrals())
pprint(await lighter.referral_create())
pprint(await lighter.referral_get())
# pprint(await lighter.referral_kickback_update(kickback_percentage=10))
# pprint(await lighter.referral_update(new_referral_code='MYCODE'))
# pprint(await lighter.referral_use(referral_code='quantpylib', x='<x>', signature='<sig>'))
'''fee credits'''
pprint(await lighter.lease_options())
pprint(await lighter.leases())
# pprint(await lighter.lit_lease(tx_info='<signed_tx>', lease_amount='1000000', duration_days=30))
return
async def explorer_examples():
'''account'''
pprint(await lighter.account_logs())
pprint(await lighter.account_positions())
pprint(await lighter.account_assets())
'''batches'''
pprint(await lighter.batches())
pprint(await lighter.batch_id(batch_id=164607))
'''blocks'''
pprint(await lighter.blocks())
pprint(await lighter.block_id(block_id=222526303))
'''logs'''
pprint(await lighter.log_hash(hash='c250762308fc8626100d6e6991d44cd3f89b151bb001556ef7bba94d7bb07fc87d9797587104acf5'))
'''markets'''
pprint(await lighter.markets())
pprint(await lighter.markets_log(symbol='ETH'))
'''search'''
# pprint(await lighter.search(q='0x...'))
'''stats'''
pprint(await lighter.stats_tx(aggregation_period='1h'))
pprint(await lighter.stats_total())
return
async def gateway_examples():
'''utilities'''
ticker = "LIT"
amount = 20
resting_price = 0.5
pprint(lighter.get_nonce())
pprint(lighter.get_price_precision(ticker))
pprint(lighter.get_lot_precision(ticker))
pprint(lighter.get_min_base(ticker))
pprint(lighter.get_min_quote(ticker))
pprint(lighter.rand_cloid())
'''account'''
pprint(await lighter.account_balance())
await lighter.account_fill_subscribe(handler=print_handler)
await asyncio.sleep(4)
await lighter.account_fill_unsubscribe()
'''exchange'''
pprint(await lighter.contract_specifications(is_perpetuals=True))
pprint(await lighter.contract_specifications(is_perpetuals=False))
pprint(await lighter.get_funding_info())
pprint(await lighter.get_funding_info(ticker=ticker))
'''executor'''
pprint(await lighter.get_all_mids())
pprint(await lighter.get_all_marks())
pprint(await lighter.get_all_indexes())
# pprint(await lighter.limit_order(ticker=ticker, amount=amount, price=resting_price, tif='ALO'))
# pprint(await lighter.limit_order(ticker=ticker, amount=amount, price=resting_price, tif='GTC'))
# pprint(await lighter.cancel_open_orders(ticker=ticker))
# pprint(await lighter.cancel_open_orders())
# pprint(await lighter.cancel_order(ticker=ticker, oid='<oid>'))
# pprint(await lighter.market_order(ticker=ticker, amount=amount))
pprint(await lighter.l2_book_get(ticker=ticker))
pprint(await lighter.l2_book_get(ticker=ticker, depth=5))
ob = await lighter.l2_book_mirror(ticker=ticker, as_dict=False)
for _ in range(4):
await asyncio.sleep(1)
print(f"mid: {ob.get_mid()}")
await lighter.l2_book_subscribe(ticker=ticker, handler=print_handler)
await asyncio.sleep(4)
await lighter.l2_book_unsubscribe(ticker=ticker)
await lighter.trades_subscribe(ticker=ticker, handler=print_handler)
await asyncio.sleep(4)
await lighter.trades_unsubscribe(ticker=ticker)
await lighter.all_mids_subscribe(handler=print_handler)
await asyncio.sleep(4)
await lighter.all_mids_unsubscribe()
'''orders'''
# pprint(await lighter.order_query(ticker=ticker, oid='<order_id>'))
pprint(await lighter.order_query(ticker=ticker, cloid=12345))
pprint(await lighter.orders_get())
orders = await lighter.orders_mirror(on_update=print_handler)
pprint(lighter.orders_peek())
await lighter.order_updates_subscribe(handler=print_handler)
await asyncio.sleep(4)
await lighter.order_updates_unsubscribe()
'''positions'''
pprint(await lighter.positions_get())
pos = await lighter.positions_mirror(as_dict=True, on_update=print_handler)
print(pos)
pos = lighter.positions_peek()
'''datapoller'''
df = await lighter.get_trade_bars(
ticker="BTC",
start=datetime.utcnow() - timedelta(days=1),
end=datetime.utcnow(),
granularity=Period.HOURLY,
granularity_multiplier=1,
)
print(df)
df = await lighter.get_funding_rates(
ticker="BTC",
start=datetime.utcnow() - timedelta(days=7),
end=datetime.utcnow(),
)
print(df)
async def socket_examples():
aws = lighter.aws_manager
ticker = "LIT"
async def stream_for(sub,unsub,duration=10):
print('sub:', sub.__name__)
await asyncio.sleep(1)
await sub
await asyncio.sleep(duration)
await unsub
await asyncio.sleep(1)
await stream_for(
aws.order_book_subscribe(market_id=0, handler=print_handler),
aws.order_book_unsubscribe(market_id=0)
)
await stream_for(
aws.ticker_subscribe(market_id=0, handler=print_handler),
aws.ticker_unsubscribe(market_id=0)
)
await stream_for(
aws.market_stats_subscribe(market_id=0, handler=print_handler),
aws.market_stats_unsubscribe(market_id=0)
)
await stream_for(
aws.trade_subscribe(market_id=0, handler=print_handler),
aws.trade_unsubscribe(market_id=0)
)
await stream_for(
aws.account_all_subscribe(handler=print_handler),
aws.account_all_unsubscribe()
)
await stream_for(
aws.account_market_subscribe(market_id=0, handler=print_handler),
aws.account_market_unsubscribe(market_id=0)
)
await stream_for(
aws.user_stats_subscribe(handler=print_handler),
aws.user_stats_unsubscribe()
)
await stream_for(
aws.account_tx_subscribe(handler=print_handler),
aws.account_tx_unsubscribe()
)
await stream_for(
aws.account_all_orders_subscribe(handler=print_handler),
aws.account_all_orders_unsubscribe()
)
await stream_for(
aws.height_subscribe(handler=print_handler),
aws.height_unsubscribe()
)
await stream_for(
aws.pool_data_subscribe(handler=print_handler),
aws.pool_data_unsubscribe()
)
await stream_for(
aws.pool_info_subscribe(handler=print_handler),
aws.pool_info_unsubscribe()
)
await stream_for(
aws.notification_subscribe(handler=print_handler),
aws.notification_unsubscribe()
)
await stream_for(
aws.account_orders_subscribe(market_id='all', handler=print_handler),
aws.account_orders_unsubscribe(market_id='all')
)
await stream_for(
aws.account_all_trades_subscribe(handler=print_handler),
aws.account_all_trades_unsubscribe()
)
await stream_for(
aws.account_all_positions_subscribe(handler=print_handler),
aws.account_all_positions_unsubscribe()
)
await stream_for(
aws.spot_market_stats_subscribe(market_id='all', handler=print_handler),
aws.spot_market_stats_unsubscribe(market_id='all')
)
await stream_for(
aws.account_all_assets_subscribe(handler=print_handler),
aws.account_all_assets_unsubscribe()
)
await stream_for(
aws.account_spot_avg_entry_prices_subscribe(handler=print_handler),
aws.account_spot_avg_entry_prices_unsubscribe()
)
return
async def main():
await lighter.init_client()
try:
'''uncomment examples to run
NOTE: that some code may trigger exchange actions such as live orders
'''
# await endpoint_examples()
# await explorer_examples()
# await gateway_examples()
await socket_examples()
except Exception as e:
logging.exception("Error in SDK examples: %s", e)
await lighter.cleanup()
if __name__ == "__main__":
import asyncio
asyncio.run(main())
Documentation
Notes
binaries in quantpylib/wrappers/lighter_/* is generated from: https://github.com/elliottech/lighter-go/tree/main
AsyncWebsocketManager
account_all_assets_subscribe(handler)
async
Subscribe to account_all_assets channel.
account_all_assets_unsubscribe()
async
Unsubscribe from account_all_assets channel.
account_all_orders_subscribe(handler)
async
Subscribe to account_all_orders channel.
account_all_orders_unsubscribe()
async
Unsubscribe from account_all_orders channel.
account_all_positions_subscribe(handler)
async
Subscribe to account_all_positions channel.
account_all_positions_unsubscribe()
async
Unsubscribe from account_all_positions channel.
account_all_subscribe(handler)
async
Subscribe to account_all channel.
account_all_trades_subscribe(handler)
async
Subscribe to account_all_trades channel.
account_all_trades_unsubscribe()
async
Unsubscribe from account_all_trades channel.
account_all_unsubscribe()
async
Unsubscribe from account_all channel.
account_market_subscribe(market_id, handler)
async
Subscribe to account_market channel.
account_market_unsubscribe(market_id)
async
Unsubscribe from account_market channel.
account_orders_subscribe(market_id, handler)
async
Subscribe to account_orders channel.
account_orders_unsubscribe(market_id)
async
Unsubscribe from account_orders channel.
account_spot_avg_entry_prices_subscribe(handler)
async
Subscribe to account_spot_avg_entry_prices channel.
account_spot_avg_entry_prices_unsubscribe()
async
Unsubscribe from account_spot_avg_entry_prices channel.
account_tx_subscribe(handler)
async
Subscribe to account_tx channel.
account_tx_unsubscribe()
async
Unsubscribe from account_tx channel.
height_subscribe(handler)
async
Subscribe to height channel.
height_unsubscribe()
async
Unsubscribe from height channel.
market_stats_subscribe(market_id, handler)
async
Subscribe to market_stats channel.
market_stats_unsubscribe(market_id)
async
Unsubscribe from market_stats channel.
notification_subscribe(handler)
async
Subscribe to notification channel.
notification_unsubscribe()
async
Unsubscribe from notification channel.
order_book_subscribe(market_id, handler)
async
Subscribe to order_book channel.
order_book_unsubscribe(market_id)
async
Unsubscribe from order_book channel.
pool_data_subscribe(handler)
async
Subscribe to pool_data channel.
pool_data_unsubscribe()
async
Unsubscribe from pool_data channel.
pool_info_subscribe(handler)
async
Subscribe to pool_info channel.
pool_info_unsubscribe()
async
Unsubscribe from pool_info channel.
spot_market_stats_subscribe(market_id, handler)
async
Subscribe to spot_market_stats channel.
spot_market_stats_unsubscribe(market_id)
async
Unsubscribe from spot_market_stats channel.
ticker_subscribe(market_id, handler)
async
Subscribe to ticker channel.
ticker_unsubscribe(market_id)
async
Unsubscribe from ticker channel.
trade_subscribe(market_id, handler)
async
Subscribe to trade channel.
trade_unsubscribe(market_id)
async
Unsubscribe from trade channel.
user_stats_subscribe(handler)
async
Subscribe to user_stats channel.
user_stats_unsubscribe()
async
Unsubscribe from user_stats channel.
Lighter
__init__(key, secret, account_index=None, all_secret=None, maker_secret=None, reserve_from=RESERVE_FROM, cache_stream=False, **kwargs)
Initialize a Lighter client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
L1 ETH address of the master account. |
required |
secret
|
str
|
L1 ETH private key for the master account. |
required |
account_index
|
int
|
Pre-resolved Lighter account index, can be dynamically populated. |
None
|
all_secret
|
str
|
L2 private key for general-purpose path. Defaults to environment variable |
None
|
maker_secret
|
str
|
L2 private key for the maker-only optimised path. Defaults to environment variable |
None
|
reserve_from
|
int
|
Defaults to RESERVE_FROM (123). |
RESERVE_FROM
|
cache_stream
|
bool
|
If True, |
False
|
account(by='index', value=None)
async
Retrieve account snapshot — positions, collateral, margin requirements, assets.
account_active_orders(market_id=None, account_idx=None, **kwargs)
async
Retrieve all currently open orders for the account.
account_assets(param=None, **kwargs)
async
Retrieve spot asset balances from the explorer.
account_balance(**kwargs)
async
Retrieve balance details of the user, such as equity, margin (total, maintenance) and pnl.
Returns:
| Type | Description |
|---|---|
dict
|
Balance details. |
account_fill_subscribe(handler, standardize_schema=True, **kwargs)
async
Subscribe to order fill events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
standardize_schema
|
bool
|
If True, processes the incoming message to
a standardized |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
account_fill_unsubscribe(**kwargs)
async
Unsubscribe from order fill events.
account_inactive_orders(market_id=None, account_idx=None, limit=100, **kwargs)
async
Retrieve historical (filled/cancelled) orders for the account, paginated.
account_limits(account_idx=None)
async
Retrieve per-account trading limits.
account_logs(param=None, **kwargs)
async
Retrieve activity logs for the account from the explorer.
account_metadata(by='index', value=None, cursor=None)
async
Retrieve account metadata (tier, name, description, etc).
account_positions(param=None, **kwargs)
async
Retrieve positions snapshot from the explorer.
accounts_by_l1_address(l1_address=None)
async
Retrieve all sub-account indices for the given L1 ETH address.
all_mids_subscribe(handler, standardize_schema=True, **kwargs)
async
Subscribe to mid prices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
standardize_schema
|
(bool, True)
|
Processes the incoming message to standard schema. |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
all_mids_unsubscribe(**kwargs)
async
Unsubscribe from mid prices.
announcement()
async
Retrieve current exchange announcements.
apikeys(account_idx=None, api_key_index=NIL_API_KEY_INDEX)
async
Retrieve registered L2 api keys for the account.
approve_integrator(integrator_account_index, max_perps_taker_fee, max_perps_maker_fee, max_spot_taker_fee, max_spot_maker_fee, expired_at, *, eth_private_key=None, **kwargs)
async
Placeholder for integrator-fee approval. Not yet wired.
asset_details(asset_id=None)
async
Retrieve metadata for a specific asset (or all assets when asset_id is None).
batch_id(batch_id)
async
Retrieve a specific batch by id from the explorer.
batches(**kwargs)
async
Retrieve recent batches from the explorer.
block_id(block_id)
async
Retrieve a specific block by id from the explorer.
blocks(**kwargs)
async
Retrieve recent blocks from the explorer.
burn_shares(public_pool_index, share_amount, **kwargs)
async
Placeholder for public-pool share burn. Not yet wired.
cancel_open_orders(ticker=None, **kwargs)
async
Cancel open orders on the exchange.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol. Defaults to None, which means cancel all open orders. |
None
|
**kwargs
|
Additional keyword arguments for further customization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The result of the cancellation request. Returns |
cancel_order(ticker, oid=None, cloid=None, is_index=False, **kwargs)
async
Cancel an order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
oid
|
int
|
Order ID to cancel. |
None
|
cloid
|
int
|
Client Order ID to cancel (must be in |
None
|
is_index
|
bool
|
If True, the |
False
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
candles(market_id, resolution='1h', start=None, end=None, count_back=1000, set_timestamp_to_end=False, **kwargs)
async
Retrieve OHLCV candles for a market over the requested window.
change_account_tier(new_tier, account_idx=None)
async
Switch account tier (e.g. standard ↔ premium).
change_api_key(slot, new_pubkey, *, eth_private_key=None, **kwargs)
async
Rotate the L2 public key registered at the given api_key_index slot. Always L1-signed — requires the master account's ETH private key. Be aware that rotating the key without retaining the matching private key locally locks the slot out for subsequent signing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slot
|
int
|
The api_key_index slot to rotate. |
required |
new_pubkey
|
str
|
Hex-encoded new L2 public key. |
required |
eth_private_key
|
str
|
L1 ETH private key for the L1 signature.
Defaults to None (uses |
None
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The |
cleanup()
async
Cleans up open sessions with Lighter server
conditional_order(ticker, amount, trigger_price, kind='TP', limit_price=None, **kwargs)
async
Placeholder for stop-loss / take-profit conditional orders. Not yet wired.
contract_specifications(is_perpetuals=True, **kwargs)
async
Retrieve the contract's trading rules from the exchange.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
is_perpetuals
|
bool
|
Specifies whether to fetch perpetual contracts. Defaults to True. |
True
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing contract specifications for each asset with key-values: - SYMBOL_PRICE_PRECISION. - SYMBOL_QUANTITY_PRECISION. - SYMBOL_MIN_NOTIONAL - SYMBOL_BASE_ASSET - SYMBOL_QUOTE_ASSET |
create_intent_address(chain_id, from_addr, amount, is_external_deposit=None, **kwargs)
async
Create a deposit intent address for cross-chain bridging.
create_public_pool(operator_fee, initial_total_shares, min_operator_share_rate, **kwargs)
async
Placeholder for public-pool creation. Not yet wired.
create_sub_account(api_key_index=None, **kwargs)
async
Create a new sub-account under the master account.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key_index
|
int
|
Override the api_key_index used for signing. Defaults to None (uses |
None
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The |
deposit_history(l1_address=None, account_idx=None, **kwargs)
async
Retrieve deposit history for the account.
deposit_latest(l1_address=None)
async
Retrieve the latest deposit for the L1 address.
deposit_networks()
async
Retrieve the list of supported deposit networks.
exchange_metrics(period, kind, **kwargs)
async
Retrieve aggregated exchange metrics by period and kind.
exchange_stats()
async
Retrieve exchange-wide volume / trade-count stats.
execute_stats(period)
async
Retrieve execution stats by period.
export(dtype, account_idx=None, **kwargs)
async
Trigger a CSV export job for the account ('trade' | 'funding').
fast_withdraw(tx_info, to_address)
async
Submit a fast-withdraw request.
fast_withdraw_info(account_idx=None)
async
Retrieve fast-withdraw eligibility and parameters for the account.
fastbridge_info()
async
Retrieve fast-bridge configuration.
funding_rates()
async
Retrieve current funding-rate snapshot across all markets and exchanges.
fundings(market_id, resolution='1h', start=None, end=None, count_back=1000, **kwargs)
async
Retrieve historical funding rates for a market.
get_all_indexes(ticker=None, **kwargs)
async
Retrieve index prices for all perpetuals. Requires cache_stream=True on init.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary of ticker to index price (Decimal). |
get_all_marks(ticker=None, **kwargs)
async
Retrieve mark prices for all perpetuals. Requires cache_stream=True on init.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary of ticker to mark price (Decimal). |
get_all_mids(ticker=None, **kwargs)
async
Retrieve the mid-price for a specific ticker or all available tickers. Requires
cache_stream=True on init.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The symbol of the specific contract for which to retrieve the mid-price. If not provided, mid-prices for all contracts will be returned. Defaults to None. |
None
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Decimal |
The mid-price of the specified ticker if |
|
dict |
A dictionary with contract symbols as keys and their corresponding mid-prices (Decimal) as values
if |
get_funding_info(ticker=None, **kwargs)
async
Retrieve funding rate information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
If provided, returns funding info for this ticker only. |
None
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Funding info keyed by ticker, or a single ticker's funding info if |
get_funding_rates(ticker, start, end, is_index=False, **kwargs)
async
Retrieve funding rates data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol for the asset. |
required |
start
|
datetime
|
Start datetime for the data retrieval. |
required |
end
|
datetime
|
End datetime for the data retrieval. |
required |
is_index
|
bool
|
If True, treat ticker as the integer market_id. Defaults to False. |
False
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing the funding rates data. |
get_lot_precision(ticker, is_index=False)
Get the lot precision for a specified asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
is_index
|
bool
|
If True, the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
The number of decimal places used for the asset's lot size precision. |
get_maker_only_apikeys(account_idx=None)
async
Retrieve the list of api_key_indexes registered as maker-only.
get_min_base(ticker, is_index=False)
Get the minimum base-asset order size for a specified asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
is_index
|
bool
|
If True, the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
The minimum allowed base amount. |
get_min_quote(ticker, is_index=False)
Get the minimum quote-asset notional for a specified asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
is_index
|
bool
|
If True, the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
The minimum allowed quote notional. |
get_nonce()
Get a unique nonce value using a nonce buffer to ensure no overlaps between exchange requests.
Returns:
| Name | Type | Description |
|---|---|---|
int |
A unique nonce value. |
get_price_precision(ticker, is_index=False)
Get the price precision for a specified asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
is_index
|
bool
|
If True, the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
The number of decimal places used for the asset's price precision. |
get_trade_bars(ticker, start, end, granularity, granularity_multiplier, kline_close=False, is_index=False, **kwargs)
async
Retrieve trade bars data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol for the asset. |
required |
start
|
datetime
|
Start datetime for the data retrieval. |
required |
end
|
datetime
|
End datetime for the data retrieval. |
required |
granularity
|
Period
|
Granularity of the data. |
required |
granularity_multiplier
|
int
|
Multiplier for the granularity. |
required |
kline_close
|
bool
|
Timestamp candle by the candles' start or end timestamp. Defaults to |
False
|
is_index
|
bool
|
If True, treat ticker as the integer market_id. Defaults to False. |
False
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing the trade bars data. |
grouped_orders(orders, grouping_type=GROUPING_OCO, **kwargs)
async
Placeholder for grouped (OCO/OTO/OTOCO) order submission. Not yet wired.
info()
async
Retrieve general info about the exchange.
init_client()
async
Initializes the exchange client with important metadata for mapping tickers to asset ids, contract precision and mapping. Should be called upon object initialization.
l1_metadata(l1_address=None)
async
Retrieve L1 deposit/withdraw metadata for the address.
l2_book_get(ticker, depth=None, is_index=False, **kwargs)
async
Retrieve L2 snapshot for a given coin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The coin symbol. |
required |
depth
|
int
|
Depth of the order-book representation. Defaults to None (full depth). |
None
|
is_index
|
bool
|
If True, the |
False
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the L2 snapshot information. |
l2_book_mirror(ticker, depth=100, buffer_size=100, as_dict=True, on_update=None, apply_shadow_depth=False, is_index=False, **kwargs)
async
Keep a live, internal L2 Order Book representation using a l2-book subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
depth
|
int
|
Depth of the order-book representation, if |
100
|
buffer_size
|
int
|
Size of the order-book buffer, if |
100
|
as_dict
|
(bool, True)
|
If |
True
|
on_update
|
coroutine
|
A coroutine handler when order book state is updated. |
None
|
apply_shadow_depth
|
(bool, False)
|
If True, applies shadow depth to the LOB. |
False
|
is_index
|
bool
|
If True, the |
False
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
l2_book_peek(ticker, as_dict=True, is_index=False, **kwargs)
Retrieve the mirrored, local internal L2 Order Book representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
as_dict
|
(bool, True)
|
If |
True
|
is_index
|
bool
|
If True, the |
False
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
l2_book_subscribe(ticker, handler, is_index=False, standardize_schema=True, **kwargs)
async
Subscribe to L2 Order Book stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
is_index
|
bool
|
If True, the |
False
|
standardize_schema
|
(bool, True)
|
Processes the incoming message to |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
l2_book_unsubscribe(ticker, is_index=False, **kwargs)
async
Unsubscribe from L2 Order Book.
layer1_basic_info()
async
Retrieve basic L1 chain info (chain id, contract address, etc).
lease_options()
async
Retrieve available lease options.
leases(account_idx=None, **kwargs)
async
Retrieve the account's active fee-credit leases.
limit_order(ticker, amount, price, tif='GTC', cloid=None, reduce_only=False, trigger_price=NIL_TRIGGER_PRICE, order_expiry=EXPIRY_28D, api_key_index=None, round_price=False, round_size=False, is_index=False, submit=True, **kwargs)
async
Submit a limit order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol. |
required |
amount
|
float or Decimal
|
The signed quantity of contracts to long or short. |
required |
price
|
float
|
The price at which to execute the order. |
required |
tif
|
str
|
The time in force for the order. Defaults to "GTC". Allowed values are: - "GTC" / "GTD" (good till time, 28d default) - "ALO" (add liquidity only / post-only) - "IOC" (immediate or cancel) |
'GTC'
|
cloid
|
int
|
Client order ID in |
None
|
reduce_only
|
bool
|
Whether the order should only reduce an existing position. Defaults to False. |
False
|
trigger_price
|
int
|
Scaled trigger price for conditional orders. Defaults to NIL_TRIGGER_PRICE. |
NIL_TRIGGER_PRICE
|
order_expiry
|
int
|
Absolute expiry timestamp (ms) or sentinel. Use
|
EXPIRY_28D
|
api_key_index
|
int
|
Override the api_key_index used for signing. Defaults to None,
which routes ALO via |
None
|
round_price
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
round_size
|
bool
|
Whether to round the size to a valid order specification. Defaults to False. |
False
|
is_index
|
bool
|
If True, the |
False
|
submit
|
bool
|
If True, sign and POST |
True
|
**kwargs
|
Additional keyword arguments for order customization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The result of the order placement. |
liquidations(account_idx=None, limit=100, **kwargs)
async
Retrieve account liquidation history.
lit_lease(tx_info, lease_amount, duration_days)
async
Submit a LIT-token fee-credit lease request.
log_hash(hash)
async
Retrieve a log entry by its hash from the explorer.
market_order(ticker, amount, cloid=None, reduce_only=False, slippage_tolerance=0.03, is_index=False, **kwargs)
async
Submit a market order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol for the asset. |
required |
amount
|
float or Decimal
|
The signed quantity of contracts to long or short. |
required |
cloid
|
int
|
Client order ID for custom tracking. Defaults to None. |
None
|
reduce_only
|
bool
|
Whether the order should only reduce an existing position. Defaults to False. |
False
|
slippage_tolerance
|
float
|
The maximum acceptable slippage, expressed as a fraction. Defaults to 0.03 (3%). |
0.03
|
is_index
|
bool
|
If True, the |
False
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The result of the order placement. |
markets()
async
Retrieve market metadata (symbol/index map) from the explorer.
markets_log(symbol, **kwargs)
async
Retrieve activity log for a specific market from the explorer.
mint_shares(public_pool_index, share_amount, **kwargs)
async
Placeholder for public-pool share mint. Not yet wired.
modify_order(ticker, oid, amount, price, trigger_price=NIL_TRIGGER_PRICE, api_key_index=None, round_price=False, round_size=False, is_index=False, submit=True, **kwargs)
async
Modify an existing open order's size and/or price (and optionally trigger_price for
conditional orders). Original time_in_force and order_expiry are preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol. |
required |
oid
|
int
|
The exchange order id. |
required |
amount
|
float | Decimal
|
New unsigned size (the original |
required |
price
|
float
|
New limit price. |
required |
trigger_price
|
int
|
New scaled trigger price for conditional orders. Defaults to NIL_TRIGGER_PRICE. |
NIL_TRIGGER_PRICE
|
api_key_index
|
int
|
Override the api_key_index used for signing. Defaults to None (uses |
None
|
round_price
|
bool
|
If True, silently round price to the market's price precision. Defaults to False. |
False
|
round_size
|
bool
|
If True, silently round amount to the market's lot precision. Defaults to False. |
False
|
is_index
|
bool
|
If True, treat |
False
|
submit
|
bool
|
If True, sign and POST |
True
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The |
next_nonce(account_idx=None, api_key_index=None)
async
Retrieve the next sequential nonce for the given api_key_index.
notification_ack(notif_id, account_idx=None)
async
Acknowledge (mark read) a notification.
order_query(ticker, oid=None, cloid=None, as_dict=True, is_index=False, **kwargs)
async
Get order details using order ID or client order ID. Only the 100 most recent inactive orders are visible; older fills/cancels return ord_status=ORDER_STATUS_UNKNOWN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
oid
|
int
|
The order ID in exchange. |
None
|
cloid
|
int
|
The client order ID. |
None
|
as_dict
|
bool
|
If True, returns as dictionary. Defaults to True. |
True
|
is_index
|
bool
|
If True, the |
False
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
order_updates_subscribe(handler, **kwargs)
async
Subscribe to creation, updation and deletion of account's orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
order_updates_unsubscribe(**kwargs)
async
Unsubscribe from order events.
orderbook_details(market_id=None, **kwargs)
async
Retrieve detailed market metadata — fees, margin fractions, decimals — per market.
orderbook_orders(market_id, limit=100, **kwargs)
async
Retrieve raw open orders on the public order book for a market.
orderbooks(market_id=None, **kwargs)
async
Retrieve the list of available markets and their basic config.
orders_get(**kwargs)
async
Get all open order details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing details of all open orders. Each key is the order ID, with value dict: - markets.TICKER: The asset's ticker symbol. - markets.ORDER_ID: The unique identifier of the order. - markets.ORDER_CLOID: The client order ID. - markets.LIMIT_PRICE: The limit price of the order. - markets.ORDER_AMOUNT: The original size of the order. - markets.ORDER_FILLED_SIZE: The remaining size of the order yet to be filled. - markets.ORDER_STATUS: The status of the order. - markets.TIMESTAMP: The timestamp when the order was created. |
orders_mirror(on_update=None, as_list=True, **kwargs)
async
Keeps a local mirror copy of the account open orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_update
|
coroutine
|
A coroutine handler for orders dictionary on order event. |
None
|
as_list
|
bool
|
If |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
orders_peek(as_dict=True, **kwargs)
Retrieves the local mirror copy of the account open orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_dict
|
bool
|
If |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
partner_stats(account_idx=None, **kwargs)
async
Retrieve partner / referral stats for the account.
pnl(by='index', value=None, resolution='1h', start=None, end=None, count_back=1000, **kwargs)
async
Retrieve realized PnL over the requested window.
position_funding(account_idx=None, limit=100, **kwargs)
async
Retrieve cumulative funding paid/received per position.
positions_get(**kwargs)
async
Get all open position details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing details of the open positions. |
positions_mirror(on_update=None, as_dict=True, **kwargs)
async
Keeps a local mirror copy of the account open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_update
|
coroutine
|
A coroutine handler for positions dictionary on fill. |
None
|
as_dict
|
bool
|
If True, the method returns positions as a dictionary, otherwise as a |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
positions_peek(as_dict=True, **kwargs)
Retrieves the local mirror copy of the account open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_dict
|
bool
|
If True, the method returns positions as a dictionary, otherwise as a |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
public_pools_metadata(index=0, limit=100, **kwargs)
async
Retrieve metadata for public pools.
rand_cloid(**kwargs)
Generate a random client order id within Lighter's valid range [1, 2^48 - 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Additional keyword arguments for future extensibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
A random client order id, never 0 (the "no cloid" sentinel). |
recent_trades(market_id, limit=100, **kwargs)
async
Retrieve the most recent public trades for a market.
referral_create(account_idx=None)
async
Create a referral code for the account.
referral_get(account_idx=None)
async
Retrieve the account's referral details.
referral_kickback_update(kickback_percentage, account_idx=None)
async
Update the referral kickback percentage.
referral_update(new_referral_code, account_idx=None)
async
Update the account's referral code.
referral_use(referral_code, x, signature, l1_address=None, **kwargs)
async
Apply a referral code to the account.
search(q)
async
Search the explorer by free-text query.
send_tx(tx_type, tx_info)
async
POST a signed L2 transaction to /sendTx.
send_tx_batch(tx_types, tx_infos)
async
POST a batch of signed L2 transactions to /sendTxBatch.
set_maker_only_apikeys(api_key_indexes, account_idx=None)
async
Mark the given api_key_index list as maker-only on-chain.
stake_assets(staking_pool_index, share_amount, **kwargs)
async
Placeholder for staking deposit. Not yet wired.
stats_total()
async
Retrieve total exchange stats from the explorer.
stats_tx(aggregation_period='1h')
async
Retrieve aggregated transaction stats from the explorer.
status()
async
Retrieve the exchange's health status.
system_config()
async
Retrieve the exchange's system configuration.
token_list()
async
Retrieve the list of supported tokens.
tokens(account_idx=None)
async
Retrieve all auth tokens for the account.
tokens_create(name, sub_account_access, expiry=None, account_idx=None, **kwargs)
async
Create a new auth token for the account.
tokens_revoke(token_id, account_idx=None)
async
Revoke an existing auth token by id.
trades(sort_by='timestamp', market_id=None, account_idx=None, limit=100, **kwargs)
async
Retrieve historical trades, optionally filtered by market or account.
trades_subscribe(ticker, handler, is_index=False, standardize_schema=True, **kwargs)
async
Subscribe to ticker trades.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol for the asset. |
required |
handler
|
coroutine
|
A coroutine handler for processing the received trade messages. |
required |
is_index
|
bool
|
If True, the |
False
|
standardize_schema
|
bool
|
If True, processes the incoming message to a
standardized |
True
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
trades_unsubscribe(ticker, is_index=False, **kwargs)
async
Unsubscribe from trade data.
transfer(to_account_index, asset, amount, fee=0, memo='', eth_private_key=None, **kwargs)
async
Placeholder for same- and cross-master transfers. Not yet wired.
transfer_fee_info(account_idx=None, **kwargs)
async
Retrieve transfer fee information for the account.
transfer_history(account_idx=None, **kwargs)
async
Retrieve transfer history for the account.
tx(value, by='hash')
async
Retrieve a transaction by hash or sequence index.
tx_from_l1_txhash(hash)
async
Retrieve the L2 transaction that originated from the given L1 tx hash.
unstake_assets(staking_pool_index, share_amount, **kwargs)
async
Placeholder for staking withdraw. Not yet wired.
update_account_config(account_trading_mode, **kwargs)
async
Placeholder for account trading-mode change. Not yet wired.
update_leverage(ticker, fraction, margin_mode=MARGIN_CROSS, **kwargs)
async
Placeholder for per-market leverage update. Not yet wired.
update_margin(ticker, usdc_amount, direction=MARGIN_ADD_COLLATERAL, **kwargs)
async
Placeholder for isolated-margin collateral adjust. Not yet wired.
update_public_pool(public_pool_index, status, operator_fee, min_operator_share_rate, **kwargs)
async
Placeholder for public-pool config update. Not yet wired.
user_referrals(l1_address=None, **kwargs)
async
Retrieve the account's referral history.
withdraw(asset, amount, route_type=0, **kwargs)
async
Placeholder for L2 withdraw. Not yet wired.
withdraw_history(account_idx=None, **kwargs)
async
Retrieve withdraw history for the account.
withdrawal_delay()
async
Retrieve the current withdrawal delay (in seconds).
Signer
sign_approve_integrator(integrator_account_index, max_perps_taker_fee, max_perps_maker_fee, max_spot_taker_fee, max_spot_maker_fee, expired_at, *, eth_private_key=None, nonce, skip_nonce=1, api_key_index=None)
eth_private_key=None for same-master; pass an L1 key for cross-master.
sign_change_api_key(new_pubkey, *, eth_private_key, nonce, skip_nonce=1, api_key_index=None)
Always L1-signed — requires the ETH private key of the master account.
sign_create_grouped_orders(grouping_type, orders, integrator_account_index=0, integrator_taker_fee=0, integrator_maker_fee=0, *, nonce, skip_nonce=1, api_key_index=None)
orders: list of dicts with _CreateOrderTxReq fields.
sign_transfer(to_account_index, asset_id, route_from, route_to, usdc_amount, fee, memo='', *, nonce, skip_nonce=1, api_key_index=None, eth_private_key=None)
eth_private_key=None for same-master transfer; pass an L1 key for cross-master.
Subscription
Represents the various Lighter websocket subscription channels.
Attributes:
| Name | Type | Description |
|---|---|---|
ORDER_BOOK |
str
|
The "order_book/{market_id}" channel — full L2 snapshot + delta updates. |
TICKER |
str
|
The "ticker/{market_id}" channel — top-of-book BBO. |
MARKET_STATS |
str
|
The "market_stats/{market_id}" channel — mid/mark/index price + funding stats. |
TRADE |
str
|
The "trade/{market_id}" channel — public trade tape for a market. |
ACCOUNT_ALL |
str
|
The "account_all/{account_id}" channel — combined account snapshot. |
ACCOUNT_MARKET |
str
|
The "account_market/{market_id}/{account_id}" channel — per-market account state. |
USER_STATS |
str
|
The "user_stats/{account_id}" channel — account stats (volume, fees, tier). |
ACCOUNT_TX |
str
|
The "account_tx/{account_id}" channel — account transactions. |
ACCOUNT_ALL_ORDERS |
str
|
The "account_all_orders/{account_id}" channel — all open and recent orders. |
HEIGHT |
str
|
The "height" channel — current block height. |
POOL_DATA |
str
|
The "pool_data/{account_id}" channel — public pool data. |
POOL_INFO |
str
|
The "pool_info/{account_id}" channel — public pool config. |
NOTIFICATION |
str
|
The "notification/{account_id}" channel — account notifications. |
ACCOUNT_ORDERS |
str
|
The "account_orders/{market_id}/{account_id}" channel — per-market orders. |
ACCOUNT_ALL_TRADES |
str
|
The "account_all_trades/{account_id}" channel — account fills across all markets. |
ACCOUNT_ALL_POSITIONS |
str
|
The "account_all_positions/{account_id}" channel — open positions snapshot + deltas. |
SPOT_MARKET_STATS |
str
|
The "spot_market_stats/{market_id}" channel — spot market stats. |
ACCOUNT_ALL_ASSETS |
str
|
The "account_all_assets/{account_id}" channel — spot asset balances. |
ACCOUNT_SPOT_AVG_ENTRY_PRICES |
str
|
The "account_spot_avg_entry_prices/{account_id}" channel — per-asset average entry prices. |