### Minimal Trading Loop Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/00-index.md Demonstrates the basic setup for a trading loop, including initializing an OrderBook, starting a market stream, and placing a limit order. ```python book = OrderBook(token_id="...", tick_size=0.01) market_stream.start() order, resp = order_manager.limit_order(price=book.best_bid_price + 0.01, ...) ``` -------------------------------- ### MarketStream Ready Check Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Demonstrates how to start a stream, wait for it to be ready with a timeout, and access book data. Handles potential connection timeouts. ```python stream.start() if stream.wait_ready(timeout=10): # Books are synced print(stream.books[0].best_bid_price) else: print("Stream connection timeout") ``` -------------------------------- ### Complete Polypy Streams Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md A full example showing how to set up and use OrderManager, PositionManager, MarketStream, and UserStream. It includes posting an order, checking its status, and verifying positions. ```python import polypy as plp import time # Create managers order_mgr = plp.OrderManager( rest_endpoint=plp.ENDPOINT.REST, private_key="0x...", api_key="...", secret="...", passphrase="...", maker_funder="0x...", signature_type=plp.SIGNATURE_TYPE.EOA, ) pos_mgr = plp.PositionManager( rest_endpoint=plp.ENDPOINT.REST, gamma_endpoint=plp.ENDPOINT.GAMMA, usdc_position=1000, ) # Create and start market stream book = plp.OrderBook(token_id="0x...", tick_size=0.01) market_stream = plp.MarketStream( ws_endpoint=plp.ENDPOINT.WS, books=book, check_hash_params=plp.CheckHashParams(nth_price_change=100, max_emission_delay=10), rest_endpoint=plp.ENDPOINT.REST, ) market_stream.start() market_stream.wait_ready(timeout=10) # Create and start user stream user_stream = plp.UserStream( ws_endpoint=plp.ENDPOINT.WS, tuple_manager=(order_mgr, pos_mgr), market_triplets=[], # All markets api_key=order_mgr.api_key, secret=order_mgr.secret, passphrase=order_mgr.passphrase, ) user_stream.start() user_stream.wait_ready(timeout=10) # Post order using live book data best_bid = book.best_bid_price order, resp = order_mgr.limit_order( price=best_bid + book.tick_size, size=10, token_id="0x...", side=plp.SIDE.BUY, tick_size=book.tick_size, ) # Wait for updates via streams time.sleep(5) # Check order status tracked = order_mgr.get_by_id(order.id) print(f"Order status: {tracked.status}") print(f"Matched: {tracked.size_matched}") # Check position print(f"Balance: ${pos_mgr.balance}") print(f"Positions: {pos_mgr.total}") # Cleanup market_stream.stop() user_stream.stop() ``` -------------------------------- ### Install Polypy Source: https://github.com/hbr-l/polypy/blob/main/docs/guide.md Clone the repository and install polypy using pip. You can also install with example or development dependencies. ```bash >> git clone https://github.com/hbr-l/polypy.git >> cd polypy >> pip install . ``` ```bash >> pip install .[examples] (includes dependencies for examples) ``` ```bash >> pip install -e .[dev] (editable with development dependencies e.g., for testing) ``` ```bash >> pip install '.[examples]' ``` -------------------------------- ### Complete Polypy RPC Workflow Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md A comprehensive example demonstrating a typical workflow using Polypy. It includes setting up Web3, checking balances, approving tokens, splitting positions, and merging positions. ```python from web3 import Web3 import polypy as plp # Setup Web3 rpc = plp.ENDPOINT.RPC_POLYGON w3 = plp.W3POA(Web3.HTTPProvider(rpc)) # Check USDC balance balance_wei = plp.get_balance_USDC( w3=w3, chain_id=plp.CHAIN_ID.POLYGON, address="0x...", ) print(f"USDC: {int(balance_wei) / 1e6}") # Approve USDC (auto-approve if needed) mtx_approve = plp.auto_approve_USDC( w3=w3, chain_id=plp.CHAIN_ID.POLYGON, private_key="0x...", amount=1000, maker_funder="0x...", gas_factor=1.1, ) if mtx_approve: print(f"Approved: {mtx_approve.txn_hash}") # Split 100 USDC into YES/NO tokens mtx_split = plp.split_positions( w3=w3, chain_id=plp.CHAIN_ID.POLYGON, private_key="0x...", condition_id="0x...", amount=100, maker_funder="0x...", gas_factor=1.1, ) print(f"Split: {mtx_split.txn_hash}") if mtx_split.receipt: print(f"Mined: Block {mtx_split.receipt['blockNumber']}") # Check token balance token_balance = plp.get_balance_token( w3=w3, chain_id=plp.CHAIN_ID.POLYGON, token_id="0x...", # YES token address="0x...", ) print(f"YES tokens: {int(token_balance) / 1e6}") # Later, merge back to USDC mtx_merge = plp.merge_positions( w3=w3, chain_id=plp.CHAIN_ID.POLYGON, private_key="0x...", condition_id="0x...", amount=100, maker_funder="0x...", ) print(f"Merged: {mtx_merge.txn_hash}") ``` -------------------------------- ### Initialize and Start PolyPy Trading Components Source: https://github.com/hbr-l/polypy/blob/main/README.md This snippet demonstrates the initialization of key PolyPy components: OrderBook, MarketStream, OrderManager, and PositionManager. It also shows how to start the associated streams for real-time updates. Ensure all necessary API keys, private keys, and endpoints are correctly configured. ```python import time import polypy as plp # create an order book, which keeps tracks of resting limit orders # due to the complementary character of the unified order book for YES and NO tokens, # we only need to track one them book = plp.OrderBook(token_id="...", tick_size=0.01) # assign order book to a market stream, which updates the order book automatically in a separate thread # this way, the order book is always up-to-date (including tick size) market_stream = plp.MarketStream( ws_endpoint=plp.ENDPOINT.WS, books=book, check_hash_params=None, rest_endpoint=plp.ENDPOINT.REST ) market_stream.start() # create an order manager, which is used to create and manipulate orders, store and manage them order_manager = plp.OrderManager( rest_endpoint=plp.ENDPOINT.REST, private_key="...", api_key="...", secret="...", passphrase="...", maker_funder="your_wallet_addr", signature_type=plp.SIGNATURE_TYPE.POLY_PROXY, chain_id=plp.CHAIN_ID.POLYGON ) # create a position_manager with an initial bankroll (100 USDC), which stores and manages current positions (holdings) position_manager = plp.PositionManager(rest_endpoint=plp.ENDPOINT.REST, gamma_endpoint=plp.ENDPOINT.GAMMA, usdc_position=100) # assign order_manager and position_manager to a user stream # this way, orders in order_manager and positions in position_manager will be updated automatically (e.g. if an # order is executed, the corresponding position will be created and/or updated in the position manager, and the # order will be updated in the order_manager) user_stream = plp.UserStream( ws_endpoint=plp.ENDPOINT.WS, tuple_manager=(order_manager, position_manager), market_triplets=("market_id", "yes_token_id", "no_token_id"), api_key="...", secret="...", passphrase="..." ) user_stream.start() ``` -------------------------------- ### start() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Starts the WebSocket market data stream in a separate background thread, allowing for non-blocking operation. ```APIDOC ## start() ```python def start() -> None ``` Start the stream in a background thread. ``` -------------------------------- ### Complete Polypy Utility Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/10-utilities.md This example demonstrates the integrated use of various Polypy utilities, including numeric conversion, array creation, market identifier handling, signing, type inference, and batching. It showcases how these functions can be combined in a practical application. ```python import polypy as plp from decimal import Decimal # Numeric conversion and rounding price = plp.dec("0.5555") rounded = plp.round_half_even(price, 2) print(f"Price: {rounded}") # 0.56 # Array creation bids = plp.zeros_dec(10) bids[0] = Decimal("0.55") # Market identifiers triplet = plp.MarketIdTriplet.from_tuple( "0x123...", # condition_id "0x456...", # yes_token "0x789...", # no_token ) # Signing address = plp.private_key_checksum_address("0x...") print(f"Address: {address}") # Type inference price_type = plp.infer_numeric_type(0.55) qty_type = plp.infer_numeric_type(Decimal(10)) # Batching for batch in plp.batched(range(10), 3): print(batch) ``` -------------------------------- ### Python Code Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/README.md Illustrates actual usage of Python code within the project. ```python # Python code examples showing actual usage ``` -------------------------------- ### RPCSettings Example Usage Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Demonstrates how to instantiate RPCSettings and use its parameters with other Polypy functions like split_positions and merge_positions. ```python rpc_settings = plp.RPCSettings( w3=w3, chain_id=plp.CHAIN_ID.POLYGON, private_key="0x...", maker_funder="0x...", gas_factor=1.2, # 20% above base gas endpoint_relayer=plp.ENDPOINT.RELAYER, ) # Use in multiple operations mtx1 = plp.split_positions(..., **vars(rpc_settings)) mtx2 = plp.merge_positions(..., **vars(rpc_settings)) ``` -------------------------------- ### Example Usage of create_limit_order Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/03-orders.md Demonstrates how to use the `create_limit_order` function to place a buy limit order. Ensure necessary imports are included. ```python from polypy.order import create_limit_order, SIDE, TIME_IN_FORCE from polypy.constants import CHAIN_ID from polypy.signing import SIGNATURE_TYPE order = create_limit_order( price=0.55, size=10.5, token_id="0x1234567890abcdef", side=SIDE.BUY, tick_size=0.01, neg_risk=False, chain_id=CHAIN_ID.POLYGON, private_key="0x...", # private key hex string maker="0x...", # wallet address signature_type=SIGNATURE_TYPE.EOA, tif=TIME_IN_FORCE.GTC, strategy_id="my_strategy_v1" ) print(f"Order ID: {order.id}") print(f"Status: {order.status}") # DEFINED print(f"Price: {order.price}") ``` -------------------------------- ### W3POA Class Example Usage Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Shows how to initialize a W3POA instance using an HTTPProvider and access basic blockchain information like connection status and chain ID. ```python w3 = plp.W3POA( Web3.HTTPProvider(plp.ENDPOINT.RPC_POLYGON) ) print(f"Connected: {w3.is_connected()}") print(f"Chain ID: {w3.eth.chain_id}") ``` -------------------------------- ### Start MarketStream Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Starts the MarketStream in a background thread for continuous data reception. ```python def start() -> None ``` -------------------------------- ### Complete Polypy Position Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/08-positions.md Demonstrates creating, acting on, and reverting token and USDC positions, including freezing a position. ```python import polypy as plp # Create USDC position usdc = plp.Position.create( asset_id=plp.USDC, size=1000, n_digits_size=plp.N_DIGITS_USDC, allow_neg=False, ) print(f"USDC balance: ${usdc.size}") # Create token position token = plp.Position.create( asset_id="0x1234...", size=0, n_digits_size=plp.N_DIGITS_SIZE, allow_neg=False, ) # Simulate buying 10 tokens at 0.5 (costs $5) # User receives tokens (TAKER) token.act( delta_size=10, trade_id="trade_1", act_side=plp.ACT_SIDE.TAKER, trade_status=plp.TRADE_STATUS.MATCHED, ) # User pays USDC (MAKER) usdc.act( delta_size=5, trade_id="trade_1", act_side=plp.ACT_SIDE.MAKER, trade_status=plp.TRADE_STATUS.MATCHED, ) print(f"After buy: {token.size} tokens, ${usdc.size} cash") # Output: After buy: 10 tokens, $995 cash # If trade fails, revert token.act( delta_size=10, trade_id="trade_1", act_side=plp.ACT_SIDE.TAKER, trade_status=plp.TRADE_STATUS.FAILED, ) usdc.act( delta_size=5, trade_id="trade_1", act_side=plp.ACT_SIDE.MAKER, trade_status=plp.TRADE_STATUS.FAILED, ) print(f"After failure: {token.size} tokens, ${usdc.size} cash") # Output: After failure: 0 tokens, $1000 cash # Check if positions are empty if token.empty and usdc.size == 1000: print("Positions reverted") # Freeze positions to make read-only frozen_token = plp.frozen_position(token) try: frozen_token.size = 50 except plp.PositionException: print("Cannot modify frozen position") ``` -------------------------------- ### Complete OrderBook Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/04-orderbook.md Illustrates the full lifecycle of an OrderBook, from creation and synchronization to continuous updates via MarketStream. Shows how to access various order book metrics. ```python import polypy as plp from polypy.constants import ENDPOINT # Create order book book = plp.OrderBook( token_id="0xabcd...", tick_size=0.01, ) # Sync from REST book.sync(ENDPOINT.REST) print(f"Best bid: {book.best_bid_price}") print(f"Best ask: {book.best_ask_price}") print(f"Midpoint: {book.midpoint_price}") # Or attach to MarketStream for continuous updates market_stream = plp.MarketStream( ws_endpoint=ENDPOINT.WS, books=book, check_hash_params=plp.CheckHashParams(nth_price_change=100, max_emission_delay=10), rest_endpoint=ENDPOINT.REST ) market_stream.start() market_stream.wait_ready() # Now book updates automatically price = book.midpoint_price size = book.best_bid_size ``` -------------------------------- ### UserStream.start() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Starts the WebSocket stream in a background thread, enabling the reception of real-time user updates. ```APIDOC ## start() ### Description Starts the stream in a background thread. ### Method ```python def start() -> None ``` ``` -------------------------------- ### Polypy Manager Usage Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Demonstrates the initialization and usage of OrderManager and PositionManager for trading operations. Includes posting limit orders, checking buying power, and tracking positions. ```python import polypy as plp # Create managers order_mgr = plp.OrderManager( rest_endpoint=plp.ENDPOINT.REST, private_key="0x...", api_key="...", secret="...", passphrase="...", maker_funder="0x...", signature_type=plp.SIGNATURE_TYPE.EOA, chain_id=plp.CHAIN_ID.POLYGON, ) pos_mgr = plp.PositionManager( rest_endpoint=plp.ENDPOINT.REST, gamma_endpoint=plp.ENDPOINT.GAMMA, usdc_position=1000, # $1000 initial ) # Post limit order order, resp = order_mgr.limit_order( price=0.55, size=20, token_id="0x...", side=plp.SIDE.BUY, tick_size=0.01, ) print(f"Posted {order.id}") # Check available cash power = pos_mgr.buying_power(order_mgr) print(f"Remaining buying power: ${power}") # Search orders live = order_mgr.get(status=plp.INSERT_STATUS.LIVE) print(f"Live orders: {len(live)}") # Track external order ext_order = plp.create_limit_order(...) order_mgr.track(ext_order, sync=True) # Position update (typically via stream) pos_mgr.transact( asset_id="0x...", delta=20, trade_id="trade_123", act_side=plp.ACT_SIDE.TAKER, trade_status=plp.TRADE_STATUS.MATCHED, ) ``` -------------------------------- ### Polypy Usage Examples Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/11-exceptions.md Illustrates the practical application of the safe functions for order management, book price retrieval, and stream connection. ```python # Usage order_mgr = plp.OrderManager(...) order = safe_post_order(order_mgr, 0.55, 10, "0x...") book = plp.OrderBook(token_id="0x...", tick_size=0.01) price = safe_get_book_price(book) market_stream = plp.MarketStream(...) connected = safe_stream_connect(market_stream, timeout=15) ``` -------------------------------- ### Python Stream Callback Setup Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Defines callback functions for market messages, user messages, and exceptions. Initializes and configures MarketStream and UserStream instances with these callbacks. ```python def on_market_message(stream, msg): """Called when order book updates.""" token_id = msg.asset_id if hasattr(msg, "asset_id") else None print(f"Book updated: {token_id}") def on_user_message(stream, msg): """Called when order/position updates.""" event_type = msg.get("event_type", "unknown") print(f"User event: {event_type}") def on_exception(stream, exc): """Called on stream errors.""" print(f"Stream error: {exc}") market_stream = plp.MarketStream( ws_endpoint=plp.ENDPOINT.WS, books=book, check_hash_params=..., rest_endpoint=plp.ENDPOINT.REST, callback_msg=on_market_message, callback_exc=on_exception, ) user_stream = plp.UserStream( ws_endpoint=plp.ENDPOINT.WS, tuple_manager=(order_mgr, pos_mgr), market_triplets=[], api_key="...", secret="...", passphrase="...", callback_msg=on_user_message, callback_exc=on_exception, ) ``` -------------------------------- ### Initialize and Track Positions Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/01-overview.md Initialize a PositionManager with relevant endpoints and an initial cash position. Start the user stream to receive position updates and check balances or buying power. ```python position_manager = PositionManager( rest_endpoint=ENDPOINT.REST, gamma_endpoint=ENDPOINT.GAMMA, usdc_position=100 # Initial cash position ) user_stream.start() user_stream.wait_ready() # Check positions usdc_balance = position_manager.balance buying_power = position_manager.buying_power(order_manager) ``` -------------------------------- ### MarketStream Initialization with CheckHashParams Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Example of initializing a MarketStream with custom hash checking parameters. Set check_hash_params to None to disable hash checking. ```python params = plp.CheckHashParams(nth_price_change=100, max_emission_delay=10) stream = plp.MarketStream( ws_endpoint=plp.ENDPOINT.WS, books=book, check_hash_params=params, rest_endpoint=plp.ENDPOINT.REST, ) ``` -------------------------------- ### Polypy REST API Complete Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/07-rest-api.md Demonstrates fetching market info, order book data, tick size, creating and posting orders, checking open orders, and canceling orders using the Polypy REST API. ```python import polypy as plp from datetime import datetime # Get market info market = plp.get_market(plp.ENDPOINT.REST, "0x...") print(f"Question: {market.question}") print(f"Active: {market.active}") print(f"Accepting orders: {market.accepting_orders}") # Fetch order book books = plp.get_book_summaries( endpoint=plp.ENDPOINT.REST, token_ids=[market.tokens[0].token_id], ) book = books[0] print(f"Mid price: {book.mid_price}") # Get tick size tick_size = plp.get_tick_size( endpoint=plp.ENDPOINT.REST, token_id=market.tokens[0].token_id, ) # Create and post order order = plp.create_limit_order( price=float(book.mid_price), size=10, token_id=market.tokens[0].token_id, side=plp.SIDE.BUY, tick_size=tick_size, neg_risk=market.neg_risk, chain_id=plp.CHAIN_ID.POLYGON, private_key="0x...", maker="0x...", signature_type=plp.SIGNATURE_TYPE.EOA, ) resp = plp.post_order( endpoint=plp.ENDPOINT.REST, order=order, private_key="0x...", api_key="...", secret="...", passphrase="...", ) print(f"Posted: {resp.success}, Order ID: {resp.orderID}") # Check open orders open_orders = plp.get_orders_info( endpoint=plp.ENDPOINT.REST, order_ids=None, private_key="0x...", api_key="...", secret="...", passphrase="...", ) print(f"Open orders: {len(open_orders)}") # Cancel order cancel_resp = plp.cancel_orders( endpoint=plp.ENDPOINT.REST, orders=order, private_key="0x...", api_key="...", secret="...", passphrase="...", ) print(f"Canceled: {cancel_resp.canceled}") ``` -------------------------------- ### Integrate Market Data Stream Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/01-overview.md Set up and start a market data stream to receive real-time updates for an order book. Access the best bid and ask prices directly from the updated book object. ```python # Create and start market updates book = OrderBook(token_id="...", tick_size=0.01) market_stream = MarketStream( ws_endpoint=ENDPOINT.WS, books=book, check_hash_params=CheckHashParams(nth_price_change=100, max_emission_delay=10), rest_endpoint=ENDPOINT.REST ) market_stream.start() market_stream.wait_ready() # Access updated book best_bid = book.best_bid_price best_ask = book.best_ask_price ``` -------------------------------- ### Floating Point Imprecision Example Source: https://github.com/hbr-l/polypy/blob/main/docs/guide.md Demonstrates the potential for floating-point imprecision in standard Python arithmetic. ```python 0.1 * 3 >> 0.30000000000000004 # instead of 0.3 ``` -------------------------------- ### SharedOrderBook Usage Example Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/04-orderbook.md Demonstrates how to initialize a SharedOrderBook in a parent process and access the same order book from a child process using the shared memory name. Ensure shared memory names for bid and ask arrays are unique if using SharedDecimalArray factories. ```python from polypy.book import SharedOrderBook from polypy.ipc import SharedDecimalArray # Parent process book = SharedOrderBook( token_id="...", tick_size=0.01, shm_name="my_orderbook_shared", zeros_factory_bid=SharedDecimalArray.factory("my_bid_shared"), zeros_factory_ask=SharedDecimalArray.factory("my_ask_shared"), ) # Child process can access same book child_book = SharedOrderBook( token_id="...", shm_name="my_orderbook_shared", ) ``` -------------------------------- ### Handle SubscriptionException Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/11-exceptions.md Example of catching and handling a SubscriptionException during stream operations. Includes a retry mechanism with a delay. ```python try: stream.start() stream.wait_ready(timeout=10) except plp.SubscriptionException as e: print(f"Stream connection failed: {e}") # Retry with backoff time.sleep(5) stream.start() ``` -------------------------------- ### Get Generic Token Balance Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Fetches the balance of a specified token in wei. Most tokens are scaled by 1e6. ```python def get_balance_token( w3: W3POA, chain_id: CHAIN_ID, token_id: str, address: str, ) -> int ``` -------------------------------- ### get() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Search tracked orders by criteria. This method allows for flexible querying of orders based on various optional parameters like ID, status, token ID, side, and strategy ID. Multiple criteria are combined with AND logic. ```APIDOC ## get() ### Description Search tracked orders by criteria. ### Method GET (conceptual) ### Parameters #### Query Parameters - **id** (string) - Optional - Exact order ID - **status** (string or list[string]) - Optional - Order status (or list of statuses) - **token_id** (string) - Optional - Token ID - **side** (string) - Optional - BUY or SELL - **strategy_id** (string) - Optional - Strategy label ### Response #### Success Response - **list[FrozenOrder]** - List of frozen (read-only) orders ### Request Example ```python # Find all live orders for a token live_orders = order_manager.get(token_id="0x...", status=plp.INSERT_STATUS.LIVE) # Find all buy orders in a strategy buy_orders = order_manager.get(side=plp.SIDE.BUY, strategy_id="my_strat") ``` ``` -------------------------------- ### Get POL Balance Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Retrieves the POL (MATIC) balance in wei. ```python def get_balance_POL(w3: W3POA, address: str) -> Wei ``` -------------------------------- ### get Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Retrieves a specific position by its asset ID or a list of all positions if no asset ID is provided. ```APIDOC ## get() ### Description Retrieve position(s) by asset. ### Parameters - **asset_id** (str | None) - Optional - Specific token/USDC position - **kwargs** - Additional keyword arguments ### Returns Single position or list of positions ``` -------------------------------- ### Get First Element from Iterable Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/10-utilities.md Retrieves the first element from an iterable, offering efficiency for sets. ```python def first_iterable_element(s: set[T] | Iterable[T]) -> T: pass ``` -------------------------------- ### Initialize PositionManager and UserStream Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/08-positions.md Demonstrates initializing a PositionManager with the standard Position class and setting up a UserStream for real-time position updates. The UserStream automatically updates the PositionManager's state. ```python # PositionManager uses Position internally pos_mgr = plp.PositionManager( rest_endpoint=plp.ENDPOINT.REST, gamma_endpoint=plp.ENDPOINT.GAMMA, usdc_position=1000, position_factory=plp.Position, # Use Position class n_digits_size=plp.N_DIGITS_SIZE, ) # User stream automatically updates positions user_stream = plp.UserStream( ws_endpoint=plp.ENDPOINT.WS, tuple_manager=pos_mgr, market_triplets=[], api_key="...", secret="...", passphrase="...", ) user_stream.start() # Positions update automatically via stream time.sleep(5) # Access updated positions print(pos_mgr.balance) # Current USDC print(pos_mgr.total) # All positions ``` -------------------------------- ### Initialize OrderBook Class Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/04-orderbook.md Instantiates an OrderBook object with various configuration parameters. Use this to set up a new order book for a specific token, defining tick size, market conditions, and data types. ```python class OrderBook: def __init__( self, token_id: str, tick_size: NumericAlias, market_id: str | None = None, min_order_size: int | None = None, neg_risk: bool | None = None, dtype: type = float, zeros_factory_bid: ZerosFactoryFunc = np.zeros, zeros_factory_ask: ZerosFactoryFunc = np.zeros, coerce_inbound_prices: bool = False, strict_type_check: bool = False, ) -> None ``` -------------------------------- ### Handle RelayerException Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/11-exceptions.md Example of catching and handling a RelayerException. It demonstrates conditional retrying, either with fallback or by bypassing the relayer. ```python try: mtx = plp.split_positions( ..., endpoint_relayer=plp.ENDPOINT.RELAYER, ) except plp.RelayerException as e: if "allow_fallback_unrelayed": # Already retried on-chain raise else: # Retry on-chain without relayer mtx = plp.split_positions( ..., endpoint_relayer=None, ) ``` -------------------------------- ### Get Current Prices Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/07-rest-api.md Fetches the current prices for specified tokens or markets. Can filter by token IDs or market IDs. ```python def get_prices( endpoint: str | ENDPOINT, token_ids: list[str] | None = None, market_ids: list[str] | None = None, ) -> dict[str, float] ``` -------------------------------- ### Place a Limit Order and Check Status Source: https://github.com/hbr-l/polypy/blob/main/README.md This snippet shows how to place a limit order using the OrderManager and then check its status after a delay. It also demonstrates how to retrieve the current cash balance and buying power from the PositionManager. ```python # post an order 1 tick size above current best bid best_bid = book.best_bid_price order, response = order_manager.limit_order( price=best_bid + book.tick_size, size=10, token_id="yes_token_id", side=plp.SIDE.BUY, tick_size=book.tick_size, tif=plp.TIME_IN_FORCE.GTC, expiration=None, neg_risk=None ) # check after 10 seconds time.sleep(10) # check order status status = order_manager.get_by_id(order.id).status # check cash position balance = position_manager.balance # check buying power (to submit next buy order) position_manager.buying_power(order_manager) ``` -------------------------------- ### RPCSettings Class Definition Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Defines the configuration object for RPC operations. It can be reused across multiple operations, simplifying setup. ```python class RPCSettings: def __init__( self, w3: W3POA, chain_id: CHAIN_ID, private_key: str | PrivateKey | PrivateKeyType, maker_funder: str, gas_factor: NumericAlias = 1.0, max_gas_price: int | None = None, allow_fallback_unrelayed: bool = False, endpoint_relayer: str | ENDPOINT | None = None, cookies: dict[str, str] | None = None, max_gas_limit_relayer: int | None = None, receipt_timeout: float | None = 300, ) -> None ``` -------------------------------- ### Get Order by ID Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Retrieve a specific order using its unique ID. Returns the frozen order object or None if not found. ```python def get_by_id(self, order_id: str) -> FrozenOrder | None ``` -------------------------------- ### Initialize OrderBook Source: https://github.com/hbr-l/polypy/blob/main/docs/guide.md Instantiate an OrderBook object with a token ID and tick size. The token ID must be specified by the user. ```python import polypy as plp token_id = "..." # needs to be specified by user tick_size = 0.01 book = plp.OrderBook(token_id, tick_size) ``` -------------------------------- ### ready() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Provides a non-blocking check to determine if the WebSocket stream is currently connected and ready to process data. ```APIDOC ## ready() ```python def ready() -> bool ``` Check if stream is ready (non-blocking). ``` -------------------------------- ### RPCSettings Class Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Configuration object for RPC operations. It can be reused across multiple operations, simplifying the setup for various transaction types. ```APIDOC ## RPCSettings Class ### Description Configuration object for RPC operations. Can be reused across multiple operations. ### Parameters - **w3** (W3POA) - Required - Web3 instance with POA support. - **chain_id** (CHAIN_ID) - Required - The ID of the blockchain. - **private_key** (str | PrivateKey | PrivateKeyType) - Required - The private key for signing transactions. - **maker_funder** (str) - Required - The address of the maker funder. - **gas_factor** (NumericAlias) - Optional - Multiplier for gas price. Defaults to 1.0. - **max_gas_price** (int | None) - Optional - Maximum gas price allowed in wei. - **allow_fallback_unrelayed** (bool) - Optional - Whether to allow fallback for unrelayed transactions. Defaults to False. - **endpoint_relayer** (str | ENDPOINT | None) - Optional - The relayer endpoint. - **cookies** (dict[str, str] | None) - Optional - Cookies for the relayer. - **max_gas_limit_relayer** (int | None) - Optional - Maximum gas limit for the relayer. - **receipt_timeout** (float | None) - Optional - Timeout for transaction receipt in seconds. Defaults to 300. ``` -------------------------------- ### Handle OrderPlacementMarketNotReady Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/11-exceptions.md Shows how to catch OrderPlacementMarketNotReady when a market is not yet accepting orders. It includes logic to wait until the market is ready. ```python try: order, resp = order_manager.limit_order(...) except plp.OrderPlacementMarketNotReady as e: # Retry after accepting_order_timestamp market = plp.get_market(plp.ENDPOINT.REST, market_id) if market.accepting_order_timestamp: wait_until = market.accepting_order_timestamp print(f"Market ready at {wait_until}") time.sleep(wait_until - datetime.now().timestamp()) ``` -------------------------------- ### Initialize PositionManager with CSMPosition Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/08-positions.md Shows how to initialize a PositionManager using the CSMPosition class for more robust position tracking. This is an alternative to using the default Position class. ```python # Or use CSMPosition for more robust tracking pos_mgr_robust = plp.PositionManager( rest_endpoint=plp.ENDPOINT.REST, gamma_endpoint=plp.ENDPOINT.GAMMA, usdc_position=1000, position_factory=plp.CSMPosition, # Use CSMPosition ) ``` -------------------------------- ### Get USDC Allowance Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Checks the USDC approval amount for the Conditional contract. Requires a Web3 instance, chain ID, and wallet address. ```python def get_allowance_USDC( w3: W3POA, chain_id: CHAIN_ID, address: str, ) -> Decimal ``` -------------------------------- ### Get USDC Balance Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/09-rpc-operations.md Retrieves the USDC balance in wei, scaled by 1e6. Requires a Web3 instance, chain ID, and wallet address. ```python def get_balance_USDC( w3: W3POA, chain_id: CHAIN_ID, address: str, ) -> Decimal ``` ```python balance_wei = plp.get_balance_USDC(w3, plp.CHAIN_ID.POLYGON, "0x...") balance_usdc = int(balance_wei) / 1e6 print(f"USDC: ${balance_usdc}") ``` -------------------------------- ### Example of Float Imprecision Source: https://github.com/hbr-l/polypy/blob/main/README.md Demonstrates floating-point imprecision in Python and how Polypy attempts to counteract it with rounding. For critical precision, consider using Python's `decimal.Decimal`. ```python 0.1 + 0.2 == 0.30000000000000004 ``` ```python plp.round_down(123.46 - 0.2, 6) == py_clob_client.order_builder.helpers.round_down(123.46 - 0.2, 6) != 123.26 -> 123.259999 ``` -------------------------------- ### sync() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/04-orderbook.md Fetches the complete order book from a REST endpoint. ```APIDOC ## sync() ### Description Fetch complete order book from REST endpoint. ### Method Signature ```python def sync(self, endpoint: str | ENDPOINT) -> None ``` ### Parameters - `endpoint` (str | ENDPOINT) - REST API endpoint (e.g., `ENDPOINT.REST`) ### Raises - `OrderBookException` if sync fails ### Example ```python book = OrderBook(token_id="...", tick_size=0.01) book.sync(ENDPOINT.REST) print(book.best_bid_price) # Updated ``` ``` -------------------------------- ### wait_ready() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Blocks execution until the WebSocket stream is successfully connected and the initial market data (books) are synchronized. It can be configured with a timeout. ```APIDOC ## wait_ready() ```python def wait_ready(timeout: float | None = None) -> bool ``` Wait until stream is connected and books are ready. **Parameters**: - `timeout` — Max seconds to wait; None = indefinite **Returns**: True if ready, False if timeout **Example**: ```python stream.start() if stream.wait_ready(timeout=10): # Books are synced print(stream.books[0].best_bid_price) else: print("Stream connection timeout") ``` ``` -------------------------------- ### AugmentedConversionCache Initialization Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Initializes a cache for augmented negative-risk conversions to reduce redundant Gamma API calls. ```python class AugmentedConversionCache: def __init__(self, gamma_endpoint: str | ENDPOINT) -> None: # ... implementation details ... pass ``` -------------------------------- ### Get Tick Size for a Token Source: https://github.com/hbr-l/polypy/blob/main/docs/guide.md Retrieve the tick size for a specific token using the polypy library's REST endpoint. Ensure you have the correct token ID. ```python import polypy as plp token_id = "..." # ID of token tick_size = plp.get_tick_size(plp.ENDPOINT.REST, token_id) ``` -------------------------------- ### Create and Post Market Order Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Use this method to create and submit a market order. It requires amount, token_id, side, and tick_size. The tif parameter defaults to FOK (Fill Or Kill). ```python def market_order( amount: NumericAlias, token_id: str, side: SIDE, tick_size: NumericAlias | float, tif: TIME_IN_FORCE = TIME_IN_FORCE.FOK, neg_risk: bool | None = None, strategy_id: str | None = None, salt: int | None = None, **kwargs, ) -> tuple[FrozenOrder, PostOrderResponse] ``` -------------------------------- ### RPCSettings Initialization Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Configures settings for on-chain RPC operations including splits, merges, redeems, and conversions. ```python class RPCSettings: def __init__( self, w3: W3POA, chain_id: CHAIN_ID, private_key: str | PrivateKey | PrivateKeyType, maker_funder: str, gas_factor: NumericAlias = 1.0, max_gas_price: int | None = None, allow_fallback_unrelayed: bool = False, endpoint_relayer: str | ENDPOINT | None = None, cookies: dict[str, str] | None = None, max_gas_limit_relayer: int | None = None, receipt_timeout: float | None = 300, ) -> None: # ... implementation details ... pass ``` -------------------------------- ### UserStream.ready() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/06-streams.md Checks if the stream is currently ready (connected and authenticated) in a non-blocking manner. ```APIDOC ## ready() ### Description Check if stream is ready (non-blocking). ### Method ```python def ready() -> bool ``` ### Returns - bool: True if the stream is ready, False otherwise. ``` -------------------------------- ### Get Open Order Information Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/07-rest-api.md Retrieve details for open orders. Can fetch information for specific order IDs or all open orders by passing None for order_ids. Requires authentication. ```python def get_orders_info( endpoint: str | ENDPOINT, order_ids: list[str] | str | None, private_key: str | PrivateKey | PrivateKeyType, api_key: str, secret: str, passphrase: str, ) -> list[OpenOrderInfo] open_orders = plp.get_orders_info( endpoint=plp.ENDPOINT.REST, order_ids=None, # All orders private_key=private_key, api_key=api_key, secret=secret, passphrase=passphrase, ) for oi in open_orders: print(f"{oi.id}: {oi.status}") ``` -------------------------------- ### Create Market Order Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/03-orders.md Use this function to create a market order that executes immediately at the best available price. Ensure all required parameters like amount, token_id, side, and private_key are provided. ```python def create_market_order( amount: NumericAlias, token_id: str, side: SIDE, tick_size: float | NumericAlias, neg_risk: bool, chain_id: CHAIN_ID, private_key: PrivateKey | str | PrivateKeyType, maker: str | None, signature_type: SIGNATURE_TYPE, tif: TIME_IN_FORCE = TIME_IN_FORCE.FOK, salt: int | None = None, order_id: str | None = None, signature: str | None = None, strategy_id: str | None = None, aux_id: str | None = None, status: INSERT_STATUS = INSERT_STATUS.DEFINED, size_matched: NumericAlias | None = None, created_at: int | None = None, defined_at: int | None = None, expiration: int = 0, nonce: int = 0, fee_rate_bps: int = 0, taker: str = ZERO_ADDRESS, signer: str | None = None, ) -> Order ``` ```python order = create_market_order( amount=50.0, # $50 USDC notional token_id="0x1234...", side=SIDE.BUY, tick_size=0.01, neg_risk=False, chain_id=CHAIN_ID.POLYGON, private_key="0x...", maker="0x...", signature_type=SIGNATURE_TYPE.EOA, tif=TIME_IN_FORCE.FOK ) # Market order will execute immediately; size derived from amount/price print(f"Amount: {order.amount}") print(f"Size: {order.size}") ``` -------------------------------- ### Get Position by Asset Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Retrieves a specific token or USDC position, or a list of all positions if no asset ID is provided. Supports additional keyword arguments for filtering or specific retrieval logic. ```python def get( self, asset_id: str | None = None, **kwargs, ) -> PositionProtocol | None | list[PositionProtocol]: # Retrieve position(s) by asset. # Parameters: # - asset_id — Specific token/USDC position # Returns: Single position or list pass ``` -------------------------------- ### Create and Post Limit Order Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Use this method to create and submit a limit order to the exchange. Ensure all required parameters like price, size, token_id, side, and tick_size are provided. The tif parameter defaults to GTC (Good 'Til Cancelled). ```python def limit_order( price: NumericAlias, size: NumericAlias, token_id: str, side: SIDE, tick_size: NumericAlias | float, tif: TIME_IN_FORCE = TIME_IN_FORCE.GTC, expiration: int | None = None, neg_risk: bool | None = None, strategy_id: str | None = None, salt: int | None = None, **kwargs, ) -> tuple[FrozenOrder, PostOrderResponse] ``` ```python order, response = order_manager.limit_order( price=0.55, size=10, token_id="0x...", side=plp.SIDE.BUY, tick_size=0.01, tif=plp.TIME_IN_FORCE.GTC, strategy_id="my_strat" ) print(f"Order {order.id} posted: {response.status}") ``` -------------------------------- ### Get EIP-712 Domain for Signing Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/10-utilities.md Retrieves the EIP-712 domain structure necessary for signing orders on specific chains. Parameters include chain ID and a flag for negative risk markets. ```python @lru_cache(maxsize=4) def polymarket_domain( chain_id: CHAIN_ID, neg_risk: bool, ) -> EIP712Struct: # Implementation details omitted for brevity pass ``` -------------------------------- ### Handle OrderPlacementFailure Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/11-exceptions.md Demonstrates catching OrderPlacementFailure for server-side rejections or network errors during order submission. It shows how to access the 'order' attribute for details. ```python try: order, resp = order_manager.limit_order(...) except plp.OrderPlacementFailure as e: print(f"Failed to post: {e}") print(f"Order ID: {e.order.id}") # Inspect order for retry logic if "invalid_signature" in str(e): # Regenerate signature pass ``` -------------------------------- ### Get Orders by Criteria Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Search tracked orders using optional query parameters like ID, status, token ID, side, or strategy ID. Returns a list of frozen orders. ```python def get(self, **kwargs) -> list[FrozenOrder] ``` ```python # Find all live orders for a token live_orders = order_manager.get(token_id="0x...", status=plp.INSERT_STATUS.LIVE) # Find all buy orders in a strategy buy_orders = order_manager.get(side=plp.SIDE.BUY, strategy_id="my_strat") ``` -------------------------------- ### market_order() Source: https://github.com/hbr-l/polypy/blob/main/_autodocs/05-managers.md Creates and posts a market order in a single step. This method is used for immediate execution at the best available market price. ```APIDOC ## market_order() Create and post a market order in one step. ### Parameters Similar to `limit_order()`, but with `amount` instead of `price` and `size`. ### Returns - `tuple[FrozenOrder, PostOrderResponse]` - A tuple containing the created frozen order and the REST API response. ```