CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rqalpha

Comprehensive algorithmic trading framework for Python with backtesting, simulation, and live trading capabilities

Pending
Overview
Eval results
Files

constants-enums.mddocs/

Constants and Enums

Trading system constants and enumerations defining order status, position effects, instrument types, exchanges, execution phases, and system configuration values. All enums inherit from CustomEnum and provide validation and type safety.

Capabilities

Order Status and Lifecycle

Enumerations defining order states throughout the order lifecycle.

ORDER_STATUS = CustomEnum([
    'PENDING_NEW',      # Order submitted but not yet active
    'ACTIVE',           # Order active in market
    'FILLED',           # Order completely filled
    'REJECTED',         # Order rejected by broker/exchange
    'PENDING_CANCEL',   # Order cancellation pending
    'CANCELLED'         # Order cancelled
])

ORDER_TYPE = CustomEnum([
    'MARKET',          # Market order for immediate execution
    'LIMIT',           # Limit order with specified price
    'ALGO'             # Algorithmic order (TWAP, VWAP, etc.)
])

Trading Sides and Position Effects

Enumerations for order sides and position effects in trading operations.

SIDE = CustomEnum([
    'BUY',             # Buy order
    'SELL',            # Sell order
    'FINANCING',       # Margin financing buy
    'MARGIN',          # Margin short sell
    'CONVERT_STOCK'    # Convert bond to stock
])

POSITION_EFFECT = CustomEnum([
    'OPEN',            # Open new position
    'CLOSE',           # Close existing position
    'CLOSE_TODAY',     # Close today's position (futures)
    'EXERCISE',        # Exercise option/warrant
    'MATCH'            # Position matching
])

POSITION_DIRECTION = CustomEnum([
    'LONG',            # Long position
    'SHORT'            # Short position
])

Account Types and System Modes

Enumerations for account classification and system operation modes.

DEFAULT_ACCOUNT_TYPE = CustomEnum([
    'STOCK',           # Stock trading account
    'FUTURE',          # Futures trading account
    'BOND'             # Bond trading account
])

RUN_TYPE = CustomEnum([
    'BACKTEST',        # Backtesting mode
    'PAPER_TRADING',   # Paper trading simulation
    'LIVE_TRADING'     # Live trading mode
])

MATCHING_TYPE = CustomEnum([
    'CURRENT_BAR',     # Match at current bar price
    'NEXT_BAR',        # Match at next bar price
    'VWAP',            # Volume-weighted average price matching
    'TWAP'             # Time-weighted average price matching
])

Instrument Types and Classifications

Enumerations for financial instrument types and market classifications.

INSTRUMENT_TYPE = CustomEnum([
    'CS',              # Common stock
    'FUTURE',          # Futures contract
    'OPTION',          # Option contract
    'ETF',             # Exchange-traded fund
    'LOF',             # Listed open-end fund
    'FenjiMu',         # Structured fund parent
    'FenjiA',          # Structured fund A shares
    'FenjiB',          # Structured fund B shares
    'INDX',            # Index
    'BOND',            # Bond
    'CONVERTIBLE',     # Convertible bond
    'REPO',            # Repurchase agreement
    'WARRANT',         # Warrant
    'SPOT'             # Spot commodity
])

EXCHANGE = CustomEnum([
    'XSHE',            # Shenzhen Stock Exchange
    'XSHG',            # Shanghai Stock Exchange
    'SHFE',            # Shanghai Futures Exchange
    'DCE',             # Dalian Commodity Exchange
    'CZCE',            # Zhengzhou Commodity Exchange
    'CFFEX',           # China Financial Futures Exchange
    'INE'              # Shanghai International Energy Exchange
])

Strategy Execution Phases

Enumerations for strategy lifecycle and execution phase management.

EXECUTION_PHASE = CustomEnum([
    'GLOBAL',          # Global phase (outside strategy)
    'ON_INIT',         # Strategy initialization phase
    'BEFORE_TRADING',  # Pre-market phase
    'OPEN_AUCTION',    # Opening auction phase
    'ON_BAR',          # Bar data processing phase
    'ON_TICK',         # Tick data processing phase
    'AFTER_TRADING',   # Post-market phase
    'FINALIZED'        # Strategy finalization phase
])

System Constants

System-wide constants for calendar calculations and configuration.

class DAYS_CNT:
    """Calendar constants for date calculations."""
    DAYS_A_YEAR = 365          # Calendar days per year
    TRADING_DAYS_A_YEAR = 252  # Trading days per year
    HOURS_A_YEAR = 365 * 24    # Hours per year
    MINUTES_A_YEAR = 365 * 24 * 60  # Minutes per year

Error and Exit Codes

Enumerations for system error handling and exit codes.

EXIT_CODE = CustomEnum([
    'EXIT_SUCCESS',    # Successful execution
    'EXIT_USER_ERROR', # User configuration error
    'EXIT_SYSTEM_ERROR'# System/internal error
])

EXC_TYPE = CustomEnum([
    'NOTSET',          # Exception type not set
    'USER_EXC',        # User code exception
    'SYSTEM_EXC'       # System exception
])

Commission and Fee Types

Enumerations for transaction cost calculations.

COMMISSION_TYPE = CustomEnum([
    'PER_SHARE',       # Commission per share
    'PER_ORDER',       # Commission per order
    'PER_VALUE'        # Commission by order value percentage
])

HEDGE_TYPE = CustomEnum([
    'HEDGE',           # Hedge position (futures)
    'SPECULATION'      # Speculative position (futures)
])

