### Futu API Quick Start Example Source: https://github.com/futunnopen/py-futu-api/blob/master/README.md This example demonstrates how to use the Futu API for both market data and trading. It covers initializing contexts, subscribing to data, fetching various market data points, placing orders, and querying account information. Ensure FutuOpenD is running before executing. ```python # 导入futu-api import futu as ft # 实例化行情上下文对象 quote_ctx = ft.OpenQuoteContext(host="127.0.0.1", port=11111) # 上下文控制 quote_ctx.start() # 开启异步数据接收 quote_ctx.set_handler(ft.TickerHandlerBase()) # 设置用于异步处理数据的回调对象(可派生支持自定义) # 低频数据接口 market = ft.Market.HK code = 'HK.00123' code_list = [code] plate = 'HK.BK1107' print(quote_ctx.request_trading_days(market, start=None, end=None)) # 获取交易日 print(quote_ctx.get_stock_basicinfo(market, stock_type=ft.SecurityType.STOCK)) # 获取股票信息 print(quote_ctx.get_market_snapshot(code_list)) # 获取市场快照 print(quote_ctx.get_plate_list(market, ft.Plate.ALL)) # 获取板块集合下的子板块列表 print(quote_ctx.get_plate_stock(plate)) # 获取板块下的股票列表 # 高频数据接口 quote_ctx.subscribe(code, [ft.SubType.QUOTE, ft.SubType.TICKER, ft.SubType.K_DAY, ft.SubType.ORDER_BOOK, ft.SubType.RT_DATA, ft.SubType.BROKER]) print(quote_ctx.get_stock_quote(code)) # 获取报价 print(quote_ctx.get_rt_ticker(code)) # 获取逐笔 print(quote_ctx.get_cur_kline(code, num=100, ktype=ft.KLType.K_DAY)) #获取当前K线 print(quote_ctx.get_order_book(code)) # 获取摆盘 print(quote_ctx.get_rt_data(code)) # 获取分时数据 print(quote_ctx.get_broker_queue(code)) # 获取经纪队列 # 停止异步数据接收 quote_ctx.stop() # 关闭对象 quote_ctx.close() # 实例化港股交易上下文对象 trade_hk_ctx = ft.OpenHKTradeContext(host="127.0.0.1", port=11111) # 交易接口列表 print(trade_hk_ctx.unlock_trade(password='123456')) # 解锁接口 print(trade_hk_ctx.accinfo_query(trd_env=ft.TrdEnv.SIMULATE)) # 查询账户信息 print(trade_hk_ctx.place_order(price=1.1, qty=2000, code=code, trd_side=ft.TrdSide.BUY, order_type=ft.OrderType.NORMAL, trd_env=ft.TrdEnv.SIMULATE)) # 下单接口 print(trade_hk_ctx.order_list_query(trd_env=ft.TrdEnv.SIMULATE)) # 查询订单列表 print(trade_hk_ctx.position_list_query(trd_env=ft.TrdEnv.SIMULATE)) # 查询持仓列表 trade_hk_ctx.close() ``` -------------------------------- ### Install futu-api Source: https://github.com/futunnopen/py-futu-api/blob/master/README.md Install the futu-api package using pip. This API supports Python 2.7 and Python 3.x. ```bash pip install futu-api ``` -------------------------------- ### US Stock Trading Example Source: https://context7.com/futunnopen/py-futu-api/llms.txt Demonstrates US stock trading using OpenUSTradeContext, including account information query and placing orders with support for pre- and post-market trading. Ensure the host and port are correctly configured. ```python from futu import * # 初始化美股交易上下文 trd_ctx = OpenUSTradeContext(host='127.0.0.1', port=11111) # 查询账户信息 ret, data = trd_ctx.accinfo_query(trd_env=TrdEnv.SIMULATE) if ret == RET_OK: print('美股账户资产:', data[['total_assets', 'cash', 'market_val', 'currency']]) # 美股下单(支持盘前盘后交易) ret, data = trd_ctx.place_order( price=180.0, qty=10, code='US.AAPL', trd_side=TrdSide.BUY, order_type=OrderType.NORMAL, trd_env=TrdEnv.SIMULATE, fill_outside_rth=True, # 允许盘前盘后成交 time_in_force=TimeInForce.DAY # 当日有效 ) if ret == RET_OK: print('美股下单成功:', data) trd_ctx.close() ``` -------------------------------- ### Get Order Book Data - Python Source: https://context7.com/futunnopen/py-futu-api/llms.txt Fetches the order book (bid and ask prices) for a given stock symbol. Requires an initialized quote context. ```python from futu import * ret, data = quote_ctx.get_order_book('HK.00700', num=10) # 获取10档 if ret == RET_OK: print('股票代码:', data['code']) print('\n卖盘 (Ask):') for price, volume, order_num, details in data['Ask']: print(f' 价格: {price}, 数量: {volume}, 订单数: {order_num}') print('\n买盘 (Bid):') for price, volume, order_num, details in data['Bid']: print(f' 价格: {price}, 数量: {volume}, 订单数: {order_num}') else: print('error:', data) quote_ctx.close() ``` -------------------------------- ### Set Up Trade Order Push Callbacks Source: https://context7.com/futunnopen/py-futu-api/llms.txt Implement real-time push handling for order status updates and trade executions by inheriting from TradeOrderHandlerBase and TradeDealHandlerBase. Ensure asynchronous reception is started. ```python from futu import * from time import sleep # 订单状态更新推送处理 class MyOrderHandler(TradeOrderHandlerBase): def on_recv_rsp(self, rsp_pb): ret, data = super(MyOrderHandler, self).on_recv_rsp(rsp_pb) if ret == RET_OK: print('订单状态更新:') print(data[['order_id', 'order_status', 'dealt_qty', 'last_err_msg']]) return ret, data # 成交推送处理 class MyDealHandler(TradeDealHandlerBase): def on_recv_rsp(self, rsp_pb): ret, data = super(MyDealHandler, self).on_recv_rsp(rsp_pb) if ret == RET_OK: print('收到成交推送:') print(data[['deal_id', 'code', 'qty', 'price', 'trd_side']]) return ret, data trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) # 设置推送处理器 trd_ctx.set_handler(MyOrderHandler()) trd_ctx.set_handler(MyDealHandler()) # 启动异步接收 trd_ctx.start() # 下单后会收到订单状态和成交推送 ret, data = trd_ctx.place_order( price=360.0, qty=100, code='HK.00700', trd_side=TrdSide.BUY, trd_env=TrdEnv.SIMULATE ) sleep(30) # 等待接收推送 trd_ctx.close() ``` -------------------------------- ### Get Real-time Ticker Data - Python Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves real-time tick data for a stock, including price, volume, and direction. Requires subscribing to the ticker data first. ```python from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # 需要先订阅逐笔数据 quote_ctx.subscribe(['HK.00700'], [SubType.TICKER]) # 获取最近500个逐笔数据 ret, data = quote_ctx.get_rt_ticker('HK.00700', num=500) if ret == RET_OK: print(data[['code', 'time', 'price', 'volume', 'turnover', 'ticker_direction', 'type']]) else: print('error:', data) quote_ctx.close() ``` -------------------------------- ### Get Plate List and Constituent Stocks - Python Source: https://context7.com/futunnopen/py-futu-api/llms.txt Fetches industry plate lists and the stocks belonging to a specific plate. Requires an initialized quote context. ```python from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # 获取港股市场的行业板块列表 ret, plate_list = quote_ctx.get_plate_list(Market.HK, Plate.INDUSTRY) if ret == RET_OK: print('行业板块列表:') print(plate_list[['code', 'plate_name', 'plate_id']].head(10)) # 获取第一个板块的成分股 plate_code = plate_list['code'].iloc[0] ret, stock_list = quote_ctx.get_plate_stock(plate_code) if ret == RET_OK: print(f'\n{plate_code} 板块成分股:') print(stock_list[['code', 'stock_name', 'lot_size', 'stock_type']].head(10)) else: print('error:', plate_list) quote_ctx.close() ``` -------------------------------- ### Get Market Snapshot Source: https://context7.com/futunnopen/py-futu-api/llms.txt Fetches market snapshot data for specified stocks, including latest price, open, high, low, volume, turnover, and P/E and P/B ratios. This provides a comprehensive view of the real-time market status for multiple securities. ```python from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # Get market snapshots for multiple stocks code_list = ['HK.00700', 'HK.00005', 'US.AAPL'] ret, data = quote_ctx.get_market_snapshot(code_list) if ret == RET_OK: print(data[['code', 'name', 'last_price', 'open_price', 'high_price', 'low_price', 'volume', 'turnover', 'pe_ratio', 'pb_ratio']]) # Output example: # code name last_price open_price high_price low_price volume turnover pe_ratio pb_ratio # 0 HK.00700 腾讯控股 368.20 370.00 372.00 365.50 15234500 5621340000.0 24.56 5.12 # 1 HK.00005 汇丰控股 52.35 52.00 52.80 51.80 8765400 458970000.0 8.23 0.75 # 2 US.AAPL 苹果 178.50 177.00 179.20 176.80 45678900 8123450000.0 28.45 4.67 else: print('error:', data) quote_ctx.close() ``` -------------------------------- ### Get Stock Associated Data - Python Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves information about which plates a stock belongs to and lists associated securities like warrants. Requires an initialized quote context. ```python from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # 获取股票所属板块 code_list = ['HK.00700', 'HK.00005'] ret, data = quote_ctx.get_owner_plate(code_list) if ret == RET_OK: print('股票所属板块:') print(data[['code', 'plate_code', 'plate_name', 'plate_type']]) # 获取正股相关的窝轮列表 ret, data = quote_ctx.get_referencestock_list('HK.00700', SecurityReferenceType.WARRANT) if ret == RET_OK: print('\n腾讯相关窝轮:') print(data[['code', 'stock_name', 'lot_size', 'stock_type', 'wrt_type']].head(10)) else: print('error:', data) quote_ctx.close() ``` -------------------------------- ### Get Option Chain Data Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieve option chain data for a given stock, including call and put options within a specified date range. The output includes contract details like code, name, strike price, and lot size. Ensure the quote context is properly initialized. ```python from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # 获取腾讯的期权链(30天内到期) ret, data = quote_ctx.get_option_chain( code='HK.00700', start='2024-01-15', end='2024-02-15', option_type=OptionType.ALL, # 全部期权(看涨+看跌) option_cond_type=OptionCondType.ALL # 全部(价内+价外) ) if ret == RET_OK: print('期权链数据:') print(data[['code', 'name', 'option_type', 'strike_price', 'strike_time', 'stock_owner', 'lot_size']]) # 输出示例: # code name option_type strike_price strike_time stock_owner lot_size # 0 HK.TCH240215C360 腾讯240215购360 CALL 360.00 2024-02-15 HK.00700 100 # 1 HK.TCH240215P360 腾讯240215沽360 PUT 360.00 2024-02-15 HK.00700 100 # 获取期权到期日列表 ret, data = quote_ctx.get_option_expiration_date('HK.00700') if ret == RET_OK: print(' 期权到期日:') print(data[['strike_time', 'option_expiry_date_distance']]) quote_ctx.close() ``` -------------------------------- ### Get Real-time Order Book Data Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves real-time order book data (buy and sell orders) for a stock, showing multiple levels of bid and ask prices along with their corresponding quantities. This requires prior subscription to the ORDER_BOOK subtype. ```python from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # Must first subscribe to order book data quote_ctx.subscribe(['HK.00700'], [SubType.ORDER_BOOK]) ``` -------------------------------- ### Initialize Quote Context Source: https://context7.com/futunnopen/py-futu-api/llms.txt Initializes the OpenQuoteContext to connect to the local FutuOpenD gateway for market data operations. Retrieves basic stock information for the Hong Kong market. ```python from futu import * # Initialize quote context, connect to local FutuOpenD gateway quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # Get basic stock information for the Hong Kong market ret, data = quote_ctx.get_stock_basicinfo(Market.HK, SecurityType.STOCK) if ret == RET_OK: print(data) # Output example: # code name lot_size stock_type stock_child_type stock_owner ... # 0 HK.00001 长和 500 STOCK N/A N/A # 1 HK.00002 中电控股 500 STOCK N/A N/A else: print('error:', data) # Close context quote_ctx.close() ``` -------------------------------- ### Initialize and Unlock HK Trade Context - Python Source: https://context7.com/futunnopen/py-futu-api/llms.txt Initializes a trade context for Hong Kong markets and demonstrates unlocking the trade environment for real transactions. Requires a trade password for unlocking. ```python from futu import * # 初始化港股交易上下文 trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) # 获取交易账户列表 ret, acc_list = trd_ctx.get_acc_list() if ret == RET_OK: print('交易账户列表:') print(acc_list[['acc_id', 'trd_env', 'acc_type', 'security_firm']]) # 解锁交易(真实环境必须先解锁) ret, data = trd_ctx.unlock_trade(password='your_trade_password') if ret == RET_OK: print('交易解锁成功') else: print('解锁失败:', data) trd_ctx.close() ``` -------------------------------- ### Query Position List - Python Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves the current holdings in a trading account, including quantity, cost price, market value, and profit/loss. Requires an initialized trade context. ```python from futu import * trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) ``` -------------------------------- ### Query Simulated Order List Source: https://context7.com/futunnopen/py-futu-api/llms.txt Fetches the list of orders for the current day in the simulated trading environment. Supports filtering by order status and stock code. ```python from futu import * trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) # 查询所有待成交订单 ret, data = trd_ctx.order_list_query( trd_env=TrdEnv.SIMULATE, status_filter_list=[OrderStatus.SUBMITTED, OrderStatus.WAITING_SUBMIT] ) if ret == RET_OK: print('待成交订单:') print(data[['order_id', 'code', 'stock_name', 'trd_side', 'order_status', 'qty', 'dealt_qty', 'price', 'dealt_avg_price']]) # 输出示例: # order_id code stock_name trd_side order_status qty dealt_qty price dealt_avg_price # 0 1234567890123456 HK.00700 腾讯控股 BUY SUBMITTED 100 0 360.00 0.00 # 按股票代码筛选订单 ret, data = trd_ctx.order_list_query( code='HK.00700', trd_env=TrdEnv.SIMULATE ) # 查询历史订单(90天内) ret, data = trd_ctx.history_order_list_query( trd_env=TrdEnv.SIMULATE, start='2024-01-01', end='2024-01-31', status_filter_list=[OrderStatus.FILLED_ALL] # 全部成交 ) trd_ctx.close() ``` -------------------------------- ### Subscribe to Real-time Market Data Source: https://context7.com/futunnopen/py-futu-api/llms.txt Subscribes to real-time market data including quotes, K-lines, ticks, and order books for specified stocks. Requires setting up a custom handler to receive asynchronous push notifications. The subscription status can be queried, and subscriptions can be later cancelled. ```python from futu import * from time import sleep # Custom quote push handler class class MyQuoteHandler(StockQuoteHandlerBase): def on_recv_rsp(self, rsp_pb): ret_code, data = super(MyQuoteHandler, self).on_recv_rsp(rsp_pb) if ret_code == RET_OK: print("Received quote push:") print(data) return ret_code, data quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # Set quote push callback quote_ctx.set_handler(MyQuoteHandler()) # Subscribe to quote, K-line, tick, and order book data for stocks code_list = ['HK.00700', 'HK.00005'] subtype_list = [SubType.QUOTE, SubType.K_DAY, SubType.TICKER, SubType.ORDER_BOOK] ret, err = quote_ctx.subscribe(code_list, subtype_list, is_first_push=True) if ret == RET_OK: print('Subscription successful') # Query current subscription status ret, sub_info = quote_ctx.query_subscription(is_all_conn=True) print('Subscription info:', sub_info) # Output example: # {'total_used': 8, 'own_used': 8, 'remain': 492, # 'sub_list': {'QUOTE': ['HK.00700', 'HK.00005'], 'K_DAY': ['HK.00700', 'HK.00005']}} else: print('Subscription failed:', err) sleep(30) # Wait to receive push data # Cancel subscription quote_ctx.unsubscribe(code_list, subtype_list) quote_ctx.close() ``` -------------------------------- ### Query Simulated Trading Positions Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves a list of current positions in the simulated trading environment. Allows filtering by profit and loss ratio. ```python ret, data = trd_ctx.position_list_query(trd_env=TrdEnv.SIMULATE) if ret == RET_OK: print('持仓列表:') print(data[['code', 'stock_name', 'qty', 'can_sell_qty', 'cost_price', 'market_val', 'pl_ratio', 'pl_val', 'position_side']]) # 输出示例: # code stock_name qty can_sell_qty cost_price market_val pl_ratio pl_val position_side # 0 HK.00700 腾讯控股 1000 1000 320.50 368200.00 14.88 47700.00 LONG # 按盈亏比例筛选持仓 ret, data = trd_ctx.position_list_query( trd_env=TrdEnv.SIMULATE, pl_ratio_min=-10, # 最小盈亏比例 -10% pl_ratio_max=50 # 最大盈亏比例 50% ) ``` -------------------------------- ### Query Account Asset Information - Python Source: https://context7.com/futunnopen/py-futu-api/llms.txt Queries the asset information of a trading account, including funds, market value, and purchasing power. Can specify the trading environment (e.g., simulate). ```python from futu import * trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) # 查询模拟交易环境的账户信息 ret, data = trd_ctx.accinfo_query(trd_env=TrdEnv.SIMULATE) if ret == RET_OK: print('账户资产信息:') print(data[['power', 'total_assets', 'cash', 'market_val', 'frozen_cash', 'avl_withdrawal_cash', 'currency']]) else: print('error:', data) trd_ctx.close() ``` -------------------------------- ### Query Simulated Trading Position List Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves the list of positions in the simulated trading environment. Supports filtering by profit and loss ratio. ```APIDOC ## GET /api/positions ### Description Queries the list of positions in the simulated trading environment. This endpoint can be filtered by profit and loss ratio. ### Method GET ### Endpoint /api/positions ### Parameters #### Query Parameters - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). - **pl_ratio_min** (float) - Optional - Minimum profit and loss ratio for filtering. - **pl_ratio_max** (float) - Optional - Maximum profit and loss ratio for filtering. ### Response #### Success Response (200) - **code** (string) - Stock code. - **stock_name** (string) - Stock name. - **qty** (integer) - Quantity of shares held. - **can_sell_qty** (integer) - Quantity of shares that can be sold. - **cost_price** (float) - Average cost price. - **market_val** (float) - Market value of the position. - **pl_ratio** (float) - Profit and loss ratio. - **pl_val** (float) - Profit and loss value. - **position_side** (string) - Position side (e.g., LONG, SHORT). ### Response Example ```json { "code": "HK.00700", "stock_name": "腾讯控股", "qty": 1000, "can_sell_qty": 1000, "cost_price": 320.50, "market_val": 368200.00, "pl_ratio": 14.88, "pl_val": 47700.00, "position_side": "LONG" } ``` ``` -------------------------------- ### Place Order Source: https://context7.com/futunnopen/py-futu-api/llms.txt Submits buy or sell orders, supporting various order types like limit, market, and auction orders. ```APIDOC ## POST /api/orders/place ### Description Places a buy or sell order in the trading environment. Supports various order types including limit, market, and auction orders. ### Method POST ### Endpoint /api/orders/place ### Parameters #### Request Body - **price** (float) - Required - The order price. For market orders, this might be ignored or have a specific meaning depending on the `order_type`. - **qty** (integer) - Required - The quantity of shares to trade. - **code** (string) - Required - The stock code (e.g., 'HK.00700'). - **trd_side** (enum) - Required - Trading side (BUY or SELL). - **order_type** (enum) - Required - Type of order (e.g., NORMAL for limit order, MARKET for market order). - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). - **remark** (string) - Optional - A remark for the order. ### Request Example ```json { "price": 360.0, "qty": 100, "code": "HK.00700", "trd_side": "BUY", "order_type": "NORMAL", "trd_env": "SIMULATE", "remark": "API测试订单" } ``` ### Response #### Success Response (200) - **order_id** (string) - The unique identifier for the placed order. - **code** (string) - Stock code. - **trd_side** (string) - Trading side (BUY or SELL). - **order_type** (string) - Type of order. - **order_status** (string) - Current status of the order (e.g., SUBMITTED, WAITING_SUBMIT). - **qty** (integer) - Quantity of shares ordered. - **price** (float) - Order price. - **create_time** (string) - Timestamp when the order was created. #### Response Example ```json { "order_id": "1234567890123456", "code": "HK.00700", "trd_side": "BUY", "order_type": "NORMAL", "order_status": "SUBMITTED", "qty": 100, "price": 360.0, "create_time": "2024-01-15 10:30:00" } ``` ``` -------------------------------- ### Place Simulated Trading Order Source: https://context7.com/futunnopen/py-futu-api/llms.txt Submits a trading order (e.g., limit order) in the simulated trading environment. Requires specifying price, quantity, stock code, trade side, and order type. ```python from futu import * trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) # 模拟交易环境下单(无需解锁) ret, data = trd_ctx.place_order( price=360.0, # 委托价格 qty=100, # 委托数量 code='HK.00700', # 股票代码 trd_side=TrdSide.BUY, # 买卖方向:买入 order_type=OrderType.NORMAL, # 订单类型:普通限价单 trd_env=TrdEnv.SIMULATE, # 交易环境:模拟 remark='API测试订单' # 备注 ) if ret == RET_OK: print('下单成功:') print(data[['order_id', 'code', 'trd_side', 'order_type', 'order_status', 'qty', 'price', 'create_time']]) # 输出示例: # order_id code trd_side order_type order_status qty price create_time # 0 1234567890123456 HK.00700 BUY NORMAL SUBMITTED 100 360.00 2024-01-15 10:30:00 order_id = data['order_id'].iloc[0] else: print('下单失败:', data) trd_ctx.close() ``` -------------------------------- ### Query Max Tradable Quantity Source: https://context7.com/futunnopen/py-futu-api/llms.txt Query the maximum tradable quantity for a given stock at a specific price. Ensure the trading context is properly initialized. ```python ret, data = trd_ctx.acctradinginfo_query( order_type=OrderType.NORMAL, code='HK.00700', price=360.0, trd_env=TrdEnv.SIMULATE ) if ret == RET_OK: print('最大可交易数量:') print(data[['max_cash_buy', 'max_cash_and_margin_buy', 'max_position_sell', 'max_sell_short', 'max_buy_back']]) # 输出示例: # max_cash_buy max_cash_and_margin_buy max_position_sell max_sell_short max_buy_back # 0 4000.0 8000.0 1000.0 0.0 0.0 # 解释: 现金最多可买4000股,使用融资最多可买8000股,持仓可卖1000股 else: print('error:', data) trd_ctx.close() ``` -------------------------------- ### Query Order List Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves the list of orders for the current day, with options to filter by order status and stock code. Also supports querying historical orders. ```APIDOC ## GET /api/orders ## GET /api/orders/history ### Description Queries the list of orders. `order_list_query` retrieves orders for the current day, while `history_order_list_query` retrieves historical orders within a specified date range. Filtering by order status and stock code is supported. ### Method GET ### Endpoint - Current Day Orders: `/api/orders` - Historical Orders: `/api/orders/history` ### Parameters #### Query Orders (GET /api/orders) - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). - **status_filter_list** (array of enums) - Optional - List of order statuses to filter by (e.g., SUBMITTED, WAITING_SUBMIT, FILLED_ALL). - **code** (string) - Optional - Stock code to filter orders by. #### History Orders (GET /api/orders/history) - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). - **start** (string) - Required - Start date for historical query (YYYY-MM-DD). - **end** (string) - Required - End date for historical query (YYYY-MM-DD). - **status_filter_list** (array of enums) - Optional - List of order statuses to filter by (e.g., FILLED_ALL). - **code** (string) - Optional - Stock code to filter orders by. ### Response #### Success Response (200) - **order_id** (string) - The unique identifier for the order. - **code** (string) - Stock code. - **stock_name** (string) - Stock name. - **trd_side** (string) - Trading side (BUY or SELL). - **order_status** (string) - Current status of the order. - **qty** (integer) - Quantity of shares ordered. - **dealt_qty** (integer) - Quantity of shares already dealt. - **price** (float) - Order price. - **dealt_avg_price** (float) - Average price of dealt shares. ### Response Example ```json { "order_id": "1234567890123456", "code": "HK.00700", "stock_name": "腾讯控股", "trd_side": "BUY", "order_status": "SUBMITTED", "qty": 100, "dealt_qty": 0, "price": 360.0, "dealt_avg_price": 0.00 } ``` ``` -------------------------------- ### Query Simulated Deal Records Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves today's executed trades or historical trades within a specified date range from the simulated trading environment. Can filter by stock code. ```python from futu import * trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) # 查询当日成交记录 ret, data = trd_ctx.deal_list_query(trd_env=TrdEnv.SIMULATE) if ret == RET_OK: print('当日成交记录:') print(data[['deal_id', 'order_id', 'code', 'stock_name', 'trd_side', 'qty', 'price', 'create_time']]) # 输出示例: # deal_id order_id code stock_name trd_side qty price create_time # 0 9876543210123456 1234567890123456 HK.00700 腾讯控股 BUY 100 359.80 2024-01-15 10:35:20 # 查询历史成交记录 ret, data = trd_ctx.history_deal_list_query( trd_env=TrdEnv.SIMULATE, code='HK.00700', start='2024-01-01', end='2024-01-31' ) if ret == RET_OK: print('\n历史成交记录:') print(data) trd_ctx.close() ``` -------------------------------- ### Modify and Cancel Simulated Orders Source: https://context7.com/futunnopen/py-futu-api/llms.txt Allows modification of existing orders (price, quantity) or cancellation of individual orders and all orders in the simulated trading environment. ```python from futu import * trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) # 假设已有订单ID order_id = '1234567890123456' # 修改订单价格和数量 ret, data = trd_ctx.modify_order( modify_order_op=ModifyOrderOp.NORMAL, # 普通改单 order_id=order_id, qty=200, # 新数量 price=358.0, # 新价格 trd_env=TrdEnv.SIMULATE ) if ret == RET_OK: print('改单成功:', data) # 取消订单 ret, data = trd_ctx.modify_order( modify_order_op=ModifyOrderOp.CANCEL, # 取消订单 order_id=order_id, qty=0, price=0, trd_env=TrdEnv.SIMULATE ) if ret == RET_OK: print('撤单成功:', data) else: print('撤单失败:', data) # 取消所有订单 ret, msg = trd_ctx.cancel_all_order(trd_env=TrdEnv.SIMULATE) print('取消全部订单:', msg) trd_ctx.close() ``` -------------------------------- ### Query Deal Records Source: https://context7.com/futunnopen/py-futu-api/llms.txt Retrieves today's deal records and historical deal records within a specified date range. ```APIDOC ## GET /api/deals ## GET /api/deals/history ### Description Retrieves deal records. `deal_list_query` fetches today's transactions, while `history_deal_list_query` fetches historical transactions within a specified date range. Filtering by stock code is supported for historical queries. ### Method GET ### Endpoint - Today's Deals: `/api/deals` - Historical Deals: `/api/deals/history` ### Parameters #### Today's Deals (GET /api/deals) - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). #### Historical Deals (GET /api/deals/history) - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). - **code** (string) - Optional - Stock code to filter deals by. - **start** (string) - Required - Start date for historical query (YYYY-MM-DD). - **end** (string) - Required - End date for historical query (YYYY-MM-DD). ### Response #### Success Response (200) - **deal_id** (string) - The unique identifier for the deal. - **order_id** (string) - The ID of the order associated with the deal. - **code** (string) - Stock code. - **stock_name** (string) - Stock name. - **trd_side** (string) - Trading side (BUY or SELL). - **qty** (integer) - Quantity of shares traded in the deal. - **price** (float) - Price per share for the deal. - **create_time** (string) - Timestamp when the deal occurred. ### Response Example ```json { "deal_id": "9876543210123456", "order_id": "1234567890123456", "code": "HK.00700", "stock_name": "腾讯控股", "trd_side": "BUY", "qty": 100, "price": 359.80, "create_time": "2024-01-15 10:35:20" } ``` ``` -------------------------------- ### Request Historical K-line Data Source: https://context7.com/futunnopen/py-futu-api/llms.txt Requests historical K-line data for a stock, supporting various K-line types (daily, weekly, monthly, minute) and different types of historical adjustments (forward, backward). The function supports fetching data in pages for large datasets. ```python from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # Get daily K-line data for Tencent Holdings (forward adjusted) ret, data, page_req_key = quote_ctx.request_history_kline( code='HK.00700', start='2024-01-01', end='2024-01-31', ktype=KLType.K_DAY, # K-line type: daily autype=AuType.QFQ, # Adjustment type: forward adjustment fields=[KL_FIELD.ALL], # Return all fields max_count=100 # Maximum number of records to return ) if ret == RET_OK: print(data[['code', 'time_key', 'open', 'high', 'low', 'close', 'volume', 'turnover_rate']]) # Output example: # code time_key open high low close volume turnover_rate # 0 HK.00700 2024-01-02 00:00:00 295.00 298.00 293.50 296.80 12345678 0.13 # 1 HK.00700 2024-01-03 00:00:00 297.00 302.00 296.00 301.50 15678900 0.16 else: print('error:', data) # Supports paginated fetching of large amounts of data if page_req_key is not None: ret, data, page_req_key = quote_ctx.request_history_kline( code='HK.00700', start='2024-01-01', end='2024-01-31', ktype=KLType.K_DAY, page_req_key=page_req_key # Pass the key returned last time to continue fetching ) quote_ctx.close() ``` -------------------------------- ### Query Maximum Tradable Quantity Source: https://context7.com/futunnopen/py-futu-api/llms.txt Queries the maximum number of shares that can be bought or sold at a specified price, useful for calculating order quantities. ```APIDOC ## GET /api/trading/info ### Description Queries the maximum tradable quantity (buy or sell) for a given stock at a specific price. This information is crucial for accurately calculating order quantities. ### Method GET ### Endpoint /api/trading/info ### Parameters #### Query Parameters - **code** (string) - Required - The stock code (e.g., 'HK.00700'). - **price** (float) - Required - The price at which to check tradable quantity. - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). ### Response #### Success Response (200) - **max_buy_qty** (integer) - Maximum quantity that can be bought. - **max_sell_qty** (integer) - Maximum quantity that can be sold. ### Response Example ```json { "max_buy_qty": 5000, "max_sell_qty": 4500 } ``` ``` -------------------------------- ### Modify and Cancel Orders Source: https://context7.com/futunnopen/py-futu-api/llms.txt Modifies or cancels submitted orders, supporting price and quantity adjustments, as well as full cancellation. ```APIDOC ## PUT /api/orders/modify ## DELETE /api/orders/cancel ### Description Modifies or cancels existing orders. Supports adjusting price and quantity, or completely canceling an order. Also provides a method to cancel all orders for the account. ### Method PUT (for modify), DELETE (for cancel) ### Endpoint - Modify Order: `/api/orders/modify` - Cancel Order: `/api/orders/cancel` - Cancel All Orders: `/api/orders/cancel_all` ### Parameters #### Modify Order (PUT /api/orders/modify) - **modify_order_op** (enum) - Required - Operation type (e.g., NORMAL for modification, CANCEL for cancellation). - **order_id** (string) - Required - The ID of the order to modify. - **qty** (integer) - Required - The new quantity (use 0 for cancellation if `modify_order_op` is CANCEL). - **price** (float) - Required - The new price (use 0 for cancellation if `modify_order_op` is CANCEL). - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). #### Cancel Order (DELETE /api/orders/cancel) - **order_id** (string) - Required - The ID of the order to cancel. - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). #### Cancel All Orders (DELETE /api/orders/cancel_all) - **trd_env** (enum) - Required - Trading environment (e.g., SIMULATE, REAL). ### Request Example (Modify Order) ```json { "modify_order_op": "NORMAL", "order_id": "1234567890123456", "qty": 200, "price": 358.0, "trd_env": "SIMULATE" } ``` ### Request Example (Cancel Order) ```json { "order_id": "1234567890123456", "trd_env": "SIMULATE" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of the operation. #### Response Example ```json { "message": "Order modified successfully." } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.