### Complete Feed Configuration Example Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/configuration.md A comprehensive example showing the setup of the FeedClient, including WebSocket URL, error handling, callback registration, and starting the price update listener. ```python from avantis_trader_sdk import TraderClient, FeedClient from avantis_trader_sdk.types import TradeInput import avantis_trader_sdk # Trader client configuration (used for getting trade related parameters) provider_url = "https://mainnet.base.org" # Replace with the provider URL for the Base Mainnet Chain trader_client = TraderClient(provider_url) # Real-time price feed configuration (used for getting real-time prices of the pairs) # **This can be skipped if you don't need real-time price updates** ws_url = "wss://" def ws_error_handler(e): print(f"Websocket error: {e}") feed_client = FeedClient( ws_url, on_error=ws_error_handler, on_close=ws_error_handler ) feed_client.register_price_feed_callback( "0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace", lambda data: print(data), ) feed_client.register_price_feed_callback("ETH/USD", lambda data: print(data)) await feed_client.listen_for_price_updates() def ws_error_handler(e): print(f"Websocket error: {e}") ``` -------------------------------- ### Basic Trader Setup and Address Retrieval Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md An asynchronous example demonstrating the basic setup of TraderClient, setting a local signer, and retrieving the trader's Ethereum address. ```python import asyncio from avantis_trader_sdk import TraderClient async def main(): provider_url = "https://mainnet.base.org" trader_client = TraderClient(provider_url) trader_client.set_local_signer("0xYOUR_PRIVATE_KEY") trader = trader_client.get_signer().get_ethereum_address() print(f"Trader address: {trader}") asyncio.run(main()) ``` -------------------------------- ### Complete Trader Client Configuration Example Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/configuration.md A complete example demonstrating the import and configuration of the TraderClient for trading operations. ```python from avantis_trader_sdk import TraderClient, FeedClient from avantis_trader_sdk.types import TradeInput import avantis_trader_sdk # Trader client configuration (used for getting trade related parameters) provider_url = "https://mainnet.base.org" # Replace with the provider URL for the Base Mainnet Chain trader_client = TraderClient(provider_url) ``` -------------------------------- ### Install SDK from GitHub Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/getting_started.md Install the Avantis Trader SDK directly from its GitHub repository using pip. ```bash pip install git+https://github.com/Avantis-Labs/avantis_trader_sdk.git ``` -------------------------------- ### Install SDK using pip Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/getting_started.md Install the Avantis Trader SDK from PyPI. Ensure Python 3.6+ is installed. ```bash pip install avantis-trader-sdk ``` -------------------------------- ### Install SDK from Local Source Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/getting_started.md Install the Avantis Trader SDK from a local clone of the source code. This requires git and pip. ```bash git clone https://github.com/yourusername/avantis-trader-sdk.git cd avantis-trader-sdk pip install . ``` -------------------------------- ### Verify SDK Installation Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/getting_started.md Verify the Avantis Trader SDK installation by importing it and printing its version. This confirms the SDK is accessible in your Python environment. ```python import avantis_trader_sdk print(avantis_trader_sdk.__version__) ``` -------------------------------- ### Python Example: Placing a Limit Order Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/trade.md This snippet demonstrates how to initialize the TraderClient, set up a limit order with a specific open price, calculate fees, and submit the transaction. ```python import asyncio from avantis_trader_sdk import TraderClient, TradeInput, TradeInputOrderType private_key = "0xmyprivatekey" async def main(): # Initialize TraderClient provider_url = "https://mainnet.base.org" # Find provider URL for Base Mainnet Chain from https://chainlist.org/chain/8453 or use a dedicated node (Alchemy, Infura, etc.) trader_client = TraderClient(provider_url) # Set local signer trader_client.set_local_signer(private_key) # Alternatively, you can use set_aws_kms_signer() to use a key from AWS KMS or create your own signer by inheriting BaseSigner class trader = trader_client.get_signer().get_ethereum_address() # Get trader's USDC balance balance = await trader_client.get_usdc_balance(trader) print(f"Balance of {trader} is {balance} USDC") # Check allowance of USDC allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"Allowance of {trader} is {allowance} USDC") amount_of_collateral = 10 if allowance < amount_of_collateral: print(f"Allowance of {trader} is less than {amount_of_collateral} USDC. Approving...") await trader_client.approve_usdc_for_trading(amount_of_collateral) allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"New allowance of {trader} is {allowance} USDC") # Get pair index of the pair. For example, ETH/USD pair_index_of_eth_usd = await trader_client.pairs_cache.get_pair_index("ETH/USD") # Prepare trade input trade_input = TradeInput( trader=trader, # Trader's wallet address open_price=1500, # Open price of the trade (Desired execution price) pair_index=pair_index_of_eth_usd, # Pair index collateral_in_trade=amount_of_collateral, # Amount of collateral in trade (in USDC) is_long=True, # True for long, False for short leverage=25, # Leverage for the trade index=0, # This is the index of the trade for a pair (0 for the first trade, 1 for the second, etc.) tp=4000.5, # Take profit price. Max allowed is 500% of open price. sl=0, # Stop loss price timestamp=0, # Timestamp of the trade. 0 for now ) # --------------------------------------------- # Get opening fee data opening_fee_usdc = await trader_client.fee_parameters.get_opening_fee( trade_input=trade_input ) print(f"Opening fee for this trade: {opening_fee_usdc} USDC") # Get loss protection percentage loss_protection_info = ( await trader_client.trading_parameters.get_loss_protection_for_trade_input( trade_input, opening_fee_usdc=opening_fee_usdc ) ) print(f"Loss protection percentage for this trade: {loss_protection_info.percentage}%") print(f"You'll receive up to ${loss_protection_info.amount} as a loss rebate if the trade goes against you.") # --------------------------------------------- # 1% slippage slippage_percentage = 1 # Order type for the trade (LIMIT in this case) trade_input_order_type = TradeInputOrderType.LIMIT # Open trade as a limit order open_transaction = await trader_client.trade.build_trade_open_tx( trade_input, trade_input_order_type, slippage_percentage ) receipt = await trader_client.sign_and_get_receipt(open_transaction) print(receipt) print("Order placed successfully!") # Run the example asyncio.run(main()) ``` -------------------------------- ### Start Listening for Price Updates Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/configuration.md Initiate listening for real-time price updates using the `listen_for_price_updates()` method. This function is asynchronous. ```python await feed_client.listen_for_price_updates() ``` -------------------------------- ### Build and Sign Transactions Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Demonstrates the process of building a trade open transaction and then signing and sending it to the network to get a transaction receipt. ```python # Build transaction transaction = await trader_client.trade.build_trade_open_tx(...) # Sign and send receipt = await trader_client.sign_and_get_receipt(transaction) ``` -------------------------------- ### Get Trading Snapshot Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Retrieves the current snapshot of trading parameters, including open interest, asset utilization, and skew. Use this to get the latest market state. ```python snapshot = await trader_client.snapshot.get_snapshot() print("Snapshot:", snapshot) ``` -------------------------------- ### Get All Pairs Information Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves and prints information for all available trading pairs. Requires an active trader client. ```python pairs_info = await trader_client.pairs_cache.get_pairs_info() for index, pair in pairs_info.items(): print(f"{index}: {pair.from_}/{pair.to}") ``` -------------------------------- ### Quick Start: Open a Trade Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/README.md Initialize the TraderClient, set your signer, check and approve USDC allowance, and then open a market order for a long ETH position with specified collateral, leverage, take profit, and stop loss. ```python import asyncio from avantis_trader_sdk import TraderClient from avantis_trader_sdk.types import TradeInput, TradeInputOrderType async def main(): # Initialize client trader_client = TraderClient("https://mainnet.base.org") trader_client.set_local_signer("0xYOUR_PRIVATE_KEY") trader = trader_client.get_signer().get_ethereum_address() # Check and approve USDC allowance allowance = await trader_client.get_usdc_allowance_for_trading(trader) if allowance < 100: await trader_client.approve_usdc_for_trading(100) # Open a 10x long ETH position with $100 collateral trade_input = TradeInput( trader=trader, pair_index=1, # ETH/USD collateral_in_trade=100, is_long=True, leverage=10, tp=5000, # take profit sl=2500, # stop loss ) tx = await trader_client.trade.build_trade_open_tx( trade_input, TradeInputOrderType.MARKET, slippage_percentage=1 ) receipt = await trader_client.sign_and_get_receipt(tx) print("Trade opened!", receipt.transactionHash.hex()) asyncio.run(main()) ``` -------------------------------- ### Get Pair Information Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/getting_started.md Connect to the Avantis platform and retrieve information about available trading pairs. Requires asyncio and the TraderClient. ```python import asyncio from avantis_trader_sdk import TraderClient, __version__ import avantis_trader_sdk print(avantis_trader_sdk.__version__) async def main(): provider_url = "https://mainnet.base.org" trader_client = TraderClient(provider_url) print("----- GETTING PAIR INFO -----") result = await trader_client.pairs_cache.get_pairs_info() print(result) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Python Example: Updating Trade Margin Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/trade.md This script demonstrates how to deposit or withdraw collateral from an open trade. It includes steps for initializing the TraderClient, checking and approving USDC allowance, building the margin update transaction, and signing it. Ensure you have sufficient allowance before depositing. ```python import asyncio from avantis_trader_sdk import TraderClient, MarginUpdateType private_key = "0xmyprivatekey" async def main(): # Initialize TraderClient provider_url = "https://mainnet.base.org" # Find provider URL for Base Mainnet Chain from https://chainlist.org/chain/8453 or use a dedicated node (Alchemy, Infura, etc.) trader_client = TraderClient(provider_url) # Set local signer trader_client.set_local_signer(private_key) # Alternatively, you can use set_aws_kms_signer() to use a key from AWS KMS or create your own signer by inheriting BaseSigner class trader = trader_client.get_signer().get_ethereum_address() # Get open trades trades, _ = await trader_client.trade.get_trades(trader) print("Trades: ", trades) # Select first trade to update trade_to_update = trades[0] # Check allowance of USDC allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"Allowance of {trader} is {allowance} USDC") amount_of_collateral = 5 if allowance < amount_of_collateral: print(f"Allowance of {trader} is less than {amount_of_collateral} USDC. Approving...") await trader_client.approve_usdc_for_trading(amount_of_collateral) allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"New allowance of {trader} is {allowance} USDC") # --------------------------------------------- # NOTE: Any accrued margin fee on the trade will # be deducted from the deposited amount # --------------------------------------------- # Update trade margin deposit_transaction = await trader_client.trade.build_trade_margin_update_tx( trader=trader, pair_index=trade_to_update.trade.pair_index, trade_index=trade_to_update.trade.trade_index, margin_update_type=MarginUpdateType.DEPOSIT, # Type of margin update (DEPOSIT or WITHDRAW) # margin_update_type=MarginUpdateType.WITHDRAW, # Uncomment this to withdraw collateral collateral_change=amount_of_collateral, # Amount of collateral to deposit or withdraw ) receipt = await trader_client.sign_and_get_receipt(private_key, deposit_transaction) print(receipt) print("Trade updated successfully!") # Run the example asyncio.run(main()) ``` -------------------------------- ### Get Trading Fees Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves the opening fee for a new trade. This is crucial for calculating the cost of initiating a trade. ```APIDOC ## Get Trading Fees ### Description Retrieves the opening fee for a new trade. ### Method Asynchronous function call ### Endpoint `trader_client.fee_parameters.get_new_trade_opening_fee(trade_input)` ### Parameters #### Request Body - **trade_input** (TradeInput): An object representing the trade details for which to calculate the fee. ### Response - **opening_fee** (float): The calculated opening fee in USDC. ``` -------------------------------- ### BaseSigner.get_ethereum_address Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/api_reference.md Abstract method to get the Ethereum address. ```APIDOC ## get_ethereum_address() Abstract method to get the Ethereum address. ``` -------------------------------- ### Get Market Snapshot Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves a snapshot of the market, including open interest, utilization, and skew for all groups and pairs. ```APIDOC ## Get Market Snapshot ### Description Retrieves a snapshot of the market, including open interest, utilization, and skew for all groups and pairs. ### Method Asynchronous function call ### Endpoint `trader_client.snapshot.get_snapshot()` ### Parameters None ### Response - **snapshot** (object): An object containing market snapshot data, including open interest, utilization, and skew. ``` -------------------------------- ### Get New Trade Opening Fee Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Calculates the opening fee for a new trade. Requires a trade input object and an active trader client. ```python # Get opening fee for a trade opening_fee = await trader_client.fee_parameters.get_new_trade_opening_fee(trade_input) print(f"Opening fee: {opening_fee} USDC") ``` -------------------------------- ### Get All Pairs Info Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves comprehensive information for all available trading pairs. This is useful for understanding the available markets and their details. ```APIDOC ## Get All Pairs Info ### Description Retrieves comprehensive information for all available trading pairs. ### Method Asynchronous function call ### Endpoint `trader_client.pairs_cache.get_pairs_info()` ### Parameters None ### Response - **pairs_info** (dict): A dictionary where keys are pair indices and values are pair objects containing `from_` and `to` currency information. ``` -------------------------------- ### Open and Close Trade with Avantis Trader SDK Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md This Python script demonstrates the full lifecycle of a trade, from setup and collateral approval to opening a long position and subsequently closing it. Ensure you have set up your local signer with a valid private key. ```python import asyncio from avantis_trader_sdk import TraderClient from avantis_trader_sdk.types import TradeInput, TradeInputOrderType async def main(): # Setup trader_client = TraderClient("https://mainnet.base.org") trader_client.set_local_signer("0xYOUR_PRIVATE_KEY") trader = trader_client.get_signer().get_ethereum_address() # Check and approve USDC allowance = await trader_client.get_usdc_allowance_for_trading(trader) if allowance < 100: await trader_client.approve_usdc_for_trading(100) # Open long ETH position trade_input = TradeInput( trader=trader, pair_index=1, # ETH/USD collateral_in_trade=100, is_long=True, leverage=10, tp=5000, sl=2500, ) open_tx = await trader_client.trade.build_trade_open_tx( trade_input, TradeInputOrderType.MARKET, slippage_percentage=1 ) await trader_client.sign_and_get_receipt(open_tx) print("Trade opened!") # Wait for execution await asyncio.sleep(30) # Get trades and close trades, _ = await trader_client.trade.get_trades(trader) if trades: trade = trades[0] close_tx = await trader_client.trade.build_trade_close_tx( pair_index=trade.trade.pair_index, trade_index=trade.trade.trade_index, collateral_to_close=trade.trade.collateral_in_trade, trader=trader, ) await trader_client.sign_and_get_receipt(close_tx) print("Trade closed!") asyncio.run(main()) ``` -------------------------------- ### Get Market Snapshot Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves a market snapshot containing open interest, utilization, and skew for all groups and pairs. Requires an active trader client. ```python snapshot = await trader_client.snapshot.get_snapshot() # Contains open interest, utilization, skew for all groups/pairs ``` -------------------------------- ### Get Opening Fees for All Pairs and Both Directions Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Call get_opening_fee without specifying 'is_long' or 'pair' to retrieve both long and short opening fees for all trading pairs. This is useful for a complete market fee analysis. ```python opening_fee = await trader_client.fee_parameters.get_opening_fee(position_size=1000) print("Opening Fee for all pairs (Long):", opening_fee.long) print("Opening Fee for all pairs (Short):", opening_fee.short) ``` -------------------------------- ### Listen for Price Updates Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Starts listening for real-time price updates from the Pyth price feed websocket. This is an asynchronous coroutine that must be awaited. Registered callbacks will be invoked upon receiving updates. ```python async def price_update_callback(data): print("Price Update:", data) feed_client.register_price_feed_callback("ETH/USD", price_update_callback) await feed_client.listen_for_price_updates() ``` -------------------------------- ### Get Loss Protection for Trade Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves loss protection details for a trade, including percentage and maximum rebate amount. Requires trade input and opening fee. ```python loss_protection = await trader_client.trading_parameters.get_loss_protection_for_trade_input( trade_input, opening_fee_usdc=opening_fee ) print(f"Loss protection: {loss_protection.percentage}%") print(f"Max rebate: ${loss_protection.amount}") ``` -------------------------------- ### TraderClient Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/api_reference.md The TraderClient class provides methods to interact with the Avantis smart contracts. It allows users to approve USDC for trading, get balances, chain IDs, gas prices, transaction counts, and more. It also supports loading contracts, reading from and writing to contracts, and managing signers. ```APIDOC ## TraderClient ### Description This class provides methods to interact with the Avantis smart contracts. ### Methods #### async approve_usdc_for_trading(amount=100000) Approves the USDC amount for the Trading Storage contract. * **Parameters:** * **amount** (*optional*) – The amount to approve. Defaults to $100,000. * **Returns:** The transaction hash. #### async get_balance(address=None) Gets the balance. * **Parameters:** * **address** (*optional*) – The address. * **Returns:** The balance. #### async get_chain_id() Gets the chain id. * **Returns:** The chain id. #### async get_gas_estimate(transaction) Gets the gas estimate. * **Parameters:** * **transaction** – The transaction object. * **Returns:** The gas estimate. #### async get_gas_price() Gets the gas price. * **Returns:** The gas price. #### get_signer() Gets the signer. #### async get_transaction_count(address=None) Gets the transaction count. * **Parameters:** * **address** (*optional*) – The address. * **Returns:** The transaction count. #### async get_transaction_hex(transaction) Gets the transaction hex. * **Parameters:** * **transaction** – The transaction object. * **Returns:** The transaction hex. #### async get_usdc_allowance_for_trading(address=None) Gets the USDC allowance for the Trading Storage contract. * **Parameters:** * **address** (*optional*) – The address. * **Returns:** The USDC allowance. #### async get_usdc_balance(address=None) Gets the USDC balance. * **Parameters:** * **address** (*optional*) – The address. * **Returns:** The USDC balance. #### has_signer() Checks if the signer is set. #### load_contract(name) Loads the contract ABI and address from the local filesystem. * **Parameters:** * **name** – The name of the contract. * **Returns:** A Contract object. #### load_contracts() Loads all the contracts mentioned in the config from the local filesystem. * **Returns:** A dictionary containing the contract names as keys and the Contract objects as values. #### async read_contract(contract_name, function_name, *args, decode=True) Calls a read-only function of a contract. * **Parameters:** * **contract_name** – The name of the contract. * **function_name** – The name of the function. * **args** – The arguments to the function. * **Returns:** The result of the function call. #### remove_signer() Removes the signer. #### async send_and_get_transaction_hash(signed_txn) Gets the transaction hash. * **Parameters:** * **signed_txn** – The signed transaction object. * **Returns:** The transaction hash. #### set_aws_kms_signer(kms_key_id, region_name='us-east-1') Sets the AWS KMS signer. #### set_local_signer(private_key) Sets the local signer. #### set_signer(signer) Sets the signer. * **Parameters:** * **signer** ([*BaseSigner*](avantis_trader_sdk.signers.md#avantis_trader_sdk.signers.base.BaseSigner)) #### async sign_and_get_receipt(transaction) Signs a transaction and waits for it to be mined. * **Parameters:** * **transaction** – The transaction object. * **Returns:** The transaction receipt. #### async sign_transaction(transaction) Signs a transaction. * **Parameters:** * **transaction** – The transaction object. * **Returns:** The signed transaction object. #### async wait_for_transaction_receipt(tx_hash) Waits for the transaction to be mined. * **Parameters:** * **tx_hash** – The transaction hash. * **Returns:** The transaction receipt. #### async write_contract(contract_name, function_name, *args, **kwargs) Calls a write function of a contract. * **Parameters:** * **contract_name** – The name of the contract. * **function_name** – The name of the function. * **args** – The arguments to the function. * **Returns:** The transaction hash or the transaction object if signer is None. ``` -------------------------------- ### Get Open Interest Limits Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Retrieves the maximum allowable open interest for each trading pair. Use this to manage risk and liquidity. Limits are returned in units of the quote currency. ```python oi_limits = await trader_client.asset_parameters.get_oi_limits() print("Open Interest Limits:", oi_limits.limits) ``` -------------------------------- ### Get All Pairs Information Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Retrieves detailed information for all trading pairs. The data is cached by default to optimize blockchain interactions. Set force_update=True to bypass the cache. ```python pairs_info = await trader_client.pairs_cache.get_pairs_info() print("Pairs Info:", pairs_info) ``` -------------------------------- ### Get Trade Referral Rebate Percentage Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Retrieves the trade referral rebate percentage for a trader. This percentage depends on the referrer's tier and offers a discount on trading fees. If no valid referrer is found, the rebate is 0. ```python trader_address = "0xmywalletaddress" rebate_percentage = await trader_client.trading_parameters.get_trade_referral_rebate_percentage(trader_address) print("Trade Referral Rebate Percentage:", rebate_percentage) ``` -------------------------------- ### Get Opening Fees for All Pairs in a Specific Direction Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md To retrieve opening fees for all available trading pairs in a specific direction (e.g., long), omit the 'pair' parameter. This provides a comprehensive overview of fees across the market for that direction. ```python opening_fee = await trader_client.fee_parameters.get_opening_fee(position_size=1000, is_long=True) print("Opening Fee for all pairs (Long):", opening_fee.long) ``` -------------------------------- ### Get Loss Protection Details for Trade Input Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Retrieves both the loss protection percentage and the corresponding amount in USDC for a given trade input. This provides a comprehensive view of the protection offered. ```python trade_input = TradeInput( pair_index=await trader_client.pairs_cache.get_pair_index("ARB/USD"), open_collateral=1, is_long=False, leverage=2, ) loss_protection_info = await trader_client.trading_parameters.get_loss_protection_for_trade_input(trade_input) print("Loss Protection Percentage:", loss_protection_info.percentage) print("Loss Protection Amount in USDC:", loss_protection_info.amount) ``` -------------------------------- ### Get Opening Fee for Specific Pair and Direction Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Use this snippet to retrieve the opening fee for a specific trading pair and direction (long or short). Ensure the pair and is_long parameters are correctly set. ```python opening_fee = await trader_client.fee_parameters.get_opening_fee(position_size=1000, is_long=True, pair="ETH/USD") print("Opening Fee for ETH/USD (Long):", opening_fee.long["ETH/USD"]) ``` -------------------------------- ### Get Open Interest Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Retrieves the current long and short open interest ratios for all trading pairs. This metric indicates market liquidity and trader sentiment. Ratios are returned as percentages. ```python oi = await trader_client.asset_parameters.get_oi() print("Open Interest (Long):", oi.long) print("Open Interest (Short):", oi.short) ``` -------------------------------- ### Get Trading Pair from Feed ID Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Use this method to obtain the trading pair string (e.g., "ETH/USD") associated with a specific price feed ID. The feed ID should be a hexadecimal string. If it doesn't start with "0x", it will be automatically prefixed. ```python pair_string = feed_client.get_pair_from_feed_id("0x09f7c1d7dfbb7df2b8fe3d3d87ee94a2259d212da4f30c1f0540d066dfa44723") print("Pair String:", pair_string) ``` -------------------------------- ### Get Asset Utilization Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Calculates the percentage of the available open interest limit currently being used by open positions for each trading pair. High utilization can impact trading costs. Utilization is returned as a percentage. ```python utilization = await trader_client.asset_parameters.get_utilization() print("Asset Utilization:", utilization.utilization) ``` -------------------------------- ### Get Opening Fees for Both Directions of a Specific Pair Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Omit the 'is_long' parameter to obtain both long and short opening fees for a specified trading pair. This is useful for comparing fees across different trade directions. ```python opening_fee = await trader_client.fee_parameters.get_opening_fee(position_size=1000, pair="ETH/USD") print("Opening Fee for ETH/USD (Long):", opening_fee.long["ETH/USD"]) print("Opening Fee for ETH/USD (Short):", opening_fee.short["ETH/USD"]) ``` -------------------------------- ### Set Up Wallet Delegation Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Builds and signs a transaction to set up a delegate for trading on behalf of a main wallet. Requires the delegate's address and the main wallet's address. ```python # Main wallet sets delegate delegate_address = "0xDELEGATE_ADDRESS" set_delegate_tx = await trader_client.trade.build_set_delegate_tx( delegate=delegate_address, trader=main_wallet_address, ) receipt = await trader_client.sign_and_get_receipt(set_delegate_tx) ``` -------------------------------- ### Open a Market Trade Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/trade.md This snippet demonstrates how to open a market trade using the `build_trade_open_tx` method. It includes initializing the TraderClient, setting up the local signer, checking and approving USDC allowance, retrieving pair indices, preparing the trade input, calculating opening fees and loss protection, and finally building and signing the transaction. ```python import asyncio from avantis_trader_sdk import TraderClient, TradeInput, TradeInputOrderType private_key = "0xmyprivatekey" async def main(): # Initialize TraderClient provider_url = "https://mainnet.base.org" # Find provider URL for Base Mainnet Chain from https://chainlist.org/chain/8453 or use a dedicated node (Alchemy, Infura, etc.) trader_client = TraderClient(provider_url) # Set local signer trader_client.set_local_signer(private_key) # Alternatively, you can use set_aws_kms_signer() to use a key from AWS KMS or create your own signer by inheriting BaseSigner class trader = trader_client.get_signer().get_ethereum_address() # Check allowance of USDC allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"Allowance of {trader} is {allowance} USDC") amount_of_collateral = 10 if allowance < amount_of_collateral: print(f"Allowance of {trader} is less than {amount_of_collateral} USDC. Approving...") await trader_client.approve_usdc_for_trading(amount_of_collateral) allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"New allowance of {trader} is {allowance} USDC") # Get pair index of the pair. For example, ETH/USD pair_index_of_eth_usd = await trader_client.pairs_cache.get_pair_index("ETH/USD") # Prepare trade input trade_input = TradeInput( trader=trader, # Trader's wallet address open_price=None, # (Optional) Open price of the trade. Current price in case of Market orders. If None then it will default to the current price pair_index=pair_index_of_eth_usd, # Pair index collateral_in_trade=amount_of_collateral, # Amount of collateral in trade (in USDC) is_long=True, # True for long, False for short leverage=25, # Leverage for the trade index=0, # This is the index of the trade for a pair (0 for the first trade, 1 for the second, etc.) tp=4000.5, # Take profit price. Max allowed is 500% of open price. sl=0, # Stop loss price timestamp=0, # Timestamp of the trade. 0 for now ) # --------------------------------------------- # Get opening fee data # Read more: https://docs.avantisfi.com/trading/trading-fees/crypto#dynamic-opening-fee-0.04-0.1-position-size opening_fee_usdc = await trader_client.fee_parameters.get_opening_fee( trade_input=trade_input ) print(f"Opening fee for this trade: {opening_fee_usdc} USDC") # Get loss protection percentage # Read more: https://docs.avantisfi.com/rewards/loss-protection loss_protection_info = ( await trader_client.trading_parameters.get_loss_protection_for_trade_input( trade_input, opening_fee_usdc=opening_fee_usdc ) ) print( f"Loss protection percentage for this trade: {loss_protection_info.percentage}%" ) print( f"You'll receive up to ${loss_protection_info.amount} as a loss rebate if the trade goes against you." ) # --------------------------------------------- # 1% slippage slippage_percentage = 1 # Order type for the trade (MARKET or LIMIT or STOP_LIMIT or MARKET_ZERO_FEE) trade_input_order_type = TradeInputOrderType.MARKET # Open trade open_transaction = await trader_client.trade.build_trade_open_tx( trade_input, trade_input_order_type, slippage_percentage ) receipt = await trader_client.sign_and_get_receipt(open_transaction) print(receipt) print("Trade opened successfully!") # Run the example asyncio.run(main()) ``` -------------------------------- ### Get Price Impact Spread for a Specific Pair and Position Type Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Use this snippet to get the price impact spread for a specific trading pair and whether the position is long or short. Requires specifying position size, is_long, and pair. ```python price_impact_spread = await trader_client.asset_parameters.get_price_impact_spread(position_size=1000, is_long=True, pair="ETH/USD") print("Price Impact Spread for ETH/USD (Long):", price_impact_spread.long["ETH/USD"]) ``` -------------------------------- ### Open Zero Fee Market Trade with Python SDK Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/trade.md Use this Python script to initialize the TraderClient, prepare trade inputs, and build a transaction for opening a zero-fee market trade. Ensure correct provider URL and private key are set. The script checks USDC allowance and approves if necessary before opening the trade. ```python import asyncio from avantis_trader_sdk import TraderClient, TradeInput, TradeInputOrderType private_key = "0xmyprivatekey" async def main(): # Initialize TraderClient provider_url = "https://mainnet.base.org" # Find provider URL for Base Mainnet Chain from https://chainlist.org/chain/8453 or use a dedicated node (Alchemy, Infura, etc.) trader_client = TraderClient(provider_url) # Set local signer trader_client.set_local_signer(private_key) # Alternatively, you can use set_aws_kms_signer() to use a key from AWS KMS or create your own signer by inheriting BaseSigner class trader = trader_client.get_signer().get_ethereum_address() # Check allowance of USDC allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"Allowance of {trader} is {allowance} USDC") amount_of_collateral = 10 if allowance < amount_of_collateral: print(f"Allowance of {trader} is less than {amount_of_collateral} USDC. Approving...") await trader_client.approve_usdc_for_trading(amount_of_collateral) allowance = await trader_client.get_usdc_allowance_for_trading(trader) print(f"New allowance of {trader} is {allowance} USDC") # Get pair index of the pair. For example, ETH/USD pair_index_of_eth_usd = await trader_client.pairs_cache.get_pair_index("ETH/USD") # Prepare trade input trade_input = TradeInput( trader=trader, # Trader's wallet address open_price=None, # (Optional) Open price of the trade. Current price in case of Market orders. If None then it will default to the current price pair_index=pair_index_of_eth_usd, # Pair index collateral_in_trade=amount_of_collateral, # Amount of collateral in trade (in USDC) is_long=True, # True for long, False for short leverage=25, # Leverage for the trade index=0, # This is the index of the trade for a pair (0 for the first trade, 1 for the second, etc.) tp=4000.5, # Take profit price. Max allowed is 500% of open price. sl=0, # Stop loss price timestamp=0, # Timestamp of the trade. 0 for now ) # 1% slippage slippage_percentage = 1 # Order type for the trade (MARKET or LIMIT or STOP_LIMIT or MARKET_ZERO_FEE) trade_input_order_type = TradeInputOrderType.MARKET_ZERO_FEE # Notes: # - Limit orders are not supported for zero fee trades # - Withdrawing collateral is not supported for zero fee trades # - No referral discounts are applied for zero fee trades # - Loss protection is not applied for zero fee trades # Open trade open_transaction = await trader_client.trade.build_trade_open_tx( trade_input, trade_input_order_type, slippage_percentage ) receipt = await trader_client.sign_and_get_receipt(open_transaction) print(receipt) print("Trade opened successfully!") # Run the example asyncio.run(main()) ``` -------------------------------- ### Get Both Long and Short Skew Impact Spreads for All Pairs Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md This snippet retrieves both long and short skew impact spreads for all trading pairs. Omit both `is_long` and `pair` parameters to get spreads for all pairs and both position types. Ensure `position_size` is provided. ```python skew_impact_spread = await trader_client.asset_parameters.get_skew_impact_spread(position_size=1000) print("Skew Impact Spread for all pairs (Long):", skew_impact_spread.long) print("Skew Impact Spread for all pairs (Short):", skew_impact_spread.short) ``` -------------------------------- ### Get Both Long and Short Skew Impact Spreads for a Specific Pair Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md This snippet retrieves both the long and short skew impact spreads for a specified trading pair. Omit the `is_long` parameter to get spreads for both position types. Ensure `position_size` and `pair` are specified. ```python skew_impact_spread = await trader_client.asset_parameters.get_skew_impact_spread(position_size=1000, pair="ETH/USD") print("Skew Impact Spread for ETH/USD (Long):", skew_impact_spread.long["ETH/USD"]) print("Skew Impact Spread for ETH/USD (Short):", skew_impact_spread.short["ETH/USD"]) ``` -------------------------------- ### Get Opening Price Impact Spread for Long Position Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Specify the trading pair, position size, open price, and indicate a long position to retrieve the specific price impact for a buy order. This snippet demonstrates how to get the price impact for a single direction. ```python opening_price_impact_spread = await trader_client.asset_parameters.get_opening_price_impact_spread( pair="ETH/USD", position_size=1000, open_price=3200, is_long=True ) print("Opening Price Impact Spread for ETH/USD (Long):", opening_price_impact_spread.long["ETH/USD"]) ``` -------------------------------- ### Initialize TraderClient Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Initialize the main client for trading operations. Requires a provider URL for the Base network. ```python from avantis_trader_sdk import TraderClient provider_url = "https://mainnet.base.org" trader_client = TraderClient(provider_url) ``` -------------------------------- ### Download AGENT.md for AI Development Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/README.md Download the AGENT.md file, which provides comprehensive documentation for AI agents. This file can be copied to your project or pasted into an AI chat. ```bash curl -o AGENT.md https://raw.githubusercontent.com/Avantis-Labs/avantis_trader_sdk/main/AGENT.md ``` -------------------------------- ### Get Loss Protection Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves loss protection details for a trade, including the percentage and maximum rebate amount. ```APIDOC ## Get Loss Protection ### Description Retrieves loss protection details for a trade, including the percentage and maximum rebate amount. ### Method Asynchronous function call ### Endpoint `trader_client.trading_parameters.get_loss_protection_for_trade_input(trade_input, opening_fee_usdc)` ### Parameters #### Request Body - **trade_input** (TradeInput): An object representing the trade details. - **opening_fee_usdc** (float): The opening fee in USDC for the trade. ### Response - **loss_protection** (object): An object containing loss protection details. - **percentage** (float): The loss protection percentage. - **amount** (float): The maximum rebate amount in USDC. ``` -------------------------------- ### Initialize FeedClient Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Initialize the client for accessing price feeds and real-time data. No specific parameters are required for initialization. ```python from avantis_trader_sdk import FeedClient feed_client = FeedClient() ``` -------------------------------- ### TraderClient Initialization Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/avantis_trader_sdk.md Initializes the TraderClient with necessary provider URLs and optional signer and feed client. ```APIDOC ## TraderClient(provider_url, l1_provider_url='https://eth.llamarpc.com', signer=None, feed_client=None) ### Description This class provides methods to interact with the Avantis smart contracts. ### Parameters: * **provider_url** (string) - The URL for the primary provider. * **l1_provider_url** (string) - Optional. The URL for the L1 provider. Defaults to 'https://eth.llamarpc.com'. * **signer** ([*BaseSigner*](avantis_trader_sdk.signers.md#avantis_trader_sdk.signers.base.BaseSigner)) - Optional. The signer object. * **feed_client** ([*FeedClient*](avantis_trader_sdk.feed.md#avantis_trader_sdk.feed.feed_client.FeedClient)) - Optional. The feed client object. ``` -------------------------------- ### Calculate Opening Fee and Loss Protection Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/trade.md Use this snippet to calculate the opening fee in USDC and the loss protection percentage and amount for a given trade input. The opening fee is optional when calculating loss protection as the SDK can compute it internally. ```python # Calculate Opening Fee opening_fee_usdc = await trader_client.fee_parameters.get_opening_fee( trade_input=trade_input ) print(f"Opening fee for this trade: {opening_fee_usdc} USDC") # Calculate Loss Protection loss_protection_info = ( await trader_client.trading_parameters.get_loss_protection_for_trade_input( trade_input, opening_fee_usdc=opening_fee_usdc # Opening fee is optional (it will be calculated if not provided) ) ) print(f"Loss protection percentage for this trade: {loss_protection_info.percentage}%") print(f"You'll receive up to ${loss_protection_info.amount} as a loss rebate if the trade goes against you.") ``` -------------------------------- ### Get Lazer Feed ID Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Retrieves the Lazer feed ID associated with a given trading pair index. ```APIDOC ## Get Lazer Feed ID ### Description Retrieves the Lazer feed ID for a specified trading pair index. ### Method `get_lazer_feed_id` ### Parameters #### Path Parameters None #### Query Parameters * **pair_index** (int) - Required - The index of the trading pair. ### Request Example ```python lazer_id = await trader_client.pairs_cache.get_lazer_feed_id(pair_index=0) ``` ### Response #### Success Response Returns the Lazer feed ID as an integer. #### Response Example ```json { "lazer_id": 0 } ``` ``` -------------------------------- ### Set Up Delegation Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Allows a main wallet to authorize another wallet (delegate) to trade on its behalf. This involves building and signing a transaction to set the delegate address. ```APIDOC ## Set Up Delegation ### Description Enables a main wallet to authorize another wallet (the delegate) to perform trades on its behalf. This process involves constructing and signing a transaction to register the delegate's address. ### Method `build_set_delegate_tx` ### Parameters #### Path Parameters None #### Query Parameters * **delegate** (string) - Required - The address of the wallet that will act as the delegate. * **trader** (string) - Required - The address of the main wallet that is granting delegation. ### Request Example ```python delegate_address = "0xDELEGATE_ADDRESS" set_delegate_tx = await trader_client.trade.build_set_delegate_tx(delegate=delegate_address, trader=main_wallet_address) receipt = await trader_client.sign_and_get_receipt(set_delegate_tx) ``` ### Response #### Success Response Returns a transaction receipt confirming the delegation setup. #### Response Example ```json { "transaction_hash": "0x...", "status": 1 } ``` ``` -------------------------------- ### Get Pair Spread Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/get_information_and_parameters.md Retrieves the spread percentage for all trading pairs. Use this to assess market liquidity and trading costs. ```python pair_spread = await trader_client.fee_parameters.get_pair_spread() print("Pair Spread:", pair_spread.spread) ``` -------------------------------- ### FeedClient Initialization Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/docs/source/avantis_trader_sdk.feed.md Initializes the FeedClient for interacting with Pyth price feeds. It can be configured with various URLs and optional fetcher functions. ```APIDOC ## class FeedClient(ws_url='wss://hermes.pyth.network/ws', on_error=None, on_close=None, hermes_url='https://hermes.pyth.network/v2/updates/price/latest', socket_api=AVANTIS_SOCKET_API, pair_fetcher=None, feed_v3_url=AVANTIS_FEED_V3_URL, lazer_sse_url=PYTH_LAZER_SSE_URL) ### Description Client for interacting with the Pyth price feed websocket. ### Parameters * **ws_url** (str) - WebSocket URL for the Pyth price feed. * **on_error** (Callable, optional) - Callback function for errors. * **on_close** (Callable, optional) - Callback function for connection closure. * **hermes_url** (str) - URL for the Pyth Hermes API. * **socket_api** (str) - URL for the Avantis socket API. * **pair_fetcher** (Callable, optional) - Function to fetch trading pairs. * **feed_v3_url** (str) - URL for the Avantis Feed V3 API. * **lazer_sse_url** (str) - URL for the Pyth Lazer SSE stream. ``` -------------------------------- ### Get Trading Pair Count Source: https://github.com/avantis-labs/avantis_trader_sdk/blob/main/AGENT.md Fetches the total number of available trading pairs. Requires an active trader client. ```python count = await trader_client.pairs_cache.get_pairs_count() ```