or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-commands.mdconstants-enums.mddata-access.mddata-models.mdframework-core.mdindex.mdportfolio-management.mdstrategy-execution.mdtrading-api.md

data-models.mddocs/

0

# Data Models

1

2

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.

3

4

## Capabilities

5

6

### Order Models

7

8

Data structures representing trading orders throughout their lifecycle.

9

10

```python { .api }

11

class Order:

12

"""

13

Order object with properties and lifecycle tracking.

14

15

Properties:

16

- order_id (str): Unique order identifier

17

- instrument (Instrument): Instrument object

18

- order_book_id (str): Instrument identifier

19

- quantity (float): Order quantity (positive=buy, negative=sell)

20

- unfilled_quantity (float): Remaining unfilled quantity

21

- side (SIDE): Order side (BUY, SELL, etc.)

22

- position_effect (POSITION_EFFECT): Position effect (OPEN, CLOSE, etc.)

23

- status (ORDER_STATUS): Current order status

24

- type (ORDER_TYPE): Order type (MARKET, LIMIT, ALGO)

25

- style (OrderStyle): Order execution style

26

- price (float): Order price (for limit orders)

27

- avg_price (float): Average fill price

28

- transaction_cost (float): Total transaction costs

29

- created_at (datetime): Order creation timestamp

30

- updated_at (datetime): Last update timestamp

31

- filled_at (datetime): Fill completion timestamp

32

- is_final (bool): Whether order is in final state

33

- is_active (bool): Whether order is active

34

"""

35

```

36

37

### Trade Models

38

39

Data structures representing executed trades and fills.

40

41

```python { .api }

42

class Trade:

43

"""

44

Trade execution record.

45

46

Properties:

47

- trade_id (str): Unique trade identifier

48

- order_id (str): Associated order identifier

49

- order_book_id (str): Instrument identifier

50

- instrument (Instrument): Instrument object

51

- last_price (float): Execution price

52

- last_quantity (float): Execution quantity

53

- side (SIDE): Trade side

54

- position_effect (POSITION_EFFECT): Position effect

55

- datetime (datetime): Execution timestamp

56

- commission (float): Commission paid

57

- tax (float): Tax paid

58

- transaction_cost (float): Total transaction cost

59

"""

60

```

61

62

### Instrument Models

63

64

Data structures representing financial instruments and their metadata.

65

66

```python { .api }

67

class Instrument:

68

"""

69

Financial instrument with comprehensive metadata.

70

71

Properties:

72

- order_book_id (str): Unique instrument identifier

73

- symbol (str): Trading symbol

74

- abbrev_symbol (str): Abbreviated symbol

75

- round_lot (int): Minimum trading unit

76

- sector_code (str): Sector classification code

77

- sector_code_name (str): Sector name

78

- industry_code (str): Industry classification code

79

- industry_name (str): Industry name

80

- exchange (EXCHANGE): Exchange code

81

- board_type (str): Board type (主板, 中小板, 创业板, etc.)

82

- status (str): Trading status

83

- special_type (str): Special instrument type

84

- de_listed_date (date): Delisting date

85

- listed_date (date): Listing date

86

- type (INSTRUMENT_TYPE): Instrument type

87

- concept_names (list): Concept categories

88

- last_price (float): Last traded price

89

- limit_up (float): Daily limit up price

90

- limit_down (float): Daily limit down price

91

"""

92

```

93

94

### Market Data Models

95

96

Data structures for market data including bars and ticks.

97

98

```python { .api }

99

class BarObject:

100

"""

101

OHLCV bar data with properties and metadata.

102

103

Properties:

104

- order_book_id (str): Instrument identifier

105

- datetime (datetime): Bar timestamp

106

- open (float): Opening price

107

- high (float): High price

108

- low (float): Low price

109

- close (float): Closing price

110

- volume (float): Trading volume

111

- total_turnover (float): Total turnover value

112

- count (int): Number of trades

113

- settlement (float): Settlement price (futures)

114

- prev_settlement (float): Previous settlement price

115

- open_interest (float): Open interest (futures)

116

- basis_spread (float): Basis spread

117

- limit_up (float): Daily limit up

118

- limit_down (float): Daily limit down

119

- discount_rate (float): Discount rate

120

- acc_net_value (float): Accumulated net value

121

- unit_net_value (float): Unit net value

122

- adj_factor (float): Adjustment factor

123

"""

124

125

class TickObject:

126

"""

127

Tick/quote data with bid/ask information.

128

129

Properties:

130

- order_book_id (str): Instrument identifier

131

- datetime (datetime): Tick timestamp

132

- last_price (float): Last traded price

133

- volume (float): Tick volume

134

- total_turnover (float): Total turnover

135

- open_interest (float): Open interest

136

- prev_close (float): Previous close price

137

- limit_up (float): Daily limit up

138

- limit_down (float): Daily limit down

139

- bid_price_1 (float): Best bid price

140

- bid_volume_1 (float): Best bid volume

141

- ask_price_1 (float): Best ask price

142

- ask_volume_1 (float): Best ask volume

143

- bid_price_2 to bid_price_5 (float): Additional bid levels

144

- bid_volume_2 to bid_volume_5 (float): Additional bid volumes

145

- ask_price_2 to ask_price_5 (float): Additional ask levels

146

- ask_volume_2 to ask_volume_5 (float): Additional ask volumes

147

"""

148

149

class BarMap:

150

"""

151

Dictionary-like container for bar data across multiple instruments.

152

153

Methods:

154

- keys(): Return instrument IDs

155

- values(): Return BarObject instances

156

- items(): Return (instrument_id, BarObject) pairs

157

- [instrument_id]: Access BarObject by instrument ID

158

"""

159

```

