### Install XQShare from source Source: https://context7.com/jasonhu/xqshare/llms.txt Install XQShare from its source code. Clone the repository and then install using pip. ```bash git clone https://gitee.com/jdragonhu/xqshare.git cd xqshare pip install -e . ``` -------------------------------- ### Example Script: Get Stock List Source: https://github.com/jasonhu/xqshare/blob/main/README.md Run a Python script to get a stock list, demonstrating the use of environment variables for configuration. ```bash # 设置环境变量 export XQSHARE_REMOTE_HOST="192.168.1.100" export XQSHARE_CLIENT_SECRET="your-secret" # 获取股票列表 python examples/get_stock_list.py --sector "沪深300" ``` -------------------------------- ### Install xqshare from Source Source: https://github.com/jasonhu/xqshare/blob/main/README.md Install xqshare from its source code repository. Clone the repository from Gitee (recommended for China) or GitHub, then install using pip. ```bash # Gitee(国内推荐) git clone https://gitee.com/jdragonhu/xqshare.git # GitHub(备用) git clone https://github.com/jasonhu/xqshare.git cd xqshare pip install -e . ``` -------------------------------- ### Install xqshare via Pip Source: https://github.com/jasonhu/xqshare/blob/main/README.md Install the xqshare package from PyPI using pip. This is the recommended installation method. ```bash pip install xqshare ``` -------------------------------- ### Calculate Start Time Steps Source: https://github.com/jasonhu/xqshare/blob/main/skills/stock-strategy-ma-cross/SKILL.md Provides a step-by-step guide to calculating the `start_time` for data retrieval, ensuring sufficient historical data for the MA cross strategy. ```text 1. Calculate required K-lines: `bars_needed = max(slow_period, 20) + sustain_period + 14 + 10` 2. Recommended acquisition quantity: `bars_recommended = bars_needed * 1.5` 3. Calculate days based on period: `days = ceil(bars_recommended / bars_per_day)` 4. Calculate start_time: `Current Date - days` ``` -------------------------------- ### Start XQShare Server using command-line tool Source: https://context7.com/jasonhu/xqshare/llms.txt Start the XQShare server using the `xqshare-server` command-line tool. This is an alternative to running the module directly. ```bash xqshare-server ``` -------------------------------- ### Verify Installation Source: https://github.com/jasonhu/xqshare/blob/main/README.md Confirms that the xqshare package has been installed correctly by importing a key class. ```python from xqshare import XtQuantRemote; print('OK') ``` -------------------------------- ### Example Script: Get Market Data Source: https://github.com/jasonhu/xqshare/blob/main/README.md Run a Python script to fetch market data (K-lines) for specified codes and periods. Supports various periods like 1d, 1m, 5m. ```bash # 获取K线数据(支持 1d/1m/5m/15m/30m/60m) python examples/get_market_data_ex.py --codes "000001.SZ,600000.SH" --period 1d ``` -------------------------------- ### Example Script: Show Help Source: https://github.com/jasonhu/xqshare/blob/main/README.md Display the help message for a Python example script, showing available command-line arguments and options. ```bash # 查看帮助 python examples/get_stock_list.py --help ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/jasonhu/xqshare/blob/main/README.md Installs the project and its development dependencies. Use this before running tests or contributing to the project. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install Packaging and Publishing Tools Source: https://github.com/jasonhu/xqshare/blob/main/README.md Installs the necessary tools for building and publishing Python packages. ```bash pip install build twine ``` -------------------------------- ### 启动交易客户端 Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md 调用 `start()` 方法来启动交易客户端。此操作是启动客户端的第一步。 ```python trader.start() ``` -------------------------------- ### Install from TestPyPI Source: https://github.com/jasonhu/xqshare/blob/main/README.md Installs the package from the TestPyPI repository. Useful for verifying installation and functionality in a test environment. ```bash pip install --index-url https://test.pypi.org/simple/ xqshare ``` -------------------------------- ### Install Dependencies Source: https://github.com/jasonhu/xqshare/blob/main/README.md Install the rpyc library, which is a dependency for xqshare. ```bash pip install rpyc ``` -------------------------------- ### Start XQShare Server with custom port and log level Source: https://context7.com/jasonhu/xqshare/llms.txt Start the XQShare server specifying a custom port and log level. Useful for debugging or managing multiple instances. ```bash xqshare-server --port 18813 --log-level DEBUG ``` -------------------------------- ### Credit Trade - Financing Buy Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of placing a financing buy order using xtconstant.CREDIT_FIN_BUY. ```python # 融资买入 order_id = trader.order_stock( credit_account, "600000.SH", order_type=xtconstant.CREDIT_FIN_BUY, order_volume=100, price_type=xtconstant.FIX_PRICE, price=10.5 ) ``` -------------------------------- ### Stock Buy Order Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of placing a stock buy order using xtconstant.STOCK_BUY. ```python from xtquant import xtconstant # 买入 order_id = trader.order_stock( account, "600000.SH", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.FIX_PRICE, price=10.5 ) ``` -------------------------------- ### Start Trading Client Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Starts the trading client to enable trading operations. ```APIDOC ## Start Trading Client ### Description Starts the trading client. ### Method `start()` ### Usage ```python trader.start() ``` ``` -------------------------------- ### Asynchronous Trading Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Example of placing a stock order asynchronously and how to handle the response via callbacks. ```APIDOC ## Asynchronous Trading Example ### Description This example demonstrates how to place a stock order asynchronously and receive the response through a callback. ### Code ```python # Asynchronous order placement seq = trader.order_stock_async( account, "000001.SZ", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.LATEST_PRICE, price=0 ) print(f"Order request sequence number: {seq}") # The callback is received in on_order_stock_async_response ``` ``` -------------------------------- ### Start XQShare Server with SSL encryption Source: https://context7.com/jasonhu/xqshare/llms.txt Start the XQShare server with SSL/TLS encryption enabled. Requires generating SSL certificates first. ```bash openssl genrsa -out server.key 2048 openssl req -new -x509 -days 365 -key server.key -out server.crt ``` ```bash xqshare-server --ssl --cert server.crt --key server.key ``` -------------------------------- ### Start xqshare Server on Windows Source: https://github.com/jasonhu/xqshare/blob/main/README.md Run the xqshare server on a Windows machine. Ensure Python and miniQMT are set up and logged in. ```powershell python -m xqshare.server ``` -------------------------------- ### Stock Sell Order Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of placing a stock sell order using xtconstant.STOCK_SELL. ```python # 卖出 order_id = trader.order_stock( account, "600000.SH", order_type=xtconstant.STOCK_SELL, order_volume=100, price_type=xtconstant.FIX_PRICE, price=10.5 ) ``` -------------------------------- ### XtQuantRemote Client Connection Examples Source: https://context7.com/jasonhu/xqshare/llms.txt Demonstrates how to connect to the XtQuantRemote service with different client IDs and secrets, including examples for standard and enterprise users, and how to configure SSL connections. ```APIDOC ```python # 对应客户端连接 from xqshare import XtQuantRemote # 标准用户(可订阅行情) with XtQuantRemote("192.168.1.100", client_id="quant-app", client_secret="quant-secret-32chars-minimum!!!!") as xt: seq = xt.xtdata.subscribe_quote("000001.SZ", period="tick", callback=lambda d: print(d)) # ... # 企业用户(可下单) with XtQuantRemote("192.168.1.100", client_id="trading-bot", client_secret="bot-secret-32chars-minimum!!!!!!") as xt: trader = xt.create_trader("C:\\QMT\\userdata_mini") # ... # 多客户端也可通过环境变量配置(服务端) # XQSHARE_CLIENT_app1=secret-for-app1 # XQSHARE_CLIENT_app2=secret-for-app2 ``` ``` ```APIDOC ```python from xqshare import XtQuantRemote # 客户端 SSL 连接(自签名证书需关闭证书验证) with XtQuantRemote( host="192.168.1.100", client_secret="my-secret", use_ssl=True, ssl_verify=False # 自签名证书设为 False;CA 签发证书设为 True ) as xt: stocks = xt.xtdata.get_stock_list_in_sector("沪深A股") print(f"SSL 连接成功,股票数: {len(stocks)}") ``` ``` -------------------------------- ### Get Main Contract Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Retrieves the main contract for a given market. Can fetch the current main contract or a historical series. ```python # 当前主力 code = xtdata.get_main_contract("IF00.IF") # 历史主力序列 series = xtdata.get_main_contract("IF00.IF", "20230101", "20240101") ``` -------------------------------- ### Example Script: Get Tick Data Source: https://github.com/jasonhu/xqshare/blob/main/README.md Execute a Python script to retrieve real-time tick data, including five-level market depth, for specified stock codes. ```bash # 获取实时行情(含五档盘口) python examples/get_tick_data.py --codes "000001.SZ" ``` -------------------------------- ### Market Price Order (Latest Price) Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of placing a market price order using the latest price with xtconstant.LATEST_PRICE. Price should be set to 0 for market orders. ```python # 市价委托(最新价) order_id = trader.order_stock( account, "600000.SH", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.LATEST_PRICE, # 最新价 price=0 # 市价时价格填0 ) ``` -------------------------------- ### Dynamic Start Time Calculation Template Source: https://github.com/jasonhu/xqshare/blob/main/skills/stock-strategy-ma-cross/SKILL.md A template for dynamically calculating the start time for data downloads based on trading period and required bars. ```python bars_needed = max(slow_period, 20) + sustain_period + 14 + 10 # 最小需求 bars_recommended = bars_needed * 1.5 # 推荐数量 period=1d: start_time = today - ceil(bars_recommended / 1) (天) period=60m: start_time = today - ceil(bars_recommended / 4) (天) period=30m: start_time = today - ceil(bars_recommended / 8) (天) period=15m: start_time = today - ceil(bars_recommended / 16) (天) period=5m: start_time = today - ceil(bars_recommended / 48) (天) period=1m: start_time = today - ceil(bars_recommended / 240) (天) ``` -------------------------------- ### Limit Price Order Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Demonstrates placing a limit price order using xtconstant.FIX_PRICE. ```python from xtquant import xtconstant # 限价委托 order_id = trader.order_stock( account, "600000.SH", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.FIX_PRICE, # 限价 price=10.5 ) ``` -------------------------------- ### Full Trading Workflow Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Demonstrates a complete trading process: initialization, connection, subscription, querying assets and positions, placing an order, and canceling it. Includes necessary imports and callback implementation. ```python from xtquant import xttrader from xtquant.xttype import StockAccount from xtquant import xtconstant # 1. 创建回调类 class MyCallback(xttrader.XtQuantTraderCallback): def on_connected(self): print("连接成功") def on_disconnected(self): print("连接断开") def on_stock_order(self, order): print(f"委托回报: {order.stock_code} {order.order_volume}股 " f"状态:{order.order_status}") def on_stock_trade(self, trade): print(f"成交回报: {trade.stock_code} {trade.traded_volume}股 " f"价格:{trade.traded_price}") def on_order_error(self, order_error): print(f"委托失败: {order_error.error_msg}") # 2. 初始化交易对象 path = "C:/国金证券QMT交易端/userdata_mini" session_id = 123456 trader = xttrader.XtQuantTrader(path, session_id, MyCallback()) # 3. 启动并连接 trader.start() trader.connect() # 4. 订阅账号 account = StockAccount("8888888888", "STOCK") trader.subscribe(account) # 5. 查询资产 asset = trader.query_stock_asset(account) print(f"可用: {asset.cash}, 总资产: {asset.total_asset}") # 6. 查询持仓 positions = trader.query_stock_positions(account) for pos in positions: print(f"{pos.stock_code}: {pos.volume}股, 成本{pos.avg_price}") # 7. 下单 order_id = trader.order_stock( account, "600000.SH", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.FIX_PRICE, price=10.5 ) print(f"委托号: {order_id}") # 8. 撤单(如需要) if order_id > 0: trader.cancel_order_stock(account, order_id) # 9. 停止 trader.stop() ``` -------------------------------- ### Example Minimum Data Calculation Source: https://github.com/jasonhu/xqshare/blob/main/skills/stock-strategy-ma-cross/SKILL.md An example calculation for the minimum K-lines needed when the slow period is 10 and the sustain period is 2. ```text Required K-lines = max(10, 20) + 2 + 14 + 10 = 20 + 2 + 14 + 10 = 46 lines Recommended acquisition = 46 * 1.5 ≈ 69 lines ``` -------------------------------- ### Create StockAccount Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Example of creating a StockAccount object for different account types. ```python from xtquant.xttype import StockAccount # 普通股票账号 stock_account = StockAccount("1234567890", "STOCK") # 信用账号 credit_account = StockAccount("1234567890", "CREDIT") # 期货账号 future_account = StockAccount("1234567890", "FUTURE") ``` -------------------------------- ### Credit Trade - Securities Loan Sell Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of placing a securities loan sell order using xtconstant.CREDIT_SLO_SELL. ```python # 融券卖出 order_id = trader.order_stock( credit_account, "600000.SH", order_type=xtconstant.CREDIT_SLO_SELL, order_volume=100, price_type=xtconstant.FIX_PRICE, price=10.5 ) ``` -------------------------------- ### Example Script: Override Host with CLI Argument Source: https://github.com/jasonhu/xqshare/blob/main/README.md Demonstrates how to explicitly specify the server host using a command-line argument in a Python example script, overriding environment variables. ```bash # 显式指定服务端地址 python examples/get_stock_list.py --host 192.168.1.100 --sector "沪深300" ``` -------------------------------- ### Example Script: Query Positions (Trading) Source: https://github.com/jasonhu/xqshare/blob/main/README.md Execute a Python script to query stock positions. Requires setting trading-related environment variables like QMT_ACCOUNT_ID and QMT_USERDATA_PATH. ```bash # 设置交易相关环境变量 export QMT_ACCOUNT_ID="12345678" export QMT_USERDATA_PATH="C:\\QMT\\userdata_mini" # 查询持仓 python examples/query_positions.py ``` -------------------------------- ### Full Trading Workflow Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Demonstrates a complete synchronous trading workflow, including initialization, connection, account subscription, querying assets and positions, placing an order, and cancelling an order. ```APIDOC ## Full Trading Workflow Example ### Description This example illustrates a typical synchronous trading process using the XTQuant Trader API. ### Code ```python from xtquant import xttrader from xtquant.xttype import StockAccount from xtquant import xtconstant # 1. Create a callback class class MyCallback(xttrader.XtQuantTraderCallback): def on_connected(self): print("Connection successful") def on_disconnected(self): print("Connection lost") def on_stock_order(self, order): print(f"Order回报: {order.stock_code} {order.order_volume} shares " f"Status:{order.order_status}") def on_stock_trade(self, trade): print(f"Trade回报: {trade.stock_code} {trade.traded_volume} shares " f"Price:{trade.traded_price}") def on_order_error(self, order_error): print(f"Order failed: {order_error.error_msg}") # 2. Initialize the trader object path = "C:/GuoJinSecuritiesQMT/userdata_mini" session_id = 123456 trader = xttrader.XtQuantTrader(path, session_id, MyCallback()) # 3. Start and connect trader.start() trader.connect() # 4. Subscribe to account account = StockAccount("8888888888", "STOCK") trader.subscribe(account) # 5. Query assets asset = trader.query_stock_asset(account) print(f"Available: {asset.cash}, Total Asset: {asset.total_asset}") # 6. Query positions positions = trader.query_stock_positions(account) for pos in positions: print(f"{pos.stock_code}: {pos.volume} shares, Cost {pos.avg_price}") # 7. Place an order order_id = trader.order_stock( account, "600000.SH", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.FIX_PRICE, price=10.5 ) print(f"Order ID: {order_id}") # 8. Cancel order (if needed) if order_id > 0: trader.cancel_order_stock(account, order_id) # 9. Stop trader.stop() ``` ``` -------------------------------- ### Futures Order - Open Long Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of placing a futures order to open a long position using xtconstant.FUTURE_OPEN_LONG. ```python # 开多 order_id = trader.order_stock( future_account, "IF2401.CFFEX", order_type=xtconstant.FUTURE_OPEN_LONG, order_volume=1, price_type=xtconstant.FIX_PRICE, price=4000 ) ``` -------------------------------- ### Credit Trading Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Placeholder for credit trading examples. Specific API calls for credit trading operations would be detailed here. ```APIDOC ## Credit Trading Example ### Description This section is intended for examples related to credit trading operations. Specific API calls and usage patterns for margin financing and securities lending will be detailed here. ``` -------------------------------- ### Example Script: Override Secret with CLI Argument Source: https://github.com/jasonhu/xqshare/blob/main/README.md Shows how to specify the client secret via a command-line argument in a Python example script, which takes precedence over environment variables. ```bash # 显式指定认证密钥 python examples/get_tick_data.py --host 192.168.1.100 --secret "your-secret" --codes "000001.SZ" ``` -------------------------------- ### Stock Account Type Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Demonstrates how to use the StockAccount class and check account types using xtconstant.SECURITY_ACCOUNT. ```python from xtquant import xtconstant # 使用示例 account = StockAccount("8888888888", "STOCK") # 或使用常量判断账号类型 if account.account_type == xtconstant.SECURITY_ACCOUNT: print("股票账号") ``` -------------------------------- ### Example Script: Download History Data Source: https://github.com/jasonhu/xqshare/blob/main/README.md Execute a Python script to download historical data. This may require initial data download. ```bash # 下载历史数据(首次使用需要先下载数据) python examples/download_history_data2.py ``` -------------------------------- ### Get Instrument Details with xtdata Source: https://github.com/jasonhu/xqshare/blob/main/skills/stock-strategy-ma-cross/SKILL.md Fetch detailed information about a specific stock instrument using its code. ```bash xtdata get_instrument_detail --stock-code "000001.SZ" ``` -------------------------------- ### Parsing Asset Data Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Example of how to parse and display asset information retrieved from the trading system. ```Python asset = trader.query_stock_asset(account) print(f"=== Asset Information ===") print(f"Fund Account: {asset.account_id}") print(f"Available Funds: {asset.cash:.2f}") print(f"Frozen Funds: {asset.frozen_cash:.2f}") print(f"Market Value: {asset.market_value:.2f}") print(f"Total Assets: {asset.total_asset:.2f}") print(f"Withdrawal Balance: {asset.fetch_balance:.2f}") ``` -------------------------------- ### Get Market Data Ex (Multiple Stocks) Source: https://github.com/jasonhu/xqshare/blob/main/skills/xtdata/SKILL.md Fetch K-line data for multiple stocks, organized by stock. This command is recommended for its output structure. ```bash xtdata get_market_data_ex --stock-list "[\"000001.SZ\",\"600000.SH\",\"000002.SZ\"]" --period "1d" --start-time "20260101" ``` -------------------------------- ### Time Range Calculation for 5m K-line Source: https://github.com/jasonhu/xqshare/blob/main/skills/stock-strategy-ma-cross/SKILL.md Illustrates how to calculate the start time for data retrieval based on the number of K-lines needed and the K-line period, specifically for a 5-minute interval. ```text Example (slow=10, sustain_period=2, recommended 69 K-lines): - 5m period: 69/48 ≈ 2 days ago -> start_time = Current Date - 2 days ``` -------------------------------- ### Example Script: Subscribe Quote Source: https://github.com/jasonhu/xqshare/blob/main/README.md Run a Python script to subscribe to real-time quote data. Set duration for continuous subscription or a specific time. ```bash # 订阅行情推送(duration=0 持续订阅,Ctrl+C 停止) python examples/subscribe_quote.py --codes "000001.SZ" --duration 60 ``` -------------------------------- ### Integrate Quantitative Strategy with xqshare Source: https://context7.com/jasonhu/xqshare/llms.txt Example of a simple moving average crossover strategy. Fetches stock lists, downloads historical data, calculates signals, and verifies with real-time quotes. ```python """ 量化策略:简单均线金叉买入策略示例 """ import time from xqshare import XtQuantRemote with XtQuantRemote( host="192.168.1.100", client_id="quant-strategy", client_secret="strategy-secret", auto_reconnect=True, heartbeat_interval=30, ) as xt: # 第一步:获取股票池 hs300 = xt.xtdata.get_stock_list_in_sector("沪深300")[:50] print(f"分析标的: {len(hs300)} 只") # 第二步:批量获取日K线(先确保数据已下载) result = xt.download_history_data2( stock_list=hs300, period="1d", start_time="20250101", end_time="20260301" ) print(f"历史数据下载: {'完成' if result['done'] else '失败'}") # 第三步:获取 K 线数据 data = xt.xtdata.get_market_data_ex( stock_list=hs300, period="1d", start_time="20250101", end_time="20260301" ) # 第四步:策略信号计算(均线金叉) buy_signals = [] for code, df in data.items(): if df is None or len(df) < 60: continue ma5 = df["close"].rolling(5).mean() ma20 = df["close"].rolling(20).mean() # 最近两天金叉信号 if ma5.iloc[-2] < ma20.iloc[-2] and ma5.iloc[-1] > ma20.iloc[-1]: buy_signals.append((code, df["close"].iloc[-1])) print(f"金叉信号: {len(buy_signals)} 只") for code, price in buy_signals[:5]: print(f" {code}: {price:.3f}") # 第五步:实时行情验证 if buy_signals: signal_codes = [c for c, _ in buy_signals[:10]] ticks = xt.xtdata.get_full_tick(signal_codes) for code, tick in ticks.items(): print(f" {code} 实时价: {tick.get('lastPrice', 'N/A')}") ``` -------------------------------- ### Get Market Data Ex (5-Minute Period) Source: https://github.com/jasonhu/xqshare/blob/main/skills/xtdata/SKILL.md Fetch 5-minute interval K-line data for a specific stock. Use the `--period "5m"` parameter to specify the interval. ```bash xtdata get_market_data_ex --stock-list "[\"000001.SZ\"]" --period "5m" --start-time "20260301" --end-time "20260309" ``` -------------------------------- ### Parsing Order Data Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Example of how to parse and display current day's order details, including type, volume, price, and status. ```Python orders = trader.query_stock_orders(account) print("=== Today's Orders ===") for order in orders: direction = "Buy" if order.order_type == 23 else "Sell" status = order.status_msg or f"Status Code:{order.order_status}" print(f"[{order.order_id}] {order.stock_code} {direction} {order.order_volume} shares") print(f" Order Price: {order.price}, Traded: {order.traded_volume} shares @ {order.traded_price}") print(f" Status: {status}") ``` -------------------------------- ### Asynchronous Stock Order Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Initiates an asynchronous stock order request and prints the sequence number returned. The response is handled in the `on_order_stock_async_response` callback. ```python # 异步下单 seq = trader.order_stock_async( account, "000001.SZ", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.LATEST_PRICE, price=0 ) print(f"下单请求序号: {seq}") # 回调在 on_order_stock_async_response 中接收 ``` -------------------------------- ### Get Real-time Tick Data (CLI) Source: https://github.com/jasonhu/xqshare/blob/main/README.md Retrieve real-time market tick data for specified stocks using the xtdata CLI. ```bash xtdata get_full_tick --stock-list "['000001.SZ', '600000.SH']" ``` -------------------------------- ### Get Market Data Ex (Stock-Oriented DataFrame) Source: https://github.com/jasonhu/xqshare/blob/main/skills/xtdata/SKILL.md Fetch K-line data organized by stock, which is the recommended approach. Specify stock list, period, and date range. ```bash xtdata get_market_data_ex --stock-list "[\"000001.SZ\"]" --period "1d" --start-time "20260101" --end-time "20260309" ``` -------------------------------- ### Implement XTQuantTraderCallback Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Example of implementing the base callback class to handle trading events like connection status, order updates, and trade confirmations. ```python class MyCallback(XtQuantTraderCallback): def on_connected(self): print("连接成功") def on_disconnected(self): print("连接断开") def on_stock_order(self, order): print(f"委托回报: {order.order_id}") ``` -------------------------------- ### Get Market Data Ex (Forward Adjusted) Source: https://github.com/jasonhu/xqshare/blob/main/skills/xtdata/SKILL.md Fetch K-line data with forward adjustments for dividends and stock splits. Use the `--dividend-type "front"` parameter. ```bash xtdata get_market_data_ex --stock-list "[\"000001.SZ\"]" --period "1d" --start-time "20260101" --dividend-type "front" ``` -------------------------------- ### Configure Client Logging Level Source: https://context7.com/jasonhu/xqshare/llms.txt Instantiate XtQuantRemote with a specified log level to control the verbosity of client-side logs. Examples show server and client log formats. ```python from xqshare import XtQuantRemote # 设置客户端日志级别 xt = XtQuantRemote("192.168.1.100", client_secret="my-secret", log_level="DEBUG") # 服务端 API 调用日志示例: # 2026-02-28 23:45:12.345 | INFO | api | [CALL] get_market_data | client=my-app@192.168.1.50 | args=(['000001.SZ'],) | kwargs={'period': '1d'} # 2026-02-28 23:45:12.456 | INFO | api | [OK] get_market_data | elapsed=111.23ms | result=DataFrame[shape=(100,6)] # 2026-02-28 23:45:20.000 | ERROR | api | [ERROR] get_market_data | elapsed=5000.00ms | error=TimeoutError # 客户端日志示例: # 2026-02-28 23:50:01.123 | INFO | [OK] xtdata.get_market_data | 111.23ms | # 2026-02-28 23:50:05.000 | ERROR | [ERROR] xtdata.get_market_data | 5000.00ms | TimeoutError # 实时监控服务端 API 调用 # tail -f logs/api_calls_*.log ``` -------------------------------- ### Configure XQShare Server using environment variables Source: https://context7.com/jasonhu/xqshare/llms.txt Configure the XQShare server using environment variables. This is recommended for production environments. ```bash # .env file XQSHARE_PORT=18812 QMT_USERDATA_PATH=C:\QMT\userdata_mini ``` -------------------------------- ### Connect to XQShare with Different Client Levels Source: https://context7.com/jasonhu/xqshare/llms.txt Demonstrates connecting to XQShare using different client IDs and secrets corresponding to the levels defined in `clients.yaml`. This includes subscribing to quotes for standard users and creating a trader for enterprise users. Environment variables can also be used for configuration. ```python # 对应客户端连接 from xqshare import XtQuantRemote # 标准用户(可订阅行情) with XtQuantRemote("192.168.1.100", client_id="quant-app", client_secret="quant-secret-32chars-minimum!!!!") as xt: seq = xt.xtdata.subscribe_quote("000001.SZ", period="tick", callback=lambda d: print(d)) # ... # 企业用户(可下单) with XtQuantRemote("192.168.1.100", client_id="trading-bot", client_secret="bot-secret-32chars-minimum!!!!!!") as xt: trader = xt.create_trader("C:\\QMT\\userdata_mini") # ... # 多客户端也可通过环境变量配置(服务端) # XQSHARE_CLIENT_app1=secret-for-app1 # XQSHARE_CLIENT_app2=secret-for-app2 ``` -------------------------------- ### Futures Order - Close Long Today Example Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of placing a futures order to close a long position opened today using xtconstant.FUTURE_CLOSE_LONG_TODAY. ```python # 平今多 order_id = trader.order_stock( future_account, "IF2401.CFFEX", order_type=xtconstant.FUTURE_CLOSE_LONG_TODAY, order_volume=1, price_type=xtconstant.FIX_PRICE, price=4000 ) ``` -------------------------------- ### Configure and Use xttrader CLI Source: https://context7.com/jasonhu/xqshare/llms.txt Set environment variables for authentication and configuration, then use xttrader to query stock positions, assets, orders, and trades. Supports querying credit accounts and viewing help. ```bash export XQSHARE_REMOTE_HOST="192.168.1.100" export XQSHARE_CLIENT_SECRET="premium-secret" export QMT_ACCOUNT_ID="12345678" export QMT_USERDATA_PATH="C:\\QMT\\userdata_mini" # 查询账户持仓 xttrader --account-id "12345678" query_stock_positions # 查询账户资产 xttrader --account-id "12345678" query_stock_asset # 查询当日委托 xttrader --account-id "12345678" query_stock_orders # 查询当日成交 xttrader --account-id "12345678" query_stock_trades # 查询信用账户持仓 xttrader --account-id "12345678" --account-type CREDIT query_stock_positions # 查看帮助 xttrader --help ``` -------------------------------- ### 配置 xqshare 客户端环境变量 Source: https://github.com/jasonhu/xqshare/blob/main/skills/xttrader/SKILL.md 在客户端配置 xqshare 服务端地址、认证密钥、资金账号和 QMT userdata_mini 路径。推荐使用环境变量进行配置。 ```bash export XQSHARE_REMOTE_HOST="192.168.1.100" export XQSHARE_CLIENT_SECRET="your-secret" export QMT_ACCOUNT_ID="你的资金账号" export QMT_USERDATA_PATH="C:\\QMT\\userdata_mini" ``` -------------------------------- ### Connect to XQShare using environment variables Source: https://context7.com/jasonhu/xqshare/llms.txt Connect to the XQShare remote server by automatically reading connection details from environment variables. This is the recommended approach for production. ```python # export XQSHARE_REMOTE_HOST="192.168.1.100" # export XQSHARE_CLIENT_SECRET="your-secret" with XtQuantRemote() as xt: # 自动读取环境变量 status = xt.get_service_status() print(status) ``` -------------------------------- ### Parse Asset Data Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Example of parsing and printing stock asset information. ```python asset = trader.query_stock_asset(account) print(f"=== 资产信息 ===") print(f"资金账号: {asset.account_id}") print(f"可用资金: {asset.cash:.2f}") print(f"冻结资金: {asset.frozen_cash:.2f}") print(f"持仓市值: {asset.market_value:.2f}") print(f"总资产: {asset.total_asset:.2f}") print(f"可取资金: {asset.fetch_balance:.2f}") ``` -------------------------------- ### Connect to xqshare using XtQuantRemote (Context Manager) Source: https://github.com/jasonhu/xqshare/blob/main/README.md Connect to the xqshare remote server using the XtQuantRemote class as a context manager. This is the recommended way to manage connections. ```python from xqshare import XtQuantRemote, connect, disconnect, xtdata, xttrader, xttype # 方式1:类实例(推荐) with XtQuantRemote("192.168.1.100", client_secret="xxx") as xt: stocks = xt.xtdata.get_stock_list_in_sector("沪深A股") ``` -------------------------------- ### Connect to XQShare and manage lifecycle manually Source: https://context7.com/jasonhu/xqshare/llms.txt Connect to the XQShare remote server and manually manage the client's lifecycle. Ensure to close the connection in a `finally` block. ```python from xqshare import XtQuantRemote xt = XtQuantRemote("192.168.1.100", client_secret="my-secret") try: df = xt.xtdata.get_market_data_ex( stock_list=["000001.SZ"], period="1d", start_time="20260101", end_time="20260228" ) print(df["000001.SZ"].head()) finally: xt.close() ``` -------------------------------- ### XtQuantTrader Constructor Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Initializes the XtQuantTrader client with the specified path, session, and an optional callback object. ```APIDOC ## XtQuantTrader Constructor ### Description Initializes the XtQuantTrader client. ### Parameters - **path** (str) - Required - Path to the mini version of XunTou极速trading client's userdata folder. - **session** (int) - Required - The session ID for the current task execution. - **callback** (XtQuantTraderCallback) - Optional - Callback object for handling events. ``` -------------------------------- ### get_instrument_detail Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Retrieves detailed information for a specific financial instrument. You can choose to get complete information or a subset. ```APIDOC ## get_instrument_detail(stock_code, iscomplete=False) ### Description 获取合约信息。 ### Parameters #### Path Parameters - **stock_code** (str) - Required - 股票代码 - **iscomplete** (bool) - Optional - 是否返回完整信息 (Default: False) ### Response #### Success Response (200) - **ExchangeID** (str) - 市场代码 - **InstrumentID** (str) - 合约代码 - **InstrumentName** (str) - 合约名称 - **ProductID** (str) - 品种ID - **ProductName** (str) - 品种名称 - **CreateDate** (str) - 上市日期 - **ExpireDate** (str) - 到期日 - **PreClose** (float) - 前收盘价 - **UpStopPrice** (float) - 涨停价 - **DownStopPrice** (float) - 跌停价 - **FloatVolume** (float) - 流通股本 - **TotalVolume** (float) - 总股本 - **PriceTick** (float) - 最小变价单位 - **VolumeMultiple** (int) - 合约乘数 - **MainContract** (int) - 主力合约标记 - **IsTrading** (bool) - 是否可交易 ### Request Example ```python info = xtdata.get_instrument_detail('000001.SZ') print(info['InstrumentName']) ``` ``` -------------------------------- ### 建立交易客户端连接 Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md 调用 `connect()` 方法来建立与交易服务器的连接。成功连接返回 0。 ```python result = trader.connect() ``` -------------------------------- ### Parsing Position Data Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Example of how to parse and display stock position details, including volume, cost, and profit/loss. ```Python positions = trader.query_stock_positions(account) print("=== Position Information ===") for pos in positions: profit = (pos.last_price - pos.avg_price) * pos.volume print(f"{pos.stock_code} {pos.instrument_name}") print(f" Holdings: {pos.volume} shares, Available: {pos.can_use_volume} shares") print(f" Cost: {pos.avg_price:.3f}, Last Price: {pos.last_price:.3f}") print(f" Market Value: {pos.market_value:.2f}, Profit/Loss: {profit:.2f}") ``` -------------------------------- ### Creating StockAccount Objects Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Demonstrates how to create StockAccount objects for different account types (stock, credit, future). ```Python from xtquant.xttype import StockAccount # Normal stock account stock_account = StockAccount("1234567890", "STOCK") # Credit account credit_account = StockAccount("1234567890", "CREDIT") # Futures account future_account = StockAccount("1234567890", "FUTURE") ``` -------------------------------- ### Parse Position Data Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Example of iterating through stock positions and printing details like volume, price, and profit/loss. ```python positions = trader.query_stock_positions(account) print("=== 持仓信息 ===") for pos in positions: profit = (pos.last_price - pos.avg_price) * pos.volume print(f"{pos.stock_code} {pos.instrument_name}") print(f" 持仓: {pos.volume}股, 可用: {pos.can_use_volume}股") print(f" 成本: {pos.avg_price:.3f}, 现价: {pos.last_price:.3f}") print(f" 市值: {pos.market_value:.2f}, 盈亏: {profit:.2f}") ``` -------------------------------- ### call_formula Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Synchronously calls a strategy model. This function is used to execute a trading strategy and get its results immediately. ```APIDOC ## call_formula(formula_name, stock_code, period, start_time='', end_time='', count=-1, dividend_type=None, extend_param={}) ### Description Synchronously calls a strategy model. ### Returns dict ``` -------------------------------- ### Create StockAccount Instance Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttype-doc.md Instantiate StockAccount for regular stock accounts or credit accounts. Ensure account_id is a string. ```python from xtquant.xttype import StockAccount # 普通股票账号 account = StockAccount("8888888888", "STOCK") # 信用账号 credit_account = StockAccount("8888888888", "CREDIT") ``` -------------------------------- ### Get Holidays - Python Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Fetches a list of public holidays as date strings. Useful for calendar-aware data processing. ```python holidays = xtdata.get_holidays() ``` -------------------------------- ### Get Markets - Python Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Fetches a dictionary of all available market codes and their corresponding names. Useful for understanding market identifiers. ```python markets = xtdata.get_markets() # {'SH': '上交所', 'SZ': '深交所', 'BJ': '北交所', ...} ``` -------------------------------- ### Get Service Status Source: https://github.com/jasonhu/xqshare/blob/main/README.md Retrieves the status of the XQShare server from the client. Provides information like uptime and active connections. ```python status = xt.get_service_status() print(status) ``` -------------------------------- ### Place Stock Order (CLI) Source: https://github.com/jasonhu/xqshare/blob/main/README.md Place a stock order using the xttrader CLI. Requires --account-id and order details like --stock-code, --order-type, and --order-volume. ```bash # 下单(需要更多参数) xttrader --account-id "12345678" order_stock --stock-code "000001.SZ" --order-type 23 --order-volume 100 ``` -------------------------------- ### Check Code with Flake8 Source: https://github.com/jasonhu/xqshare/blob/main/README.md Performs code linting using Flake8 to check for style guide violations and potential errors. ```bash flake8 xqshare/ ``` -------------------------------- ### Use Aliases for xtdata Functions Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Demonstrates using shorthand aliases for common xtdata functions to simplify code. For example, 'gmd' for 'get_market_data'. ```python # 使用简写 data = xtdata.gmd([], ['000001.SZ'], '1d') stocks = xtdata.gsl('沪深A股') ``` -------------------------------- ### Establish global connection using connect function Source: https://context7.com/jasonhu/xqshare/llms.txt Establish a global connection to the XQShare server using the `connect` function. This allows using global `xtdata`, `xttrader`, etc., without an explicit client instance. ```python from xqshare import connect, disconnect, get_client, xtdata, xttrader, xttype # 建立全局连接(支持环境变量) connect( host="192.168.1.100", port=18812, client_secret="my-secret" ) # 使用全局 xtdata 代理(无需 xt. 前缀) stocks = xtdata.get_stock_list_in_sector("沪深300") print(f"沪深300成分股: {len(stocks)} 只") ticks = xtdata.get_full_tick(["000001.SZ", "600000.SH"]) for code, tick in ticks.items(): print(f"{code}: 最新价={tick.get('lastPrice')}") # 获取全局客户端实例 client = get_client() print(client) # 断开连接 disconnect() ``` -------------------------------- ### Build Package Source: https://github.com/jasonhu/xqshare/blob/main/README.md Builds the Python package in both wheel and source distribution formats. ```bash python -m build ``` -------------------------------- ### 股票下单 Source: https://github.com/jasonhu/xqshare/blob/main/skills/xttrader/SKILL.md 使用 `order_stock` 命令进行股票买入或卖出操作。需要指定股票代码、订单类型、订单数量、价格类型和价格。 ```bash # order_type: 23=买入, 24=卖出 # price_type: 11=限价, 12=市价 xttrader order_stock --stock-code "000001.SZ" --order-type 23 --order-volume 100 --price-type 11 --price 10.0 ``` -------------------------------- ### Check Order Status Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Example of how to check the status of an order using XTQuant constants. It differentiates between fully succeeded orders and junk orders. ```python from xtquant import xtconstant # 判断委托状态 if order.order_status == xtconstant.ORDER_SUCCEEDED: print("委托已全部成交") elif order.order_status == xtconstant.ORDER_JUNK: print(f"废单: {order.status_msg}") ``` -------------------------------- ### Connect to Trading Server Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xttrader-doc.md Establishes a connection to the trading server. ```APIDOC ## Connect to Trading Server ### Description Establishes a connection to the trading server. ### Method `connect()` ### Returns - int - 0 indicates success. ``` -------------------------------- ### Get Dividend Factors - Python Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Retrieves ex-dividend and ex-right factors for a given stock code and date range. Returns a pandas DataFrame. ```python factors = xtdata.get_divid_factors('000001.SZ', '20200101', '20241231') ``` -------------------------------- ### Get Instrument Detail - Python Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtdata-doc.md Retrieves detailed information for a specific stock code. Use when needing comprehensive details about a single instrument. ```python info = xtdata.get_instrument_detail('000001.SZ') print(info['InstrumentName']) ``` -------------------------------- ### Place Stock Order with Peer Price First Source: https://github.com/jasonhu/xqshare/blob/main/doc/xtquant-xtconstant-doc.md Demonstrates placing a stock buy order using the 'MARKET_PEER_PRICE_FIRST' price type, which prioritizes the counterparty's price. ```python order_id = trader.order_stock( account, "600000.SH", order_type=xtconstant.STOCK_BUY, order_volume=100, price_type=xtconstant.MARKET_PEER_PRICE_FIRST, price=0 ) ``` -------------------------------- ### Get Market Data (JSON Output) Source: https://github.com/jasonhu/xqshare/blob/main/skills/xtdata/SKILL.md Fetch K-line data and output it in a compact JSON format. This is useful for programmatic parsing of the data. ```bash xtdata -f json --compact get_market_data --stock-list "[\"000001.SZ\"]" --period "1d" --start-time "20260101" ```