### Apex Protocol HTTP Session Setup (Python) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Initializes an HTTP session for interacting with the Apex Protocol. This example shows setting up a client for testnet or mainnet using the HttpPublic class. ```python from apexomni.constants import APEX_HTTP_TEST from apexomni.http_public import HttpPublic # Initialize client for test environment client = HttpPublic(APEX_HTTP_TEST) # For mainnet, you would use: # from apexomni.constants import APEX_HTTP_MAIN # client = HttpPublic(APEX_HTTP_MAIN) ``` -------------------------------- ### Register User and Complete V3 Account Setup Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V3.md Guides through registering a new user or re-registering an existing one for Apex omni V3. This involves deriving zkKeys, generating a nonce, registering the user, and then changing the public key. Requires a 10-second delay between registration and public key change. ```python import time from apexomni.constants import APEX_OMNI_HTTP_MAIN, NETWORKID_OMNI_MAIN_ARB, NETWORKID_MAIN from apexomni.http_private_v3 import HttpPrivate_v3 print("Hello, Apex Omni") priKey = "your eth private key" # Initialize private client with mainnet, network ID, and Ethereum private key client = HttpPrivate_v3(APEX_OMNI_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key=priKey) # Fetch configurations (required before other operations) configs = client.configs_v3() # Derive zkKeys using the default address zkKeys = client.derive_zk_key(client.default_address) print(zkKeys) # Generate nonce for registration nonceRes = client.generate_nonce_v3(refresh="false", l2Key=zkKeys['l2Key'], ethAddress=client.default_address, chainId=NETWORKID_OMNI_MAIN_ARB) # Register the user with derived keys and nonce regRes = client.register_user_v3(nonce=nonceRes['data']['nonce'], l2Key=zkKeys['l2Key'], seeds=zkKeys['seeds'], ethereum_address=client.default_address) # Extract API credentials key = regRes['data']['apiKey']['key'] secret = regRes['data']['apiKey']['secret'] passphrase = regRes['data']['apiKey']['passphrase'] # Wait for 10 seconds before changing public key time.sleep(10) # Fetch account details after registration accountRes = client.get_account_v3() print(accountRes) # Print account ID and API key details print(regRes['data']['account']['id']) print(regRes['data']['apiKey']) # Change public key to complete V3 account setup changeRes = client.change_pub_key_v3(chainId=NETWORKID_OMNI_MAIN_ARB, seeds=zkKeys.get('seeds'), ethPrivateKey=priKey, zkAccountId=accountRes.get('spotAccount').get('zkAccountId'), subAccountId=accountRes.get('spotAccount').get('defaultSubAccountId'), newPkHash=zkKeys.get('pubKeyHash'), nonce=accountRes.get('spotAccount').get('nonce'), l2Key=zkKeys.get('l2Key')) print(changeRes) # Wait again and fetch account details to confirm changes time.sleep(10) accountRes = client.get_account_v3() print(accountRes) ``` -------------------------------- ### Python: Stark Key Sign Method Example Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates initializing the `HttpPrivateStark` client and making API calls that require Stark key authentication. This includes setting up credentials for both API keys and Stark keys. ```python import time from apexomni.http_private_stark_key_sign import HttpPrivateStark from apexomni.constants import APEX_HTTP_TEST, NETWORKID_TEST # API Key credentials key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' # Stark key credentials public_key = 'your stark_public_key from register' public_key_y_coordinate = 'your stark_public_key_y_coordinate from register' private_key = 'your stark_private_key from register' # Initialize the Stark key signing client client = HttpPrivateStark(APEX_HTTP_TEST, network_id=NETWORKID_TEST, stark_public_key=public_key, stark_private_key=private_key, stark_public_key_y_coordinate=public_key_y_coordinate, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) # Example API calls requiring Stark key authentication configs = client.configs_v2() client.get_user() print(client.get_account_v2()) print(client.get_account_balance_v2()) # Example for withdrawal (commented out) # currentTime = time.time() # feeRes = client.uncommon_withdraw_fee_v2(amount='2',chainId='5', token='USDT',) # print(feeRes) # fastWithdrawRes = client.fast_withdrawal_v2(amount='2',expirationEpochSeconds= currentTime,asset='USDT',fee=feeRes['data']['fee']) # Example for creating withdrawal (commented out) # createWithdrawRes = client.create_withdrawal_v2(amount='1',expirationEpochSeconds= currentTime,asset='USDT') ``` -------------------------------- ### Initialize Apex REST Client and Get Account Info Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates how to initialize the HttpPrivateStark client with API keys and Stark keys, and retrieve basic account information like configurations and user details. ```Python from time import time from apexomni.constants import APEX_HTTP_TEST, NETWORKID_TEST from apexomni.http_api import HttpPrivateStark key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' public_key = 'your stark_public_key from register' public_key_y_coordinate = 'your stark_public_key_y_coordinate from register' private_key = 'your stark_private_key from register' client = HttpPrivateStark(APEX_HTTP_TEST, network_id=NETWORKID_TEST, stark_public_key=public_key, stark_private_key=private_key, stark_public_key_y_coordinate=public_key_y_coordinate, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) configs = client.configs() client.get_user() client.get_account() ``` -------------------------------- ### Connect to Apex WebSocket and Subscribe to Account Info Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates establishing a WebSocket connection with authentication and subscribing to account information streams. Includes example handler functions for received messages. ```Python from time import sleep from apexomni.constants import APEX_WS_TEST from apexomni.websocket_api import WebSocket key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' # Connect with authentication! ws_client = WebSocket( endpoint=APEX_WS_TEST, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}, ) def handle_account(message): print(message) contents_data = message["contents"] print(len(contents_data)) def h1(message): print(1, message) def h2(message): print(2, message) def h3(message): print(3, message) def h4(message): print(4, message) #ws_client.depth_stream(h1,'BTCUSDC',25) #ws_client.ticker_stream(h2,'BTCUSDC') #ws_client.trade_stream(h3,'BTCUSDC') #ws_client.klines_stream(h4,'BTCUSDC',1) ws_client.account_info_stream(handle_account) while True: # Run your main trading logic here. sleep(1) ``` -------------------------------- ### Install apexpro Python Package Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Installs the official Python connector for Apexpro's HTTP and WebSockets APIs using pip. Requires Python 3.6.1 - 3.10.0. ```bash pip3 install apexpro ``` -------------------------------- ### Install apex omni Python Package Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V3.md Installs the apex omni library using pip. This package provides the necessary tools to interact with Apex omni's HTTP and WebSocket APIs. ```bash pip3 install apexomni ``` -------------------------------- ### Install apex omni with pip Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README.md Shows how to install the `apex omni` Python package using pip. ```python pip3 install apexomni ``` -------------------------------- ### Python: HTTP Private API Example Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates initializing the `HttpPrivate` client and making various API calls using standard API key authentication. This includes fetching account data, fills, transfers, orders, and notifications. ```python # need apiKey={'key': key,'secret': secret, 'passphrase': passphrase} for private api key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' # Initialize the HTTP private client client = HttpPrivate(APEX_HTTP_TEST, network_id=NETWORKID_TEST, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) # Example API calls configs = client.configs_v2() accountRes = client.get_account_v2() print(accountRes) fillsRes = client.fills_v2(limit=100, page=0, symbol="BTC-USDT", side="BUY", token="USDT") print(fillsRes) transfersRes = client.transfers_v2(limit=100, page=0, currencyId="USDT", chainIds="1,5,13,97") print(transfersRes) withdrawListRes = client.withdraw_list_v2(limit=100, page=0, beginTimeInclusive=1651406864000, endTimeExclusive=1657105971171) print(withdrawListRes) uncommon_withdraw_feeRes = client.uncommon_withdraw_fee_v2(amount="101000.1", token="USDT", chainId=5) print(uncommon_withdraw_feeRes) transfer_limitRes = client.transfer_limit_v2(currencyId="USDT") print(transfer_limitRes) # Duplicate call for fillsRes fillsRes = client.fills_v2(limit=100, page=0, symbol="BTC-USDT", side="BUY", token="USDT") print(fillsRes) deleteOrderRes = client.delete_order_v2(id="123456") print(deleteOrderRes) deleteOrderRes = client.delete_order_by_client_order_id_v2(id="123456") print(deleteOrderRes) openOrdersRes = client.open_orders_v2(token='USDT') print(openOrdersRes) deleteOrdersRes = client.delete_open_orders_v2(symbol="BTC-USDC,ETH-USDC", token='USDT') print(deleteOrdersRes) historyOrdersRes = client.history_orders_v2(token='USDT') print(historyOrdersRes) getOrderRes = client.get_order_v2(id="123456") print(getOrderRes) getOrderRes = client.get_order_by_client_order_id_v2(id="123456") print(getOrderRes) fundingRes = client.funding_v2(limit=100, page=0, symbol="BTC-USDC", side="BUY", token='USDT') print(fundingRes) notifyListRes = client.notify_list(limit=100, page=0, unreadOnly="true", notifyCategory="1") print(notifyListRes) markNotifyReadRes = client.mark_notify_read(ids="113123,123123123") print(markNotifyReadRes) historicalPnlRes = client.historical_pnl_v2(limit=100, page=0, beginTimeInclusive=1651406864000, endTimeExclusive=1657105971171, symbol="BTC-USDC") print(historicalPnlRes) yesterdayPnlRes = client.yesterday_pnl_v2(token='USDT') print(yesterdayPnlRes) historyValueRes = client.history_value_v2(token='USDT') print(historyValueRes) markAllNotifyReadRes = client.mark_all_notify_read() print(markAllNotifyReadRes) setInitialMarginRateRes = client.set_initial_margin_rate_v2(symbol="BTC-USDC", initialMarginRate="0.1", token='USDT') print(setInitialMarginRateRes) ``` -------------------------------- ### Fetch Public Endpoint Data V3 Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V3.md Demonstrates fetching various public data points using the HttpPublic client. Supports USDT symbols and requires calling configs_v3() first to get symbol configurations. Includes examples for klines, depth, trades, ticker, and history funding. ```python from apexomni.constants import APEX_OMNI_HTTP_MAIN from apexomni.http_public import HttpPublic client = HttpPublic(APEX_OMNI_HTTP_MAIN) # Fetch configurations for V3 endpoints print(client.configs_v3()) # Fetch klines data for ETHUSDT print(client.klines_v3(symbol="ETHUSDT", interval=5, start=1718358480, end=1718950620, limit=5)) # Fetch depth data for BTCUSDT print(client.depth_v3(symbol="BTCUSDT")) # Fetch trades data for BTCUSDT print(client.trades_v3(symbol="BTCUSDT")) # Fetch klines data with a different interval print(client.klines_v3(symbol="BTCUSDT", interval="15")) # Fetch ticker data for BTCUSDT print(client.ticker_v3(symbol="BTCUSDT")) # Fetch history funding data for BTC-USDT print(client.history_funding_v3(symbol="BTC-USDT")) ``` -------------------------------- ### Delete Apex Open Orders Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Provides examples for deleting open orders. The first example targets a specific symbol, while the second deletes all open orders for the authenticated account. ```Python deleteOrderRes = client.delete_open_orders(symbol="BTC-USDC") print(deleteOrderRes) deleteOrderRes = client.delete_open_orders() print(deleteOrderRes) ``` -------------------------------- ### Access Private Apex Protocol Endpoints Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Shows how to access private API endpoints after registration. This requires providing API key credentials (key, secret, passphrase) to the `HttpPrivate` client. It includes examples for fetching user data, modifying user profiles, retrieving account information, and querying orders and notifications. ```Python from apexomni.http_private import HttpPrivate from apexomni.constants import APEX_HTTP_TEST, NETWORKID_TEST # need apiKey={'key': key,'secret': secret, 'passphrase': passphrase} for private api key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' client = HttpPrivate(APEX_HTTP_TEST, network_id=NETWORKID_TEST, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) configs = client.configs() userRes = client.get_user() print(userRes) modifyUserRes = client.modify_user(username="pythonTest", email="11@aa.com", emailNotifyGeneralEnable="false") print(modifyUserRes) accountRes = client.get_account() print(accountRes) openOrdersRes = client.open_orders() print(openOrdersRes) historyOrdersRes = client.history_orders() print(historyOrdersRes) fundingRes = client.funding(limit=100, page=0, symbol="BTC-USDC", side="BUY") print(fundingRes) notifyListRes = client.notify_list(limit=100, page=0, unreadOnly="true", notifyCategory="1") print(notifyListRes) ... ``` -------------------------------- ### Register User with Apex Protocol Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates how to register a new user with the Apex Protocol. This involves deriving Stark key pairs, generating a nonce, and submitting registration details to obtain API keys. Requires the `apexomni.http_private` module and constants for network configuration. ```Python from apexomni.http_private import HttpPrivate from apexomni.constants import APEX_HTTP_TEST, NETWORKID_TEST, APEX_HTTP_MAIN, NETWORKID_MAIN priKey = "your eth private key" client = HttpPrivate(APEX_HTTP_TEST, network_id=NETWORKID_TEST, eth_private_key=priKey) configs = client.configs() stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address) nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'], ethAddress=client.default_address, chainId=NETWORKID_TEST) regRes = client.register_user(nonce=nonceRes['data']['nonce'], starkKey=stark_key_pair_with_y_coordinate['public_key'], stark_public_key_y_coordinate=stark_key_pair_with_y_coordinate['public_key_y_coordinate'], ethereum_address=client.default_address) key = regRes['data']['apiKey']['key'] secret = regRes['data']['apiKey']['secret'] passphrase = regRes['data']['apiKey']['passphrase'] #back stark_key_pair, apiKey,and accountId for private Api or create-order or withdraw print(stark_key_pair_with_y_coordinate) print(regRes['data']['account']['positionId']) print(regRes['data']['apiKey']) ``` -------------------------------- ### APIDOC: Account and Configuration Management Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Retrieve account details, network configurations, and user information. Requires API key credentials for authentication. The `configs_v2` method fetches network configurations, while `get_account_v2` retrieves user account details. `get_user` and `get_account_balance_v2` are specific to the Stark key signing client. ```APIDOC HttpPrivate Client Initialization: client = HttpPrivate(APEX_HTTP_TEST, network_id=NETWORKID_TEST, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) configs_v2(): - Fetches network configurations. - Parameters: None - Returns: Dictionary containing network configuration details. get_account_v2(): - Retrieves the user's account information. - Parameters: None - Returns: Dictionary containing account details. HttpPrivateStark Client Initialization: client = HttpPrivateStark(APEX_HTTP_TEST, network_id=NETWORKID_TEST, stark_public_key=public_key, stark_private_key=private_key, stark_public_key_y_coordinate=public_key_y_coordinate, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) get_user(): - Retrieves user profile information using Stark key authentication. - Parameters: None - Returns: Dictionary containing user profile data. get_account_balance_v2(): - Retrieves account balances using Stark key authentication. - Parameters: None - Returns: Dictionary containing account balance information. ``` -------------------------------- ### Create Market and Limit Orders with Apex Protocol API Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V3.md Demonstrates how to initialize the Apex Protocol HTTP client and place both market sell and limit buy orders with take-profit/stop-loss (TP/SL) functionality. Requires API keys, zk seeds, and l2Key for authentication. ```python from apexomni.constants import NETWORKID_TEST, APEX_OMNI_HTTP_TEST from apexomni.http_api import HttpPrivateSign import time import decimal print("Hello, Apex omni") key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' seeds = 'your zk seeds from register' l2Key = 'your l2Key seeds from register' client = HttpPrivateSign(APEX_OMNI_HTTP_TEST, network_id=NETWORKID_TEST, zk_seeds=seeds, zk_l2Key=l2Key, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) configs = client.configs_v3() accountData = client.get_account_v3() currentTime = time.time() createOrderRes = client.create_order_v3(symbol="BTC-USDT", side="SELL", type="MARKET", size="0.001", timestampSeconds=currentTime, price="60000") print(createOrderRes) # sample6 # Create a TP/SL order # first, Set a slippage to get an acceptable slPrice or tpPrice #slippage is recommended to be greater than 0.1 # when buying, the price = price*(1 + slippage). when selling, the price = price*(1 - slippage) slippage = decimal.Decimal("-0.1") slPrice = decimal.Decimal("58000") * (decimal.Decimal("1") + slippage) tpPrice = decimal.Decimal("79000") * (decimal.Decimal("1") - slippage) createOrderRes = client.create_order_v3(symbol="BTC-USDT", side="BUY", type="LIMIT", size="0.01", price="65000", isOpenTpslOrder=True, isSetOpenSl=True, slPrice=slPrice, slSide="SELL", slSize="0.01", slTriggerPrice="58000", isSetOpenTp=True, tpPrice=tpPrice, tpSide="SELL", tpSize="0.01", tpTriggerPrice="79000", ) print(createOrderRes) print("end, apexomni") ``` -------------------------------- ### Initialize Public HTTP Client (V2) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Creates an instance of the HttpPublic client for accessing public API endpoints, typically for test environments. Requires importing necessary constants and classes. ```python from apexomni.constants import APEX_HTTP_TEST from apexomni.http_public import HttpPublic client = HttpPublic(APEX_HTTP_TEST) ``` -------------------------------- ### Create Apex Limit Order Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Shows how to place a limit order for a given symbol, side, size, and price. It retrieves the taker fee rate and uses the current time for expiration. ```Python currentTime = time.time() limitFeeRate = client.account['takerFeeRate'] createOrderRes = client.create_order(symbol="BTC-USDC", side="BUY", type="LIMIT", size="0.01", price="1991", limitFeeRate=limitFeeRate, accountId=client.account['positionId'], expirationEpochSeconds=currentTime) print(createOrderRes) ``` -------------------------------- ### Create Apex Market Order Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates placing a market order, fetching the worst price for the specified symbol and side, and using it as the order price. Includes a note about market order price not being none. ```Python worstPrice = client.get_worst_price(symbol="BTC-USDC", side="SELL", size="0.1") price = worstPrice['data']['worstPrice'] ##market order price must not none createOrderRes = client.create_order(symbol="BTC-USDC", side="SELL", type="MARKET", size="1", price=price, limitFee=limitFee, expirationEpochSeconds=currentTime) print(createOrderRes) ``` -------------------------------- ### APIDOC: Margin and Configuration Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Set initial margin rates for trading pairs. The `set_initial_margin_rate_v2` method allows specifying the symbol, the desired initial margin rate, and the associated token. ```APIDOC set_initial_margin_rate_v2(symbol: str, initialMarginRate: str, token: str): - Sets the initial margin rate for a trading symbol. - Parameters: - symbol: The trading pair (e.g., "BTC-USDC"). - initialMarginRate: The desired initial margin rate (e.g., "0.1"). - token: The currency token (e.g., 'USDT'). - Returns: Response indicating success or failure of the operation. ``` -------------------------------- ### Initialize Private HTTP Client (V2) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Creates an instance of the HttpPrivate client for accessing private API endpoints, requiring network configuration and the user's Ethereum private key. ```python from apexomni.http_private import HttpPrivate from apexomni.constants import APEX_HTTP_TEST, NETWORKID_TEST priKey = "your eth private key" client = HttpPrivate(APEX_HTTP_TEST, network_id=NETWORKID_TEST, eth_private_key=priKey) ``` -------------------------------- ### Initialize HTTP Public Client Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README.md Demonstrates how to create an HTTP session for Inverse on APEX_OMNI_HTTP_TEST or APEX_OMNI_HTTP_MAIN using the `HttpPublic` class. ```python from apexomni.constants import APEX_OMNI_HTTP_TEST from apexomni.http_public import HttpPublic client = HttpPublic(APEX_OMNI_HTTP_TEST) ``` -------------------------------- ### HttpPrivateSign Client: Create Order Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README.md Demonstrates how to initialize the HttpPrivateSign client with API credentials and zk-related keys, and then use it to create market and limit orders, including take-profit/stop-loss (TP/SL) orders. Requires API keys, zk seeds, and zk l2Key for authentication. ```python from apexomni.constants import NETWORKID_TEST, APEX_OMNI_HTTP_TEST from apexomni.http_private_sign import HttpPrivateSign import time import decimal print("Hello, Apex omni") key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' seeds = 'your zk seeds from register' l2Key = 'your l2Key seeds from register' client = HttpPrivateSign(APEX_OMNI_HTTP_TEST, network_id=NETWORKID_TEST, zk_seeds=seeds, zk_l2Key=l2Key, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) configs = client.configs_v3() accountData = client.get_account_v3() currentTime = time.time() createOrderRes = client.create_order_v3(symbol="BTC-USDT", side="SELL", type="MARKET", size="0.001", timestampSeconds=currentTime, price="60000") print(createOrderRes) # sample6 # Create a TP/SL order # first, Set a slippage to get an acceptable slPrice or tpPrice #slippage is recommended to be greater than 0.1 # when buying, the price = price*(1 + slippage). when selling, the price = price*(1 - slippage) slippage = decimal.Decimal("-0.1") slPrice = decimal.Decimal("58000") * (decimal.Decimal("1") + slippage) tpPrice = decimal.Decimal("79000") * (decimal.Decimal("1") - slippage) createOrderRes = client.create_order_v3(symbol="BTC-USDT", side="BUY", type="LIMIT", size="0.01", price="65000", isOpenTpslOrder=True, isSetOpenSl=True, slPrice=slPrice, slSide="SELL", slSize="0.01", slTriggerPrice="58000", isSetOpenTp=True, tpPrice=tpPrice, tpSide="SELL", tpSize="0.01", tpTriggerPrice="79000", ) print(createOrderRes) print("end, Apexomni") ``` -------------------------------- ### Apexpro Public API Endpoints (V2) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates usage of various public API endpoints for fetching market data, configurations, and server status. Supports USDT and USDC symbols. Requires calling configs_v2() to obtain symbol configurations. ```APIDOC HttpPublic.configs_v2() - Fetches configuration details for symbols, supporting both USDT and USDC. - Returns: Dictionary containing symbol configurations. HttpPublic.history_funding_v2(symbol: str, limit: int = None, page: int = None, beginTimeInclusive: int = None, endTimeExclusive: int = None) - Retrieves historical funding rates for a given symbol. Supports pagination and time range filtering. - Parameters: - symbol: The trading symbol (e.g., "BTC-USDT"). - limit: Maximum number of records to return. - page: Page number for pagination. - beginTimeInclusive: Start timestamp (inclusive) for funding data. - endTimeExclusive: End timestamp (exclusive) for funding data. - Returns: List of historical funding records. HttpPublic.klines(symbol: str, interval: str, start: int = None, end: int = None, limit: int = None) - Retrieves candlestick (kline) data for a given symbol and interval. Supports time range and limit. - Parameters: - symbol: The trading symbol (e.g., "ETHUSDT"). - interval: The interval for klines (e.g., "5", "15"). - start: Start timestamp for kline data. - end: End timestamp for kline data. - limit: Maximum number of klines to return. - Returns: List of kline data. HttpPublic.server_time() - Retrieves the current server time. - Returns: Dictionary with server timestamp. HttpPublic.depth(symbol: str, limit: int = None) - Retrieves the order book depth for a given symbol. Supports limiting the number of entries. - Parameters: - symbol: The trading symbol (e.g., "BTC-USDC"). - limit: Maximum number of bid/ask entries to return. - Returns: Dictionary containing order book data. HttpPublic.trades(symbol: str, limit: int = None) - Retrieves recent trades for a given symbol. Supports limiting the number of trades. - Parameters: - symbol: The trading symbol (e.g., "BTC-USDC"). - limit: Maximum number of trades to return. - Returns: List of trade records. HttpPublic.ticker(symbol: str) - Retrieves ticker information for a given symbol. - Parameters: - symbol: The trading symbol (e.g., "BTC-USDT"). - Returns: Dictionary with ticker information. HttpPublic.history_funding(symbol: str) - Retrieves historical funding rates for a given symbol. - Parameters: - symbol: The trading symbol (e.g., "BTC-USDT"). - Returns: List of historical funding records. ``` -------------------------------- ### Apex Protocol HTTP API V2 Operations (Python) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Demonstrates various V2 HTTP API calls for managing orders, retrieving history, and checking fees. Requires an initialized client object. ```python from time import time # Assuming 'client' is an initialized HttpApi object # from apexomni.http_api import HttpApi # client = HttpApi(APEX_HTTP_MAIN) currentTime = int(time()) limitFeeRate = '0.0005' # Example: Get history of orders historyOrdersRes = client.history_orders_v2(token="USDT") print(historyOrdersRes) # Example: Get order fills for a specific order orderFills = client.order_fills_v2(orderId='498441108374684453') print(orderFills) # Example: Delete open orders for a token deleteOrdersRes = client.delete_open_orders_v2(token="USDT") print(deleteOrdersRes) # Example: Create a limit order createOrderRes = client.create_order_v2(symbol="BTC-USDT", side="SELL", type="LIMIT", size="0.01", expirationEpochSeconds=currentTime, price="36890", limitFeeRate=limitFeeRate, timeInForce="POST_ONLY") # print(createOrderRes) # Example: Get fills for a symbol fillsRes = client.fills_v2(limit=100, page=0, symbol="BTC-USDT", token="USDT") print(fillsRes) # Example: Get open orders for a token openOrderRes = client.open_orders_v2(token='USDT') print(openOrderRes) # Example: Get withdrawal fee feeRes = client.uncommon_withdraw_fee_v2(amount='2', chainId='97', token='USDT') print(feeRes) # Example: Cross-chain withdrawal crossWithdrawRes = client.cross_chain_withdraw_v2(amount='2', expirationEpochSeconds=currentTime, asset='USDT', fee=feeRes['data']['fee'], chainId='97') print(crossWithdrawRes) ``` -------------------------------- ### Initialize HTTP Public Client Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V3.md Creates an HTTP session for Inverse trading on Apex omni test or mainnet. Requires importing the HttpPublic class and specifying the API endpoint. ```python from apexomni.constants import APEX_OMNI_HTTP_TEST from apexomni.http_public import HttpPublic client = HttpPublic(APEX_OMNI_HTTP_TEST) ``` -------------------------------- ### Initialize HTTP Private Client V3 Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README.md Demonstrates how to create an HTTP session for private API calls using `HttpPrivate_v3`, requiring API keys and network configuration. ```python from apexomni.constants import APEX_OMNI_HTTP_MAIN, NETWORKID_OMNI_MAIN_ARB, NETWORKID_MAIN import time priKey = "your eth private key" client = HttpPrivate_v3(APEX_OMNI_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key=priKey) ``` -------------------------------- ### Subscribe to WebSocket Streams with Apex Protocol Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V3.md Demonstrates how to connect to the Apex Protocol WebSocket API and subscribe to various data streams like trades, klines, and account information. Requires API key credentials for authentication. ```python from time import sleep from apexomni.constants import APEX_OMNI_WS_MAIN from apexomni.websocket_api import WebSocket key = 'your apiKey-key from register V3' secret = 'your apiKey-secret from register V3' passphrase = 'your apiKey-passphrase from register V3' # Connect with authentication! # APEX_OMNI_WS_MAIN for mainnet, APEX_OMNI_WS_TEST for testnet ws_client = WebSocket( endpoint=APEX_OMNI_WS_MAIN, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}, ) def handle_account(message): print(message) contents_data = message["contents"] print(len(contents_data)) def h1(message): print(1, message) def h2(message): print(2, message) def h3(message): print(3, message) def h4(message): print(4, message) #ws_client.depth_stream(h1,'BTCUSDT',25) #ws_client.ticker_stream(h2,'BTCUSDT') ws_client.trade_stream(h3,'BTCUSDT') ws_client.klines_stream(h4,'BTCUSDT',1) ws_client.account_info_stream_v3(handle_account) while True: # Run your main trading logic here. sleep(1) ``` -------------------------------- ### Register User Account (V2) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Registers a user account for trading USDT or USDC symbols using the v2 interface. Requires generating a nonce and deriving Stark key pair. If a USDC account was previously registered with v1, re-registration is not needed. ```APIDOC HttpPrivate.derive_stark_key(eth_address: str) - Derives the Stark key pair (public key and public key y-coordinate) from an Ethereum address. - Parameters: - eth_address: The user's Ethereum address. - Returns: Dictionary containing 'public_key' and 'public_key_y_coordinate'. HttpPrivate.generate_nonce(starkKey: str, ethAddress: str, chainId: int) - Generates a nonce required for user registration and other private API calls. - Parameters: - starkKey: The public Stark key. - ethAddress: The user's Ethereum address. - chainId: The network chain ID (e.g., NETWORKID_TEST, NETWORKID_MAIN). - Returns: Dictionary containing the nonce. HttpPrivate.register_user_v2(token: str, nonce: str, starkKey: str, stark_public_key_y_coordinate: str, ethereum_address: str) - Registers a user account for trading a specific token (USDT or USDC). - Parameters: - token: The token to register ('USDT' or 'USDC'). - nonce: The nonce obtained from generate_nonce. - starkKey: The public Stark key. - stark_public_key_y_coordinate: The y-coordinate of the public Stark key. - ethereum_address: The user's Ethereum address. - Returns: Dictionary containing apiKey (key, secret, passphrase), account details (positionId), and Stark key information. ``` -------------------------------- ### Apexpro Private API Endpoints (V2) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Details on accessing private API endpoints, which require authentication. Users need to call configs_v2() and get_account_v2() to obtain account configurations. Authentication information like stark_key_pair, apiKey, and accountId are obtained via registration. ```APIDOC HttpPrivate.get_account_v2() - Retrieves account configuration details for private endpoints. Must be called after client initialization and configs_v2(). - Returns: Dictionary containing account-specific configurations. HttpPrivate.create_order(symbol: str, order_type: str, side: str, order_qty: str, price: str = None, time_in_force: str = None, reduce_only: bool = False, post_only: bool = False, client_order_id: str = None) - Places a new order on the Apexpro platform. - Parameters: - symbol: The trading symbol (e.g., "BTC-USDT"). - order_type: Type of order (e.g., "LIMIT", "MARKET"). - side: Order side ('BUY' or 'SELL'). - order_qty: The quantity of the asset to trade. - price: The price for limit orders. - time_in_force: Duration the order remains active (e.g., "GTC", "IOC"). - reduce_only: If true, the order only reduces the existing position. - post_only: If true, the order will only be posted to the order book and not matched immediately. - client_order_id: Optional unique identifier for the order. - Returns: Dictionary with order details. HttpPrivate.withdraw(token: str, amount: str, address: str, chainId: int, network: str = None, memo: str = None) - Initiates a withdrawal of assets from the Apexpro account. - Parameters: - token: The token to withdraw (e.g., "USDT"). - amount: The amount to withdraw. - address: The destination withdrawal address. - chainId: The network chain ID. - network: The specific network for withdrawal (e.g., "ERC20", "TRC20"). - memo: Optional memo for certain cryptocurrencies. - Returns: Dictionary with withdrawal status and details. ``` -------------------------------- ### Apex Protocol WebSocket Account Info Stream (Python) Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Connects to the Apex Protocol WebSocket API to subscribe to account information updates. Requires authentication credentials and defines handler functions for incoming messages. ```python from time import sleep from apexomni.constants import APEX_WS_TEST from apexomni.websocket_api import WebSocket key = 'your apiKey-key from register' secret = 'your apiKey-secret from register' passphrase = 'your apiKey-passphrase from register' # Connect with authentication! ws_client = WebSocket( endpoint=APEX_WS_TEST, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}, ) def handle_account(message): print(message) contents_data = message["contents"] print(len(contents_data)) # Subscribe to account info stream ws_client.account_info_stream(handle_account) while True: # Run your main trading logic here. sleep(1) ``` -------------------------------- ### Python: Private Endpoints V3 Usage Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V3.md Demonstrates how to use private API endpoints for account and order management with Apex Omni. Requires API key credentials for authentication. ```python from apexomni.constants import APEX_OMNI_HTTP_MAIN, NETWORKID_OMNI_MAIN_ARB from apexomni.http_private_v3 import HttpPrivate_v3 print("Hello, Apex Omni") # need api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase} for private api key = 'your apiKey-key from register V3' secret = 'your apiKey-secret from register V3' passphrase = 'your apiKey-passphrase from register V3' client = HttpPrivate_v3(APEX_OMNI_HTTP_MAIN, network_id=NETWORKID_OMNI_MAIN_ARB, api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase}) configs = client.configs_v3() userRes = client.get_user_v3() print(userRes) accountRes = client.get_account_v3() print(accountRes) accountBalanceRes = client.get_account_balance_v3() print(accountBalanceRes) fillsRes = client.fills_v3(limit=100, page=0, symbol="BTC-USDT", side="BUY", token="USDT") print(fillsRes) transfersRes = client.transfers_v3(limit=100) print(transfersRes) transferRes = client.transfer_v3(ids='586213648326721628') print(transferRes) transfersRes = client.contract_transfers_v3(limit=100) print(transfersRes) transferRes = client.contract_transfer_v3(ids='588301879870489180') print(transferRes) # deleteOrderRes = client.delete_order_v3(id="588302655921587036") # print(deleteOrderRes) # deleteOrderRes = client.delete_order_by_client_order_id_v3(id="123456") # print(deleteOrderRes) openOrdersRes = client.open_orders_v3() print(openOrdersRes) deleteOrdersRes = client.delete_open_orders_v3(symbol="BTC-USDT") print(deleteOrdersRes) historyOrdersRes = client.history_orders_v3(token='USDT') print(historyOrdersRes) getOrderRes = client.get_order_v3(id="123456") print(getOrderRes) getOrderRes = client.get_order_by_client_order_id_v3(id="123456") print(getOrderRes) fundingRes = client.funding_v3(limit=100) print(fundingRes) historicalPnlRes = client.historical_pnl_v3(limit=100) print(historicalPnlRes) yesterdayPnlRes = client.yesterday_pnl_v3() print(yesterdayPnlRes) historyValueRes = client.history_value_v3() print(historyValueRes) setInitialMarginRateRes = client.set_initial_margin_rate_v3(symbol="BTC-USDT", initialMarginRate="0.05") print(setInitialMarginRateRes) ``` -------------------------------- ### Stark Key Signature Authentication for Apex Protocol Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Details the requirement for Stark key signature authentication for specific Apex Protocol endpoints, such as creating orders and processing withdrawals. This method utilizes the `HttpPrivateStark` class for signing requests. ```Python import time from apexomni.http_private_stark_key_sign import HttpPrivateStark from apexomni.constants import APEX_HTTP_TEST, NETWORKID_TEST # need api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase} for private api ``` -------------------------------- ### APIDOC: Fills and Funding Source: https://github.com/apex-protocol/apexpro-openapi/blob/main/README_V2.md Retrieve details about executed trades (fills) and funding rates. The `fills_v2` method allows filtering by symbol, side, and token, with pagination. `funding_v2` retrieves funding information for a given symbol and token. ```APIDOC fills_v2(limit: int = 100, page: int = 0, symbol: str, side: str, token: str): - Retrieves a list of executed trades (fills). - Parameters: - limit: Maximum number of results per page. - page: Page number for pagination. - symbol: Trading pair (e.g., "BTC-USDT"). - side: Side of the trade ('BUY' or 'SELL'). - token: The currency token (e.g., 'USDT'). - Returns: List of fill objects. funding_v2(limit: int = 100, page: int = 0, symbol: str, side: str, token: str): - Retrieves funding rates and information. - Parameters: - limit: Maximum number of results per page. - page: Page number for pagination. - symbol: Trading pair (e.g., "BTC-USDC"). - side: Side of the trade ('BUY' or 'SELL'). - token: The currency token (e.g., 'USDT'). - Returns: List of funding rate objects. ```