### Run Example: Get Info Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Execute the get_info.py example script to retrieve information. ```sh python examples/get_info.py ``` -------------------------------- ### Run Lighter Python SDK Examples Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt These commands execute example Python scripts for the Lighter SDK. They showcase different functionalities such as reading API functions, synchronizing order books and accounts via websockets, and managing orders. Ensure you have the SDK installed and the example files are present in the 'examples' directory. ```sh python examples/get_info.py ``` ```sh python examples/ws.py ``` ```sh python examples/create_cancel_order.py ``` -------------------------------- ### Deploy Market Maker to VPS Source: https://github.com/djienne/lighter_market_making/blob/main/GRID_QUICKSTART.md Deploy the lighter_MM project to a VPS from your local machine using a provided script. After deployment, connect to the VPS, install dependencies, build the Cython extension, and start the market maker. ```bash # From your local machine python deploy.py --host YOUR_VPS_IP --key path/to/key.pem # Then on the VPS cd /home/ubuntu/lighter_MM pip install -r requirements.txt python setup_cython.py build_ext --inplace python -u market_maker_v2.py --symbol BTC --grid grid_config.json ``` -------------------------------- ### Run Example: Create and Cancel Orders Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Execute the create_cancel_order.py example script to demonstrate creating and canceling orders. ```sh python examples/create_cancel_order.py ``` -------------------------------- ### Run Example: Websocket Sync Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Execute the ws.py example script to demonstrate Websocket synchronization for order books and accounts. ```sh python examples/ws.py ``` -------------------------------- ### Install Dependencies and Build Cython Extension Source: https://github.com/djienne/lighter_market_making/blob/main/GRID_QUICKSTART.md Navigate to the lighter_MM directory, install Python dependencies, and build the Cython extension for performance improvements. No .env file is needed for grid mode as it's paper-trading only. ```bash cd lighter_MM # Install dependencies pip install -r requirements.txt # Build Cython extension (required — ~10x speedup on hot path) python setup_cython.py build_ext --inplace ``` -------------------------------- ### DailyReturn Model Example Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Provides an example of how to work with the DailyReturn model, including instantiation from JSON and dictionaries, and conversion to JSON and dictionaries. ```python from lighter.models.daily_return import DailyReturn json = "{}" daily_return_instance = DailyReturn.from_json(json) print(DailyReturn.to_json()) daily_return_dict = daily_return_instance.to_dict() daily_return_from_dict = DailyReturn.from_dict(daily_return_dict) ``` -------------------------------- ### Get Funding Rates using Funding API Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Demonstrates how to fetch current funding rates using the Funding API. It shows the setup of the API client, making the asynchronous request, and handling the response or exceptions. Requires the 'lighter' library and its associated models. ```python import lighter from lighter.models.funding_rates import FundingRates from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.FundingApi(api_client) try: # funding-rates api_response = await api_instance.funding_rates() print("The response of FundingApi->funding_rates:\n") pprint(api_response) except Exception as e: print("Exception when calling FundingApi->funding_rates: %s\n" % e) ``` -------------------------------- ### Install Lighter Python SDK Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt This command installs the Lighter Python SDK directly from its GitHub repository using pip. Ensure you have Python 3.8+ installed. This is a prerequisite for using the SDK. ```sh pip install git+https://github.com/elliottech/lighter-python.git ``` -------------------------------- ### Install Dependencies and Build Cython Extension Source: https://github.com/djienne/lighter_market_making/blob/main/README.md Installs project dependencies and compiles the Cython extension for performance. Ensure Python 3.13+ and a C compiler are installed. ```bash python -m venv venv source venv/bin/activate pip install -r requirements.txt python setup_cython.py build_ext --inplace ``` -------------------------------- ### SpotAvgEntryPrice Model Example Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Provides an example of creating a SpotAvgEntryPrice instance from JSON and converting it to a dictionary. Import the SpotAvgEntryPrice model from lighter.models.spot_avg_entry_price. ```python from lighter.models.spot_avg_entry_price import SpotAvgEntryPrice # TODO update the JSON string below json = "{}" # create an instance of SpotAvgEntryPrice from a JSON string spot_avg_entry_price_instance = SpotAvgEntryPrice.from_json(json) # print the JSON string representation of the object print(SpotAvgEntryPrice.to_json()) # convert the object into a dict spot_avg_entry_price_dict = spot_avg_entry_price_instance.to_dict() # create an instance of SpotAvgEntryPrice from a dict spot_avg_entry_price_from_dict = SpotAvgEntryPrice.from_dict(spot_avg_entry_price_dict) ``` -------------------------------- ### Example API Call for Account Transactions in Python Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Shows an example of how to call the `account_txs` API endpoint to retrieve transactions for a specific account. It includes setting up the API client and handling potential API exceptions. ```python import lighter from lighter.models.txs import Txs from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) ``` -------------------------------- ### Install Lighter Python SDK Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Install the Lighter Python SDK directly from its GitHub repository using pip. Ensure you have Python 3.8+. ```sh pip install git+https://github.com/elliottech/lighter-python.git ``` -------------------------------- ### POST /sendTxBatch Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Submits a batch of transactions to the server after they have been signed. Refer to the 'Get Started For Programmers' guide for signing details. ```APIDOC ## POST /sendTxBatch ### Description Submits a batch of signed transactions to the server. Ensure transactions are properly signed before sending. Detailed instructions can be found in the [Get Started For Programmers](https://apidocs.lighter.xyz/docs/get-started-for-programmers) documentation. ### Method POST ### Endpoint `/sendTxBatch` ### Parameters #### Query Parameters - **tx_types** (string) - Required - Specifies the types of transactions in the batch. - **tx_infos** (string) - Required - Contains the details for each transaction in the batch. #### Request Body This endpoint does not appear to have a request body. Parameters are expected as query parameters. ### Request Example ```json { "tx_types": "transfer,swap", "tx_infos": "[{'from': '0x...', 'to': '0x...', 'amount': '100'}, {'tokenA': '0x...', 'tokenB': '0x...', 'amountA': '50'}]" } ``` ### Response #### Success Response (200) - **transaction_hash** (string) - The hash of the submitted transaction batch. - **status** (string) - The status of the transaction batch submission. #### Response Example ```json { "transaction_hash": "0xabc123...", "status": "submitted" } ``` #### Error Response (400) - **code** (integer) - The error code. - **message** (string) - A description of the error. #### Error Response Example ```json { "code": 400, "message": "Invalid transaction format" } ``` ``` -------------------------------- ### Submit Signed Transaction with TransactionApi Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Submits a signed transaction to the Lighter network. Before calling this endpoint, the transaction body must be signed. Refer to the 'Get Started For Programmers' guide for detailed signing instructions. This method is part of the TransactionApi. ```python import lighter from lighter.models.resp_send_tx import RespSendTx from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) ``` -------------------------------- ### Python: System Setup and Logging Configuration Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Imports necessary libraries including asyncio, logging, time, eth_account, and lighter. Configures basic logging to display debug messages. This forms the foundation for running the market making scripts. ```python import asyncio import logging import time import eth_account import lighter logging.basicConfig(level=logging.DEBUG) # this is a dummy private key which is registered on Testnet. ``` -------------------------------- ### Get Account Active Orders Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Retrieves a list of active orders for a given account and market. Ensure the 'lighter' library is installed and configured with the correct host. ```python import lighter from lighter.models.orders import Orders from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.OrderApi(api_client) account_index = 56 # int | market_id = 56 # int | authorization = 'authorization_example' # str | make required after integ is done (optional) auth = 'auth_example' # str | made optional to support header auth clients (optional) try: # accountActiveOrders api_response = await api_instance.account_active_orders(account_index, market_id, authorization=authorization, auth=auth) print("The response of OrderApi->account_active_orders:\n") pprint(api_response) except Exception as e: print("Exception when calling OrderApi->account_active_orders: %s\n" % e) ``` -------------------------------- ### Get L1 metadata Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Retrieve L1 metadata for a given address. This endpoint supports optional authorization headers. Ensure the `lighter` library is installed and configured. ```python import lighter from lighter.models.l1_metadata import L1Metadata from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.AccountApi(api_client) l1_address = 'l1_address_example' # str | authorization = 'authorization_example' # str | make required after integ is done (optional) auth = 'auth_example' # str | made optional to support header auth clients (optional) try: # l1Metadata api_response = await api_instance.l1_metadata(l1_address, authorization=authorization, auth=auth) print("The response of AccountApi->l1_metadata:\n") pprint(api_response) except Exception as e: print("Exception when calling AccountApi->l1_metadata: %s\n" % e) ``` -------------------------------- ### Python Script for System Setup (Testnet) Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt This Python script, `system_setup.py`, is used to configure the Lighter market making environment for testnet. It requires an Ethereum private key to generate API keys and account indices. The output of this script is crucial for configuring other trading scripts. ```python import asyncio import logging import lighter import json logging.basicConfig(level=logging.DEBUG) # The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. ``` -------------------------------- ### Initialize Lighter Client and Fetch Deposit History Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Example of initializing the Lighter client with a specific host and fetching deposit history. Ensure correct parameters are provided. ```python import lighter from lighter.models.deposit_history import DepositHistory from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) ``` -------------------------------- ### Get User Referrals API Call Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Example of how to call the referral_user_referrals endpoint to retrieve user referral data. Ensure the API client is configured with the correct host and authentication. ```python import lighter from lighter.models.user_referrals import UserReferrals from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.ReferralApi(api_client) l1_address = 'l1_address_example' # str | authorization = 'authorization_example' # str | (optional) auth = 'auth_example' # str | (optional) cursor = 'cursor_example' # str | (optional) try: # referral_userReferrals api_response = await api_instance.referral_user_referrals(l1_address, authorization=authorization, auth=auth, cursor=cursor) print("The response of ReferralApi->referral_user_referrals:\n") pprint(api_response) except Exception as e: print("Exception when calling ReferralApi->referral_user_referrals: %s\n" % e) ``` -------------------------------- ### Call Announcement API Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Example of how to call the announcement API endpoint using the lighter client. Includes configuration, API client instantiation, and error handling. Ensure the lighter library is installed and configured. ```python import lighter from lighter.models.announcements import Announcements from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.AnnouncementApi(api_client) try: # announcement api_response = await api_instance.announcement() print("The response of AnnouncementApi->announcement:\n") pprint(api_response) except Exception as e: print("Exception when calling AnnouncementApi->announcement: %s\n" % e) ``` -------------------------------- ### Initialize API Client and Fetch Fundings Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Demonstrates how to initialize the API client within an async context and call the fundings endpoint. Ensure proper configuration is provided before use. ```python async with lighter.ApiClient(configuration) as api_client: api_instance = lighter.CandlestickApi(api_client) market_id = 56 resolution = 'resolution_example' start_timestamp = 56 end_timestamp = 56 count_back = 56 try: api_response = await api_instance.fundings(market_id, resolution, start_timestamp, end_timestamp, count_back) print("The response of CandlestickApi->fundings:\n") pprint(api_response) except Exception as e: print("Exception when calling CandlestickApi->fundings: %s\n" % e) ``` -------------------------------- ### Initialize ApiClient and Call All Example APIs Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt This main function initializes the lighter.ApiClient, connects to the testnet endpoint, and then calls all the example API functions (account, block, candlestick, order, transaction). Finally, it closes the client connection. Requires asyncio to run. ```python import asyncio import datetime import lighter import logging logging.basicConfig(level=logging.INFO) # The address provided belongs to a dummy account registered on Testnet. L1_ADDRESS = "0x8D7f03FdE1A626223364E592740a233b72395235" ACCOUNT_INDEX = 65 async def print_api(method, *args, **kwargs): logging.info(f"{method.__name__}: {await method(*args, **kwargs)}") async def account_apis(client: lighter.ApiClient): logging.info("ACCOUNT APIS") account_instance = lighter.AccountApi(client) await print_api(account_instance.account, by="l1_address", value=L1_ADDRESS) await print_api(account_instance.account, by="index", value=str(ACCOUNT_INDEX)) await print_api(account_instance.accounts_by_l1_address, l1_address=L1_ADDRESS) await print_api(account_instance.apikeys, account_index=ACCOUNT_INDEX, api_key_index=1) await print_api(account_instance.public_pools, filter="all", limit=1, index=0) async def block_apis(client: lighter.ApiClient): logging.info("BLOCK APIS") block_instance = lighter.BlockApi(client) await print_api(block_instance.block, by="height", value="1") await print_api(block_instance.blocks, index=0, limit=2, sort="asc") await print_api(block_instance.current_height) async def candlestick_apis(client: lighter.ApiClient): logging.info("CANDLESTICK APIS") candlestick_instance = lighter.CandlestickApi(client) await print_api( candlestick_instance.candlesticks, market_id=0, resolution="1h", start_timestamp=int(datetime.datetime.now().timestamp() - 60 * 60 * 24), end_timestamp=int(datetime.datetime.now().timestamp()), count_back=2, ) await print_api( candlestick_instance.fundings, market_id=0, resolution="1h", start_timestamp=int(datetime.datetime.now().timestamp() - 60 * 60 * 24), end_timestamp=int(datetime.datetime.now().timestamp()), count_back=2, ) async def order_apis(client: lighter.ApiClient): logging.info("ORDER APIS") order_instance = lighter.OrderApi(client) await print_api(order_instance.exchange_stats) await print_api(order_instance.order_book_details, market_id=0) await print_api(order_instance.order_books) await print_api(order_instance.recent_trades, market_id=0, limit=2) async def transaction_apis(client: lighter.ApiClient): logging.info("TRANSACTION APIS") transaction_instance = lighter.TransactionApi(client) await print_api(transaction_instance.block_txs, by="block_height", value="1") await print_api( transaction_instance.next_nonce, account_index=int(ACCOUNT_INDEX), api_key_index=0, ) # use with a valid sequence index # await print_api(transaction_instance.tx, by="sequence_index", value="5") await print_api(transaction_instance.txs, index=0, limit=2) async def main(): client = lighter.ApiClient(configuration=lighter.Configuration(host="https://testnet.zklighter.elliot.ai")) await account_apis(client) await block_apis(client) await candlestick_apis(client) await order_apis(client) await transaction_apis(client) await client.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### POST /sendTx Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Submits a transaction with specified details. Requires transaction body to be signed beforehand. Refer to Get Started docs for more information. ```APIDOC ## POST /sendTx ### Description Submits a transaction with specified details. Requires transaction body to be signed beforehand. Refer to Get Started docs for more information. ### Method POST ### Endpoint /sendTx ### Parameters #### Query Parameters - **tx_type** (integer) - Required - The type of transaction. - **tx_info** (string) - Required - Information related to the transaction. - **price_protection** (boolean) - Optional - Enables price protection for the transaction. ### Request Example ```json { "tx_type": 1, "tx_info": "transaction_data_string", "price_protection": true } ``` ### Response #### Success Response (200) - **RespSendTx** (object) - Contains the response details for a successful transaction submission. #### Error Response (400) - **ResultCode** (object) - Contains error codes and messages for an invalid request. #### Response Example ```json { "result": "success", "transaction_id": "0xabc123..." } ``` ``` -------------------------------- ### POST /api/sendTx Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Sends a signed transaction to the server. Ensure the transaction body is signed before sending. Refer to the Get Started documentation for more details. ```APIDOC ## POST /api/sendTx ### Description Sends a signed transaction to the server. Ensure the transaction body is signed before sending. Refer to the Get Started documentation for more details. ### Method POST ### Endpoint /api/sendTx ### Parameters #### Query Parameters - **tx_type** (int) - Required - The type of the transaction. - **tx_info** (str) - Required - Information related to the transaction. - **price_protection** (bool) - Optional - Controls price protection for the transaction. ### Request Example ```json { "tx_type": 1, "tx_info": "0x...", "price_protection": true } ``` ### Response #### Success Response (200) - **RespSendTx** (object) - The response containing details of the sent transaction. #### Response Example ```json { "transaction_hash": "0x...", "status": "success" } ``` #### Error Response (400) - **ResultCode** (object) - An error object indicating the issue with the request. ``` -------------------------------- ### Send Batched Transactions with Lighter API Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt This method allows sending multiple transactions in a batch. Refer to the 'Get Started For Programmers' documentation for transaction signing details. The API client must be initialized with the correct configuration. ```python import lighter from lighter.models.resp_send_tx_batch import RespSendTxBatch from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.TransactionApi(api_client) tx_types = 'tx_types_example' # str | tx_infos = 'tx_infos_example' # str | try: # sendTxBatch api_response = await api_instance.send_tx_batch(tx_types, tx_infos) print("The response of TransactionApi->send_tx_batch:\n") pprint(api_response) except Exception as e: print("Exception when calling TransactionApi->send_tx_batch: %s\n" % e) ``` -------------------------------- ### Announcement API Client Example (Python) Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Shows how to use the lighter.AnnouncementApi to fetch announcements. It includes setting up the API client, handling potential exceptions, and printing the response. The API client is asynchronous. ```python import lighter from lighter.models.announcements import Announcements from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.AnnouncementApi(api_client) try: # announcement api_response = await api_instance.announcement() print("The response of AnnouncementApi->announcement:\n") pprint(api_response) except Exception as e: print("Exception when calling AnnouncementApi->announcement: %s\n" % e) ``` -------------------------------- ### Get Account Inactive Orders Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Retrieves a list of inactive orders for a given account. This endpoint supports filtering by market ID, order side, timestamp range, and pagination using a cursor. Ensure the 'lighter' library is installed and configured. ```python import lighter from lighter.models.orders import Orders from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) ``` -------------------------------- ### Initialize Configuration with Logging and SSL Settings Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Initializes the Configuration object with parameters for logging, SSL/TLS verification, certificate files, and hostname verification. It sets up default logging formats and handlers, and allows customization of SSL verification behavior. ```python def __init__(self, debug=None, retries=3, ssl_ca_cert=None): """Access token """ self.logger = {} """Logging Settings """ self.logger["package_logger"] = logging.getLogger("lighter") self.logger["urllib3_logger"] = logging.getLogger("urllib3") self.logger_format = '%(asctime)s %(levelname)s %(message)s' """Log format """ self.logger_stream_handler = None """Log stream handler """ self.logger_file_handler: Optional[FileHandler] = None """Log file handler """ self.logger_file = None """Debug file location """ if debug is not None: self.debug = debug else: self.__debug = False """Debug switch """ self.verify_ssl = True """SSL/TLS verification Set this to false to skip verifying SSL certificate when calling API from https server. """ self.ssl_ca_cert = ssl_ca_cert """Set this to customize the certificate file to verify the peer. """ self.cert_file = None """client certificate file """ self.key_file = None """client key file """ self.assert_hostname = None """Set this to True/False to enable/disable SSL hostname verification. """ self.tls_server_name = None """SSL/TLS Server Name Indication (SNI) Set this to the SNI value expected by the server. """ self.connection_pool_maxsize = 100 """This value is passed to the aiohttp to limit simultaneous connections. Default values is 100, None means no-limit. """ self.proxy: Optional[str] = None """Proxy URL """ self.proxy_headers = None """Proxy headers """ self.safe_chars_for_path_param = '' """Safe chars for path_param """ self.retries = retries """Adding retries to override urllib3 default value 3 """ # Enable client side validation self.client_side_validation = True self.socket_options = None """Options to pass down to the underlying urllib3 socket """ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" """datetime format """ self.date_format = "%Y-%m-%d" """date format """ ``` -------------------------------- ### Get Current Height - Python API Example Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Retrieves the current height of the blockchain using the lighter client library. This function does not require any parameters and handles potential API exceptions, printing the response. ```python import lighter from lighter.models.current_height import CurrentHeight from lighter.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai # See configuration.py for a list of all supported configuration parameters. configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) # Enter a context with an instance of the API client async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.BlockApi(api_client) try: # currentHeight api_response = await api_instance.current_height() print("The response of BlockApi->current_height:\n") pprint(api_response) except Exception as e: print("Exception when calling BlockApi->current_height: %s\n" % e) ``` -------------------------------- ### Python ApiClient Initialization and Configuration Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Demonstrates how to initialize the ApiClient, with options for custom configurations, default headers, and cookies. It highlights the use of a default configuration if none is provided and sets up the REST client object. ```python from lighter.configuration import Configuration from lighter import rest # Initialize with default configuration api_client_default = ApiClient() # Initialize with a custom configuration custom_config = Configuration() # ... set custom_config properties ... api_client_custom = ApiClient(configuration=custom_config) # Initialize with custom headers and cookies api_client_with_headers = ApiClient( header_name='X-Custom-Header', header_value='CustomValue', cookie='session_id=12345' ) ``` -------------------------------- ### Get Fundings using Python Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Retrieves funding data for a given market. Requires market ID, resolution, start and end timestamps, and a count back parameter. This function interacts with the /api/v1/fundings endpoint. ```python import lighter from lighter.models.fundings import Fundings from lighter.rest import ApiException from pprint import pprint configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliot.ai" ) async with lighter.ApiClient(configuration) as api_client: api_instance = lighter.CandlestickApi(api_client) market_id = 56 resolution = 'resolution_example' start_timestamp = 56 end_timestamp = 56 count_back = 56 try: api_response = await api_instance.fundings(market_id, resolution, start_timestamp, end_timestamp, count_back) print("The response of CandlestickApi->fundings:\n") pprint(api_response) except Exception as e: print("Exception when calling CandlestickApi->fundings: %s\n" % e) ``` -------------------------------- ### Retrieve Candlestick and Funding Data with ApiClient Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt This example shows how to fetch candlestick and funding rate data for a given market using lighter.ApiClient. It requires a market ID, resolution, and time range. The start and end timestamps are calculated based on the current time. ```python import asyncio import datetime import lighter import logging logging.basicConfig(level=logging.INFO) async def print_api(method, *args, **kwargs): logging.info(f"{method.__name__}: {await method(*args, **kwargs)}") async def candlestick_apis(client: lighter.ApiClient): logging.info("CANDLESTICK APIS") candlestick_instance = lighter.CandlestickApi(client) await print_api( candlestick_instance.candlesticks, market_id=0, resolution="1h", start_timestamp=int(datetime.datetime.now().timestamp() - 60 * 60 * 24), end_timestamp=int(datetime.datetime.now().timestamp()), count_back=2, ) await print_api( candlestick_instance.fundings, market_id=0, resolution="1h", start_timestamp=int(datetime.datetime.now().timestamp() - 60 * 60 * 24), end_timestamp=int(datetime.datetime.now().timestamp()), count_back=2, ) async def main(): client = lighter.ApiClient(configuration=lighter.Configuration(host="https://testnet.zklighter.elliot.ai")) await candlestick_apis(client) # ... other API calls ... await client.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize DryRunEngine Source: https://context7.com/djienne/lighter_market_making/llms.txt Set up the DryRunEngine for paper trading simulation. It requires references to the market making state, order manager, and other configuration parameters like leverage and simulated latency. ```python from dry_run import DryRunEngine # Initialize engine with state references engine = DryRunEngine( state=mm_state, # MMState instance order_manager=order_manager, # OrderManager instance client_to_exchange_id={}, # Client to exchange ID mapping leverage=2, logger=logger, sim_latency_s=0.050, # Simulated exchange latency (50ms) log_interval=60.0, # Summary log interval trade_logger=trade_logger, # TradeLogger instance state_path="logs/dry_run_state.json", maker_fee_rate=0.00004, # 0.004% maker fee ) ``` -------------------------------- ### Create and Cancel Orders with SignerClient Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt This example demonstrates how to initialize a SignerClient for market making, create multiple limit orders, and then cancel all open orders. It requires API keys and account index configuration. The client checks for errors before proceeding. ```python import asyncio import lighter # Use examples/system_setup.py or the apikeys page (for mainnet) to generate new api keys KEYS = { 5: "API_PRIVATE_KEY_5", 6: "API_PRIVATE_KEY_6", 7: "API_PRIVATE_KEY_7", } ACCOUNT_INDEX = 100 # replace with your account_index BASE_URL = "https://testnet.zklighter.elliot.ai" # Replace with your base URL if not testnet async def main(): client = lighter.SignerClient( url=BASE_URL, private_key=KEYS[5], account_index=ACCOUNT_INDEX, api_key_index=5, max_api_key_index=7, private_keys=KEYS, ) err = client.check_client() if err is not None: print(f"CheckClient error: {err}") return for i in range(20): res_tuple = await client.create_order( market_index=0, client_order_index=123 + i, base_amount=100000 + i, price=385000 + i, is_ask=True, order_type=lighter.SignerClient.ORDER_TYPE_LIMIT, time_in_force=lighter.SignerClient.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, reduce_only=0, trigger_price=0, ) print(res_tuple) await client.cancel_all_orders(time_in_force=client.CANCEL_ALL_TIF_IMMEDIATE, time=0) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Candlesticks using Python Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt Retrieves candlestick data for a given market. Requires market ID, resolution, start and end timestamps, and a count back parameter. An optional parameter to set the timestamp to the end is available. This function interacts with the /api/v1/candlesticks endpoint. ```python import lighter from lighter.models.candlesticks import Candlesticks from lighter.rest import ApiException from pprint import pprint configuration = lighter.Configuration( host = "https://mainnet.zklighter.elliots.ai" ) async with lighter.ApiClient(configuration) as api_client: api_instance = lighter.CandlestickApi(api_client) market_id = 56 resolution = 'resolution_example' start_timestamp = 56 end_timestamp = 56 count_back = 56 set_timestamp_to_end = False try: api_response = await api_instance.candlesticks(market_id, resolution, start_timestamp, end_timestamp, count_back, set_timestamp_to_end=set_timestamp_to_end) print("The response of CandlestickApi->candlesticks:\n") pprint(api_response) except Exception as e: print("Exception when calling CandlestickApi->candlesticks: %s\n" % e) ``` -------------------------------- ### Create Market Order with Lighter SDK Source: https://github.com/djienne/lighter_market_making/blob/main/LIGHTER_doc_code.txt This example shows how to create a market order using the Lighter SignerClient. It initializes the client with API credentials and then places a market order with specified parameters such as market index, base amount, and average execution price. It requires the 'lighter' library and 'asyncio'. ```python import asyncio import logging import lighter logging.basicConfig(level=logging.DEBUG) # The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. # It was generated using the setup_system.py script, and serves as an example. BASE_URL = "https://testnet.zklighter.elliot.ai" API_KEY_PRIVATE_KEY = "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b" ACCOUNT_INDEX = 65 API_KEY_INDEX = 3 def trim_exception(e: Exception) -> str: return str(e).strip().split("\n")[-1] async def main(): client = lighter.SignerClient( url=BASE_URL, private_key=API_KEY_PRIVATE_KEY, account_index=ACCOUNT_INDEX, api_key_index=API_KEY_INDEX, ) tx = await client.create_market_order( market_index=0, client_order_index=0, base_amount=1000, # 0.1 ETH avg_execution_price=170000, # $1700 -- worst acceptable price for the order is_ask=True, ) print("Create Order Tx:", tx) await client.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create and Convert RespGetLeaseOptions Instance Source: https://github.com/djienne/lighter_market_making/blob/main/DOC/LIGHTER_doc_code.txt Demonstrates creating a RespGetLeaseOptions instance from a JSON string and converting it to a dictionary. It also shows how to create an instance from a dictionary. ```python from lighter.models.resp_get_lease_options import RespGetLeaseOptions # TODO update the JSON string below json = "{}" # create an instance of RespGetLeaseOptions from a JSON string resp_get_lease_options_instance = RespGetLeaseOptions.from_json(json) # print the JSON string representation of the object print(RespGetLeaseOptions.to_json()) # convert the object into a dict resp_get_lease_options_dict = resp_get_lease_options_instance.to_dict() # create an instance of RespGetLeaseOptions from a dict resp_get_lease_options_from_dict = RespGetLeaseOptions.from_dict(resp_get_lease_options_dict) ```