Event System

Event types for the internal event messaging system.

EVENT = CustomEnum([
    'PRE_BEFORE_TRADING',      # Before pre-trading phase
    'BEFORE_TRADING',          # Pre-trading phase
    'AFTER_BEFORE_TRADING',    # After pre-trading phase
    'PRE_BAR',                 # Before bar processing
    'BAR',                     # Bar data event
    'AFTER_BAR',               # After bar processing
    'PRE_TICK',                # Before tick processing
    'TICK',                    # Tick data event
    'AFTER_TICK',              # After tick processing
    'PRE_AFTER_TRADING',       # Before post-trading phase
    'AFTER_TRADING',           # Post-trading phase
    'AFTER_AFTER_TRADING',     # After post-trading phase
    'PRE_SETTLEMENT',          # Before settlement
    'SETTLEMENT',              # Settlement event
    'ORDER_PENDING_NEW',       # Order pending
    'ORDER_CREATION_PASS',     # Order creation success
    'ORDER_CREATION_REJECT',   # Order creation rejected
    'ORDER_PENDING_CANCEL',    # Order pending cancellation
    'ORDER_CANCELLATION_PASS', # Order cancellation success
    'ORDER_CANCELLATION_REJECT',# Order cancellation rejected
    'ORDER_UNSOLICITED_UPDATE', # Unsolicited order update
    'TRADE'                    # Trade execution event
])

Usage Examples

Order Status Checking

def handle_bar(context, bar_dict):
    open_orders = get_open_orders()
    
    for order in open_orders:
        if order.status == ORDER_STATUS.ACTIVE:
            logger.info(f"Order {order.order_id} is active")
        elif order.status == ORDER_STATUS.REJECTED:
            logger.warning(f"Order {order.order_id} was rejected")
            
        # Check order type
        if order.type == ORDER_TYPE.LIMIT:
            logger.info(f"Limit order at price {order.price}")

Position Direction Handling

def handle_bar(context, bar_dict):
    # Get long position
    long_pos = get_position("RB2401", POSITION_DIRECTION.LONG)
    if long_pos.quantity > 0:
        logger.info(f"Long position: {long_pos.quantity} contracts")
    
    # Get short position
    short_pos = get_position("RB2401", POSITION_DIRECTION.SHORT)
    if short_pos.quantity > 0:
        logger.info(f"Short position: {short_pos.quantity} contracts")

Instrument Type Filtering

def init(context):
    # Get all instruments
    all_instruments_df = all_instruments()
    
    # Filter by instrument type
    stocks = all_instruments_df[
        all_instruments_df['type'] == INSTRUMENT_TYPE.CS
    ]
    
    etfs = all_instruments_df[
        all_instruments_df['type'] == INSTRUMENT_TYPE.ETF
    ]
    
    futures = all_instruments_df[
        all_instruments_df['type'] == INSTRUMENT_TYPE.FUTURE
    ]
    
    context.stock_universe = stocks['order_book_id'].tolist()
    context.etf_universe = etfs['order_book_id'].tolist()

Exchange-specific Logic

def handle_bar(context, bar_dict):
    for stock in context.universe:
        instrument = instruments(stock)
        
        if instrument.exchange == EXCHANGE.XSHE:
            # Shenzhen-specific logic
            min_order_size = 100
        elif instrument.exchange == EXCHANGE.XSHG:
            # Shanghai-specific logic
            min_order_size = 100
        
        # Place order with minimum size
        if context.portfolio.cash > instrument.last_price * min_order_size:
            order_shares(stock, min_order_size)

Account Type Management

def init(context):
    # Initialize different account strategies
    context.stock_strategy = "momentum"
    context.future_strategy = "mean_reversion"

def handle_bar(context, bar_dict):
    # Stock account trading
    if context.stock_account.cash > 10000:
        # Stock momentum strategy
        pass
    
    # Future account trading
    if context.future_account.cash > 5000:
        # Futures mean reversion strategy
        pass
    
    # Account-specific deposits
    if context.stock_account.cash < 5000:
        deposit(DEFAULT_ACCOUNT_TYPE.STOCK, 10000)

Event Handling

from rqalpha.apis import subscribe_event

def init(context):
    # Subscribe to trade events
    subscribe_event(EVENT.TRADE, on_trade)
    subscribe_event(EVENT.ORDER_CREATION_PASS, on_order_created)

def on_trade(context, trade):
    logger.info(f"Trade executed: {trade.order_book_id} "
                f"{trade.quantity} @ {trade.last_price}")

def on_order_created(context, order):
    logger.info(f"Order created: {order.order_id}")

Phase-aware Strategy Logic

def handle_bar(context, bar_dict):
    # Check execution phase
    current_phase = Environment.get_instance().phase
    
    if current_phase == EXECUTION_PHASE.ON_BAR:
        # Normal bar processing logic
        pass
    elif current_phase == EXECUTION_PHASE.OPEN_AUCTION:
        # Opening auction specific logic
        pass

Commission Type Configuration

# In strategy configuration
config = {
    "mod": {
        "sys_transaction_cost": {
            "commission_type": COMMISSION_TYPE.PER_VALUE,
            "commission_rate": 0.0003,  # 0.03%
            "min_commission": 5.0       # Minimum 5 yuan
        }
    }
}

Install with Tessl CLI

npx tessl i tessl/pypi-rqalpha

docs

cli-commands.md

constants-enums.md

data-access.md

data-models.md

framework-core.md

index.md

portfolio-management.md

strategy-execution.md

trading-api.md

tile.json