160

161

### Order Style Models

162

163

Data structures defining order execution styles and parameters.

164

165

```python { .api }

166

class OrderStyle:

167

"""Base order style class for order execution parameters."""

168

169

class MarketOrder(OrderStyle):

170

"""

171

Market order style for immediate execution at current market price.

172

173

Usage:

174

order_shares("000001.XSHE", 100, MarketOrder())

175

"""

176

177

class LimitOrder(OrderStyle):

178

"""

179

Limit order style with specified price constraint.

180

181

Parameters:

182

- limit_price (float): Maximum price for buy orders, minimum for sell orders

183

184

Usage:

185

order_shares("000001.XSHE", 100, LimitOrder(10.50))

186

"""

187

188

class AlgoOrder(OrderStyle):

189

"""Base class for algorithmic order styles."""

190

191

class TWAPOrder(AlgoOrder):

192

"""

193

Time-weighted average price order.

194

195

Parameters:

196

- start_time (str): Start time for execution (HH:MM format)

197

- end_time (str): End time for execution (HH:MM format)

198

199

Usage:

200

order_shares("000001.XSHE", 1000, TWAPOrder("09:30", "15:00"))

201

"""

202

203

class VWAPOrder(AlgoOrder):

204

"""

205

Volume-weighted average price order.

206

207

Parameters:

208

- start_time (str): Start time for execution

209

- end_time (str): End time for execution

210

211

Usage:

212

order_shares("000001.XSHE", 1000, VWAPOrder("09:30", "15:00"))

213

"""

214

```

215

216

### Classification Models

217

218

Data structures for industry and sector classifications.

219

220

```python { .api }

221

class IndustryCode:

222

"""

223

Industry classification system.

224

225

Properties:

226

- code (str): Industry code

227

- name (str): Industry name

228

- level (int): Classification level

229

- source (str): Classification source (citics, sw, zjw)

230

"""

231

232

class IndustryCodeItem:

233

"""

234

Individual industry code item.

235

236

Properties:

237

- code (str): Specific industry code

238

- name (str): Industry name

239

- instruments (list): List of instrument IDs in industry

240

"""

241

242

class SectorCode:

243

"""

244

Sector classification system.

245

246

Properties:

247

- code (str): Sector code

248

- name (str): Sector name

249

- level (int): Classification level

250

"""

251

252

class SectorCodeItem:

253

"""

254

Individual sector code item.

255

256

Properties:

257

- code (str): Specific sector code

258

- name (str): Sector name

259

- instruments (list): List of instrument IDs in sector

260

"""

261

```

262

263

## Data Model Usage Examples

264

265

### Working with Orders

266

267

```python

268

def handle_bar(context, bar_dict):

269

# Create a limit order

270

order = order_shares("000001.XSHE", 100, LimitOrder(10.50))

271

272

if order:

273

logger.info(f"Order created: {order.order_id}")

274

logger.info(f"Instrument: {order.instrument.symbol}")

275

logger.info(f"Quantity: {order.quantity}")

276

logger.info(f"Price: {order.price}")

277

logger.info(f"Status: {order.status}")

278

279

# Check order properties

280

if order.is_active:

281

logger.info("Order is active in market")

282

283

if order.type == ORDER_TYPE.LIMIT:

284

logger.info(f"Limit order at {order.price}")

285

```

286

287

### Accessing Trade Information

288

289

```python

290

from rqalpha.apis import subscribe_event, EVENT

291

292

def init(context):

293

subscribe_event(EVENT.TRADE, on_trade_event)

294

295

def on_trade_event(context, trade):

296

# Access trade properties

297

logger.info(f"Trade executed:")

298

logger.info(f" Trade ID: {trade.trade_id}")

299

logger.info(f" Order ID: {trade.order_id}")

300

logger.info(f" Instrument: {trade.instrument.symbol}")

301

logger.info(f" Price: {trade.last_price}")

302

logger.info(f" Quantity: {trade.last_quantity}")

303

logger.info(f" Side: {trade.side}")

304

logger.info(f" Commission: {trade.commission}")

305

logger.info(f" Total Cost: {trade.transaction_cost}")

306

```

307

308

### Working with Instrument Metadata

309

310

