Comprehensive algorithmic trading framework for Python with backtesting, simulation, and live trading capabilities
—
Core data structures representing orders, trades, instruments, market data, and portfolio components with comprehensive metadata and properties. These models provide the foundation for trading operations and data access in RQAlpha.
Data structures representing trading orders throughout their lifecycle.
class Order:
"""
Order object with properties and lifecycle tracking.
Properties:
- order_id (str): Unique order identifier
- instrument (Instrument): Instrument object
- order_book_id (str): Instrument identifier
- quantity (float): Order quantity (positive=buy, negative=sell)
- unfilled_quantity (float): Remaining unfilled quantity
- side (SIDE): Order side (BUY, SELL, etc.)
- position_effect (POSITION_EFFECT): Position effect (OPEN, CLOSE, etc.)
- status (ORDER_STATUS): Current order status
- type (ORDER_TYPE): Order type (MARKET, LIMIT, ALGO)
- style (OrderStyle): Order execution style
- price (float): Order price (for limit orders)
- avg_price (float): Average fill price
- transaction_cost (float): Total transaction costs
- created_at (datetime): Order creation timestamp
- updated_at (datetime): Last update timestamp
- filled_at (datetime): Fill completion timestamp
- is_final (bool): Whether order is in final state
- is_active (bool): Whether order is active
"""Data structures representing executed trades and fills.
class Trade:
"""
Trade execution record.
Properties:
- trade_id (str): Unique trade identifier
- order_id (str): Associated order identifier
- order_book_id (str): Instrument identifier
- instrument (Instrument): Instrument object
- last_price (float): Execution price
- last_quantity (float): Execution quantity
- side (SIDE): Trade side
- position_effect (POSITION_EFFECT): Position effect
- datetime (datetime): Execution timestamp
- commission (float): Commission paid
- tax (float): Tax paid
- transaction_cost (float): Total transaction cost
"""Data structures representing financial instruments and their metadata.
class Instrument:
"""
Financial instrument with comprehensive metadata.
Properties:
- order_book_id (str): Unique instrument identifier
- symbol (str): Trading symbol
- abbrev_symbol (str): Abbreviated symbol
- round_lot (int): Minimum trading unit
- sector_code (str): Sector classification code
- sector_code_name (str): Sector name
- industry_code (str): Industry classification code
- industry_name (str): Industry name
- exchange (EXCHANGE): Exchange code
- board_type (str): Board type (主板, 中小板, 创业板, etc.)
- status (str): Trading status
- special_type (str): Special instrument type
- de_listed_date (date): Delisting date
- listed_date (date): Listing date
- type (INSTRUMENT_TYPE): Instrument type
- concept_names (list): Concept categories
- last_price (float): Last traded price
- limit_up (float): Daily limit up price
- limit_down (float): Daily limit down price
"""Data structures for market data including bars and ticks.
class BarObject:
"""
OHLCV bar data with properties and metadata.
Properties:
- order_book_id (str): Instrument identifier
- datetime (datetime): Bar timestamp
- open (float): Opening price
- high (float): High price
- low (float): Low price
- close (float): Closing price
- volume (float): Trading volume
- total_turnover (float): Total turnover value
- count (int): Number of trades
- settlement (float): Settlement price (futures)
- prev_settlement (float): Previous settlement price
- open_interest (float): Open interest (futures)
- basis_spread (float): Basis spread
- limit_up (float): Daily limit up
- limit_down (float): Daily limit down
- discount_rate (float): Discount rate
- acc_net_value (float): Accumulated net value
- unit_net_value (float): Unit net value
- adj_factor (float): Adjustment factor
"""
class TickObject:
"""
Tick/quote data with bid/ask information.
Properties:
- order_book_id (str): Instrument identifier
- datetime (datetime): Tick timestamp
- last_price (float): Last traded price
- volume (float): Tick volume
- total_turnover (float): Total turnover
- open_interest (float): Open interest
- prev_close (float): Previous close price
- limit_up (float): Daily limit up
- limit_down (float): Daily limit down
- bid_price_1 (float): Best bid price
- bid_volume_1 (float): Best bid volume
- ask_price_1 (float): Best ask price
- ask_volume_1 (float): Best ask volume
- bid_price_2 to bid_price_5 (float): Additional bid levels
- bid_volume_2 to bid_volume_5 (float): Additional bid volumes
- ask_price_2 to ask_price_5 (float): Additional ask levels
- ask_volume_2 to ask_volume_5 (float): Additional ask volumes
"""
class BarMap:
"""
Dictionary-like container for bar data across multiple instruments.
Methods:
- keys(): Return instrument IDs
- values(): Return BarObject instances
- items(): Return (instrument_id, BarObject) pairs
- [instrument_id]: Access BarObject by instrument ID
"""Data structures defining order execution styles and parameters.
class OrderStyle:
"""Base order style class for order execution parameters."""
class MarketOrder(OrderStyle):
"""
Market order style for immediate execution at current market price.
Usage:
order_shares("000001.XSHE", 100, MarketOrder())
"""
class LimitOrder(OrderStyle):
"""
Limit order style with specified price constraint.
Parameters:
- limit_price (float): Maximum price for buy orders, minimum for sell orders
Usage:
order_shares("000001.XSHE", 100, LimitOrder(10.50))
"""
class AlgoOrder(OrderStyle):
"""Base class for algorithmic order styles."""
class TWAPOrder(AlgoOrder):
"""
Time-weighted average price order.
Parameters:
- start_time (str): Start time for execution (HH:MM format)
- end_time (str): End time for execution (HH:MM format)
Usage:
order_shares("000001.XSHE", 1000, TWAPOrder("09:30", "15:00"))
"""
class VWAPOrder(AlgoOrder):
"""
Volume-weighted average price order.
Parameters:
- start_time (str): Start time for execution
- end_time (str): End time for execution
Usage:
order_shares("000001.XSHE", 1000, VWAPOrder("09:30", "15:00"))
"""Data structures for industry and sector classifications.
class IndustryCode:
"""
Industry classification system.
Properties:
- code (str): Industry code
- name (str): Industry name
- level (int): Classification level
- source (str): Classification source (citics, sw, zjw)
"""
class IndustryCodeItem:
"""
Individual industry code item.
Properties:
- code (str): Specific industry code
- name (str): Industry name
- instruments (list): List of instrument IDs in industry
"""
class SectorCode:
"""
Sector classification system.
Properties:
- code (str): Sector code
- name (str): Sector name
- level (int): Classification level
"""
class SectorCodeItem:
"""
Individual sector code item.
Properties:
- code (str): Specific sector code
- name (str): Sector name
- instruments (list): List of instrument IDs in sector
"""def handle_bar(context, bar_dict):
# Create a limit order
order = order_shares("000001.XSHE", 100, LimitOrder(10.50))
if order:
logger.info(f"Order created: {order.order_id}")
logger.info(f"Instrument: {order.instrument.symbol}")
logger.info(f"Quantity: {order.quantity}")
logger.info(f"Price: {order.price}")
logger.info(f"Status: {order.status}")
# Check order properties
if order.is_active:
logger.info("Order is active in market")
if order.type == ORDER_TYPE.LIMIT:
logger.info(f"Limit order at {order.price}")from rqalpha.apis import subscribe_event, EVENT
def init(context):
subscribe_event(EVENT.TRADE, on_trade_event)
def on_trade_event(context, trade):
# Access trade properties
logger.info(f"Trade executed:")
logger.info(f" Trade ID: {trade.trade_id}")
logger.info(f" Order ID: {trade.order_id}")
logger.info(f" Instrument: {trade.instrument.symbol}")
logger.info(f" Price: {trade.last_price}")
logger.info(f" Quantity: {trade.last_quantity}")
logger.info(f" Side: {trade.side}")
logger.info(f" Commission: {trade.commission}")
logger.info(f" Total Cost: {trade.transaction_cost}")def handle_bar(context, bar_dict):
for stock_id in context.universe:
instrument = instruments(stock_id)
# Access instrument properties
logger.info(f"Instrument: {instrument.symbol}")
logger.info(f"Exchange: {instrument.exchange}")
logger.info(f"Sector: {instrument.sector_code_name}")
logger.info(f"Industry: {instrument.industry_name}")
logger.info(f"Board Type: {instrument.board_type}")
logger.info(f"Listed Date: {instrument.listed_date}")
# Check instrument type
if instrument.type == INSTRUMENT_TYPE.CS:
logger.info("Common stock")
elif instrument.type == INSTRUMENT_TYPE.ETF:
logger.info("ETF")
# Price limits
logger.info(f"Limit Up: {instrument.limit_up}")
logger.info(f"Limit Down: {instrument.limit_down}")def handle_bar(context, bar_dict):
for stock_id, bar in bar_dict.items():
# Access bar properties
logger.info(f"Bar data for {stock_id}:")
logger.info(f" DateTime: {bar.datetime}")
logger.info(f" OHLC: {bar.open}, {bar.high}, {bar.low}, {bar.close}")
logger.info(f" Volume: {bar.volume}")
logger.info(f" Turnover: {bar.total_turnover}")
# Calculate price changes
price_change = bar.close - bar.open
price_change_pct = price_change / bar.open
logger.info(f" Price Change: {price_change:.2f} ({price_change_pct:.2%})")
# Check for gaps
if hasattr(context, 'prev_close'):
gap = bar.open - context.prev_close.get(stock_id, bar.open)
if abs(gap) > bar.open * 0.05: # 5% gap
logger.warning(f"Large gap detected: {gap:.2f}")
# Store previous close
if not hasattr(context, 'prev_close'):
context.prev_close = {}
context.prev_close[stock_id] = bar.closedef handle_tick(context, tick):
# Access tick properties
logger.info(f"Tick data for {tick.order_book_id}:")
logger.info(f" Time: {tick.datetime}")
logger.info(f" Last Price: {tick.last_price}")
logger.info(f" Volume: {tick.volume}")
# Bid/Ask spread analysis
spread = tick.ask_price_1 - tick.bid_price_1
mid_price = (tick.ask_price_1 + tick.bid_price_1) / 2
spread_bps = (spread / mid_price) * 10000
logger.info(f" Bid: {tick.bid_price_1} ({tick.bid_volume_1})")
logger.info(f" Ask: {tick.ask_price_1} ({tick.ask_volume_1})")
logger.info(f" Spread: {spread:.4f} ({spread_bps:.1f} bps)")
# Market depth
total_bid_volume = sum([
tick.bid_volume_1, tick.bid_volume_2, tick.bid_volume_3,
tick.bid_volume_4, tick.bid_volume_5
])
total_ask_volume = sum([
tick.ask_volume_1, tick.ask_volume_2, tick.ask_volume_3,
tick.ask_volume_4, tick.ask_volume_5
])
logger.info(f" Total Bid Volume: {total_bid_volume}")
logger.info(f" Total Ask Volume: {total_ask_volume}")def handle_bar(context, bar_dict):
stock = "000001.XSHE"
current_price = bar_dict[stock].close
# Market order
market_order = order_shares(stock, 100, MarketOrder())
# Limit order with 1% below current price
limit_price = current_price * 0.99
limit_order = order_shares(stock, 100, LimitOrder(limit_price))
# TWAP order for large quantity
twap_order = order_shares(stock, 1000, TWAPOrder("09:30", "15:00"))
# VWAP order
vwap_order = order_shares(stock, 1000, VWAPOrder("10:00", "14:30"))
# Check order styles
if limit_order and isinstance(limit_order.style, LimitOrder):
logger.info(f"Limit order placed at {limit_order.style.limit_price}")def init(context):
# Get stocks by industry
tech_stocks = get_industry("软件服务", source="sw")
bank_stocks = get_industry("银行", source="citics")
# Get industry classification for specific stocks
stock_industries = get_instrument_industry(
["000001.XSHE", "000002.XSHE"],
source="citics",
level=1
)
for stock_id, industry_info in stock_industries.items():
logger.info(f"{stock_id}: {industry_info}")
context.universe = tech_stocks[:20] # Top 20 tech stocksInstall with Tessl CLI
npx tessl i tessl/pypi-rqalpha