0
# RQAlpha
1
2
RQAlpha is a comprehensive algorithmic trading framework for Python that provides a complete solution for quantitative traders, covering data acquisition, algorithmic trading strategies, backtesting engine, simulated trading, live trading, and data analysis. The framework features a flexible configuration system, powerful extensibility through modules (Mods), and supports various trading scenarios from research and backtesting to production trading.
3
4
## Package Information
5
6
- **Package Name**: rqalpha
7
- **Language**: Python
8
- **Installation**: `pip install rqalpha`
9
- **License**: Custom (Apache 2.0 for non-commercial use)
10
- **Documentation**: http://rqalpha.readthedocs.io/zh_CN/latest/
11
12
## Core Imports
13
14
```python
15
import rqalpha
16
```
17
18
Common for strategy execution:
19
20
```python
21
from rqalpha import run_file, run_code, run_func
22
```
23
24
## Basic Usage
25
26
```python
27
import rqalpha
28
29
# Execute a strategy from file
30
config = {
31
"base": {
32
"start_date": "2020-01-01",
33
"end_date": "2020-12-31",
34
"accounts": {"stock": 100000}
35
}
36
}
37
38
result = rqalpha.run_file("my_strategy.py", config=config)
39
40
# Execute strategy from code string
41
strategy_code = """
42
def init(context):
43
context.stocks = ["000001.XSHE"]
44
45
def handle_bar(context, bar_dict):
46
order_target_percent("000001.XSHE", 0.5)
47
"""
48
49
result = rqalpha.run_code(strategy_code, config=config)
50
51
# Execute strategy using function callbacks
52
def init(context):
53
context.stocks = ["000001.XSHE"]
54
55
def handle_bar(context, bar_dict):
56
order_target_percent("000001.XSHE", 0.5)
57
58
result = rqalpha.run_func(config=config, init=init, handle_bar=handle_bar)
59
```
60
61
## Architecture
62
63
RQAlpha follows a modular architecture enabling flexible trading system construction:
64
65
- **Strategy Layer**: User-defined trading logic with lifecycle callbacks (init, handle_bar, handle_tick, etc.)
66
- **API Layer**: Comprehensive trading APIs for order management, data access, and portfolio operations
67
- **Core Engine**: Strategy execution, event processing, and phase management
68
- **Data Layer**: Market data access, historical data, and real-time feeds
69
- **Portfolio System**: Multi-account portfolio management with position tracking and P&L calculation
70
- **Broker Interface**: Order execution simulation and live trading integration
71
- **Mod System**: Extensible plugin architecture for custom functionality
72
73
This design enables RQAlpha to serve both individual traders and institutional users, providing APIs for strategy development, data handling, and integration with external trading systems.
74
75
## Capabilities
76
77
### Strategy Execution
78
79
Core entry points for running trading strategies, supporting file-based strategies, code strings, and function callbacks with comprehensive configuration options.
80
81
```python { .api }
82
def run_file(strategy_file_path: str, config: dict = None) -> dict:
83
"""Execute strategy from file path with optional configuration."""
84
85
def run_code(code: str, config: dict = None) -> dict:
86
"""Execute strategy from code string with optional configuration."""
87
88
def run_func(**kwargs) -> dict:
89
"""Execute strategy using function callbacks (init, handle_bar, etc.)."""
90
```
91
92
[Strategy Execution](./strategy-execution.md)
93
94
### Trading API
95
96
Order placement and management functions supporting stocks, futures, options, and bonds with various order types and position effects.
97
98
```python { .api }
99
def order_shares(id_or_ins, amount, price_or_style=None):
100
"""Order by number of shares."""
101
102
def order_target_percent(id_or_ins, percent, price_or_style=None):
103
"""Target position by portfolio percentage."""
104
105
def get_open_orders():
106
"""Get all pending orders."""
107
108
def cancel_order(order):
109
"""Cancel pending order."""
110
```
111
112
[Trading API](./trading-api.md)
113
114
### Data Access
115
116
Market data and historical data functions providing comprehensive access to pricing data, instrument information, calendar data, and financial metrics.
117
118
```python { .api }
119
def history_bars(order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type='pre', adjust_orig=None):
120
"""Historical OHLCV bar data with adjustments."""
121
122
def current_snapshot(id_or_symbol):
123
"""Current market snapshot with bid/ask and volume."""
124
125
def all_instruments(type=None, date=None):
126
"""Get all available instruments by type and date."""
127
128
def get_trading_dates(start_date, end_date):
129
"""Get trading calendar dates between start and end."""
130
```
131
132
[Data Access](./data-access.md)
133
134
### Portfolio Management
135
136
Portfolio, account, and position management with real-time P&L tracking, multi-account support, and comprehensive position analytics.
137
138
```python { .api }
139
def get_positions():
140
"""Get all current positions."""
141
142
def get_position(order_book_id, direction=POSITION_DIRECTION.LONG):
143
"""Get specific position with direction."""
144
145
def deposit(account_type, amount, receiving_days=0):
146
"""Deposit funds to account."""
147
148
def finance(amount, account_type=DEFAULT_ACCOUNT_TYPE.STOCK):
149
"""Finance/borrow funds."""
150
```
151
152
[Portfolio Management](./portfolio-management.md)
153
154
### Constants and Enums
155
156
Trading system constants and enumerations defining order status, position effects, instrument types, exchanges, and execution phases.
157
158
```python { .api }
159
ORDER_STATUS = CustomEnum([
160
'PENDING_NEW', 'ACTIVE', 'FILLED', 'REJECTED', 'CANCELLED'
161
])
162
163
SIDE = CustomEnum([
164
'BUY', 'SELL', 'FINANCING', 'MARGIN', 'CONVERT_STOCK'
165
])
166
167
INSTRUMENT_TYPE = CustomEnum([
168
'CS', 'FUTURE', 'OPTION', 'ETF', 'LOF', 'INDX'
169
])
170
```
171
172
[Constants and Enums](./constants-enums.md)
173
174
### Data Models
175
176
Core data structures representing orders, trades, instruments, market data, and portfolio components with comprehensive metadata and properties.
177
178
```python { .api }
179
class Order:
180
"""Order object with properties like order_id, instrument, quantity, status."""
181
182
class Trade:
183
"""Trade execution record."""
184
185
class Instrument:
186
"""Financial instrument with metadata."""
187
188
class BarObject:
189
"""OHLCV bar data with properties (open, high, low, close, volume)."""
190
```
191
192
[Data Models](./data-models.md)
193
194
### Framework Core
195
196
Strategy context, execution framework, and event system providing the foundation for strategy development and lifecycle management.
197
198
```python { .api }
199
class StrategyContext:
200
"""Strategy context object (exposed as 'context' in strategies)."""
201
portfolio: Portfolio
202
stock_account: Account
203
future_account: Account
204
now: datetime
205
universe: list
206
207
def subscribe_event(event_type, handler):
208
"""Subscribe to system events."""
209
```
210
211
[Framework Core](./framework-core.md)
212
213
### Command Line Interface
214
215
Command line tools for strategy execution, data management, configuration generation, and system administration.
216
217
```python { .api }
218
# CLI Commands (via 'rqalpha' command):
219
# rqalpha run - Run a trading strategy
220
# rqalpha create-bundle - Create data bundle using RQDatac
221
# rqalpha update-bundle - Update existing data bundle
222
# rqalpha generate-config - Generate default configuration file
223
# rqalpha mod - Mod management (install/uninstall/list/enable/disable)
224
```
225
226
[CLI Commands](./cli-commands.md)
227
228
## Types
229
230
```python { .api }
231
# Configuration Types
232
Config = dict # Strategy configuration dictionary
233
StrategyConfig = dict # Strategy-specific configuration
234
235
# Execution Result
236
ExecutionResult = dict # Strategy execution results with performance metrics
237
238
# Market Data Types
239
BarData = dict # OHLCV bar data dictionary
240
TickData = dict # Tick/quote data dictionary
241
Snapshot = dict # Market snapshot data
242
243
# Order Types
244
OrderId = str # Unique order identifier
245
InstrumentId = str # Instrument identifier (order_book_id)
246
Price = float # Price value
247
Quantity = float # Quantity/amount value
248
249
# Date/Time Types
250
DateLike = Union[str, datetime.date, datetime.datetime] # Date specification
251
Frequency = str # Data frequency ('1d', '1m', etc.)
252
```