```python

311

def handle_bar(context, bar_dict):

312

for stock_id in context.universe:

313

instrument = instruments(stock_id)

314

315

# Access instrument properties

316

logger.info(f"Instrument: {instrument.symbol}")

317

logger.info(f"Exchange: {instrument.exchange}")

318

logger.info(f"Sector: {instrument.sector_code_name}")

319

logger.info(f"Industry: {instrument.industry_name}")

320

logger.info(f"Board Type: {instrument.board_type}")

321

logger.info(f"Listed Date: {instrument.listed_date}")

322

323

# Check instrument type

324

if instrument.type == INSTRUMENT_TYPE.CS:

325

logger.info("Common stock")

326

elif instrument.type == INSTRUMENT_TYPE.ETF:

327

logger.info("ETF")

328

329

# Price limits

330

logger.info(f"Limit Up: {instrument.limit_up}")

331

logger.info(f"Limit Down: {instrument.limit_down}")

332

```

333

334

### Processing Bar Data

335

336

```python

337

def handle_bar(context, bar_dict):

338

for stock_id, bar in bar_dict.items():

339

# Access bar properties

340

logger.info(f"Bar data for {stock_id}:")

341

logger.info(f" DateTime: {bar.datetime}")

342

logger.info(f" OHLC: {bar.open}, {bar.high}, {bar.low}, {bar.close}")

343

logger.info(f" Volume: {bar.volume}")

344

logger.info(f" Turnover: {bar.total_turnover}")

345

346

# Calculate price changes

347

price_change = bar.close - bar.open

348

price_change_pct = price_change / bar.open

349

350

logger.info(f" Price Change: {price_change:.2f} ({price_change_pct:.2%})")

351

352

# Check for gaps

353

if hasattr(context, 'prev_close'):

354

gap = bar.open - context.prev_close.get(stock_id, bar.open)

355

if abs(gap) > bar.open * 0.05: # 5% gap

356

logger.warning(f"Large gap detected: {gap:.2f}")

357

358

# Store previous close

359

if not hasattr(context, 'prev_close'):

360

context.prev_close = {}

361

context.prev_close[stock_id] = bar.close

362

```

363

364

### Working with Tick Data

365

366

```python

367

def handle_tick(context, tick):

368

# Access tick properties

369

logger.info(f"Tick data for {tick.order_book_id}:")

370

logger.info(f" Time: {tick.datetime}")

371

logger.info(f" Last Price: {tick.last_price}")

372

logger.info(f" Volume: {tick.volume}")

373

374

# Bid/Ask spread analysis

375

spread = tick.ask_price_1 - tick.bid_price_1

376

mid_price = (tick.ask_price_1 + tick.bid_price_1) / 2

377

spread_bps = (spread / mid_price) * 10000

378

379

logger.info(f" Bid: {tick.bid_price_1} ({tick.bid_volume_1})")

380

logger.info(f" Ask: {tick.ask_price_1} ({tick.ask_volume_1})")

381

logger.info(f" Spread: {spread:.4f} ({spread_bps:.1f} bps)")

382

383

# Market depth

384

total_bid_volume = sum([

385

tick.bid_volume_1, tick.bid_volume_2, tick.bid_volume_3,

386

tick.bid_volume_4, tick.bid_volume_5

387

])

388

total_ask_volume = sum([

389

tick.ask_volume_1, tick.ask_volume_2, tick.ask_volume_3,

390

tick.ask_volume_4, tick.ask_volume_5

391

])

392

393

logger.info(f" Total Bid Volume: {total_bid_volume}")

394

logger.info(f" Total Ask Volume: {total_ask_volume}")

395

```

396

397

### Using Order Styles

398

399

```python

400

def handle_bar(context, bar_dict):

401

stock = "000001.XSHE"

402

current_price = bar_dict[stock].close

403

404

# Market order

405

market_order = order_shares(stock, 100, MarketOrder())

406

407

# Limit order with 1% below current price

408

limit_price = current_price * 0.99

409

limit_order = order_shares(stock, 100, LimitOrder(limit_price))

410

411

# TWAP order for large quantity

412

twap_order = order_shares(stock, 1000, TWAPOrder("09:30", "15:00"))

413

414

# VWAP order

415

vwap_order = order_shares(stock, 1000, VWAPOrder("10:00", "14:30"))

416

417

# Check order styles

418

if limit_order and isinstance(limit_order.style, LimitOrder):

419

logger.info(f"Limit order placed at {limit_order.style.limit_price}")

420

```

421

422

### Industry Classification Usage

423

424

```python

425

def init(context):

426

# Get stocks by industry

427

tech_stocks = get_industry("软件服务", source="sw")

428

bank_stocks = get_industry("银行", source="citics")

429

430

# Get industry classification for specific stocks

431

stock_industries = get_instrument_industry(

432

["000001.XSHE", "000002.XSHE"],

433

source="citics",

434

level=1

435

)

436

437

for stock_id, industry_info in stock_industries.items():

438

logger.info(f"{stock_id}: {industry_info}")

439

440

context.universe = tech_stocks[:20] # Top 20 tech stocks

441

```