0
# Constants and Enums
1
2
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.
3
4
## Capabilities
5
6
### Order Status and Lifecycle
7
8
Enumerations defining order states throughout the order lifecycle.
9
10
```python { .api }
11
ORDER_STATUS = CustomEnum([
12
'PENDING_NEW', # Order submitted but not yet active
13
'ACTIVE', # Order active in market
14
'FILLED', # Order completely filled
15
'REJECTED', # Order rejected by broker/exchange
16
'PENDING_CANCEL', # Order cancellation pending
17
'CANCELLED' # Order cancelled
18
])
19
20
ORDER_TYPE = CustomEnum([
21
'MARKET', # Market order for immediate execution
22
'LIMIT', # Limit order with specified price
23
'ALGO' # Algorithmic order (TWAP, VWAP, etc.)
24
])
25
```
26
27
### Trading Sides and Position Effects
28
29
Enumerations for order sides and position effects in trading operations.
30
31
```python { .api }
32
SIDE = CustomEnum([
33
'BUY', # Buy order
34
'SELL', # Sell order
35
'FINANCING', # Margin financing buy
36
'MARGIN', # Margin short sell
37
'CONVERT_STOCK' # Convert bond to stock
38
])
39
40
POSITION_EFFECT = CustomEnum([
41
'OPEN', # Open new position
42
'CLOSE', # Close existing position
43
'CLOSE_TODAY', # Close today's position (futures)
44
'EXERCISE', # Exercise option/warrant
45
'MATCH' # Position matching
46
])
47
48
POSITION_DIRECTION = CustomEnum([
49
'LONG', # Long position
50
'SHORT' # Short position
51
])
52
```
53
54
### Account Types and System Modes
55
56
Enumerations for account classification and system operation modes.
57
58
```python { .api }
59
DEFAULT_ACCOUNT_TYPE = CustomEnum([
60
'STOCK', # Stock trading account
61
'FUTURE', # Futures trading account
62
'BOND' # Bond trading account
63
])
64
65
RUN_TYPE = CustomEnum([
66
'BACKTEST', # Backtesting mode
67
'PAPER_TRADING', # Paper trading simulation
68
'LIVE_TRADING' # Live trading mode
69
])
70
71
MATCHING_TYPE = CustomEnum([
72
'CURRENT_BAR', # Match at current bar price
73
'NEXT_BAR', # Match at next bar price
74
'VWAP', # Volume-weighted average price matching
75
'TWAP' # Time-weighted average price matching
76
])
77
```
78
79
### Instrument Types and Classifications
80
81
Enumerations for financial instrument types and market classifications.
82
83
```python { .api }
84
INSTRUMENT_TYPE = CustomEnum([
85
'CS', # Common stock
86
'FUTURE', # Futures contract
87
'OPTION', # Option contract
88
'ETF', # Exchange-traded fund
89
'LOF', # Listed open-end fund
90
'FenjiMu', # Structured fund parent
91
'FenjiA', # Structured fund A shares
92
'FenjiB', # Structured fund B shares
93
'INDX', # Index
94
'BOND', # Bond
95
'CONVERTIBLE', # Convertible bond
96
'REPO', # Repurchase agreement
97
'WARRANT', # Warrant
98
'SPOT' # Spot commodity
99
])
100
101
EXCHANGE = CustomEnum([
102
'XSHE', # Shenzhen Stock Exchange
103
'XSHG', # Shanghai Stock Exchange
104
'SHFE', # Shanghai Futures Exchange
105
'DCE', # Dalian Commodity Exchange
106
'CZCE', # Zhengzhou Commodity Exchange
107
'CFFEX', # China Financial Futures Exchange
108
'INE' # Shanghai International Energy Exchange
109
])
110
```
111
112
### Strategy Execution Phases
113
114
Enumerations for strategy lifecycle and execution phase management.
115
116
```python { .api }
117
EXECUTION_PHASE = CustomEnum([
118
'GLOBAL', # Global phase (outside strategy)
119
'ON_INIT', # Strategy initialization phase
120
'BEFORE_TRADING', # Pre-market phase
121
'OPEN_AUCTION', # Opening auction phase
122
'ON_BAR', # Bar data processing phase
123
'ON_TICK', # Tick data processing phase
124
'AFTER_TRADING', # Post-market phase
125
'FINALIZED' # Strategy finalization phase
126
])
127
```
128
129
### System Constants
130
131
System-wide constants for calendar calculations and configuration.
132
133
```python { .api }
134
class DAYS_CNT:
135
"""Calendar constants for date calculations."""
136
DAYS_A_YEAR = 365 # Calendar days per year
137
TRADING_DAYS_A_YEAR = 252 # Trading days per year
138
HOURS_A_YEAR = 365 * 24 # Hours per year
139
MINUTES_A_YEAR = 365 * 24 * 60 # Minutes per year
140
```
141
142
### Error and Exit Codes
143
144
Enumerations for system error handling and exit codes.
145
146
```python { .api }
147
EXIT_CODE = CustomEnum([
148
'EXIT_SUCCESS', # Successful execution
149
'EXIT_USER_ERROR', # User configuration error
150
'EXIT_SYSTEM_ERROR'# System/internal error
151
])
152
153
EXC_TYPE = CustomEnum([
154
'NOTSET', # Exception type not set
155
'USER_EXC', # User code exception
156
'SYSTEM_EXC' # System exception
157
])
158
```
159
160
### Commission and Fee Types
161
162
Enumerations for transaction cost calculations.
163
164
```python { .api }
165
COMMISSION_TYPE = CustomEnum([
166
'PER_SHARE', # Commission per share
167
'PER_ORDER', # Commission per order
168
'PER_VALUE' # Commission by order value percentage
169
])
170
171
HEDGE_TYPE = CustomEnum([
172
'HEDGE', # Hedge position (futures)
173
'SPECULATION' # Speculative position (futures)
174
])
175
```
176
177
### Event System
178
179
Event types for the internal event messaging system.
180
181
```python { .api }
182
EVENT = CustomEnum([
183
'PRE_BEFORE_TRADING', # Before pre-trading phase
184
'BEFORE_TRADING', # Pre-trading phase
185
'AFTER_BEFORE_TRADING', # After pre-trading phase
186
'PRE_BAR', # Before bar processing
187
'BAR', # Bar data event
188
'AFTER_BAR', # After bar processing
189
'PRE_TICK', # Before tick processing
190
'TICK', # Tick data event
191
'AFTER_TICK', # After tick processing
192
'PRE_AFTER_TRADING', # Before post-trading phase
193
'AFTER_TRADING', # Post-trading phase
194
'AFTER_AFTER_TRADING', # After post-trading phase
195
'PRE_SETTLEMENT', # Before settlement
196
'SETTLEMENT', # Settlement event
197
'ORDER_PENDING_NEW', # Order pending
198
'ORDER_CREATION_PASS', # Order creation success
199
'ORDER_CREATION_REJECT', # Order creation rejected
200
'ORDER_PENDING_CANCEL', # Order pending cancellation
201
'ORDER_CANCELLATION_PASS', # Order cancellation success
202
'ORDER_CANCELLATION_REJECT',# Order cancellation rejected
203
'ORDER_UNSOLICITED_UPDATE', # Unsolicited order update
204
'TRADE' # Trade execution event
205
])
206
```
207
208
## Usage Examples
209
210
### Order Status Checking
211
212
```python
213
def handle_bar(context, bar_dict):
214
open_orders = get_open_orders()
215
216
for order in open_orders:
217
if order.status == ORDER_STATUS.ACTIVE:
218
logger.info(f"Order {order.order_id} is active")
219
elif order.status == ORDER_STATUS.REJECTED:
220
logger.warning(f"Order {order.order_id} was rejected")
221
222
# Check order type
223
if order.type == ORDER_TYPE.LIMIT:
224
logger.info(f"Limit order at price {order.price}")
225
```
226
227
### Position Direction Handling
228
229
```python
230
def handle_bar(context, bar_dict):
231
# Get long position
232
long_pos = get_position("RB2401", POSITION_DIRECTION.LONG)
233
if long_pos.quantity > 0:
234
logger.info(f"Long position: {long_pos.quantity} contracts")
235
236
# Get short position
237
short_pos = get_position("RB2401", POSITION_DIRECTION.SHORT)
238
if short_pos.quantity > 0:
239
logger.info(f"Short position: {short_pos.quantity} contracts")
240
```
241
242
### Instrument Type Filtering
243
244
```python
245
def init(context):
246
# Get all instruments
247
all_instruments_df = all_instruments()
248
249
# Filter by instrument type
250
stocks = all_instruments_df[
251
all_instruments_df['type'] == INSTRUMENT_TYPE.CS
252
]
253
254
etfs = all_instruments_df[
255
all_instruments_df['type'] == INSTRUMENT_TYPE.ETF
256
]
257
258
futures = all_instruments_df[
259
all_instruments_df['type'] == INSTRUMENT_TYPE.FUTURE
260
]
261
262
context.stock_universe = stocks['order_book_id'].tolist()
263
context.etf_universe = etfs['order_book_id'].tolist()
264
```
265
266
### Exchange-specific Logic
267
268
```python
269
def handle_bar(context, bar_dict):
270
for stock in context.universe:
271
instrument = instruments(stock)
272
273
if instrument.exchange == EXCHANGE.XSHE:
274
# Shenzhen-specific logic
275
min_order_size = 100
276
elif instrument.exchange == EXCHANGE.XSHG:
277
# Shanghai-specific logic
278
min_order_size = 100
279
280
# Place order with minimum size
281
if context.portfolio.cash > instrument.last_price * min_order_size:
282
order_shares(stock, min_order_size)
283
```
284
285
### Account Type Management
286
287
```python
288
def init(context):
289
# Initialize different account strategies
290
context.stock_strategy = "momentum"
291
context.future_strategy = "mean_reversion"
292
293
def handle_bar(context, bar_dict):
294
# Stock account trading
295
if context.stock_account.cash > 10000:
296
# Stock momentum strategy
297
pass
298
299
# Future account trading
300
if context.future_account.cash > 5000:
301
# Futures mean reversion strategy
302
pass
303
304
# Account-specific deposits
305
if context.stock_account.cash < 5000:
306
deposit(DEFAULT_ACCOUNT_TYPE.STOCK, 10000)
307
```
308
309
### Event Handling
310
311
```python
312
from rqalpha.apis import subscribe_event
313
314
def init(context):
315
# Subscribe to trade events
316
subscribe_event(EVENT.TRADE, on_trade)
317
subscribe_event(EVENT.ORDER_CREATION_PASS, on_order_created)
318
319
def on_trade(context, trade):
320
logger.info(f"Trade executed: {trade.order_book_id} "
321
f"{trade.quantity} @ {trade.last_price}")
322
323
def on_order_created(context, order):
324
logger.info(f"Order created: {order.order_id}")
325
```
326
327
### Phase-aware Strategy Logic
328
329
```python
330
def handle_bar(context, bar_dict):
331
# Check execution phase
332
current_phase = Environment.get_instance().phase
333
334
if current_phase == EXECUTION_PHASE.ON_BAR:
335
# Normal bar processing logic
336
pass
337
elif current_phase == EXECUTION_PHASE.OPEN_AUCTION:
338
# Opening auction specific logic
339
pass
340
```
341
342
### Commission Type Configuration
343
344
```python
345
# In strategy configuration
346
config = {
347
"mod": {
348
"sys_transaction_cost": {
349
"commission_type": COMMISSION_TYPE.PER_VALUE,
350
"commission_rate": 0.0003, # 0.03%
351
"min_commission": 5.0 # Minimum 5 yuan
352
}
353
}
354
}
355
```