### EdgeX Python SDK Quick Start Example Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md A basic example demonstrating how to initialize the client, retrieve server time, metadata, account assets, positions, and market data. Uncomment the order creation section to place a real order. ```python import asyncio import os from edgex_sdk import Client, OrderSide async def main(): # Create a new client client = Client( base_url="https://pro.edgex.exchange", # Use https://testnet.edgex.exchange for testnet account_id=12345, # Your account ID stark_private_key="your-stark-private-key" # Your private key ) # Get server time server_time = await client.get_server_time() print(f"Server Time: {server_time}") # Get exchange metadata metadata = await client.get_metadata() print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}") # Get account assets assets = await client.get_account_asset() print(f"Account Assets: {assets}") # Get account positions positions = await client.get_account_positions() print(f"Account Positions: {positions}") # Get 24-hour market data for BNB2USDT (contract ID: 10000004) quote = await client.get_24_hour_quote("10000004") print(f"BNB2USDT Price: {quote}") # Create a limit order (uncomment to place real order) # order = await client.create_limit_order( # contract_id="10000004", # BNB2USDT # size="0.01", # price="600.00", # side=OrderSide.BUY # ) # print(f"Order created: {order}") # Run the async function asyncio.run(main()) ``` -------------------------------- ### Set Up Virtual Environment and Install Dependencies Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md Create and activate a Python virtual environment, then install project dependencies. This isolates project dependencies. ```bash # Create virtual environment python3 -m venv venv # Activate virtual environment source venv/bin/activate # On Windows: venv\Scripts\activate # Install dependencies pip install -r requirements.txt # Or install in development mode pip install -e . ``` -------------------------------- ### Install from Test PyPI Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/PUBLISHING.md Install the package from the Test PyPI repository to verify its integrity and functionality before publishing to the main PyPI. ```bash pip install --index-url https://test.pypi.org/simple/ edgex-python-sdk ``` -------------------------------- ### Install EdgeX Python SDK from Source Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md Clone the repository and install the SDK locally. This is useful for development or contributing to the SDK. ```bash git clone https://github.com/edgex-Tech/edgex-python-sdk.git cd edgex-python-sdk pip install -e . ``` -------------------------------- ### Install Build Tools Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/PUBLISHING.md Install the necessary tools for building and uploading Python packages to PyPI. This includes the 'build' and 'twine' packages. ```bash pip install build twine ``` -------------------------------- ### Install Dependencies using Requirements Files Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md Install project dependencies using requirements files. Use 'requirements.txt' for production and 'requirements-dev.txt' for development. ```bash pip install -r requirements.txt ``` ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install EdgeX Python SDK Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/examples/README.md Install the EdgeX Python SDK using pip. Use the `-e` flag for editable installs when working with source code. ```bash pip install edgex-python-sdk ``` ```bash cd edgex-python-sdk pip install -e . ``` -------------------------------- ### Install from PyPI Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/PUBLISHING.md Install the EdgeX Python SDK from the main PyPI repository after a successful publication. This command is used by end-users to add the SDK to their projects. ```bash pip install edgex-python-sdk ``` -------------------------------- ### Test Basic Functionality Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/PUBLISHING.md Import the SDK and print its version to verify a successful local installation. This is a basic check for SDK availability. ```python import edgex_sdk print(edgex_sdk.__version__) ``` -------------------------------- ### Install Package Locally Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/PUBLISHING.md Install the built Python package directly from the local wheel file. This is useful for testing the package before uploading. ```bash pip install dist/edgex_python_sdk-*.whl ``` -------------------------------- ### Run Basic Usage Example Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/examples/README.md Execute the `basic_usage.py` script to demonstrate core SDK functionalities like client creation, server info retrieval, market data fetching, and basic WebSocket usage. ```bash python basic_usage.py ``` -------------------------------- ### Get Account Positions with Python SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves all open positions for the authenticated account. Requires account_id and stark_private_key for client initialization. ```python import asyncio from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) positions = await client.get_account_positions() position_list = positions.get("data", {}).get("positionAssetList", []) for position in position_list: print(f"Contract: {position.get('contractId')}") print(f"Size: {position.get('size')}") print(f"Entry Price: {position.get('avgEntryPrice')}") print(f"Unrealized PnL: {position.get('unrealizedPnl')}") print("---") asyncio.run(main()) ``` -------------------------------- ### Run Advanced Usage Example Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/examples/README.md Execute the `advanced_usage.py` script to explore advanced features such as order management, robust WebSocket handling, pagination, and error handling. ```bash python advanced_usage.py ``` -------------------------------- ### Set Integration Test Environment Variables Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/TESTING.md Example of setting environment variables required for running integration tests. These credentials should not be committed to version control. ```bash export EDGEX_ACCOUNT_ID="your_account_id_here" export EDGEX_STARK_PRIVATE_KEY="your_stark_private_key_here" ``` -------------------------------- ### Configure EdgeX Environment Variables Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/examples/README.md Set environment variables for EdgeX API endpoints and account details. Alternatively, create a `.env` file in the examples directory. ```bash EDGEX_BASE_URL=https://pro.edgex.exchange # Use https://testnet.edgex.exchange for testnet EDGEX_WS_URL=wss://quote.edgex.exchange # Use wss://quote-testnet.edgex.exchange for testnet EDGEX_ACCOUNT_ID=12345 EDGEX_STARK_PRIVATE_KEY=your-stark-private-key ``` -------------------------------- ### Get Active Orders with Python SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Use this to retrieve all active orders. Supports filtering by contract ID and order type, and includes pagination. ```python import asyncio from edgex_sdk import Client, GetActiveOrderParams async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) params = GetActiveOrderParams( size="10", offset_data="", filter_contract_id_list=["10000001"], # Optional: filter by contract filter_type_list=["LIMIT"], # Optional: filter by order type ) orders = await client.get_active_orders(params) order_list = orders.get("data", {}).get("list", []) for order in order_list: print(f"Order ID: {order.get('orderId')}") print(f"Contract: {order.get('contractId')}") print(f"Side: {order.get('side')} | Type: {order.get('type')}") print(f"Price: {order.get('price')} | Size: {order.get('size')}") print(f"Filled: {order.get('filledSize')} | Status: {order.get('status')}") print("---") # Handle pagination if orders.get("data", {}).get("hasNext"): params.offset_data = orders.get("data", {}).get("offsetData") next_page = await client.get_active_orders(params) print(f"Next page has {len(next_page.get('data', {}).get('list', []))} orders") asyncio.run(main()) ``` -------------------------------- ### Get Max Order Size Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Calculates the maximum order size that can be placed for a given contract at a specific price, based on available margin. ```APIDOC ## GET /api/v1/max_order_size ### Description Calculates the maximum order size that can be placed for a given contract at a specific price, based on available margin. ### Method GET ### Endpoint /api/v1/max_order_size ### Parameters #### Query Parameters - **contract_id** (string) - Required - The ID of the contract. - **price** (Decimal) - Required - The price at which to calculate the max order size. ### Request Example ```python # Example using the Python SDK max_size = await client.get_max_order_size( contract_id="10000001", price=Decimal("50000.00") ) ``` ### Response #### Success Response (200) - **data** (object) - **maxBuySize** (string) - The maximum order size for a buy order. - **maxSellSize** (string) - The maximum order size for a sell order. #### Response Example ```json { "data": { "maxBuySize": "0.5", "maxSellSize": "0.4" } } ``` ``` -------------------------------- ### Get Collateral Transactions Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves collateral transaction history, including deposits, withdrawals, and transfers, with pagination support. Ensure the client is initialized with account details. ```python import asyncio from edgex_sdk import Client, GetCollateralTransactionPageParams async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) params = GetCollateralTransactionPageParams( size="10", offset_data="", ) transactions = await client.account.get_collateral_transaction_page(params) for tx in transactions.get("data", {}).get("list", []): print(f"Transaction ID: {tx.get('transactionId')}") print(f"Type: {tx.get('type')}") print(f"Amount: {tx.get('amount')}") print(f"Time: {tx.get('createdTime')}") print("---") asyncio.run(main()) ``` -------------------------------- ### Get Account Positions API Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves all open positions for the authenticated account. Returns position data including size, entry price, unrealized PnL, and margin information. ```APIDOC ## Get Account Positions ### Description Retrieves all open positions for the authenticated account. Returns position data including size, entry price, unrealized PnL, and margin information. ### Method GET ### Endpoint /api/v1/account/positions ### Parameters #### Query Parameters - **account_id** (integer) - Required - The ID of the account. - **stark_private_key** (string) - Required - The private key for Stark authentication. ### Request Example ```python import asyncio from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) positions = await client.get_account_positions() print(positions) asyncio.run(main()) ``` ### Response #### Success Response (200) - **data** (object) - Contains position data. - **positionAssetList** (array) - List of open positions. - **contractId** (string) - The ID of the contract. - **size** (string) - The size of the position. - **avgEntryPrice** (string) - The average entry price. - **unrealizedPnl** (string) - The unrealized profit or loss. #### Response Example ```json { "data": { "positionAssetList": [ { "contractId": "10000001", "size": "0.001", "avgEntryPrice": "30000.00", "unrealizedPnl": "10.50" } ] } } ``` ``` -------------------------------- ### Get 24-Hour Quote with Python SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Fetches 24-hour market statistics for a given contract ID. Ensure the contract ID is valid and the client is properly initialized. ```python import asyncio from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) # Get 24-hour quote for BTCUSDT (contract ID: 10000001) quote = await client.get_24_hour_quote("10000001") data = quote.get("data", [])[0] if quote.get("data") else {} print(f"Contract: {data.get('contractId')}") print(f"Last Price: {data.get('lastPrice')}") print(f"24h High: {data.get('highPrice24h')}") print(f"24h Low: {data.get('lowPrice24h')}") print(f"24h Volume: {data.get('volume24h')}") print(f"Oracle Price: {data.get('oraclePrice')}") asyncio.run(main()) ``` -------------------------------- ### Get Max Order Size Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Calculates the maximum order size for a given contract and price based on available margin. Requires importing Decimal for price representation. ```python import asyncio from decimal import Decimal from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) # Get max order size for BTCUSDT at price 50000 max_size = await client.get_max_order_size( contract_id="10000001", price=Decimal("50000.00") ) data = max_size.get("data", {}) print(f"Max Buy Size: {data.get('maxBuySize')}") print(f"Max Sell Size: {data.get('maxSellSize')}") asyncio.run(main()) ``` -------------------------------- ### Get EdgeX Account Asset Information Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves account asset details, including collateral balance, available balance, and total equity. It prints the retrieved assets and specific balance fields. ```python import asyncio from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) assets = await client.get_account_asset() print(f"Account Assets: {assets}") # Access specific fields data = assets.get("data", {}) print(f"Total Equity: {data.get('totalEquity')}") print(f"Available Balance: {data.get('availableBalance')}") print(f"Collateral: {data.get('collateral')}") asyncio.run(main()) ``` -------------------------------- ### Get Order Book Depth with Python SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Fetches the current order book (bids and asks) for a contract. Supports depth limits of 15 or 200. Ensure the contract ID and limit are valid. ```python import asyncio from edgex_sdk import Client, GetOrderBookDepthParams async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) depth_params = GetOrderBookDepthParams( contract_id="10000001", # BTCUSDT limit=15 # Valid values: 15 or 200 ) depth = await client.quote.get_order_book_depth(depth_params) data = depth.get("data", {}) print("ASKS (Sell Orders):") for ask in data.get("asks", [])[:5]: print(f" Price: {ask[0]} | Size: {ask[1]}") print("\nBIDS (Buy Orders):") for bid in data.get("bids", [])[:5]: print(f" Price: {bid[0]} | Size: {bid[1]}") asyncio.run(main()) ``` -------------------------------- ### Get Order Fill Transactions Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves historical order fill transactions with support for filtering by contract ID and pagination. Ensure the SDK is imported and the client is initialized with your account details. ```python import asyncio from edgex_sdk import Client, OrderFillTransactionParams async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) params = OrderFillTransactionParams( size="20", offset_data="", filter_contract_id_list=["10000001"], # Optional: filter by contract ) fills = await client.get_order_fill_transactions(params) for fill in fills.get("data", {}).get("list", []): print(f"Order ID: {fill.get('orderId')}") print(f"Contract: {fill.get('contractId')}") print(f"Side: {fill.get('side')}") print(f"Price: {fill.get('price')} | Size: {fill.get('size')}") print(f"Fee: {fill.get('fee')}") print(f"Time: {fill.get('createdTime')}") print("---") asyncio.run(main()) ``` -------------------------------- ### Get K-Line Data with Python SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves candlestick data for technical analysis. Requires specifying contract ID, kline type, price type, and size. Supports various intervals and price types. ```python import asyncio from edgex_sdk import Client, GetKLineParams, KlineType, PriceType async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) # Get 1-minute K-lines for BTCUSDT kline_params = GetKLineParams( contract_id="10000001", kline_type=KlineType.MINUTE_1, price_type=PriceType.LAST_PRICE, size=10 ) klines = await client.quote.get_k_line(kline_params) for kline in klines.get("data", {}).get("list", [])[:5]: print(f"Time: {kline.get('klineTime')}") print(f"Open: {kline.get('open')} | High: {kline.get('high')}") print(f"Low: {kline.get('low')} | Close: {kline.get('close')}") print(f"Volume: {kline.get('volume')}") print("---") # Available KlineType values: # MINUTE_1, MINUTE_5, MINUTE_15, MINUTE_30 # HOUR_1, HOUR_2, HOUR_4, HOUR_6, HOUR_8, HOUR_12 # DAY_1, WEEK_1, MONTH_1 # Available PriceType values: # LAST_PRICE, INDEX_PRICE, ORACLE_PRICE, ASK1_PRICE, BID1_PRICE, OPEN_INTEREST asyncio.run(main()) ``` -------------------------------- ### Get EdgeX Exchange Metadata Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves exchange metadata including contracts, coins, and trading parameters. This data is necessary for placing orders. It prints the first 5 available contracts. ```python import asyncio from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) metadata = await client.get_metadata() # List available contracts contracts = metadata.get("data", {}).get("contractList", []) print(f"Available contracts: {len(contracts)}") for contract in contracts[:5]: print(f"ID: {contract['contractId']} - {contract['contractName']} - Tick: {contract['tickSize']}") # Output: # Available contracts: 10 # ID: 10000001 - BTCUSDT - Tick: 0.1 # ID: 10000002 - ETHUSDT - Tick: 0.01 # ID: 10000003 - SOLUSDT - Tick: 0.01 # ID: 10000004 - BNBUSDT - Tick: 0.01 asyncio.run(main()) ``` -------------------------------- ### Get K-Line Data API Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves candlestick/OHLCV data for technical analysis. Supports multiple intervals and price types including last price, index price, and oracle price. ```APIDOC ## Get K-Line Data ### Description Retrieves candlestick/OHLCV data for technical analysis. Supports multiple intervals and price types including last price, index price, and oracle price. ### Method GET ### Endpoint /api/v1/quote/kline ### Parameters #### Query Parameters - **contract_id** (string) - Required - The ID of the contract. - **kline_type** (enum) - Required - The type of K-line interval. Possible values: MINUTE_1, MINUTE_5, MINUTE_15, MINUTE_30, HOUR_1, HOUR_2, HOUR_4, HOUR_6, HOUR_8, HOUR_12, DAY_1, WEEK_1, MONTH_1. - **price_type** (enum) - Required - The type of price to use. Possible values: LAST_PRICE, INDEX_PRICE, ORACLE_PRICE, ASK1_PRICE, BID1_PRICE, OPEN_INTEREST. - **size** (integer) - Optional - The number of K-lines to retrieve. Defaults to 10. - **account_id** (integer) - Required - The ID of the account. - **stark_private_key** (string) - Required - The private key for Stark authentication. ### Request Example ```python import asyncio from edgex_sdk import Client, GetKLineParams, KlineType, PriceType async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) kline_params = GetKLineParams( contract_id="10000001", kline_type=KlineType.MINUTE_1, price_type=PriceType.LAST_PRICE, size=10 ) klines = await client.quote.get_k_line(kline_params) print(klines) asyncio.run(main()) ``` ### Response #### Success Response (200) - **data** (object) - Contains K-line data. - **list** (array) - List of K-line data. - **klineTime** (integer) - The timestamp of the K-line. - **open** (string) - The opening price. - **high** (string) - The highest price. - **low** (string) - The lowest price. - **close** (string) - The closing price. - **volume** (string) - The trading volume. #### Response Example ```json { "data": { "list": [ { "klineTime": 1678886400, "open": "30000.00", "high": "30500.00", "low": "29800.00", "close": "30200.00", "volume": "500.00" } ] } } ``` ``` -------------------------------- ### Create Client with Default Signing Adapter Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md Instantiate the Client class with your API credentials. StarkExSigningAdapter is used by default, so no explicit adapter is needed unless customizing. ```python from edgex_sdk import Client # Create a client (uses StarkExSigningAdapter by default) client = Client( base_url="https://pro.edgex.exchange", # Use https://testnet.edgex.exchange for testnet account_id=12345, stark_private_key="your-stark-private-key" ) ``` -------------------------------- ### Get Withdrawal Records Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves withdrawal history with filtering and pagination support. ```APIDOC ## Get Withdrawal Records ### Description Retrieves withdrawal history with filtering and pagination support. ### Method GET ### Endpoint /api/v1/asset/withdrawal/records ### Parameters #### Query Parameters - **size** (string) - Optional - The number of records to return per page. Defaults to 10. - **page** (string) - Optional - The page number to retrieve. Defaults to 1. - **filter_status_list** (array of strings) - Optional - A list of statuses to filter by (e.g., ["PENDING", "COMPLETED", "FAILED"]). ### Response #### Success Response (200) - **data** (object) - Contains withdrawal records. - **list** (array) - A list of withdrawal records. - **withdrawId** (string) - The ID of the withdrawal. - **amount** (string) - The amount withdrawn. - **ethAddress** (string) - The Ethereum address the withdrawal was sent to. - **status** (string) - The status of the withdrawal (e.g., PENDING, COMPLETED, FAILED). #### Response Example ```json { "code": 0, "msg": "OK", "data": { "list": [ { "withdrawId": "wd_12345abcde", "amount": "100", "ethAddress": "0x1234567890123456789012345678901234567890", "status": "COMPLETED" } ], "total": 1 } } ``` ``` -------------------------------- ### Get Withdrawable Amount Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves the maximum amount that can be withdrawn for a specific address. ```APIDOC ## Get Withdrawable Amount ### Description Retrieves the maximum amount that can be withdrawn for a specific address. ### Method GET ### Endpoint /api/v1/asset/withdrawable-amount ### Parameters #### Query Parameters - **address** (string) - Required - The address to check the withdrawable amount for. ### Response #### Success Response (200) - **data** (object) - Contains the withdrawable amount. - **amount** (string) - The maximum amount that can be withdrawn. #### Response Example ```json { "code": 0, "msg": "OK", "data": { "amount": "500.75" } } ``` ``` -------------------------------- ### Initialize EdgeX Python SDK Client Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md Load environment variables and initialize the EdgeX client. Ensure EDGEX_BASE_URL, EDGEX_ACCOUNT_ID, and EDGEX_STARK_PRIVATE_KEY are set in your .env file. ```python import os from dotenv import load_dotenv from edgex_sdk import Client # Load environment variables from .env file load_dotenv() client = Client( base_url=os.getenv("EDGEX_BASE_URL"), account_id=int(os.getenv("EDGEX_ACCOUNT_ID")), stark_private_key=os.getenv("EDGEX_STARK_PRIVATE_KEY") ) ``` -------------------------------- ### Create Client with Custom Signing Adapter Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md Provide a custom signing adapter instance to the Client constructor if you need to implement custom cryptographic operations beyond the default StarkExSigningAdapter. ```python from edgex_sdk import Client, StarkExSigningAdapter # Create a custom signing adapter (optional) signing_adapter = StarkExSigningAdapter() # Create a client with a custom signing adapter client = Client( base_url="https://pro.edgex.exchange", # Use https://testnet.edgex.exchange for testnet account_id=12345, stark_private_key="your-stark-private-key", signing_adapter=signing_adapter ) ``` -------------------------------- ### Get Collateral Transactions Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves collateral transaction history including deposits, withdrawals, and transfers. ```APIDOC ## GET /api/v1/collateral/transactions ### Description Retrieves collateral transaction history including deposits, withdrawals, and transfers. ### Method GET ### Endpoint /api/v1/collateral/transactions ### Parameters #### Query Parameters - **size** (string) - Optional - Number of records to return per page. - **offset_data** (string) - Optional - Offset for pagination. ### Request Example ```python # Example using the Python SDK params = GetCollateralTransactionPageParams( size="10", offset_data="" ) transactions = await client.account.get_collateral_transaction_page(params) ``` ### Response #### Success Response (200) - **data** (object) - Contains the list of transactions and pagination info. - **list** (array) - List of collateral transactions. - **transactionId** (string) - The ID of the transaction. - **type** (string) - The type of transaction (e.g., DEPOSIT, WITHDRAWAL, TRANSFER). - **amount** (string) - The amount of collateral involved. - **createdTime** (string) - The timestamp when the transaction occurred. #### Response Example ```json { "data": { "list": [ { "transactionId": "ctrx456", "type": "DEPOSIT", "amount": "1.0", "createdTime": "2023-10-27T11:00:00Z" } ], "total": 1 } } ``` ``` -------------------------------- ### Get Position Transactions Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves position transaction history including entries, exits, and liquidations with pagination support. ```APIDOC ## GET /api/v1/positions/transactions ### Description Retrieves position transaction history including entries, exits, and liquidations with pagination support. ### Method GET ### Endpoint /api/v1/positions/transactions ### Parameters #### Query Parameters - **size** (string) - Optional - Number of records to return per page. - **offset_data** (string) - Optional - Offset for pagination. - **filter_contract_id_list** (list of strings) - Optional - Filter by contract ID. ### Request Example ```python # Example using the Python SDK params = GetPositionTransactionPageParams( size="10", offset_data="", filter_contract_id_list=["10000001"] ) transactions = await client.account.get_position_transaction_page(params) ``` ### Response #### Success Response (200) - **data** (object) - Contains the list of transactions and pagination info. - **list** (array) - List of position transactions. - **transactionId** (string) - The ID of the transaction. - **contractId** (string) - The ID of the contract. - **type** (string) - The type of transaction (e.g., ENTRY, EXIT, LIQUIDATION). - **size** (string) - The size of the position change. - **price** (string) - The price at which the transaction occurred. #### Response Example ```json { "data": { "list": [ { "transactionId": "tx123", "contractId": "10000001", "type": "ENTRY", "size": "0.01", "price": "50000.00" } ], "total": 1 } } ``` ``` -------------------------------- ### Get Order Fill Transactions Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves historical order fill transactions (trades) with filtering and pagination support. ```APIDOC ## GET /api/v1/fills ### Description Retrieves historical order fill transactions (trades) with filtering and pagination support. ### Method GET ### Endpoint /api/v1/fills ### Parameters #### Query Parameters - **size** (string) - Optional - Number of records to return per page. - **offset_data** (string) - Optional - Offset for pagination. - **filter_contract_id_list** (list of strings) - Optional - Filter by contract ID. ### Request Example ```python # Example using the Python SDK params = OrderFillTransactionParams( size="20", offset_data="", filter_contract_id_list=["10000001"] ) fills = await client.get_order_fill_transactions(params) ``` ### Response #### Success Response (200) - **data** (object) - Contains the list of transactions and pagination info. - **list** (array) - List of order fill transactions. - **orderId** (string) - The ID of the order. - **contractId** (string) - The ID of the contract. - **side** (string) - The side of the order (e.g., BUY, SELL). - **price** (string) - The price of the fill. - **size** (string) - The size of the fill. - **fee** (string) - The fee associated with the fill. - **createdTime** (string) - The timestamp when the fill was created. #### Response Example ```json { "data": { "list": [ { "orderId": "12345", "contractId": "10000001", "side": "BUY", "price": "50000.00", "size": "0.001", "fee": "0.000001", "createdTime": "2023-10-27T10:00:00Z" } ], "total": 1 } } ``` ``` -------------------------------- ### Initialize EdgeX Python SDK Client Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Initializes the EdgeX SDK client for testnet or mainnet. Use as an async context manager for automatic cleanup. Requires base URL, account ID, and Stark private key. ```python import asyncio from edgex_sdk import Client, OrderSide, OrderType async def main(): # Initialize client for testnet client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="0x1234567890abcdef..." ) # For production mainnet # client = Client( # base_url="https://pro.edgex.exchange", # account_id=12345, # stark_private_key="0x1234567890abcdef..." # ) # Use as async context manager for automatic cleanup async with Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="0x1234567890abcdef..." ) as client: server_time = await client.get_server_time() print(f"Server time: {server_time}") asyncio.run(main()) ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/TESTING.md Execute all unit tests for the SDK. Navigate to the 'python_sdk' directory first. ```bash cd python_sdk python -m unittest discover tests ``` -------------------------------- ### Create Market Order with Python SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Use this to create a market order. The SDK calculates the best available price. Price parameter is ignored. ```python import asyncio from edgex_sdk import Client, OrderSide, OrderType, CreateOrderParams async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) # Create a market buy order params = CreateOrderParams( contract_id="10000004", # BNBUSDT size="0.01", price="0", # Price is ignored for market orders type=OrderType.MARKET, side=OrderSide.BUY ) try: order = await client.create_order(params) print(f"Market order executed!") print(f"Order ID: {order.get('data', {}).get('orderId')}") except ValueError as e: print(f"Failed to create order: {e}") asyncio.run(main()) ``` -------------------------------- ### Create Limit Order with Python SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Use this to create a limit order. Specify contract ID, size, price, and side. The SDK handles StarkEx signing. ```python import asyncio from edgex_sdk import Client, OrderSide, OrderType, CreateOrderParams, TimeInForce async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) # Create a limit buy order params = CreateOrderParams( contract_id="10000004", # BNBUSDT size="0.01", price="600.00", type=OrderType.LIMIT, side=OrderSide.BUY, time_in_force=TimeInForce.GOOD_TIL_CANCEL, # Optional, defaults based on order type reduce_only=False # Optional ) try: order = await client.create_order(params) print(f"Order created successfully!") print(f"Order ID: {order.get('data', {}).get('orderId')}") print(f"Client Order ID: {order.get('data', {}).get('clientOrderId')}") except ValueError as e: print(f"Failed to create order: {e}") asyncio.run(main()) ``` -------------------------------- ### Get Position Transactions Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves position transaction history, including entries, exits, and liquidations, with pagination support. Filtering by contract ID is optional. ```python import asyncio from edgex_sdk import Client, GetPositionTransactionPageParams async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) params = GetPositionTransactionPageParams( size="10", offset_data="", filter_contract_id_list=["10000001"], # Optional ) transactions = await client.account.get_position_transaction_page(params) for tx in transactions.get("data", {}).get("list", []): print(f"Transaction ID: {tx.get('transactionId')}") print(f"Contract: {tx.get('contractId')}") print(f"Type: {tx.get('type')}") print(f"Size: {tx.get('size')}") print(f"Price: {tx.get('price')}") print("---") asyncio.run(main()) ``` -------------------------------- ### Configure EdgeX API and Account Credentials Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/README.md Sets environment variables for API base URL, WebSocket URL, account ID, and Stark private key. Use testnet URLs for the test environment. ```bash # API Configuration EDGEX_BASE_URL=https://pro.edgex.exchange # Use https://testnet.edgex.exchange for testnet EDGEX_WS_URL=wss://quote.edgex.exchange # Use wss://quote-testnet.edgex.exchange for testnet # Account Credentials EDGEX_ACCOUNT_ID=12345 EDGEX_STARK_PRIVATE_KEY=your-stark-private-key ``` -------------------------------- ### Get 24-Hour Quote API Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves 24-hour market statistics for a specific contract including price, volume, high, low, and price change. ```APIDOC ## Get 24-Hour Quote ### Description Retrieves 24-hour market statistics for a specific contract including price, volume, high, low, and price change. ### Method GET ### Endpoint /api/v1/quote/24h ### Parameters #### Query Parameters - **contract_id** (string) - Required - The ID of the contract (e.g., "10000001" for BTCUSDT). - **account_id** (integer) - Required - The ID of the account. - **stark_private_key** (string) - Required - The private key for Stark authentication. ### Request Example ```python import asyncio from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) quote = await client.get_24_hour_quote("10000001") print(quote) asyncio.run(main()) ``` ### Response #### Success Response (200) - **data** (array) - List of quote data for the specified contract. - **contractId** (string) - The ID of the contract. - **lastPrice** (string) - The last traded price. - **highPrice24h** (string) - The highest price in the last 24 hours. - **lowPrice24h** (string) - The lowest price in the last 24 hours. - **volume24h** (string) - The trading volume in the last 24 hours. - **oraclePrice** (string) - The current oracle price. #### Response Example ```json { "data": [ { "contractId": "10000001", "lastPrice": "30500.00", "highPrice24h": "31000.00", "lowPrice24h": "29500.00", "volume24h": "1000.00", "oraclePrice": "30510.00" } ] } ``` ``` -------------------------------- ### Upload to PyPI Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/PUBLISHING.md Upload the built package distribution files to the main PyPI repository. Ensure you have built the package and are authenticated. ```bash twine upload dist/* ``` -------------------------------- ### Get EdgeX Server Time Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves the current server time from the EdgeX exchange. This public endpoint does not require authentication and is useful for time synchronization. ```python import asyncio from edgex_sdk import Client async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) server_time = await client.get_server_time() print(f"Server Time: {server_time}") # Output: {'code': 'SUCCESS', 'data': {'serverTime': '1704067200000'}, ...} asyncio.run(main()) ``` -------------------------------- ### Create Git Tag and Push Source: https://github.com/edgex-tech/edgex-python-sdk/blob/main/PUBLISHING.md Use these commands to create a new version tag and push it to the origin repository, which can trigger automated GitHub Actions for publishing. ```bash git tag v0.1.0 git push origin v0.1.0 ``` -------------------------------- ### Get Withdrawal Records with Edgex SDK Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Retrieves a list of withdrawal records with support for filtering by status and pagination. The `filter_status_list` parameter can be used to narrow down results. ```python import asyncio from edgex_sdk import Client, GetWithdrawalRecordsParams async def main(): client = Client( base_url="https://testnet.edgex.exchange", account_id=12345, stark_private_key="your-stark-private-key" ) params = GetWithdrawalRecordsParams( size="10", filter_status_list=["PENDING", "COMPLETED"] # Optional ) records = await client.asset.get_withdrawal_records(params) for record in records.get("data", {}).get("list", []): print(f"ID: {record.get('withdrawId')}") print(f"Amount: {record.get('amount')}") print(f"Address: {record.get('ethAddress')}") print(f"Status: {record.get('status')}") print("---") asyncio.run(main()) ``` -------------------------------- ### Configure EdgeX Client with Environment Variables Source: https://context7.com/edgex-tech/edgex-python-sdk/llms.txt Load EdgeX client configuration from environment variables, including base URLs, account ID, and private key. Supports fallback to default testnet values if variables are not set. Ensure .env file is present for local development. ```python import asyncio import os from dotenv import load_dotenv from edgex_sdk import Client, WebSocketManager async def main(): # Load environment variables from .env file load_dotenv() # .env file contents: # EDGEX_BASE_URL=https://testnet.edgex.exchange # EDGEX_WS_URL=wss://quote-testnet.edgex.exchange # EDGEX_ACCOUNT_ID=12345 # EDGEX_STARK_PRIVATE_KEY=0x1234567890abcdef... client = Client( base_url=os.getenv("EDGEX_BASE_URL", "https://testnet.edgex.exchange"), account_id=int(os.getenv("EDGEX_ACCOUNT_ID", "0")), stark_private_key=os.getenv("EDGEX_STARK_PRIVATE_KEY", "") ) ws_manager = WebSocketManager( base_url=os.getenv("EDGEX_WS_URL", "wss://quote-testnet.edgex.exchange"), account_id=int(os.getenv("EDGEX_ACCOUNT_ID", "0")), stark_pri_key=os.getenv("EDGEX_STARK_PRIVATE_KEY", "") ) server_time = await client.get_server_time() print(f"Connected to EdgeX: {server_time}") asyncio.run(main()) ```