### Connect and Start Receiving Quotes Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Initiate the connection to the quotes server and enter the event loop to continuously receive data. This is a blocking call. ```python client.connect_and_loop_forever() ``` -------------------------------- ### gRPC Client Setup for Market Data Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Initialize the gRPC client for high-performance market data queries, including streaming. Configure host, port, and TLS settings as needed. Logging can be enabled for debugging. ```python import sys from webullsdkquotescore.grpc.grpc_client import GrpcApiClient from webullsdkmdata.quotes.grpc.market_data import MarketData from webullsdkmdata.quotes.grpc.instrument import Instrument # Create gRPC client grpc_client = GrpcApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="us", # us, hk host="grpc.webull.com", # Optional custom host port=443, tls_enable=True ) # Enable logging log_format = '%(thread)d %(asctime)s %(name)s %(levelname)s %(message)s' grpc_client.set_stream_logger(stream=sys.stdout, format_string=log_format) # Initialize market data and instrument services market_data = MarketData(grpc_client) instrument = Instrument(grpc_client) ``` -------------------------------- ### Get Account Profile Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieve basic account profile information using the Account class. Handles potential server exceptions. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.account_info import Account from webullsdkcore.exception.exceptions import ServerException api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") account = Account(api_client) try: # Get account profile (static information) response = account.get_account_profile(account_id="your_account_id") profile = response.json() print(f"Account ID: {profile.get('account_id')}") print(f"Account Type: {profile.get('account_type')}") print(f"Account Status: {profile.get('status')}") except ServerException as e: print(f"Error {e.get_error_code()}: {e.get_error_msg()}") ``` -------------------------------- ### Get Detailed Position Information Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Fetches detailed information for a specific financial instrument within an account. ```python details_response = account.get_account_position_details( account_id="your_account_id", instrument_id="913256409", size=20, last_instrument_id=None ) ``` -------------------------------- ### Get Account Positions with Pagination Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieves a paginated list of account positions. Use the last instrument ID from a previous response for subsequent pagination. ```python response = account.get_account_position( account_id="your_account_id", page_size=20, # Max 100 last_instrument_id=None # For pagination, use last ID from previous response ) positions = response.json() for position in positions.get('positions', []): print(f"Symbol: {position.get('symbol')}") print(f"Quantity: {position.get('qty')}") print(f"Market Value: {position.get('market_value')}") print(f"Unrealized P&L: {position.get('unrealized_pnl')}") print("---") ``` -------------------------------- ### Get Account Balance Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Query account balance details, including total assets, cash, and buying power, with options to specify the base currency. Requires an initialized ApiClient and Account object. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.account_info import Account from webullsdktrade.common.currency import Currency api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") account = Account(api_client) # Get account balance with HKD as base currency response = account.get_account_balance( account_id="your_account_id", total_asset_currency=Currency.HKD.name # Options: HKD, USD, CNH, CAD ) balance = response.json() print(f"Total Assets: {balance.get('total_asset')}") print(f"Cash Balance: {balance.get('cash')}") print(f"Buying Power: {balance.get('buying_power')}") print(f"Currency: {balance.get('currency')}") ``` -------------------------------- ### GET /account/subscriptions Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Query the list of accounts subscribed to your application with pagination support. ```APIDOC ## GET /account/subscriptions ### Description Query the list of accounts subscribed to your application with pagination support. ### Parameters #### Query Parameters - **subscription_id** (string) - Optional - The last subscription_id from the previous response for pagination. ### Response #### Success Response (200) - **subscriptions** (array) - List of subscription objects containing subscription_id and account_id. ``` -------------------------------- ### GET /account/positions Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieves a list of positions for a specific account with pagination support. ```APIDOC ## GET /account/positions ### Description Retrieves a list of positions for a specific account with pagination support. ### Parameters #### Query Parameters - **account_id** (string) - Required - The unique identifier for the account. - **page_size** (integer) - Optional - Number of items per page (max 100). - **last_instrument_id** (string) - Optional - The last instrument ID from the previous response for pagination. ### Response #### Success Response (200) - **positions** (array) - List of position objects containing symbol, qty, market_value, and unrealized_pnl. ``` -------------------------------- ### Get Authentication Token Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Obtain an authentication token required for creating and managing subscriptions. This token is obtained via a JSON response. ```python # Get authentication token first token_response = market_data.get_token() token = token_response.json().get('token') ``` -------------------------------- ### Get Tradeable Instruments List Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Fetches a list of tradeable instruments, currently supported only for the Japan market. Pagination is handled via `page_size` and `last_instrument_id`. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.trade_instrument import TradeInstrument api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") instrument = TradeInstrument(api_client) # Get tradeable instruments list (Japan only) instruments = instrument.get_tradeable_instruments( page_size=50, last_instrument_id=None ) for inst in instruments.json(): print(f"Instrument: {inst.get('instrument_id')} - {inst.get('symbol')}") ``` -------------------------------- ### Get Account Positions Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieve a paginated list of account positions, including instrument details, quantity, market value, and P&L. Requires an initialized ApiClient and Account object. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.account_info import Account api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") account = Account(api_client) ``` -------------------------------- ### Get Trading Calendar Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieve the trading calendar for a specified market and date range. The response includes dates and whether each date is a trading day. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.trade_calendar import TradeCalendar api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") calendar = TradeCalendar(api_client) # Get trading calendar for HK market response = calendar.get_trade_calendar( market="HK", # HK, US, JP start="2024-01-01", end="2024-01-31" ) trading_days = response.json() print(f"Trading days in January: {len(trading_days)}") for day in trading_days: print(f"Date: {day.get('date')} - Trading: {day.get('is_trading_day')}") ``` -------------------------------- ### Query Instrument Details by ID Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Use this to get detailed information about a specific tradeable instrument using its unique ID. Ensure the ApiClient is initialized with your credentials and region. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.trade_instrument import TradeInstrument api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") instrument = TradeInstrument(api_client) # Get instrument by ID response = instrument.get_trade_instrument_detail(instrument_id="913256409") details = response.json() print(f"Symbol: {details.get('symbol')}") print(f"Name: {details.get('name')}") print(f"Market: {details.get('market')}") ``` -------------------------------- ### Error Handling for API Requests Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Implement robust error handling for API requests using SDK-provided exception classes like ServerException and ClientException. This example demonstrates catching specific error codes for network issues or invalid requests. ```python from webullsdkcore.client import ApiClient from webullsdkcore.exception.exceptions import ClientException, ServerException from webullsdkcore.exception import error_code from webullsdktrade.trade.order_operation import OrderOperation api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops = OrderOperation(api_client) try: response = order_ops.place_order( account_id="your_account_id", qty=100, instrument_id="913256409", side="BUY", client_order_id="order_001", order_type="LIMIT", extended_hours_trading=False, tif="DAY", limit_price="385.00" ) result = response.json() print(f"Success: {result}") except ServerException as se: # Server-side errors (API errors, validation failures, etc.) print(f"Server Error Code: {se.get_error_code()}") print(f"Server Error Message: {se.get_error_msg()}") print(f"HTTP Status: {se.get_http_status()}") print(f"Request ID: {se.get_request_id()}") except ClientException as ce: # Client-side errors (network issues, invalid requests, etc.) print(f"Client Error Code: {ce.get_error_code()}") print(f"Client Error Message: {ce.get_error_msg()}") # Check specific error types if ce.get_error_code() == error_code.SDK_HTTP_ERROR: print("Network error occurred") elif ce.get_error_code() == error_code.SDK_INVALID_REQUEST: print("Invalid request format") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Get Streaming Token for gRPC Market Data Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Obtain an authentication token required for subscribing to real-time market data streams via gRPC. This token is essential for establishing a connection to the streaming service. ```python from webullsdkquotescore.grpc.grpc_client import GrpcApiClient from webullsdkmdata.quotes.grpc.market_data import MarketData grpc_client = GrpcApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="us" ) market_data = MarketData(grpc_client) # Get streaming token response = market_data.get_token() print(f"Request ID: {response.request_id}") print(f"Status: {response.status_code}") token = response.json().get('token') print(f"Token: {token}") ``` -------------------------------- ### Initialize MQTT Subscription Client Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Imports required for setting up the MQTT-based streaming client for real-time market data. ```python from webullsdkcore.common.region import Region from webullsdkmdata.common.category import Category from webullsdkmdata.common.subscribe_type import SubscribeType from webullsdkmdata.quotes.subscribe.default_client import DefaultQuotesClient ``` -------------------------------- ### Initialize Market Data Client Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Set up the GrpcApiClient and MarketData client for managing real-time quote subscriptions. Requires app key, secret, and region. ```python from webullsdkquotescore.grpc.grpc_client import GrpcApiClient from webullsdkmdata.quotes.grpc.market_data import MarketData grpc_client = GrpcApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="us" ) market_data = MarketData(grpc_client) ``` -------------------------------- ### Initialize Events Client Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Set up the EventsClient for subscribing to real-time order and position status changes. Configure region, host, port, TLS, and retry policy. ```python from webullsdktrade.events.types import ORDER_STATUS_CHANGED, EVENT_TYPE_ORDER, EVENT_TYPE_POSITION, POSITION_STATUS_CHANGED from webullsdktradeeventscore.events_client import EventsClient from webullsdktradeeventscore.default_retry_policy import DefaultSubscribeRetryPolicy import logging # Create events client events_client = EventsClient( app_key="your_app_key", app_secret="your_app_secret", region_id="hk", # us, hk, jp host="events.webull.hk", # Optional custom endpoint port=443, tls_enable=True, retry_policy=DefaultSubscribeRetryPolicy(max_retry_times=5) ) ``` -------------------------------- ### Initialize Subscription Settings Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Configure the default settings for real-time data subscriptions, specifying symbols, category, and data types. ```python client.init_default_settings( symbols='00700', # Single symbol or comma-separated category=Category.HK_STOCK.name, # US_STOCK, HK_STOCK, etc. sub_types=SubscribeType.SNAPSHOT.name # QUOTE, SNAPSHOT, TICK ) ``` -------------------------------- ### Initialize and Connect Quotes Client Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Configure and connect the DefaultQuotesClient for real-time data. Ensure correct region, host, and transport settings are used. ```python client = DefaultQuotesClient( app_key="your_app_key", app_secret="your_app_secret", region_id=Region.HK.value, # us, hk host="quotes.webull.hk", # Optional custom endpoint tls_enable=True, transport="tcp" ) ``` -------------------------------- ### Preview and Place Option Order Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Preview and place option orders using `preview_option` and `place_option`. Requires defining the option order details in a dictionary. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.order_operation import OrderOperation api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops = OrderOperation(api_client) # Define option order option_order = { "client_order_id": "opt_order_001", "instrument_id": "option_instrument_id", "side": "BUY", "order_type": "LIMIT", "limit_price": "5.50", "qty": "1", "tif": "DAY" } # Preview option order preview = order_ops.preview_option( account_id="your_account_id", new_orders=option_order ) print(f"Option preview: {preview.json()}") # Place option order response = order_ops.place_option( account_id="your_account_id", new_orders=option_order ) print(f"Option order placed: {response.json()}") ``` -------------------------------- ### Create Real-Time Data Subscription Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Establish a subscription for real-time market data. Specify the authentication token, symbols, category, and desired subscription types. ```python # Create subscription for real-time data symbols = ['AAPL', 'MSFT', 'GOOGL'] sub_response = market_data.create_subscription_rel( token=token, symbols=symbols, category="US_STOCK", sub_types=["SNAPSHOT", "QUOTE"] # SNAPSHOT, QUOTE, TICK ) print(f"Subscription status: {sub_response.status_code}") ``` -------------------------------- ### Configure Quotes Client Callbacks Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Set up callback functions for logging, message handling, and subscription success. These functions are invoked by the client upon specific events. ```python def on_log(client, userdata, level, buf): print(f"Log [{level}]: {buf}") def on_message(client, userdata, message): print(f"Topic: {message.topic}") print(f"Payload: {message.payload}") print(f"QoS: {message.qos}") def on_subscribe_success(client, grpc_client, token): print(f"Subscription successful with token: {token}") client.on_log = on_log client.on_message = on_message client.on_subscribe_success = on_subscribe_success ``` -------------------------------- ### Place Order V2 (Japan/HK Institutional) Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt A simplified order API for Webull Japan individual clients and Hong Kong institutional clients using symbol-based ordering. Supports previewing orders before placement. ```python import uuid from webullsdkcore.client import ApiClient from webullsdktrade.trade.v2.order_operation_v2 import OrderOperationV2 from webullsdkmdata.common.category import Category api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="jp") order_ops_v2 = OrderOperationV2(api_client) # Define order parameters new_order = { "client_order_id": uuid.uuid4().hex, "symbol": "AAPL", "instrument_type": "EQUITY", # EQUITY, OPTION "market": "US", # US, HK, JP "order_type": "LIMIT", # LIMIT, MARKET, STOP, STOP_LIMIT "limit_price": "196.00", "quantity": "10", "support_trading_session": "N", # Y for extended hours "side": "BUY", # BUY, SELL "time_in_force": "DAY", # DAY, GTC, GTD, IOC, FOK "entrust_type": "QTY" # QTY (by quantity) or CASH (by amount) } # Preview order before placing (optional) preview_response = order_ops_v2.preview_order( account_id="your_account_id", preview_orders=new_order ) print(f"Order preview: {preview_response.json()}") # Place the order response = order_ops_v2.place_order( account_id="your_account_id", new_orders=new_order ) print(f"Order result: {response.json()}") ``` -------------------------------- ### Initialize Webull API Client Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Initialize the ApiClient for HTTP-based API interactions. Supports basic and advanced configurations including custom endpoints and logging. ```python from webullsdkcore.client import ApiClient from webullsdkcore.common.region import Region # Basic client initialization api_client = ApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="hk" # Options: 'us', 'hk', 'jp' ) # Advanced client with custom settings api_client = ApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id=Region.US.value, timeout=30, # Read timeout in seconds connect_timeout=10, # Connection timeout in seconds auto_retry=True, # Enable automatic retry max_retry_num=3, # Maximum retry attempts user_id="optional_user_id" # Optional user identifier ) # Add custom endpoint for non-production environments api_client.add_endpoint("hk", "https://api-uat.webull.hk") # Enable logging for debugging api_client.set_stream_logger(log_level=logging.DEBUG) # Or log to file api_client.set_file_logger("/var/log/webull-sdk.log", log_level=logging.INFO) ``` -------------------------------- ### Configure Events Client Callbacks Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Define and set callback functions for connection success, event messages, and logging. These handlers process incoming events and client status. ```python # Enable logging events_client.enable_logger() # Define callback for connection success def on_connect(client, payload, response): print(f"Connected successfully!") print(f"Payload: {payload}") # Define callback for event messages def on_events_message(event_type, subscribe_type, payload, raw_message): if event_type == EVENT_TYPE_ORDER and subscribe_type == ORDER_STATUS_CHANGED: print("=== Order Status Changed ===") print(f"Request ID: {payload.get('request_id')}") print(f"Account ID: {payload.get('account_id')}") print(f"Client Order ID: {payload.get('client_order_id')}") print(f"Order Status: {payload.get('order_status')}") print(f"Filled Quantity: {payload.get('filled_qty')}") print(f"Filled Price: {payload.get('filled_price')}") elif event_type == EVENT_TYPE_POSITION and subscribe_type == POSITION_STATUS_CHANGED: print("=== Position Changed ===") print(f"Account ID: {payload.get('account_id')}") print(f"Instrument ID: {payload.get('instrument_id')}") print(f"Quantity: {payload.get('qty')}") # Define logging callback def on_log(level, message): print(f"[{logging.getLevelName(level)}] {message}") # Set callbacks events_client.on_connect = on_connect events_client.on_events_message = on_events_message events_client.on_log = on_log ``` -------------------------------- ### Query Instrument Details by Symbol and Market Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieve instrument details using a combination of symbol and market. This method also supports querying options data if strike price and expiration date are provided. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.trade_instrument import TradeInstrument api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") instrument = TradeInstrument(api_client) # Get instrument by symbol and market (supports options) security = instrument.get_trade_security_detail( symbol="AAPL", market="US", instrument_super_type="EQUITY", # EQUITY, OPTION instrument_type="ETF", # WARRANT, UNITS, ETF, CALL_OPTION, PUT_OPTION strike_price=None, # Required for options init_exp_date=None # Format: yyyy-MM-dd, required for options ) print(f"Security details: {security.json()}") ``` -------------------------------- ### Subscribe to Order Status Events Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Initiate a subscription to receive real-time order status change events for specified account IDs. This is a blocking call. ```python # Subscribe to events for specific accounts (blocking call) account_ids = ["account_id_1", "account_id_2"] events_client.do_subscribe(account_ids) ``` -------------------------------- ### POST /order/v2/place Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Simplified order placement interface for Webull Japan individual clients and Hong Kong institutional clients. ```APIDOC ## POST /order/v2/place ### Description The V2 order API provides a simplified interface for Webull Japan individual clients and Hong Kong institutional clients with symbol-based ordering. ### Parameters #### Request Body - **account_id** (string) - Required - The account identifier. - **new_orders** (object) - Required - Order details including client_order_id, symbol, instrument_type, market, order_type, limit_price, quantity, support_trading_session, side, time_in_force, and entrust_type. ``` -------------------------------- ### Query Today's Orders with Pagination Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieve today's orders using `list_today_orders`. Supports pagination via `page_size` and `last_client_order_id`. The maximum `page_size` is 100. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.order_operation import OrderOperation api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops = OrderOperation(api_client) # Get today's orders with pagination today_orders = order_ops.list_today_orders( account_id="your_account_id", page_size=50, # Max 100 last_client_order_id=None # For pagination ) for order in today_orders.json().get('orders', []): print(f"Order ID: {order.get('client_order_id')}") print(f"Status: {order.get('status')}") print(f"Symbol: {order.get('symbol')}") ``` -------------------------------- ### Query Open (Pending) Orders Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieve a list of currently open (pending) orders using `list_open_orders`. Pagination is supported via the `page_size` parameter. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.order_operation import OrderOperation api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops = OrderOperation(api_client) # Get open (pending) orders open_orders = order_ops.list_open_orders( account_id="your_account_id", page_size=20 ) print(f"Open orders: {open_orders.json()}") ``` -------------------------------- ### Query Specific Order Details Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Fetch detailed information for a specific order using its `account_id` and `client_order_id` with the `query_order_detail` method. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.order_operation import OrderOperation api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops = OrderOperation(api_client) # Get specific order details order_detail = order_ops.query_order_detail( account_id="your_account_id", client_order_id="unique_order_id_001" ) print(f"Order details: {order_detail.json()}") ``` -------------------------------- ### Query Real-Time Quotes and Snapshots Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieves bid/ask depth for a single symbol or market snapshots for multiple symbols. ```python from webullsdkquotescore.grpc.grpc_client import GrpcApiClient from webullsdkmdata.quotes.grpc.market_data import MarketData grpc_client = GrpcApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="us" ) market_data = MarketData(grpc_client) # Get depth quote for single symbol quote_response = market_data.get_quote(symbol="AAPL", category="US_STOCK") quote = quote_response.json() print(f"Symbol: {quote.get('symbol')}") print(f"Last Price: {quote.get('last_price')}") print(f"Bid: {quote.get('bid')} x {quote.get('bid_size')}") print(f"Ask: {quote.get('ask')} x {quote.get('ask_size')}") # Get snapshot for multiple symbols (max 100, 20 for HK BMP) snapshot_response = market_data.get_snapshot( symbols="AAPL,MSFT,GOOGL", # Comma-separated symbols category="US_STOCK" ) snapshots = snapshot_response.json() for snap in snapshots.get('snapshots', []): print(f"{snap.get('symbol')}: ${snap.get('last_price')} ({snap.get('change_percent')}%)") ``` -------------------------------- ### List App Subscriptions with Pagination Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Queries the list of accounts subscribed to your application. Supports pagination using the last subscription ID. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.account_info import Account api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") account = Account(api_client) # Get subscribed accounts (first page) response = account.get_app_subscriptions() subscriptions = response.json() for sub in subscriptions: print(f"Subscription ID: {sub.get('subscription_id')}") print(f"Account ID: {sub.get('account_id')}") # Get next page using last subscription_id next_response = account.get_app_subscriptions( subscription_id=subscriptions[-1].get('subscription_id') ) ``` -------------------------------- ### Place Limit Order (HK Market) Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Places a limit order for Hong Kong stocks or China Connect A-shares. Requires specifying instrument ID, quantity, side, order type, and limit price. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.order_operation import OrderOperation from webullsdkmdata.common.category import Category from webullsdkcore.exception.exceptions import ServerException api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops = OrderOperation(api_client) try: # Place a limit order for HK stock response = order_ops.place_order( account_id="your_account_id", qty=100, # Quantity (max 1,000,000) instrument_id="913256409", # Instrument ID (e.g., Tencent) side="BUY", # BUY or SELL client_order_id="unique_order_id_001", # Your unique order ID (max 40 chars) order_type="ENHANCED_LIMIT", # LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, ENHANCED_LIMIT, AT_AUCTION_LIMIT extended_hours_trading=False, # Pre/post market (limit orders only) tif="DAY", # DAY, GTC, GTD limit_price="385.00", # Required for limit orders stop_price=None, # Required for stop orders trailing_type=None, # For trailing stop: AMOUNT or PERCENT trailing_stop_step=None # Trailing stop value ) result = response.json() print(f"Order placed successfully: {result}") except ServerException as e: print(f"Order failed - {e.get_error_code()}: {e.get_error_msg()}") ``` -------------------------------- ### Query Instrument Information Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieves specifications and trading rules for a specific instrument. ```python from webullsdkquotescore.grpc.grpc_client import GrpcApiClient from webullsdkmdata.quotes.grpc.instrument import Instrument grpc_client = GrpcApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="us" ) instrument = Instrument(grpc_client) # Get instrument details response = instrument.get_instrument(symbol="AAPL", category="US_STOCK") info = response.json() print(f"Symbol: {info.get('symbol')}") print(f"Name: {info.get('name')}") print(f"Exchange: {info.get('exchange')}") print(f"Lot Size: {info.get('lot_size')}") print(f"Tick Size: {info.get('tick_size')}") ``` -------------------------------- ### Add Custom Headers for Rate Limiting Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Add custom headers to requests for market-specific rate limiting, such as for the Hong Kong market. Ensure custom headers are removed after the request is complete. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.order_operation import OrderOperation from webullsdkmdata.common.category import Category api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops = OrderOperation(api_client) # Add custom headers for rate limiting category custom_headers = {"category": Category.HK_STOCK.name} order_ops.add_custom_headers(custom_headers) try: # Make request with custom headers response = order_ops.place_order( account_id="your_account_id", qty=100, instrument_id="913256409", side="BUY", client_order_id="order_001", order_type="ENHANCED_LIMIT", extended_hours_trading=False, tif="DAY", limit_price="385.00" ) finally: # Always clean up custom headers after request order_ops.remove_custom_headers() ``` -------------------------------- ### POST /order/place Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Place buy or sell orders for Hong Kong stocks and China Connect A-shares. ```APIDOC ## POST /order/place ### Description Place buy or sell orders for Hong Kong stocks and China Connect A-shares. Supports multiple order types including limit, market, stop-loss, and trailing stop orders. ### Parameters #### Request Body - **account_id** (string) - Required - The account identifier. - **qty** (integer) - Required - Quantity of shares (max 1,000,000). - **instrument_id** (string) - Required - The instrument identifier. - **side** (string) - Required - BUY or SELL. - **client_order_id** (string) - Required - Unique order ID (max 40 chars). - **order_type** (string) - Required - Order type (e.g., LIMIT, MARKET, STOP_LOSS, ENHANCED_LIMIT). - **extended_hours_trading** (boolean) - Optional - Enable pre/post market trading. - **tif** (string) - Required - Time in force (DAY, GTC, GTD). - **limit_price** (string) - Optional - Required for limit orders. - **stop_price** (string) - Optional - Required for stop orders. ``` -------------------------------- ### Real-Time Quotes - Subscription Management Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Manage real-time quote subscriptions including creating and removing subscription relationships. ```APIDOC ## Real-Time Quotes - Subscription Management ### Description Manage real-time quote subscriptions including creating and removing subscription relationships. ### Method POST ### Endpoint /api/v1/quotes/subscribe ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **token** (string) - Required - Authentication token. - **symbols** (array of strings) - Required - List of symbols to subscribe to. - **category** (string) - Required - Category of the symbols (e.g., "US_STOCK", "HK_STOCK"). - **sub_types** (array of strings) - Required - Types of data to subscribe to (e.g., "SNAPSHOT", "QUOTE", "TICK"). ### Request Example ```json { "token": "your_auth_token", "symbols": ["AAPL", "MSFT", "GOOGL"], "category": "US_STOCK", "sub_types": ["SNAPSHOT", "QUOTE"] } ``` ### Response #### Success Response (200) - **status_code** (integer) - The status code of the subscription request. #### Response Example ```json { "status_code": 200 } ``` ## Remove Real-Time Quotes Subscription ### Description Remove specific or all real-time quote subscriptions. ### Method DELETE ### Endpoint /api/v1/quotes/unsubscribe ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **token** (string) - Required - Authentication token. - **symbols** (array of strings) - Optional - List of symbols to unsubscribe from. If null, all subscriptions for the given category and sub_types will be removed. - **category** (string) - Optional - Category of the symbols. If null and symbols is null, all subscriptions will be removed. - **sub_types** (array of strings) - Optional - Types of data to unsubscribe from. If null and symbols is null, all subscriptions will be removed. - **unsubscribe_all** (boolean) - Required - Set to true to remove all subscriptions. ### Request Example ```json { "token": "your_auth_token", "symbols": ["GOOGL"], "category": "US_STOCK", "sub_types": ["SNAPSHOT"], "unsubscribe_all": false } ``` ### Response #### Success Response (200) - **status_code** (integer) - The status code of the unsubscription request. #### Response Example ```json { "status_code": 200 } ``` ``` -------------------------------- ### Order Operations - Query Orders Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Query order details, today's orders, and open (pending) orders with pagination support. ```APIDOC ## GET /api/orders/today ### Description Query today's orders with pagination support. ### Method GET ### Endpoint /api/orders/today ### Parameters #### Query Parameters - **account_id** (string) - Required - The ID of the account. - **page_size** (integer) - Optional - The number of orders to return per page (max 100). - **last_client_order_id** (string) - Optional - Used for pagination to retrieve the next set of orders. ### Response #### Success Response (200) - **orders** (array) - A list of order objects. - **client_order_id** (string) - The client-defined ID of the order. - **status** (string) - The current status of the order. - **symbol** (string) - The trading symbol of the instrument. ## GET /api/orders/open ### Description Query open (pending) orders with pagination support. ### Method GET ### Endpoint /api/orders/open ### Parameters #### Query Parameters - **account_id** (string) - Required - The ID of the account. - **page_size** (integer) - Optional - The number of orders to return per page. ### Response #### Success Response (200) - **orders** (array) - A list of open order objects. ## GET /api/orders/{client_order_id} ### Description Query details for a specific order using its client order ID. ### Method GET ### Endpoint /api/orders/{client_order_id} ### Parameters #### Path Parameters - **client_order_id** (string) - Required - The unique identifier of the order to query. #### Query Parameters - **account_id** (string) - Required - The ID of the account. ### Response #### Success Response (200) - **order_detail** (object) - An object containing the details of the specified order. ``` -------------------------------- ### Remove All Subscriptions Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Cancel all active real-time data subscriptions by setting unsubscribe_all to True. Symbols, category, and sub_types can be None in this case. ```python # Remove all subscriptions market_data.remove_subscription_rel( token=token, symbols=None, category=None, sub_types=None, unsubscribe_all=True ) ``` -------------------------------- ### Query Tick-by-Tick Transaction Data Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieves detailed tick data for trade analysis. ```python from webullsdkquotescore.grpc.grpc_client import GrpcApiClient from webullsdkmdata.quotes.grpc.market_data import MarketData grpc_client = GrpcApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="us" ) market_data = MarketData(grpc_client) # Get tick data tick_response = market_data.get_tick( symbol="AAPL", category="US_STOCK", count='100' # Default 30, max 1000 ) ticks = tick_response.json() for tick in ticks.get('ticks', []): print(f"Time: {tick.get('time')}") print(f"Price: {tick.get('price')}") print(f"Volume: {tick.get('volume')}") print(f"Side: {tick.get('side')}") # BUY, SELL, or UNKNOWN ``` -------------------------------- ### Order Events - Subscribe to Order Status Changes Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Subscribe to real-time order status change events using the gRPC-based events client. Receive push notifications when orders are filled, cancelled, or modified. ```APIDOC ## Order Events - Subscribe to Order Status Changes ### Description Subscribe to real-time order status change events using the gRPC-based events client. Receive push notifications when orders are filled, cancelled, or modified. ### Method POST ### Endpoint /api/v1/events/subscribe ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **account_ids** (array of strings) - Required - List of account IDs to subscribe to. ### Request Example ```json { "account_ids": ["account_id_1", "account_id_2"] } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of the subscription request. #### Response Example ```json { "message": "Successfully subscribed to events for specified accounts." } ``` ## Order Events - Unsubscribe from Order Status Changes ### Description Unsubscribe from real-time order status change events. ### Method DELETE ### Endpoint /api/v1/events/unsubscribe ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **account_ids** (array of strings) - Required - List of account IDs to unsubscribe from. ### Request Example ```json { "account_ids": ["account_id_1"] } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of the unsubscription request. #### Response Example ```json { "message": "Successfully unsubscribed from events for specified accounts." } ``` ``` -------------------------------- ### Query Order History (V2) Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieve historical orders for the past 7 days using `get_order_history_request`. Supports date range filtering and pagination. ```python from webullsdkcore.client import ApiClient from webullsdktrade.trade.v2.order_operation_v2 import OrderOperationV2 api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret", region_id="hk") order_ops_v2 = OrderOperationV2(api_client) # Query order history with date range history = order_ops_v2.get_order_history_request( account_id="your_account_id", page_size=20, start_date="2024-01-01", # Format: yyyy-MM-dd end_date="2024-01-07", last_client_order_id=None # For pagination ) for order in history.json().get('orders', []): print(f"Order: {order.get('client_order_id')} - {order.get('status')}") ``` -------------------------------- ### Order Operations - Order History (V2) Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Query historical orders for the past 7 days with date range filtering. ```APIDOC ## GET /api/v2/orders/history ### Description Query historical orders for the past 7 days with date range filtering. ### Method GET ### Endpoint /api/v2/orders/history ### Parameters #### Query Parameters - **account_id** (string) - Required - The ID of the account. - **page_size** (integer) - Optional - The number of orders to return per page (max 20). - **start_date** (string) - Required - The start date for the history query (format: yyyy-MM-dd). - **end_date** (string) - Required - The end date for the history query (format: yyyy-MM-dd). - **last_client_order_id** (string) - Optional - Used for pagination. ### Response #### Success Response (200) - **orders** (array) - A list of historical order objects. - **client_order_id** (string) - The client-defined ID of the order. - **status** (string) - The status of the order. ``` -------------------------------- ### Query Historical Candlestick Data via gRPC Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Retrieves historical bars for single or multiple symbols with support for trading session filtering. ```python from webullsdkquotescore.grpc.grpc_client import GrpcApiClient from webullsdkmdata.quotes.grpc.market_data import MarketData grpc_client = GrpcApiClient( app_key="your_app_key", app_secret="your_app_secret", region_id="us" ) market_data = MarketData(grpc_client) # Get historical bars for single symbol response = market_data.get_history_bar( symbol="AAPL", category="US_STOCK", timespan="M5", # M1, M5, M15, M30, M60, D, W, M count='200' # Max 1200 ) print(f"Status: {response.status_code}") bars = response.json() for bar in bars.get('bars', []): print(f"{bar.get('time')}: O={bar.get('open')} H={bar.get('high')} L={bar.get('low')} C={bar.get('close')}") # Get historical bars with trading session filter trading_sessions = ['PRE', 'RTH', 'POST'] # Pre-market, Regular Trading Hours, Post-market response = market_data.get_history_bar( symbol="AAPL", category="US_STOCK", timespan="M5", real_time_required="N", # Y or N trading_sessions=trading_sessions ) # Batch query for multiple symbols symbols = ['AAPL', 'MSFT', 'GOOGL', 'TSLA'] batch_response = market_data.get_batch_history_bar( symbols=symbols, category="US_STOCK", timespan="M1", count=100 ) for symbol_data in batch_response.json().get('data', []): print(f"Symbol: {symbol_data.get('symbol')}") print(f"Bars: {len(symbol_data.get('bars', []))}") ``` -------------------------------- ### Query Historical Bars (HTTP) Source: https://context7.com/webull-inc/openapi-python-sdk/llms.txt Fetch historical candlestick/OHLCV data using the HTTP API. Supports various timeframes from 1 minute to yearly. Ensure the correct endpoint is added for the desired region. ```python from webullsdkcore.client import ApiClient from webullsdkmdata.request.get_historical_bars_request import GetHistoricalBarsRequest from webullsdkmdata.common.category import Category from webullsdkmdata.common.timespan import Timespan api_client = ApiClient(app_key="your_app_key", app_secret="your_app_secret") api_client.add_endpoint("us", "https://api.webull.com") # Create historical bars request request = GetHistoricalBarsRequest() request.set_symbol("AAPL") request.set_category(Category.US_STOCK.name) # US_STOCK, HK_STOCK, US_OPTION, CRYPTO, US_ETF, HK_ETF, CN_STOCK request.set_timespan(Timespan.D.name) # M1, M5, M15, M30, M60, M120, M240, D, W, M, Y response = api_client.get_response(request) bars = response.json() for bar in bars: print(f"Date: {bar.get('time')}") print(f"Open: {bar.get('open')}, High: {bar.get('high')}") print(f"Low: {bar.get('low')}, Close: {bar.get('close')}") print(f"Volume: {bar.get('volume')}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.