### Install build tools on Windows Source: https://quantpylib.hangukquant.com/ Setup steps for MSYS2 CLANG64 environment to support native compilation. ```powershell C:\msys64\usr\bin\bash.exe -lc "pacman -Syu --noconfirm" C:\msys64\usr\bin\bash.exe -lc "pacman -S --needed --noconfirm mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf mingw-w64-clang-x86_64-make" $env:Path = "C:\msys64\clang64\bin;$env:Path" $env:CC = "C:\msys64\clang64\bin\clang.exe" $env:CXX = "C:\msys64\clang64\bin\clang++.exe" $env:CMAKE_GENERATOR = "Ninja" $env:CMAKE_MAKE_PROGRAM = "C:\msys64\clang64\bin\ninja.exe" python3 -m pip install -e . ``` -------------------------------- ### Run Logger Example Source: https://quantpylib.hangukquant.com/logger/logger Command to execute the logger example script with a specific configuration. ```bash python example_logger.py -c jf ``` -------------------------------- ### QBN File Output Example Source: https://quantpylib.hangukquant.com/hft/hft Example output showing the file structure generated by the archival process. ```text QBN files: .archival/binance/perp/bba/2026-07-08.qbn .archival/binance/perp/l2book/2026-07-08.qbn .archival/binance/perp/trades/2026-07-08.qbn .archival/bybit/perp/bba/2026-07-08.qbn .archival/bybit/perp/l2book/2026-07-08.qbn .archival/bybit/perp/trades/2026-07-08.qbn .archival/hyperliquid/perp/bba/2026-07-08.qbn .archival/hyperliquid/perp/l2book/2026-07-08.qbn .archival/hyperliquid/perp/trades/2026-07-08.qbn ``` -------------------------------- ### Order Execution Examples Source: https://quantpylib.hangukquant.com/wrappers/lighter Examples for placing and canceling orders, commented out for safety. ```python # 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='')) # pprint(await lighter.market_order(ticker=ticker, amount=amount)) ``` -------------------------------- ### Install benchmark dependencies Source: https://quantpylib.hangukquant.com/ Install the necessary extras to run performance benchmarks. ```bash python3 -m pip install -e ".[benchmarks]" ``` -------------------------------- ### Console Output Example Source: https://quantpylib.hangukquant.com/logger/logger Example of logs printed to the console. ```text using quantpylib logger with json formatter info log warning log caught zero denominator Traceback (most recent call last): File "/Users/admin/Desktop/projects/quantpylib/examples/example_logger.py", line 16, in log 1/0 ~^~ ZeroDivisionError: division by zero ``` -------------------------------- ### Account Balance Output Example Source: https://quantpylib.hangukquant.com/gateway/gateway Example output structure for account balance queries. ```json {'equity_total': 1884.960586, 'margin_maintenance': 131.131965, 'margin_total': 262.26393, 'equity_withdrawable': 1622.696656, 'notional_position': 5232.9393} ``` -------------------------------- ### Install AsterDEX support Source: https://quantpylib.hangukquant.com/wrappers/asterdex Install the required provider connector package via pip before using the wrapper. ```bash python3 -m pip install -e ".[asterdex]" ``` -------------------------------- ### Install quantpylib in editable mode Source: https://quantpylib.hangukquant.com/ Standard command to install the package in editable mode from the repository root. ```bash python3 -m pip install -e . ``` -------------------------------- ### Setup GeneticRegression Environment Source: https://quantpylib.hangukquant.com/simulator/simulator Initializes the DataPoller and GeneticRegression setup for performing regression analysis. ```python import pytz from datetime import datetime from quantpylib.standards import Period from quantpylib.datapoller.master import DataPoller from quantpylib.simulator.models import GeneticRegression keys = {"binance":{}} datapoller = DataPoller(config_keys=keys) interval = Period.DAILY async def main(): pass #code here if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Run Buffered Rotating File Handler Example Source: https://quantpylib.hangukquant.com/logger/logger Command to execute the logger example with the buffered rotating file handler configuration. ```bash python example_logger.py -c brfh ``` -------------------------------- ### Install optional dependencies Source: https://quantpylib.hangukquant.com/ Commands to install specific extra dependencies for testing, documentation, benchmarking, or AsterDEX support. ```bash python3 -m pip install -e ".[tests]" python3 -m pip install -e ".[docs]" python3 -m pip install -e ".[benchmarks]" python3 -m pip install -e ".[asterdex]" python3 -m pip install -e ".[tests,benchmarks]" ``` -------------------------------- ### Initialize Lighter Client Source: https://quantpylib.hangukquant.com/wrappers/lighter Setup the Lighter client with environment variables and initialize the connection. ```python 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()) ``` -------------------------------- ### Contract Specifications Output Example Source: https://quantpylib.hangukquant.com/gateway/gateway Example output structure for contract specifications. ```json {'BTCUSDT': {'price_precision': 2, 'quote_precision': 8, 'quantity_precision': 3, 'min_notional': 100.0}}, 'ETHUSDT': {'price_precision': 2, 'quote_pr...} ``` -------------------------------- ### Order Data Structure Example Source: https://quantpylib.hangukquant.com/gateway/gateway Example output format for normalized order data returned by the gateway. ```python {'1234': {'ticker': 'PENDLE', 'order_id': '1234', 'limit_price': 5.001, 'amount_total': Decimal('-3.0'), 'amount_left': Decimal('-3.0'), 'timestamp': 000000}} {'1234': {'ticker': 'PENDLEUSDT', 'order_id': '1234', 'limit_price': 5.001, 'amount_total': Decimal('-3'), 'amount_filled': Decimal('-0'), 'tif': 'GTC', 'timestamp': 000000}} ``` -------------------------------- ### Example Matrix Output Source: https://quantpylib.hangukquant.com/learn/statistical_finance Sample output format for the strategy return matrix. ```text strat_0 strat_1 strat_2 strat_3 strat_4 strat_5 2019-11-16 00:00:00 -0.101047 -0.092185 -0.106894 -0.094918 0.094017 -0.083680 2019-11-17 00:00:00 -0.081593 -0.072605 -0.084810 0.074504 0.075649 -0.065085 2019-11-18 00:00:00 1.919402 1.713399 1.970364 1.750723 -1.790322 1.619088 2019-11-19 00:00:00 0.343418 0.296737 0.345931 0.302118 -0.318470 0.275414 2019-11-20 00:00:00 0.258819 0.219747 0.261856 0.224155 -0.236699 0.200970 ... 2025-05-25 00:00:00 0.053872 0.162611 0.056206 0.086591 0.089944 0.162315 2025-05-26 00:00:00 0.185495 0.124115 0.061297 0.218383 0.002774 0.065411 2025-05-27 00:00:00 0.195299 0.252760 0.014410 0.208231 0.207958 0.375513 2025-05-28 00:00:00 -0.018980 -0.238806 0.517930 -0.326797 0.379941 -0.057888 2025-05-29 00:00:00 -0.229638 -0.441048 -0.344558 -0.435272 -0.332848 -0.502409 ``` -------------------------------- ### Initialize DataPoller Source: https://quantpylib.hangukquant.com/datapoller/datapoller Setup the DataPoller with configuration keys for various data sources and initialize the clients. ```python import os import asyncio from dotenv import load_dotenv load_dotenv() from datetime import datetime from quantpylib.datapoller.master import DataPoller config_keys = { "yfinance": {"alias":"yfinance"}, "eodhd": {"eod_key":os.getenv("EOD_KEY")}, "binance": {}, "oanda": { "alias":"oanda", "account_id":os.getenv("OANDA_ACC"), "secret": os.getenv("OANDA_KEY"), "env":"practice", }, "hyperliquid": {"alias":"hyp","key":os.getenv("HYP_PUBLIC"),"secret":os.getenv("HYP_KEY")}, } async def main(): start,end=datetime(2023,9,30),datetime.now() datapoller = DataPoller(config_keys=config_keys) print(datapoller.src_pollers) await datapoller.init_clients() #...code goes between here... await datapoller.cleanup_clients() print("cleanup") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Aiosonic HTTP Client Source: https://quantpylib.hangukquant.com/throttler/throttler Setup the base URL and request parameters for the HTTP client. ```python url = "https://api.hyperliquid.xyz" http_client = HTTPClient(base_url=url) request = { "endpoint":"/info", "method":"POST", "data":{"type":"meta"} } ``` -------------------------------- ### Timing Results Output Source: https://quantpylib.hangukquant.com/throttler/throttler Example output showing the performance comparison between different HTTP clients. ```text ... >>>>>>>>> request::69ms post::225ms _aiohttp_request::69ms <<<<<<<<< >>>>>>>>> request::75ms post::221ms _aiohttp_request::87ms <<<<<<<<< >>>>>>>>> request::67ms post::230ms _aiohttp_request::82ms <<<<<<<<< >>>>>>>>> request::77ms post::226ms _aiohttp_request::67ms <<<<<<<<< ... ``` -------------------------------- ### Initialize and use WooX SDK Source: https://quantpylib.hangukquant.com/wrappers/woox Demonstrates client initialization, account balance retrieval, order execution, and websocket subscription patterns. ```python import os import pytz import asyncio from pprint import pprint from datetime import datetime from dotenv import load_dotenv load_dotenv() from quantpylib.wrappers.woox import Woox async def print_handler(msg): print(msg) async def main(): """using the SDK""" woox = Woox( key=os.getenv("WOO_KEY"), secret=os.getenv("WOO_SECRET"), app_id=os.getenv("WOO_APP"), ) """quantpylib.gateway endpoints""" await woox.init_client() print(woox.get_price_precision("PERP_BTC_USDT")) print(woox.get_lot_precision("PERP_BTC_USDT")) '''ACCOUNT ENDPOINTS''' pprint(await woox.account_balance()) await woox.account_fill_subscribe(handler=print_handler) '''EXCHANGE ENDPOINTS''' pprint(await woox.contract_specifications()) pprint(await woox.get_funding_info()) '''EXECUTOR ENDPOINTS''' cloid = woox.rand_cloid() print(cloid) pprint(await woox.get_all_mids()) pprint(await woox.get_all_marks()) pprint(await woox.limit_order(ticker="PERP_SOL_USDT",amount=1,price=99.99,cloid=cloid)) pprint(await woox.cancel_open_orders()) #or use ticker="PERP_SOL_USDT" pprint(await woox.cancel_order(ticker="PERP_SOL_USDT",cloid=cloid)) #or use oid pprint(await woox.market_order(ticker="PERP_SOL_USDT",amount=-0.5)) pprint(await woox.l2_book_get(ticker="PERP_SOL_USDT")) await woox.l2_book_mirror(ticker="PERP_BTC_USDT",on_update=print_handler) await woox.l2_book_subscribe(ticker="PERP_BTC_USDT",handler=print_handler) await woox.trades_subscribe(ticker="PERP_BTC_USDT",handler=print_handler) await woox.all_mids_subscribe(handler=print_handler) '''ORDERS ENDPOINTS''' pprint(await woox.order_query(ticker='PERP_SOL_USDT',cloid='1234')) pprint(await woox.orders_get()) await woox.orders_mirror(on_update=print_handler) await woox.order_updates_subscribe(handler=print_handler) '''POSITIONS ENDPOINTS''' pprint(await woox.positions_get()) await woox.positions_mirror(on_update=print_handler) '''DATAPOLLER ENDPOINTS''' # pprint(await woox.get_trade_bars( # ticker='PERP_BTC_USDT', # start=datetime(2021,1,1, tzinfo=pytz.utc), # end=datetime.now(pytz.utc), # granularity=Period.HOURLY, # granularity_multiplier=1, # )) '''raw exchange endpoints API - refer to docs for the other method implementations''' pprint(await woox.system_maintenance_status()) pprint(await woox.exchange_info()) pprint(await woox.market_trades(symbol="PERP_BTC_USDT")) #>... many more await asyncio.sleep(1e9) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Simulation Environment Source: https://quantpylib.hangukquant.com/tutorials/market_making Sets up imports, configuration, and the replayer for market data simulation. ```python import os import pytz import asyncio import logging import argparse import numpy as np from pprint import pprint from datetime import datetime from dotenv import load_dotenv load_dotenv() from quantpylib.hft.oms import OMS from quantpylib.hft.feed import Feed from quantpylib.hft import OrderbookMaterializerSink import quantpylib.hft.cfeatures as cfeatures from quantpylib.gateway.master import Gateway from quantpylib.standards.models import PRICE_SCALE from quantpylib.utilities.general import _time,pdf_snapshot show = False simulated = True config_keys = { "binance":{}, } exc = 'binance' tickers = ["SOLUSDT"] stream_data = { "binance":["SOLUSDT"], } run = None time = None replayer = None print_interval = 120 * 1000 if simulated: from quantpylib.hft.mocks import Replayer,Latencies capture_date = "2025-01-10" start_ns = None end_ns = None latencies={ Latencies.REQ_PUBLIC:0, Latencies.REQ_PRIVATE:0, Latencies.ACK_PUBLIC:0, Latencies.ACK_PRIVATE:0, Latencies.FEED_PUBLIC:0, Latencies.FEED_PRIVATE:0, } replayer_configs = { "maker_fees":0.000, "taker_fees":0.000, "latencies":latencies, } else: run = lambda : asyncio.sleep(1e9) time = lambda : _time() gateway = Gateway(config_keys=config_keys) ``` -------------------------------- ### QET Trace Output Source: https://quantpylib.hangukquant.com/tutorials/hft_event_journal Example output showing decoded event traces from the QET reader. ```text 92375019 0 QETOrdersSnapshot 92375019 1 QETPositionsSnapshot 92375019 2 QETOrder 92375019 3 QETOrder 92375019 4 QETOrder 92375019 5 QETOrder ``` -------------------------------- ### Install build tools on Linux Source: https://quantpylib.hangukquant.com/ Environment configuration for building with GCC 14 on Amazon Linux. ```bash sudo dnf install -y gcc14 gcc14-c++ export CC=/usr/bin/gcc14-gcc export CXX=/usr/bin/gcc14-g++ python3 -m pip install -e . ``` -------------------------------- ### Initialize and Use Bybit SDK Source: https://quantpylib.hangukquant.com/wrappers/bybit Demonstrates initializing the Bybit client and executing various account, exchange, executor, order, position, and data polling operations. ```python import os import pytz import asyncio from pprint import pprint from datetime import datetime from dotenv import load_dotenv load_dotenv() from quantpylib.standards import Period from quantpylib.wrappers.bybit import Bybit async def print_handler(msg): print(msg) async def main(): '''using the SDK''' bybit = Bybit( key=os.getenv("BYBIT_KEY"), secret=os.getenv("BYBIT_SECRET"), ) '''quantpylib.gateway endpoints''' await bybit.init_client() print(bybit.get_price_precision("BTCUSDT")) print(bybit.get_lot_precision("BTCUSDT")) '''ACCOUNT ENDPOINTS''' pprint(await bybit.account_balance()) await bybit.account_fill_subscribe(handler=print_handler) '''EXCHANGE ENDPOINTS''' pprint(await bybit.contract_specifications()) '''EXECUTOR ENDPOINTS''' cloid = bybit.rand_cloid() print(cloid) pprint(await bybit.get_all_mids()) pprint(await bybit.limit_order(ticker="SOLUSDT",amount=1,price=99.99,cloid=cloid)) pprint(await bybit.cancel_open_orders()) #or use ticker="SOLUSDT" pprint(await bybit.cancel_order(ticker="SOLUSDT",cloid=cloid)) #or use oid pprint(await bybit.market_order(ticker="SOLUSDT",amount=-0.5)) pprint(await bybit.l2_book_get(ticker="BTCUSDT")) await bybit.l2_book_mirror(ticker="BTCUSDT",on_update=print_handler) await bybit.l2_book_subscribe(ticker="BTCUSDT",handler=print_handler) await bybit.trades_subscribe(ticker="BTCUSDT",handler=print_handler) '''ORDERS ENDPOINTS''' pprint(await bybit.order_query(oid='1234')) pprint(await bybit.orders_get()) await bybit.orders_mirror(on_update=print_handler) await bybit.order_updates_subscribe(handler=print_handler) '''POSITIONS ENDPOINTS''' pprint(await bybit.positions_get()) await bybit.positions_mirror(on_update=print_handler) '''DATAPOLLER ENDPOINTS''' pprint(await bybit.get_trade_bars( ticker='BTCUSDT', start=datetime(2021,1,1, tzinfo=pytz.utc), end=datetime.now(pytz.utc), granularity=Period.HOURLY, granularity_multiplier=1, )) '''raw exchange endpoints API - refer to docs for the other method implementations''' pprint(await bybit.instruments_info()) await asyncio.sleep(1e9) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Position Data Structure Example Source: https://quantpylib.hangukquant.com/gateway/gateway Example output format for position data. ```python {'SOL': {'ticker': 'SOL', 'amount': Decimal....'unrealized_pnl': 1315.35}} ``` -------------------------------- ### Install build tools on macOS Source: https://quantpylib.hangukquant.com/ Prerequisites for building native extensions on macOS using Homebrew. ```bash xcode-select --install brew install cmake ninja python3 -m pip install -e . ``` -------------------------------- ### Default Python Logger Execution Source: https://quantpylib.hangukquant.com/logger/logger Example of running the application with default Python logging settings. ```python if __name__ == "__main__": if not args.config: print("using default python logger") #... log() ``` ```bash python example_logger.py ``` ```text using default python logger WARNING:root:warning log ERROR:root:caught zero denominator Traceback (most recent call last): File "/Users/admin/Desktop/projects/quantpylib/examples/example_logger.py", line 16, in log 1/0 ~^~ ``` -------------------------------- ### Initialize Gateway with Configuration Source: https://quantpylib.hangukquant.com/gateway/gateway Sets up the Gateway instance using environment variables for exchange credentials. ```python import os import logging import asyncio from dotenv import load_dotenv load_dotenv() from datetime import datetime import quantpylib.standards.markets as markets from quantpylib.gateway.master import Gateway config_keys={ "binance": { "alias": "binance", "key": os.getenv("BIN_PUBLIC"), "secret" : os.getenv("BIN_KEY"), }, "hyperliquid": { "alias" : "hyperliquid", "key" : os.getenv("HYP_DEMO"), "secret" : os.getenv("HYP_KEY"), } } async def main(): gateway = Gateway(config_keys=config_keys) print(gateway.exc_clients) await gateway.init_clients() #...code goes between here... await gateway.cleanup_clients() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize DataPoller and Clients Source: https://quantpylib.hangukquant.com/datapoller/datapoller Setup the DataPoller with configuration keys and manage the lifecycle of data source clients. ```python import os import asyncio from dotenv import load_dotenv load_dotenv() from datetime import datetime from quantpylib.datapoller.master import DataPoller config_keys = { "yfinance": {"alias":"yfinance"}, "eodhd": {"eod_key":os.getenv("EOD_KEY")}, "binance": {}, "oanda": { "alias":"oanda", "account_id":os.getenv("OANDA_ACC"), "secret": os.getenv("OANDA_KEY"), "env":"practice", }, "hyperliquid": {"alias":"hyp","key":os.getenv("HYP_PUBLIC"),"secret":os.getenv("HYP_KEY")}, } async def main(): start,end=datetime(2023,9,30),datetime.now() datapoller = DataPoller(config_keys=config_keys) print(datapoller.src_pollers) await datapoller.init_clients() #...code goes between here... await datapoller.cleanup_clients() print("cleanup") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Woox.__init__ Source: https://quantpylib.hangukquant.com/wrappers/woox Initializes the WooX instance with authentication credentials and environment settings. ```APIDOC ## __init__(key=None, secret=None, app_id=None, environment=Environment.PROD, logger=None) ### Description Initializes the WooX instance. ### Parameters - **key** (str) - Optional - API key for authentication. - **secret** (str) - Optional - API secret for authentication. - **app_id** (str) - Optional - Application ID for authentication. - **environment** (int) - Optional - The environment to connect to. 1 for production, 2 for staging. Defaults to 1. ``` -------------------------------- ### Bybit.__init__ Source: https://quantpylib.hangukquant.com/wrappers/bybit Initializes the Bybit instance with authentication credentials and environment settings. ```APIDOC ## __init__(key='', secret='', env='prod', key_self_generated=False, logger=None, **kwargs) ### Description Initializes the Bybit instance. ### Parameters - **key** (str) - Optional - API key for authentication. Defaults to ''. - **secret** (str) - Optional - API secret for authentication. Defaults to ''. - **key_self_generated** (bool) - Optional - Flag to indicate if RSA authentication is used. Defaults to False. ``` -------------------------------- ### Initialize and Use Paradex SDK Source: https://quantpylib.hangukquant.com/wrappers/paradex Demonstrates initializing the Paradex client and executing various account, exchange, executor, and order-related operations. ```python import os import pytz import asyncio from pprint import pprint from datetime import datetime from dotenv import load_dotenv load_dotenv() from quantpylib.wrappers.paradex import Paradex async def print_handler(msg): print(msg) async def main(): '''using the SDK''' pdx = Paradex( key=os.getenv("ETH_KEY"), l2_secret=os.getenv("PARADEX_SECRET"), ) '''quantpylib.gateway endpoints''' await pdx.init_client() print(pdx.get_price_precision("BTC-USD-PERP")) print(pdx.get_lot_precision("BTC-USD-PERP")) '''ACCOUNT ENDPOINTS''' pprint(await pdx.account_balance()) await pdx.account_fill_subscribe(handler=print_handler) '''EXCHANGE ENDPOINTS''' pprint(await pdx.contract_specifications()) pprint(await pdx.get_funding_info()) '''EXECUTOR ENDPOINTS''' cloid = pdx.rand_cloid() print(cloid) pprint(await pdx.get_all_mids()) pprint(await pdx.get_all_marks()) pprint(await pdx.limit_order(ticker="SOL-USD-PERP",amount=1,price=99.99,cloid=cloid)) pprint(await pdx.cancel_open_orders()) #or use ticker="SOL-USD-PERP" pprint(await pdx.cancel_order(ticker="SOL-USD-PERP",cloid=cloid)) #or use oid pprint(await pdx.market_order(ticker="SOL-USD-PERP",amount=-0.5)) pprint(await pdx.l2_book_get(ticker="BTC-USD-PERP")) await pdx.l2_book_mirror(ticker="BTC-USD-PERP",on_update=print_handler) await pdx.l2_book_subscribe(ticker="BTC-USD-PERP",handler=print_handler) await pdx.trades_subscribe(ticker="BTC-USD-PERP",handler=print_handler) await pdx.all_mids_subscribe(handler=print_handler) await pdx.oracle_subscribe(handler=print_handler) #get USDC/USD oracle '''ORDERS ENDPOINTS''' pprint(await pdx.order_query(ticker='SOL-USD-PERP',cloid='1234')) pprint(await pdx.orders_get()) await pdx.orders_mirror(on_update=print_handler) await pdx.order_updates_subscribe(handler=print_handler) '''POSITIONS ENDPOINTS''' pprint(await pdx.positions_get()) await pdx.positions_mirror(on_update=print_handler) '''DATAPOLLER ENDPOINTS''' # pprint(await pdx.get_trade_bars( # ticker='BTC-USD-PERP', # start=datetime(2021,1,1, tzinfo=pytz.utc), # end=datetime.now(pytz.utc), # granularity=Period.HOURLY, # granularity_multiplier=1, # )) '''raw exchange endpoints API - refer to docs for the other method implementations''' pprint(await pdx.get_account()) pprint(await pdx.get_profile()) pprint(await pdx.get_balances()) pprint(await pdx.get_fills()) pprint(await pdx.get_tradebusts()) #>... many more await asyncio.sleep(1e9) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize and Use Lighter Wrapper Source: https://quantpylib.hangukquant.com/wrappers/lighter Demonstrates the initialization of the Lighter client and provides a comprehensive list of available asynchronous methods for interacting with the exchange. ```python 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='')) # pprint(await lighter.tx_from_l1_txhash(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='')) '''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='', 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='', signature='')) '''fee credits''' pprint(await lighter.lease_options()) pprint(await lighter.leases()) # pprint(await lighter.lit_lease(tx_info='', 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 ``` -------------------------------- ### Client Initialization and Execution Source: https://quantpylib.hangukquant.com/wrappers/hyperliquid Main entry point for initializing the Hyperliquid client and running example tasks. ```python async def main(): await hyp.init_client() try: '''uncomment examples to run NOTE: that some code may trigger exchange actions such as live orders ''' #await exchange_sdk_examnples() #await info_sdk_examples() #await gateway_examples() await socket_examples() except Exception as e: logging.exception("Error in SDK examples: %s", e) await hyp.cleanup() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### get_vault_config() Source: https://quantpylib.hangukquant.com/wrappers/paradex Get vault config. ```APIDOC ## get_vault_config() ### Description Get vault config. ``` -------------------------------- ### get_transfers(**kwargs) Source: https://quantpylib.hangukquant.com/wrappers/paradex Get transfers. ```APIDOC ## get_transfers(**kwargs) ### Description Get transfers. ### Parameters - **kwargs** (dict) - Optional - Additional keyword arguments. ``` -------------------------------- ### Polymarket Client Initialization and Execution Source: https://quantpylib.hangukquant.com/wrappers/polymarket Entry point for initializing the client, running examples, and ensuring proper cleanup of resources. ```python async def main(): await poly.init_client() try: '''uncomment examples to run NOTE: that some code may trigger exchange actions such as live orders ''' # await endpoint_examples() # await gateway_examples() await socket_examples() except Exception as exc: logging.exception("Error in Polymarket examples: %s", exc) raise finally: await poly.cleanup() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### get_transactions(**kwargs) Source: https://quantpylib.hangukquant.com/wrappers/paradex Get transactions. ```APIDOC ## get_transactions(**kwargs) ### Description Get transactions. ### Parameters - **kwargs** (dict) - Optional - Additional params. ``` -------------------------------- ### Polymarket.__init__ Source: https://quantpylib.hangukquant.com/wrappers/polymarket Instantiate the Polymarket wrapper. ```APIDOC ## Polymarket.__init__(polymarket_key, secret, chain_id=POLYGON, sig_type=2, funder=None, logger=None) ### Description Instantiate the Polymarket wrapper. ### Parameters - **polymarket_key** (str) - Required - Polymarket account address used for CLOB account identity and direct portfolio reads. - **secret** (str) - Required - Private key used for Level 1 signing and local CLOB V2 order signatures. - **chain_id** (int) - Optional - Polygon chain ID. Defaults to mainnet (POLYGON). - **sig_type** (int) - Optional - Polymarket signature type. Use 1 for email or proxy wallet accounts and 2 for browser wallet accounts. Defaults to 2. - **funder** (str | None) - Optional - Funding address for orders when it differs from polymarket_key. Defaults to None. ``` -------------------------------- ### orders_get_all() Source: https://quantpylib.hangukquant.com/hft/oms Get the orders for all exchanges. ```APIDOC ## orders_get_all() ### Description Get the orders for all exchanges. Uses HTTP request. ``` -------------------------------- ### Start the QET Compiler Source: https://quantpylib.hangukquant.com/tutorials/hft_event_journal Initializes the compiler service to process HFT events with specified host, port, and buffer settings. ```bash python3.11 -m quantpylib.hft.qet_compiler serve \ --root ./qet \ --host 127.0.0.1 \ --port 33200 \ --buffer-size 48 ``` -------------------------------- ### get_nonce() Source: https://quantpylib.hangukquant.com/wrappers/hyperliquid Get a unique nonce value. ```APIDOC ## get_nonce() ### Description Get a unique nonce value using a nonce buffer to ensure no overlaps between exchange requests. ### Returns - **int** - A unique nonce value. ``` -------------------------------- ### time Source: https://quantpylib.hangukquant.com/wrappers/polymarket Get the exchange server time. ```APIDOC ## time() ### Description Get the exchange server time. ``` -------------------------------- ### positions_get Source: https://quantpylib.hangukquant.com/wrappers/bybit Get open position details. ```APIDOC ## `positions_get(ticker=None, **kwargs)` ### Description Get open position details. ### Parameters - **ticker** (optional) - Optional - Retrieve position for ticker only. - **kwargs** (dict) - Optional - Additional keyword arguments specific to the exchange wrapper. ### Returns - **dict** - A dictionary containing details of the open positions. ``` -------------------------------- ### Instantiate Polymarket Wrapper Source: https://quantpylib.hangukquant.com/wrappers/polymarket Initialize the wrapper using environment variables for credentials and signature configuration. ```python import os from quantpylib.wrappers.polymarket import Polymarket poly = Polymarket( polymarket_key=os.getenv("POLY_KEY"), secret=os.getenv("POLY_SECRET"), sig_type=int(os.getenv("POLY_SIG", "1")), funder=os.getenv("POLY_FUNDER") or os.getenv("POLY_KEY"), ) ``` -------------------------------- ### get_vaults(**kwargs) Source: https://quantpylib.hangukquant.com/wrappers/paradex Get vault details. ```APIDOC ## get_vaults(**kwargs) ### Description Get vault details. ### Parameters - **kwargs** (dict) - Optional - Additional keyword arguments. ``` -------------------------------- ### get_vault_positions(address) Source: https://quantpylib.hangukquant.com/wrappers/paradex Get vault positions. ```APIDOC ## get_vault_positions(address) ### Description Get vault positions. ### Parameters - **address** (str) - Required - The address of the vault. ``` -------------------------------- ### Initialize Lighter client Source: https://quantpylib.hangukquant.com/wrappers/lighter Initializes the Lighter client and runs example functions within an asynchronous main loop. ```python 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()) ``` -------------------------------- ### Polymarket.gamma_get_market Source: https://quantpylib.hangukquant.com/wrappers/polymarket Get a market by ID from the Gamma API. ```APIDOC ## Polymarket.gamma_get_market(id, **kwargs) ### Description Get a market by ID from the Gamma API. ### Parameters - **id** (str) - Required - The market ID. - **kwargs** (dict) - Optional - The query parameters. ``` -------------------------------- ### Polymarket.gamma_get_event Source: https://quantpylib.hangukquant.com/wrappers/polymarket Get an event by ID from the Gamma API. ```APIDOC ## Polymarket.gamma_get_event(id, **kwargs) ### Description Get an event by ID from the Gamma API. ### Parameters - **id** (str) - Required - The event ID. - **kwargs** (dict) - Optional - The query parameters. ``` -------------------------------- ### positions_get(**kwargs) Source: https://quantpylib.hangukquant.com/wrappers/asterdex Get all open position details. ```APIDOC ## positions_get(**kwargs) ### Description Get all open position details. ### Parameters - **kwargs** (dict) - Optional - Exchange wrapper specific keyword arguments. ### Returns - **dict** - A dictionary containing the open position details. ``` -------------------------------- ### Polymarket API Usage Example Source: https://quantpylib.hangukquant.com/wrappers/polymarket Demonstrates initialization of the Polymarket client and usage of various endpoints including account data, order management, and market information. ```python import os import asyncio import logging from pprint import pprint from dotenv import load_dotenv load_dotenv() from quantpylib.wrappers.polymarket import ( Polymarket, OrderArgs, CreateOrderOptions, RealTimeChannel, ) POLY_KEY = os.getenv("TEST_POLY_KEY") or os.getenv("POLY_KEY") POLY_SECRET = os.getenv("TEST_POLY_SECRET") or os.getenv("POLY_SECRET") POLY_SIG_TYPE = int(os.getenv("TEST_POLY_SIG") or os.getenv("POLY_SIG") or "1") POLY_FUNDER = os.getenv("TEST_POLY_FUNDER") or os.getenv("POLY_FUNDER") or POLY_KEY ORDER_ID = os.getenv("TEST_POLY_ORDER_ID") or os.getenv("POLY_ORDER_ID") or "" TOKEN_ID = "78433024518676680431174478322854148606578065650008220678402966840627347604025" CONDITION_ID = "0x384e2707bbb95da4bfa6f330fe7d5ccbec1c0a85e20be900cbf599987588e1a4" MARKET_SLUG = "reya-fdv-above-200m-one-day-after-launch-645-575" GAMMA_MARKET_ID = "" GAMMA_EVENT_ID = "" ORDER_PRICE = 0.01 ORDER_SIZE = 10 poly = Polymarket( polymarket_key=POLY_KEY, secret=POLY_SECRET, sig_type=POLY_SIG_TYPE, funder=POLY_FUNDER, ) async def print_handler(msg): pprint(msg) async def endpoint_examples(): '''data api''' pprint(await poly.get_positions(limit=2)) pprint(await poly.get_bet_value()) pprint(await poly.get_portfolio_equity()) '''clob account''' pprint(await poly.time()) pprint(await poly.get_collateral_allowance()) pprint(await poly.get_conditional_allowance(token_id=TOKEN_ID)) pprint(await poly.get_balance_allowance(asset_type="COLLATERAL")) # pprint(await poly.update_balance_allowance(asset_type="COLLATERAL")) pprint(await poly.get_tick_size(token_id=TOKEN_ID)) pprint(await poly.get_neg_risk(token_id=TOKEN_ID)) pprint(await poly.get_fee_rate(token_id=TOKEN_ID)) '''api keys''' # pprint(await poly.create_api_key()) pprint(await poly.derive_api_key()) pprint(await poly.get_api_keys()) # pprint(await poly.delete_api_key()) pprint(await poly.access_status()) '''orders''' order, cloid = poly.builder.create_order( OrderArgs( token_id=TOKEN_ID, price=ORDER_PRICE, size=ORDER_SIZE, side="BUY", ), CreateOrderOptions( tick_size=str((await poly.get_tick_size(TOKEN_ID))["minimum_tick_size"]), neg_risk=bool((await poly.get_neg_risk(TOKEN_ID))["neg_risk"]), ), ) # pprint(await poly.post_order(order=order, order_type="GTC")) # pprint(await poly.post_order_bytes(order_payload_bytes="")) # pprint(await poly.post_orders(orders=[order], order_types=["GTC"])) # pprint(await poly.post_orders_bytes(orders_payload_bytes="[]")) if ORDER_ID: pprint(await poly.get_order(order_id=ORDER_ID)) pprint(await poly.get_orders()) if ORDER_ID: pprint(await poly.cancel_order(order_id=ORDER_ID)) # pprint(await poly.cancel_order_bytes(cancel_payload_bytes=b'{"orderID":""}')) # pprint(await poly.cancel_orders(order_ids=[""])) # pprint(await poly.cancel_orders_bytes(cancels_payload_bytes=b'[""]')) # pprint(await poly.cancel_all_orders()) # pprint(await poly.cancel_market_orders(asset_id=TOKEN_ID)) '''trades''' # pprint(await poly.get_trades()) pprint(await poly.get_trades_page(limit=2)) '''markets''' # pprint(await poly.all_clob_markets()) pprint(await poly.all_clob_markets_page(limit=2)) # pprint(await poly.all_sampling_markets()) pprint(await poly.all_sampling_markets_page(limit=2)) # pprint(await poly.all_simplified_markets()) pprint(await poly.all_simplified_markets_page(limit=2)) # pprint(await poly.all_sampling_simplified_markets()) pprint(await poly.all_sampling_simplified_markets_page(limit=2)) if CONDITION_ID: pprint(await poly.get_market(condition_id=CONDITION_ID)) '''prices and books''' pprint(await poly.get_book(token_id=TOKEN_ID)) pprint(await poly.get_books(token_ids=[TOKEN_ID])) pprint(await poly.get_price(token_id=TOKEN_ID, side="BUY")) pprint(await poly.get_prices(token_ids=[TOKEN_ID], sides=["BUY"])) pprint(await poly.get_midpoint(token_id=TOKEN_ID)) pprint(await poly.get_midpoints(token_ids=[TOKEN_ID])) pprint(await poly.get_spread(token_id=TOKEN_ID)) pprint(await poly.get_spreads(token_ids=[TOKEN_ID])) pprint(await poly.get_prices_history(asset_id=TOKEN_ID, interval="1m", fidelity=60)) '''gamma''' pprint(await poly.gamma_get_markets(limit=2)) if GAMMA_MARKET_ID: pprint(await poly.gamma_get_market(id=GAMMA_MARKET_ID)) pprint(await poly.gamma_get_events(limit=2)) if GAMMA_EVENT_ID: pprint(await poly.gamma_get_event(id=GAMMA_EVENT_ID)) return ``` -------------------------------- ### get_vault_summary(**kwargs) Source: https://quantpylib.hangukquant.com/wrappers/paradex Get exchange vault summary. ```APIDOC ## get_vault_summary(**kwargs) ### Description Get exchange vault summary. ### Parameters - **kwargs** (dict) - Optional - Additional keyword arguments. ``` -------------------------------- ### Eodhd.get_ticker_fundamentals Source: https://quantpylib.hangukquant.com/wrappers/eodhd Get fundamental data for a specific ticker. ```APIDOC ## Eodhd.get_ticker_fundamentals(ticker, exchange='US', **kwargs) ### Description Get fundamental data for a specific ticker. ### Parameters - **ticker** (str) - Required - Ticker symbol for the asset. - **exchange** (str) - Optional - Exchange name. Defaults to "US". ### Returns - **dict** - Fundamental data for the ticker. ``` -------------------------------- ### Order Update Trigger Source: https://quantpylib.hangukquant.com/hft/hft Example of an on_update trigger payload. ```python [{'amount': Decimal('1.0'), ... 'timestamp': 1726123317580, 'tp': None},] ```