XtQuant (QMT Python SDK by ThinkTrader)
XtQuant is the Python SDK for the QMT/miniQMT quantitative trading platform, developed by ThinkTrader (XunTou Technology). It contains two core modules:
- xtdata — Market Data Module: real-time quotes, historical K-lines, tick data, Level 2 data, financial data, sector management
- xttrade — Trading Module: order placement, position/order queries, account management, margin trading, futures/options, smart algorithms
⚠️ Requires miniQMT or QMT client running on Windows. XtQuant connects to the QMT process via local TCP. You need QMT/miniQMT access enabled by your broker.
Installation
pip install xtquant
You can also download from the official website: http://dict.thinktrader.net/nativeApi/download_xtquant.html
Architecture Overview
Your Python script (any IDE, any Python version)
↓ (xtquant SDK, pip install)
├── xtdata → miniQMT (market data service, TCP connection)
└── xttrade → miniQMT (trading service, TCP connection)
↓
Broker trading system
Core Module Reference
| Module |
Import |
Purpose |
xtdata |
from xtquant import xtdata |
Market data: K-lines, tick, Level 2, financials, sectors |
xttrader |
from xtquant.xttrader import XtQuantTrader |
Trading: order placement, queries, callbacks |
xtconstant |
from xtquant import xtconstant |
Constants: order types, price types, market codes |
xttype |
from xtquant.xttype import StockAccount |
Account types: STOCK, CREDIT, FUTURE |
Quick Start — Market Data
from xtquant import xtdata
# Connect to local miniQMT (default: localhost)
xtdata.connect()
# Download historical K-line data (must download to local cache before first access)
xtdata.download_history_data('000001.SZ', '1d', start_time='20240101', end_time='20240630')
# Get local K-line data (returns a dict of DataFrames keyed by stock code)
data = xtdata.get_market_data_ex(
[], # field_list, empty list means all fields
['000001.SZ'], # stock_list, list of stock codes
period='1d',
start_time='20240101',
end_time='20240630',
dividend_type='front' # Adjustment type: none (unadjusted), front (forward-adjusted), back (backward-adjusted), front_ratio (proportional forward), back_ratio (proportional backward)
)
print(data['000001.SZ'])
Real-Time Quote Subscription
def on_data(datas):
"""Quote data callback function, receives pushed real-time data"""
for stock_code, data in datas.items():
print(stock_code, data)
# Subscribe to tick data for a single stock
xtdata.subscribe_quote('000001.SZ', period='tick', callback=on_data)
# Subscribe to full-market quote push
xtdata.subscribe_whole_quote(['SH', 'SZ'], callback=on_data)
xtdata.run() # Block the current thread, continuously receiving callback data
Financial Data
# First download financial data to local cache
xtdata.download_financial_data(['000001.SZ'])
# Then retrieve financial data from local cache
data = xtdata.get_financial_data(['000001.SZ'])
# Available financial reports: Balance (balance sheet), Income (income statement), CashFlow (cash flow statement),
# PershareIndex (per-share indicators), CapitalStructure (capital structure), TOP10HOLDER (top 10 shareholders),
# TOP10FLOWHOLDER (top 10 tradable shareholders), SHAREHOLDER (shareholder count)
Instrument Info & Sectors
# Get detailed instrument info (name, price limits, tick size, etc.)
info = xtdata.get_instrument_detail('000001.SZ')
# Get security type (stock/index/fund/bond, etc.)
itype = xtdata.get_instrument_type('000001.SZ')
# Get list of stocks in a sector
stocks = xtdata.get_stock_list_in_sector('沪深A股')
# Get list of trading dates
days = xtdata.get_trading_dates('SH', start_time='20240101', end_time='20240630')
Quick Start — Trading
from xtquant import xtconstant
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount
# Create a trader instance (path points to miniQMT's userdata_mini directory)
path = r'D:\国金证券QMT交易端\userdata_mini'
session_id = 123456 # Each strategy must use a unique session_id
xt_trader = XtQuantTrader(path, session_id)
# Register a callback class to receive real-time push notifications
class MyCallback(XtQuantTraderCallback):
def on_disconnected(self):
print('Disconnected')
def on_stock_order(self, order):
print(f'Order update: {order.stock_code} status={order.order_status}')
def on_stock_trade(self, trade):
print(f'Trade update: {trade.stock_code} {trade.traded_volume}@{trade.traded_price}')
def on_order_error(self, order_error):
print(f'Order error: {order_error.error_msg}')
def on_order_stock_async_response(self, response):
print(f'Async order response: order_id={response.order_id}')
xt_trader.register_callback(MyCallback())
xt_trader.start()
connect_result = xt_trader.connect() # Returns 0 on successful connection
# Create an account object and subscribe to push notifications
account = StockAccount('your_account_id')
xt_trader.subscribe(account) # Enable push notifications for this account
# Place order: limit buy 600000.SH, 1000 shares at price 10.5
order_id = xt_trader.order_stock(
account, '600000.SH', xtconstant.STOCK_BUY, 1000,
xtconstant.FIX_PRICE, 10.5, 'strategy1', 'test_order'
)
# Returns order_id > 0 on success, -1 on failure
# Query positions
positions = xt_trader.query_stock_positions(account)
for pos in positions:
print(pos.stock_code, pos.volume, pos.can_use_volume, pos.market_value)
# Query orders
orders = xt_trader.query_stock_orders(account)
# Query assets
asset = xt_trader.query_stock_asset(account)
print(f'Available cash: {asset.cash}, Total assets: {asset.total_asset}')
# Cancel order
xt_trader.cancel_order_stock(account, order_id)
# Block the main thread, waiting for callbacks
xt_trader.run_forever()
Stock Code Format
| Market |
Format |
Example |
| Shanghai A-shares |
XXXXXX.SH |
600000.SH |
| Shenzhen A-shares |
XXXXXX.SZ |
000001.SZ |
| Beijing Stock Exchange |
XXXXXX.BJ |
430047.BJ |
| Shanghai Index |
XXXXXX.SH |
000001.SH (SSE Composite Index) |
| Shenzhen Index |
XXXXXX.SZ |
399001.SZ (SZSE Component Index) |
| CFFEX Futures |
XXXX.IF |
IF2401.IF (CSI 300 Futures) |
| SHFE Futures |
XXXX.SF |
ag2407.SF (Silver Futures) |
| DCE Futures |
XXXX.DF |
m2405.DF (Soybean Meal Futures) |
| ZCE Futures |
XXXX.ZF |
CF405.ZF (Cotton Futures) |
| INE Futures |
XXXX.INE |
sc2407.INE (Crude Oil Futures) |
| Shanghai Options |
XXXXXXXX.SHO |
10004358.SHO |
| Shenzhen Options |
XXXXXXXX.SZO |
90000001.SZO |
| ETF |
XXXXXX.SH/SZ |
510300.SH |
| Convertible Bonds |
XXXXXX.SH/SZ |
113050.SH |
Data Periods
tick, 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1mon
Supported Asset Types
| Asset |
Market Data (xtdata) |
Trading (xttrade) |
| A-shares (Shanghai & Shenzhen) |
✅ K-lines, tick, Level 2, financials |
✅ Buy/Sell |
| ETF |
✅ K-lines, tick, IOPV |
✅ Buy/Sell, Subscribe/Redeem |
| Convertible Bonds |
✅ K-lines, tick |
✅ Buy/Sell |
| Futures |
✅ K-lines, tick |
✅ Open long/Close long/Open short/Close short |
| Options |
✅ K-lines, tick |
✅ Buy/Sell open/close, Exercise |
| Indices |
✅ K-lines, tick |
❌ |
| Funds |
✅ K-lines, tick |
✅ Buy/Sell |
| Margin Trading |
✅ Via credit account |
✅ Full credit trading |
Order Type Constants (xtconstant)
| Category |
Constants |
| Stock |
STOCK_BUY (23, buy), STOCK_SELL (24, sell) |
| Credit |
CREDIT_FIN_BUY (margin buy), CREDIT_SLO_SELL (short sell), CREDIT_BUY_SECU_REPAY (buy to repay securities), CREDIT_DIRECT_CASH_REPAY (direct cash repayment), etc. |
| Futures |
FUTURE_BUY_OPEN (open long), FUTURE_SELL_CLOSE (close long), FUTURE_SELL_OPEN (open short), FUTURE_BUY_CLOSE (close short) |
| Options |
STOCK_OPTION_BUY_OPEN (buy to open), STOCK_OPTION_SELL_CLOSE (sell to close), STOCK_OPTION_EXERCISE (exercise), etc. |
| Price Type |
FIX_PRICE (11, limit), ANY_PRICE (12, market), LATEST_PRICE (5, latest price), MARKET_PEER_PRICE_FIRST (best counterparty price), etc. |
Account Types
StockAccount('id') # Regular stock account
StockAccount('id', 'CREDIT') # Credit account (margin trading)
StockAccount('id', 'FUTURE') # Futures account
xtdata Interface Pattern
The market data module follows a unified download → retrieve pattern:
- Subscribe (subscribe):
subscribe_quote, subscribe_whole_quote — real-time push
- Download (download):
download_history_data, download_financial_data — download from server to local cache (synchronous/blocking)
- Retrieve (get):
get_market_data_ex, get_financial_data — read from local cache (fast)
xttrade Callback System
Register an XtQuantTraderCallback subclass to receive real-time push notifications:
| Callback |
Data Type |
Trigger Event |
on_stock_order(order) |
XtOrder |
Order status change |
on_stock_trade(trade) |
XtTrade |
Trade execution |
on_stock_position(position) |
XtPosition |
Position change |
on_stock_asset(asset) |
XtAsset |
Asset change |
on_order_error(error) |
XtOrderError |
Order placement failure |
on_cancel_error(error) |
XtCancelError |
Order cancellation failure |
on_disconnected() |
— |
Connection lost |
on_order_stock_async_response(resp) |
XtOrderResponse |
Async order response |
Advanced Features
- Smart Algorithm Trading: Execute algorithmic orders such as VWAP via
smart_algo_order_async
- Securities Lending: Query available securities, apply for lending, manage contracts
- Bank-Securities Transfer: Transfer funds between bank and securities accounts
- CTP Internal Transfer: Transfer funds between futures and options accounts
- Custom Sectors: Create, manage, and query custom stock groups
- Level 2 Data: l2quote, l2order, l2transaction, l2quoteaux, l2orderqueue, l2thousand (1000-level order book), limitupperformance (consecutive limit-up tracking), snapshotindex, hfiopv, fullspeedorderbook
Usage Tips
- miniQMT must be running on Windows — xtquant connects via local TCP.
session_id must be unique per strategy — different strategies need different IDs.
connect() is a one-time connection — it does not auto-reconnect after disconnection; you must call it again manually.
- Always call
subscribe(account) to receive trading push callbacks.
- Data is cached locally after download — subsequent reads are extremely fast.
- Use
dividend_type='front' to get forward-adjusted K-line data.
- In push callbacks, use async query methods to avoid deadlocks.
- Documentation: http://dict.thinktrader.net/nativeApi/start_now.html
Advanced Examples
Batch Download Full-Market Daily K-Line Data
from xtquant import xtdata
xtdata.connect()
# Get the full list of Shanghai & Shenzhen A-shares
stock_list = xtdata.get_stock_list_in_sector('沪深A股')
print(f"Total {len(stock_list)} A-shares")
# Batch download daily K-line data (recommended to download in batches to avoid timeout)
batch_size = 50
for i in range(0, len(stock_list), batch_size):
batch = stock_list[i:i+batch_size]
for stock in batch:
try:
xtdata.download_history_data(stock, '1d', start_time='20240101', end_time='20240630')
except Exception as e:
print(f"Failed to download {stock}: {e}")
print(f"Downloaded {min(i+batch_size, len(stock_list))}/{len(stock_list)}")
# Batch retrieve data
data = xtdata.get_market_data_ex(
[], stock_list[:10], period='1d',
start_time='20240101', end_time='20240630',
dividend_type='front'
)
for code, df in data.items():
print(f"{code}: {len(df)} records, latest close={df['close'].iloc[-1]}")
Real-Time Quote Monitoring + Conditional Order Trigger
from xtquant import xtdata, xtconstant
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount
import threading
# === Trading Callbacks ===
class MyCallback(XtQuantTraderCallback):
def on_stock_order(self, order):
print(f'Order: {order.stock_code} status={order.order_status} {order.status_msg}')
def on_stock_trade(self, trade):
print(f'Trade: {trade.stock_code} {trade.traded_volume}@{trade.traded_price}')
def on_order_error(self, error):
print(f'Error: {error.error_msg}')
# === Initialize Trading ===
path = r'D:\券商QMT\userdata_mini'
xt_trader = XtQuantTrader(path, 888888)
xt_trader.register_callback(MyCallback())
xt_trader.start()
xt_trader.connect()
account = StockAccount('your_account')
xt_trader.subscribe(account)
# === Quote Monitoring Parameters ===
target_stock = '000001.SZ'
buy_price = 10.50 # Target buy price
sell_price = 11.50 # Target sell price
bought = False
def on_tick(datas):
"""Real-time tick callback: automatically places orders when price hits target"""
global bought
for code, tick in datas.items():
price = tick['lastPrice']
print(f'{code}: latest price={price}')
# Price drops to or below target buy price, buy
if price <= buy_price and not bought:
order_id = xt_trader.order_stock(
account, code, xtconstant.STOCK_BUY, 100,
xtconstant.FIX_PRICE, buy_price, 'auto_buy', '条件触发买入'
)
print(f'Buy triggered: order_id={order_id}')
bought = True
# Price rises to or above target sell price, sell
elif price >= sell_price and bought:
order_id = xt_trader.order_stock(
account, code, xtconstant.STOCK_SELL, 100,
xtconstant.FIX_PRICE, sell_price, 'auto_sell', '条件触发卖出'
)
print(f'Sell triggered: order_id={order_id}')
bought = False
# === Start quote subscription (separate thread) ===
xtdata.connect()
def run_data():
xtdata.subscribe_quote(target_stock, period='tick', callback=on_tick)
xtdata.run()
t = threading.Thread(target=run_data, daemon=True)
t.start()
# Keep the main thread running
xt_trader.run_forever()
Multi-Stock Moving Average Strategy
from xtquant import xtdata, xtconstant
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount
import pandas as pd
xtdata.connect()
# Define stock pool
stock_pool = ['000001.SZ', '600036.SH', '601318.SH', '000858.SZ', '300750.SZ']
# Download historical data
for stock in stock_pool:
xtdata.download_history_data(stock, '1d', start_time='20240101', end_time='20241231')
# Retrieve data and compute signals
signals = {}
for stock in stock_pool:
data = xtdata.get_market_data_ex([], [stock], period='1d',
start_time='20240101', end_time='20241231', dividend_type='front')
df = data[stock]
# Calculate 5-day and 20-day moving averages
df['ma5'] = df['close'].rolling(5).mean()
df['ma20'] = df['close'].rolling(20).mean()
# Determine the latest signal
if len(df) >= 21:
latest = df.iloc[-1]
prev = df.iloc[-2]
if prev['ma5'] <= prev['ma20'] and latest['ma5'] > latest['ma20']:
signals[stock] = 'BUY' # Golden cross
elif prev['ma5'] >= prev['ma20'] and latest['ma5'] < latest['ma20']:
signals[stock] = 'SELL' # Death cross
else:
signals[stock] = 'HOLD' # Hold
print("Trading signals:")
for stock, signal in signals.items():
print(f" {stock}: {signal}")
Retrieve Financial Data and Screen Stocks
from xtquant import xtdata
xtdata.connect()
# Get the list of Shanghai & Shenzhen A-shares
stock_list = xtdata.get_stock_list_in_sector('沪深A股')
# Download financial data
xtdata.download_financial_data(stock_list[:100]) # Download the first 100
# Retrieve financial data
for stock in stock_list[:10]:
data = xtdata.get_financial_data([stock])
if stock in data and 'PershareIndex' in data[stock]:
psi = data[stock]['PershareIndex']
if len(psi) > 0:
latest = psi[-1]
roe = latest.get('du_return_on_equity', 0)
eps = latest.get('s_fa_eps_basic', 0)
print(f"{stock}: ROE={roe}, EPS={eps}")
社区与支持
由 大佬量化 (Boss Quant) 维护 — 量化交易教学与策略研发团队。
微信客服: bossquant1 · Bilibili · 搜索 大佬量化 on 微信公众号 / Bilibili / 抖音
1---2name: xtquant3description: XtQuant QMT Python SDK — Integrates market data (xtdata) and trading interfaces (xttrade), supporting A-shares, futures, options, and other Chinese securities markets.4---56# XtQuant (QMT Python SDK by ThinkTrader)78XtQuant is the Python SDK for the [QMT/miniQMT](http://www.thinktrader.net) quantitative trading platform, developed by ThinkTrader (XunTou Technology). It contains two core modules:910- **xtdata** — Market Data Module: real-time quotes, historical K-lines, tick data, Level 2 data, financial data, sector management11- **xttrade** — Trading Module: order placement, position/order queries, account management, margin trading, futures/options, smart algorithms1213> ⚠️ **Requires miniQMT or QMT client running on Windows**. XtQuant connects to the QMT process via local TCP. You need QMT/miniQMT access enabled by your broker.1415## Installation1617```bash18pip install xtquant19```2021You can also download from the official website: http://dict.thinktrader.net/nativeApi/download_xtquant.html2223## Architecture Overview2425```26Your Python script (any IDE, any Python version)27 ↓ (xtquant SDK, pip install)28 ├── xtdata → miniQMT (market data service, TCP connection)29 └── xttrade → miniQMT (trading service, TCP connection)30 ↓31 Broker trading system32```3334## Core Module Reference3536| Module | Import | Purpose |37|---|---|---|38| `xtdata` | `from xtquant import xtdata` | Market data: K-lines, tick, Level 2, financials, sectors |39| `xttrader` | `from xtquant.xttrader import XtQuantTrader` | Trading: order placement, queries, callbacks |40| `xtconstant` | `from xtquant import xtconstant` | Constants: order types, price types, market codes |41| `xttype` | `from xtquant.xttype import StockAccount` | Account types: STOCK, CREDIT, FUTURE |4243---4445## Quick Start — Market Data464748```python49from xtquant import xtdata5051# Connect to local miniQMT (default: localhost)52xtdata.connect()5354# Download historical K-line data (must download to local cache before first access)55xtdata.download_history_data('000001.SZ', '1d', start_time='20240101', end_time='20240630')5657# Get local K-line data (returns a dict of DataFrames keyed by stock code)58data = xtdata.get_market_data_ex(59 [], # field_list, empty list means all fields60 ['000001.SZ'], # stock_list, list of stock codes61 period='1d',62 start_time='20240101',63 end_time='20240630',64 dividend_type='front' # Adjustment type: none (unadjusted), front (forward-adjusted), back (backward-adjusted), front_ratio (proportional forward), back_ratio (proportional backward)65)66print(data['000001.SZ'])67```6869### Real-Time Quote Subscription7071```python72def on_data(datas):73 """Quote data callback function, receives pushed real-time data"""74 for stock_code, data in datas.items():75 print(stock_code, data)7677# Subscribe to tick data for a single stock78xtdata.subscribe_quote('000001.SZ', period='tick', callback=on_data)7980# Subscribe to full-market quote push81xtdata.subscribe_whole_quote(['SH', 'SZ'], callback=on_data)8283xtdata.run() # Block the current thread, continuously receiving callback data84```8586### Financial Data8788```python89# First download financial data to local cache90xtdata.download_financial_data(['000001.SZ'])91# Then retrieve financial data from local cache92data = xtdata.get_financial_data(['000001.SZ'])93# Available financial reports: Balance (balance sheet), Income (income statement), CashFlow (cash flow statement),94# PershareIndex (per-share indicators), CapitalStructure (capital structure), TOP10HOLDER (top 10 shareholders),95# TOP10FLOWHOLDER (top 10 tradable shareholders), SHAREHOLDER (shareholder count)96```9798### Instrument Info & Sectors99100```python101# Get detailed instrument info (name, price limits, tick size, etc.)102info = xtdata.get_instrument_detail('000001.SZ')103# Get security type (stock/index/fund/bond, etc.)104itype = xtdata.get_instrument_type('000001.SZ')105# Get list of stocks in a sector106stocks = xtdata.get_stock_list_in_sector('沪深A股')107# Get list of trading dates108days = xtdata.get_trading_dates('SH', start_time='20240101', end_time='20240630')109```110111---112113## Quick Start — Trading114115```python116from xtquant import xtconstant117from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback118from xtquant.xttype import StockAccount119120# Create a trader instance (path points to miniQMT's userdata_mini directory)121path = r'D:\国金证券QMT交易端\userdata_mini'122session_id = 123456 # Each strategy must use a unique session_id123xt_trader = XtQuantTrader(path, session_id)124125# Register a callback class to receive real-time push notifications126class MyCallback(XtQuantTraderCallback):127 def on_disconnected(self):128 print('Disconnected')129 def on_stock_order(self, order):130 print(f'Order update: {order.stock_code} status={order.order_status}')131 def on_stock_trade(self, trade):132 print(f'Trade update: {trade.stock_code} {trade.traded_volume}@{trade.traded_price}')133 def on_order_error(self, order_error):134 print(f'Order error: {order_error.error_msg}')135 def on_order_stock_async_response(self, response):136 print(f'Async order response: order_id={response.order_id}')137138xt_trader.register_callback(MyCallback())139xt_trader.start()140connect_result = xt_trader.connect() # Returns 0 on successful connection141142# Create an account object and subscribe to push notifications143account = StockAccount('your_account_id')144xt_trader.subscribe(account) # Enable push notifications for this account145146# Place order: limit buy 600000.SH, 1000 shares at price 10.5147order_id = xt_trader.order_stock(148 account, '600000.SH', xtconstant.STOCK_BUY, 1000,149 xtconstant.FIX_PRICE, 10.5, 'strategy1', 'test_order'150)151# Returns order_id > 0 on success, -1 on failure152153# Query positions154positions = xt_trader.query_stock_positions(account)155for pos in positions:156 print(pos.stock_code, pos.volume, pos.can_use_volume, pos.market_value)157158# Query orders159orders = xt_trader.query_stock_orders(account)160161# Query assets162asset = xt_trader.query_stock_asset(account)163print(f'Available cash: {asset.cash}, Total assets: {asset.total_asset}')164165# Cancel order166xt_trader.cancel_order_stock(account, order_id)167168# Block the main thread, waiting for callbacks169xt_trader.run_forever()170```171172---173174## Stock Code Format175176| Market | Format | Example |177|---|---|---|178| Shanghai A-shares | `XXXXXX.SH` | `600000.SH` |179| Shenzhen A-shares | `XXXXXX.SZ` | `000001.SZ` |180| Beijing Stock Exchange | `XXXXXX.BJ` | `430047.BJ` |181| Shanghai Index | `XXXXXX.SH` | `000001.SH` (SSE Composite Index) |182| Shenzhen Index | `XXXXXX.SZ` | `399001.SZ` (SZSE Component Index) |183| CFFEX Futures | `XXXX.IF` | `IF2401.IF` (CSI 300 Futures) |184| SHFE Futures | `XXXX.SF` | `ag2407.SF` (Silver Futures) |185| DCE Futures | `XXXX.DF` | `m2405.DF` (Soybean Meal Futures) |186| ZCE Futures | `XXXX.ZF` | `CF405.ZF` (Cotton Futures) |187| INE Futures | `XXXX.INE` | `sc2407.INE` (Crude Oil Futures) |188| Shanghai Options | `XXXXXXXX.SHO` | `10004358.SHO` |189| Shenzhen Options | `XXXXXXXX.SZO` | `90000001.SZO` |190| ETF | `XXXXXX.SH/SZ` | `510300.SH` |191| Convertible Bonds | `XXXXXX.SH/SZ` | `113050.SH` |192193194## Data Periods195196`tick`, `1m`, `5m`, `15m`, `30m`, `1h`, `1d`, `1w`, `1mon`197198## Supported Asset Types199200| Asset | Market Data (xtdata) | Trading (xttrade) |201|---|---|---|202| A-shares (Shanghai & Shenzhen) | ✅ K-lines, tick, Level 2, financials | ✅ Buy/Sell |203| ETF | ✅ K-lines, tick, IOPV | ✅ Buy/Sell, Subscribe/Redeem |204| Convertible Bonds | ✅ K-lines, tick | ✅ Buy/Sell |205| Futures | ✅ K-lines, tick | ✅ Open long/Close long/Open short/Close short |206| Options | ✅ K-lines, tick | ✅ Buy/Sell open/close, Exercise |207| Indices | ✅ K-lines, tick | ❌ |208| Funds | ✅ K-lines, tick | ✅ Buy/Sell |209| Margin Trading | ✅ Via credit account | ✅ Full credit trading |210211## Order Type Constants (xtconstant)212213| Category | Constants |214|---|---|215| **Stock** | `STOCK_BUY` (23, buy), `STOCK_SELL` (24, sell) |216| **Credit** | `CREDIT_FIN_BUY` (margin buy), `CREDIT_SLO_SELL` (short sell), `CREDIT_BUY_SECU_REPAY` (buy to repay securities), `CREDIT_DIRECT_CASH_REPAY` (direct cash repayment), etc. |217| **Futures** | `FUTURE_BUY_OPEN` (open long), `FUTURE_SELL_CLOSE` (close long), `FUTURE_SELL_OPEN` (open short), `FUTURE_BUY_CLOSE` (close short) |218| **Options** | `STOCK_OPTION_BUY_OPEN` (buy to open), `STOCK_OPTION_SELL_CLOSE` (sell to close), `STOCK_OPTION_EXERCISE` (exercise), etc. |219| **Price Type** | `FIX_PRICE` (11, limit), `ANY_PRICE` (12, market), `LATEST_PRICE` (5, latest price), `MARKET_PEER_PRICE_FIRST` (best counterparty price), etc. |220221## Account Types222223```python224StockAccount('id') # Regular stock account225StockAccount('id', 'CREDIT') # Credit account (margin trading)226StockAccount('id', 'FUTURE') # Futures account227```228229## xtdata Interface Pattern230231The market data module follows a unified **download → retrieve** pattern:2322331. **Subscribe** (subscribe): `subscribe_quote`, `subscribe_whole_quote` — real-time push2342. **Download** (download): `download_history_data`, `download_financial_data` — download from server to local cache (synchronous/blocking)2353. **Retrieve** (get): `get_market_data_ex`, `get_financial_data` — read from local cache (fast)236237## xttrade Callback System238239Register an `XtQuantTraderCallback` subclass to receive real-time push notifications:240241| Callback | Data Type | Trigger Event |242|---|---|---|243| `on_stock_order(order)` | XtOrder | Order status change |244| `on_stock_trade(trade)` | XtTrade | Trade execution |245| `on_stock_position(position)` | XtPosition | Position change |246| `on_stock_asset(asset)` | XtAsset | Asset change |247| `on_order_error(error)` | XtOrderError | Order placement failure |248| `on_cancel_error(error)` | XtCancelError | Order cancellation failure |249| `on_disconnected()` | — | Connection lost |250| `on_order_stock_async_response(resp)` | XtOrderResponse | Async order response |251252## Advanced Features253254- **Smart Algorithm Trading**: Execute algorithmic orders such as VWAP via `smart_algo_order_async`255- **Securities Lending**: Query available securities, apply for lending, manage contracts256- **Bank-Securities Transfer**: Transfer funds between bank and securities accounts257- **CTP Internal Transfer**: Transfer funds between futures and options accounts258- **Custom Sectors**: Create, manage, and query custom stock groups259- **Level 2 Data**: l2quote, l2order, l2transaction, l2quoteaux, l2orderqueue, l2thousand (1000-level order book), limitupperformance (consecutive limit-up tracking), snapshotindex, hfiopv, fullspeedorderbook260261## Usage Tips262263- **miniQMT must be running on Windows** — xtquant connects via local TCP.264- `session_id` must be unique per strategy — different strategies need different IDs.265- `connect()` is a one-time connection — it does not auto-reconnect after disconnection; you must call it again manually.266- Always call `subscribe(account)` to receive trading push callbacks.267- Data is cached locally after download — subsequent reads are extremely fast.268- Use `dividend_type='front'` to get forward-adjusted K-line data.269- In push callbacks, use async query methods to avoid deadlocks.270- Documentation: http://dict.thinktrader.net/nativeApi/start_now.html271272---273274## Advanced Examples275276### Batch Download Full-Market Daily K-Line Data277278```python279from xtquant import xtdata280281xtdata.connect()282283# Get the full list of Shanghai & Shenzhen A-shares284stock_list = xtdata.get_stock_list_in_sector('沪深A股')285print(f"Total {len(stock_list)} A-shares")286287# Batch download daily K-line data (recommended to download in batches to avoid timeout)288batch_size = 50289for i in range(0, len(stock_list), batch_size):290 batch = stock_list[i:i+batch_size]291 for stock in batch:292 try:293 xtdata.download_history_data(stock, '1d', start_time='20240101', end_time='20240630')294 except Exception as e:295 print(f"Failed to download {stock}: {e}")296 print(f"Downloaded {min(i+batch_size, len(stock_list))}/{len(stock_list)}")297298# Batch retrieve data299data = xtdata.get_market_data_ex(300 [], stock_list[:10], period='1d',301 start_time='20240101', end_time='20240630',302 dividend_type='front'303)304for code, df in data.items():305 print(f"{code}: {len(df)} records, latest close={df['close'].iloc[-1]}")306```307308309### Real-Time Quote Monitoring + Conditional Order Trigger310311```python312from xtquant import xtdata, xtconstant313from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback314from xtquant.xttype import StockAccount315import threading316317# === Trading Callbacks ===318class MyCallback(XtQuantTraderCallback):319 def on_stock_order(self, order):320 print(f'Order: {order.stock_code} status={order.order_status} {order.status_msg}')321 def on_stock_trade(self, trade):322 print(f'Trade: {trade.stock_code} {trade.traded_volume}@{trade.traded_price}')323 def on_order_error(self, error):324 print(f'Error: {error.error_msg}')325326# === Initialize Trading ===327path = r'D:\券商QMT\userdata_mini'328xt_trader = XtQuantTrader(path, 888888)329xt_trader.register_callback(MyCallback())330xt_trader.start()331xt_trader.connect()332account = StockAccount('your_account')333xt_trader.subscribe(account)334335# === Quote Monitoring Parameters ===336target_stock = '000001.SZ'337buy_price = 10.50 # Target buy price338sell_price = 11.50 # Target sell price339bought = False340341def on_tick(datas):342 """Real-time tick callback: automatically places orders when price hits target"""343 global bought344 for code, tick in datas.items():345 price = tick['lastPrice']346 print(f'{code}: latest price={price}')347348 # Price drops to or below target buy price, buy349 if price <= buy_price and not bought:350 order_id = xt_trader.order_stock(351 account, code, xtconstant.STOCK_BUY, 100,352 xtconstant.FIX_PRICE, buy_price, 'auto_buy', '条件触发买入'353 )354 print(f'Buy triggered: order_id={order_id}')355 bought = True356357 # Price rises to or above target sell price, sell358 elif price >= sell_price and bought:359 order_id = xt_trader.order_stock(360 account, code, xtconstant.STOCK_SELL, 100,361 xtconstant.FIX_PRICE, sell_price, 'auto_sell', '条件触发卖出'362 )363 print(f'Sell triggered: order_id={order_id}')364 bought = False365366# === Start quote subscription (separate thread) ===367xtdata.connect()368def run_data():369 xtdata.subscribe_quote(target_stock, period='tick', callback=on_tick)370 xtdata.run()371372t = threading.Thread(target=run_data, daemon=True)373t.start()374375# Keep the main thread running376xt_trader.run_forever()377```378379### Multi-Stock Moving Average Strategy380381```python382from xtquant import xtdata, xtconstant383from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback384from xtquant.xttype import StockAccount385import pandas as pd386387xtdata.connect()388389# Define stock pool390stock_pool = ['000001.SZ', '600036.SH', '601318.SH', '000858.SZ', '300750.SZ']391392# Download historical data393for stock in stock_pool:394 xtdata.download_history_data(stock, '1d', start_time='20240101', end_time='20241231')395396# Retrieve data and compute signals397signals = {}398for stock in stock_pool:399 data = xtdata.get_market_data_ex([], [stock], period='1d',400 start_time='20240101', end_time='20241231', dividend_type='front')401 df = data[stock]402403 # Calculate 5-day and 20-day moving averages404 df['ma5'] = df['close'].rolling(5).mean()405 df['ma20'] = df['close'].rolling(20).mean()406407 # Determine the latest signal408 if len(df) >= 21:409 latest = df.iloc[-1]410 prev = df.iloc[-2]411 if prev['ma5'] <= prev['ma20'] and latest['ma5'] > latest['ma20']:412 signals[stock] = 'BUY' # Golden cross413 elif prev['ma5'] >= prev['ma20'] and latest['ma5'] < latest['ma20']:414 signals[stock] = 'SELL' # Death cross415 else:416 signals[stock] = 'HOLD' # Hold417418print("Trading signals:")419for stock, signal in signals.items():420 print(f" {stock}: {signal}")421```422423### Retrieve Financial Data and Screen Stocks424425```python426from xtquant import xtdata427428xtdata.connect()429430# Get the list of Shanghai & Shenzhen A-shares431stock_list = xtdata.get_stock_list_in_sector('沪深A股')432433# Download financial data434xtdata.download_financial_data(stock_list[:100]) # Download the first 100435436# Retrieve financial data437for stock in stock_list[:10]:438 data = xtdata.get_financial_data([stock])439 if stock in data and 'PershareIndex' in data[stock]:440 psi = data[stock]['PershareIndex']441 if len(psi) > 0:442 latest = psi[-1]443 roe = latest.get('du_return_on_equity', 0)444 eps = latest.get('s_fa_eps_basic', 0)445 print(f"{stock}: ROE={roe}, EPS={eps}")446```447448---449450## 社区与支持451452由 **大佬量化 (Boss Quant)** 维护 — 量化交易教学与策略研发团队。453454微信客服: **bossquant1** · [Bilibili](https://space.bilibili.com/48693330) · 搜索 **大佬量化** on 微信公众号 / Bilibili / 抖音