Skip to content

Models

Plain data classes shared by every broker and strategy.

cjtrade.pkgs.models.order

OrderAction

Bases: str, Enum

Side of an order: BUY, SELL or CANCEL.

PriceType

Bases: str, Enum

Price type of an order: limit (LMT) or market (MKT).

OrderType

Bases: str, Enum

Common order types (time in force): ROD, IOC, FOK, GTC.

FOK = 'FOK' class-attribute instance-attribute

Not fully supported, depends on broker's actual implementation.

OrderLot

Bases: str, Enum

Order lot: intraday odd lot (盤中零股) or common lot (一般交易).

OrderStatus

Bases: str, Enum

Lifecycle status of an order.

Order(product, action, price, quantity, price_type, order_type, order_lot, id=(lambda: uuid.uuid4().hex)(), created_at=(lambda: datetime.utcnow() + timedelta(hours=8))(), broker='na', opt_field=dict()) dataclass

A CJTrade order for one product.

Attributes:

Name Type Description
product Product

What to trade.

action OrderAction

BUY or SELL.

price float

Order price.

quantity int

Order quantity.

price_type PriceType

LMT or MKT.

order_type OrderType

Time in force, e.g. ROD.

order_lot OrderLot

Common or intraday odd lot.

id str

CJ order id; a random uuid4 hex by default.

created_at datetime

Creation time as a naive UTC+8 datetime.

broker str

Broker name, 'na' by default.

opt_field dict

Optional broker-specific fields.

Warnings

created_at defaults to the wall clock (datetime.utcnow() + 8h) at construction, not to any simulated or replayed time.

OrderResult(status, message, metadata, linked_order, id=(lambda: uuid.uuid4().hex)()) dataclass

Result of an order operation reported by a broker client.

Attributes:

Name Type Description
status OrderStatus

Status after the operation.

message str

Human-readable message from the broker or engine.

metadata dict

Extra broker-specific detail.

linked_order str

Id of the order this result refers to; may be empty.

id str

Result id; a random uuid4 hex by default.

to_dict()

Return the result as a JSON-friendly dict, with status as its string value.

Source code in src/cjtrade/pkgs/models/order.py
164
165
166
167
168
169
170
171
172
173
174
def to_dict(self) -> Dict[str, Any]:
    """Return the result as a JSON-friendly dict, with ``status`` as its string value."""
    # Serialize to JSON-friendly dict
    status_val = self.status.value if hasattr(self.status, 'value') else self.status
    return {
        "status": status_val,
        "message": self.message,
        "metadata": self.metadata,
        "linked_order": self.linked_order,
        "id": self.id,
    }

cjtrade.pkgs.models.product

Exchange

Bases: str, Enum

Exchange a product is listed on (only TSE for now).

ProductType

Bases: str, Enum

Type of a product (only stocks for now).

Product(symbol, type=ProductType.STOCK, exchange=Exchange.TSE, category='', tags=list(), metadata=dict()) dataclass

An immutable tradable instrument (contract, 標的).

Attributes:

Name Type Description
symbol str

Ticker, e.g. "2330".

type ProductType

STOCK by default.

exchange Exchange

TSE by default.

category str

Category label; empty by default.

tags list of str

Free-form tags.

metadata dict

Free-form extra data.

to_dict()

Return the product as a dict, with enum fields as their string values.

Source code in src/cjtrade/pkgs/models/product.py
66
67
68
69
70
71
72
73
74
75
def to_dict(self) -> Dict[str, Any]:
    """Return the product as a dict, with enum fields as their string values."""
    return {
        "symbol": self.symbol,
        "type": self.type.value if hasattr(self.type, 'value') else self.type,
        "exchange": self.exchange.value if hasattr(self.exchange, 'value') else self.exchange,
        "category": self.category,
        "tags": self.tags,
        "metadata": self.metadata,
    }

cjtrade.pkgs.models.kbar

Kbar(timestamp, open, high, low, close, volume, symbol='')

One OHLCV bar (K線) for one symbol.

symbol is optional only for backward compatibility; anything that merges bars from several symbols into one stream (multi-symbol backtest, live feed) needs it set.

Parameters:

Name Type Description Default
timestamp datetime

Bar time.

required
open float

Bar prices.

required
high float

Bar prices.

required
low float

Bar prices.

required
close float

Bar prices.

required
volume int

Bar volume.

required
symbol str

Ticker; empty by default.

''
Source code in src/cjtrade/pkgs/models/kbar.py
22
23
24
25
26
27
28
29
30
def __init__(self, timestamp: datetime, open: float, high: float, low: float,
             close: float, volume: int, symbol: str = ""):
    self.timestamp = timestamp
    self.open = open
    self.high = high
    self.low = low
    self.close = close
    self.volume = volume
    self.symbol = symbol

from_snapshot(snapshot) classmethod

Treat a Snapshot as one closed bar.

No runner uses this any more: the trading engine publishes the broker's own 1m bars (MarketData.get_kbars). Kept for callers that only have a quote.

close and timestamp carry over exactly. open, high, low and volume do NOT describe this bar: a Snapshot reports the figures for the whole trading day so far -- that is what shioaji's api.snapshots() returns and what ArenaX now matches -- so on a 1m feed the high and low are the day's range, not the minute's, and they only widen as the session goes on.

A strategy reading bar.close is fine. One reading bar.high/low wants real per-bar extremes and has to get them from get_kbars() instead.

Source code in src/cjtrade/pkgs/models/kbar.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@classmethod
def from_snapshot(cls, snapshot) -> "Kbar":
    """Treat a Snapshot as one closed bar.

    No runner uses this any more: the trading engine publishes the
    broker's own 1m bars (MarketData.get_kbars). Kept for callers that
    only have a quote.

    `close` and `timestamp` carry over exactly. `open`, `high`, `low` and
    `volume` do NOT describe this bar: a Snapshot reports the figures for
    the whole trading day so far -- that is what shioaji's api.snapshots()
    returns and what ArenaX now matches -- so on a 1m feed the high and low
    are the day's range, not the minute's, and they only widen as the
    session goes on.

    A strategy reading bar.close is fine. One reading bar.high/low wants
    real per-bar extremes and has to get them from get_kbars() instead.
    """
    return cls(
        timestamp=snapshot.timestamp,
        open=snapshot.open,
        high=snapshot.high,
        low=snapshot.low,
        close=snapshot.close,
        volume=snapshot.volume,
        symbol=snapshot.symbol,
    )

tagged(symbol)

Copy with symbol set. For sources that only know it one level up.

Source code in src/cjtrade/pkgs/models/kbar.py
60
61
62
63
def tagged(self, symbol: str) -> "Kbar":
    """Copy with `symbol` set. For sources that only know it one level up."""
    return Kbar(self.timestamp, self.open, self.high, self.low,
                self.close, self.volume, symbol)

to_dict()

Return the bar as a dict with an ISO-format timestamp.

Source code in src/cjtrade/pkgs/models/kbar.py
69
70
71
72
73
74
75
76
77
78
79
def to_dict(self):
    """Return the bar as a dict with an ISO-format timestamp."""
    return {
        "symbol": self.symbol,
        "timestamp": self.timestamp.isoformat(),
        "open": self.open,
        "high": self.high,
        "low": self.low,
        "close": self.close,
        "volume": self.volume
    }

cjtrade.pkgs.models.quote

Product(symbol, type=ProductType.STOCK, exchange=Exchange.TSE, category='', tags=list(), metadata=dict()) dataclass

An immutable tradable instrument (contract, 標的).

Attributes:

Name Type Description
symbol str

Ticker, e.g. "2330".

type ProductType

STOCK by default.

exchange Exchange

TSE by default.

category str

Category label; empty by default.

tags list of str

Free-form tags.

metadata dict

Free-form extra data.

to_dict()

Return the product as a dict, with enum fields as their string values.

Source code in src/cjtrade/pkgs/models/product.py
66
67
68
69
70
71
72
73
74
75
def to_dict(self) -> Dict[str, Any]:
    """Return the product as a dict, with enum fields as their string values."""
    return {
        "symbol": self.symbol,
        "type": self.type.value if hasattr(self.type, 'value') else self.type,
        "exchange": self.exchange.value if hasattr(self.exchange, 'value') else self.exchange,
        "category": self.category,
        "tags": self.tags,
        "metadata": self.metadata,
    }

OrderAction

Bases: str, Enum

Side of an order: BUY, SELL or CANCEL.

PriceType

Bases: str, Enum

Price type of an order: limit (LMT) or market (MKT).

OrderType

Bases: str, Enum

Common order types (time in force): ROD, IOC, FOK, GTC.

FOK = 'FOK' class-attribute instance-attribute

Not fully supported, depends on broker's actual implementation.

OrderLot

Bases: str, Enum

Order lot: intraday odd lot (盤中零股) or common lot (一般交易).

OrderStatus

Bases: str, Enum

Lifecycle status of an order.

Order(product, action, price, quantity, price_type, order_type, order_lot, id=(lambda: uuid.uuid4().hex)(), created_at=(lambda: datetime.utcnow() + timedelta(hours=8))(), broker='na', opt_field=dict()) dataclass

A CJTrade order for one product.

Attributes:

Name Type Description
product Product

What to trade.

action OrderAction

BUY or SELL.

price float

Order price.

quantity int

Order quantity.

price_type PriceType

LMT or MKT.

order_type OrderType

Time in force, e.g. ROD.

order_lot OrderLot

Common or intraday odd lot.

id str

CJ order id; a random uuid4 hex by default.

created_at datetime

Creation time as a naive UTC+8 datetime.

broker str

Broker name, 'na' by default.

opt_field dict

Optional broker-specific fields.

Warnings

created_at defaults to the wall clock (datetime.utcnow() + 8h) at construction, not to any simulated or replayed time.

OrderResult(status, message, metadata, linked_order, id=(lambda: uuid.uuid4().hex)()) dataclass

Result of an order operation reported by a broker client.

Attributes:

Name Type Description
status OrderStatus

Status after the operation.

message str

Human-readable message from the broker or engine.

metadata dict

Extra broker-specific detail.

linked_order str

Id of the order this result refers to; may be empty.

id str

Result id; a random uuid4 hex by default.

to_dict()

Return the result as a JSON-friendly dict, with status as its string value.

Source code in src/cjtrade/pkgs/models/order.py
164
165
166
167
168
169
170
171
172
173
174
def to_dict(self) -> Dict[str, Any]:
    """Return the result as a JSON-friendly dict, with ``status`` as its string value."""
    # Serialize to JSON-friendly dict
    status_val = self.status.value if hasattr(self.status, 'value') else self.status
    return {
        "status": status_val,
        "message": self.message,
        "metadata": self.metadata,
        "linked_order": self.linked_order,
        "id": self.id,
    }

Quote dataclass

Last price and volume of a symbol.

Attributes:

Name Type Description
symbol str

Ticker.

price float

Last price.

volume int

Volume.

timestamp str

Time of the quote.

Snapshot dataclass

Market snapshot of one symbol: day OHLCV plus best bid and ask.

open, high, low and volume cover the trading day so far, not a single bar (see Kbar.from_snapshot).

Attributes:

Name Type Description
symbol str

Ticker.

exchange str

Exchange code, e.g. "TSE".

timestamp datetime

Time of the snapshot.

open, close, high, low float

Day prices; close is the latest price.

volume int

Volume.

average_price float

Average traded price.

action OrderAction

Side of the last trade (buy, sell or none).

buy_price, sell_price float

Best bid and best ask.

buy_volume, sell_volume int

Volume at the best bid and best ask.

additional_note (str, optional)

Free-form note.

from_dict(d) classmethod

Build a Snapshot from a dict such as the one to_dict returns.

Parameters:

Name Type Description Default
d dict

Snapshot fields. timestamp may be an ISO string and action a string; both are converted.

required

Returns:

Type Description
Snapshot

Raises:

Type Description
KeyError

If a required field is missing.

Source code in src/cjtrade/pkgs/models/quote.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "Snapshot":
    """Build a Snapshot from a dict such as the one `to_dict` returns.

    Parameters
    ----------
    d : dict
        Snapshot fields. ``timestamp`` may be an ISO string and ``action``
        a string; both are converted.

    Returns
    -------
    Snapshot

    Raises
    ------
    KeyError
        If a required field is missing.
    """
    ts = d.get("timestamp")
    if isinstance(ts, str):
        ts = datetime.fromisoformat(ts)
    action = d.get("action")
    if isinstance(action, str):
        action = OrderAction(action)
    return cls(
        symbol=d["symbol"],
        exchange=d["exchange"],
        timestamp=ts,
        open=float(d["open"]),
        close=float(d["close"]),
        high=float(d["high"]),
        low=float(d["low"]),
        volume=int(d["volume"]),
        average_price=float(d["average_price"]),
        action=action,
        buy_price=float(d["buy_price"]),
        buy_volume=int(d["buy_volume"]),
        sell_price=float(d["sell_price"]),
        sell_volume=int(d["sell_volume"]),
        additional_note=d.get("additional_note"),
    )

to_dict()

Return the snapshot as a JSON-friendly dict (ISO timestamp, enum values as strings).

Source code in src/cjtrade/pkgs/models/quote.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def to_dict(self) -> Dict[str, Any]:
    """Return the snapshot as a JSON-friendly dict (ISO timestamp, enum values as strings)."""
    return {
        "symbol": self.symbol,
        "exchange": self.exchange,
        "timestamp": self.timestamp.isoformat(),
        "open": self.open,
        "close": self.close,
        "high": self.high,
        "low": self.low,
        "volume": self.volume,
        "average_price": self.average_price,
        "action": self.action.value if hasattr(self.action, 'value') else self.action,
        "buy_price": self.buy_price,
        "buy_volume": self.buy_volume,
        "sell_price": self.sell_price,
        "sell_volume": self.sell_volume,
        "additional_note": self.additional_note,
    }

BidAsk dataclass

Five-level order book of one symbol.

Attributes:

Name Type Description
symbol str

Ticker.

datetime datetime

Time of the book.

bid_price, ask_price list of float

Prices of the five bid and ask levels.

bid_volume, ask_volume list of int

Volumes of the five bid and ask levels.

to_dict()

Return the order book as a JSON-friendly dict.

Source code in src/cjtrade/pkgs/models/quote.py
187
188
189
190
191
192
193
194
195
196
def to_dict(self) -> Dict[str, Any]:
    """Return the order book as a JSON-friendly dict."""
    return {
        "symbol": self.symbol,
        "datetime": self.datetime.isoformat(),
        "bid_price": self.bid_price,
        "bid_volume": self.bid_volume,
        "ask_price": self.ask_price,
        "ask_volume": self.ask_volume,
    }

cjtrade.pkgs.models.position

Position(symbol, quantity, avg_cost, current_price, market_value, unrealized_pnl=0.0) dataclass

A held position in one symbol.

Attributes:

Name Type Description
symbol str

Ticker.

quantity int

Held quantity; __str__ reports it as quantity * 1000 shares.

avg_cost float

Average cost.

current_price float

Latest price.

market_value float

Current market value.

unrealized_pnl float

Unrealized profit/loss; 0.0 by default.

to_dict()

Return the position as a dict.

Source code in src/cjtrade/pkgs/models/position.py
36
37
38
39
40
41
42
43
44
45
def to_dict(self) -> Dict[str, Any]:
    """Return the position as a dict."""
    return {
        "symbol": self.symbol,
        "quantity": self.quantity,
        "avg_cost": self.avg_cost,
        "current_price": self.current_price,
        "market_value": self.market_value,
        "unrealized_pnl": self.unrealized_pnl,
    }

cjtrade.pkgs.models.trade

Trade(id, symbol, action, quantity, price, status, order_type, price_type, order_lot, order_datetime, deals, ordno) dataclass

An order as reported back by a broker, with its status and deal count.

Attributes:

Name Type Description
id str

Order id.

symbol str

Ticker.

action, status, order_type, price_type str

String forms of the order's enums.

quantity int

Order quantity.

price float

Order price.

order_lot int

Order lot.

order_datetime str

Time the order was placed.

deals int

Number of deals (fills) so far.

ordno str

Broker order number.

to_dict()

Return the trade as a dict.

Source code in src/cjtrade/pkgs/models/trade.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def to_dict(self) -> Dict[str, Any]:
    """Return the trade as a dict."""
    return {
        "id": self.id,
        "symbol": self.symbol,
        "action": self.action,
        "quantity": self.quantity,
        "price": self.price,
        "status": self.status,
        "order_type": self.order_type,
        "price_type": self.price_type,
        "order_lot": self.order_lot,
        "order_datetime": self.order_datetime,
        "deals": self.deals,
        "ordno": self.ordno,
    }

cjtrade.pkgs.models.event

EventType

Bases: str, Enum

Kind of event delivered to a registered callback.

OrderEvent(event_type, timestamp, order_id, symbol, action, quantity, price, old_status, new_status, filled_quantity=0, filled_price=None, filled_value=None, order=None, broker_raw_data=dict(), message='') dataclass

An order changed status.

Attributes:

Name Type Description
event_type EventType

Kind of event.

timestamp datetime

When the change happened.

order_id, symbol str

The order and its ticker.

action OrderAction

BUY or SELL.

quantity int

Order quantity.

price float

Order price.

old_status, new_status OrderStatus

Status before and after the change.

filled_quantity int

Filled quantity; 0 by default.

filled_price (float, optional)

Fill price.

filled_value (float, optional)

filled_quantity * filled_price.

order (Order, optional)

The order itself.

broker_raw_data (dict, optional)

Raw broker payload.

message str

Free-form message.

Examples:

def on_order_change(event: OrderEvent):
    print(f"Order {event.order_id} status: {event.old_status} -> {event.new_status}")
    if event.new_status == OrderStatus.FILLED:
        print(f"Order filled! Total: {event.filled_quantity} @ {event.filled_price}")

client.register_order_callback(on_order_change)

is_filled()

Return True if the order is now filled or partially filled.

Source code in src/cjtrade/pkgs/models/event.py
91
92
93
def is_filled(self) -> bool:
    """Return True if the order is now filled or partially filled."""
    return self.new_status in [OrderStatus.FILLED, OrderStatus.PARTIAL]

is_completely_filled()

Return True if the order is now fully filled.

Source code in src/cjtrade/pkgs/models/event.py
95
96
97
def is_completely_filled(self) -> bool:
    """Return True if the order is now fully filled."""
    return self.new_status == OrderStatus.FILLED

is_cancelled()

Return True if the order is now cancelled.

Source code in src/cjtrade/pkgs/models/event.py
 99
100
101
def is_cancelled(self) -> bool:
    """Return True if the order is now cancelled."""
    return self.new_status == OrderStatus.CANCELLED

is_rejected()

Return True if the order is now rejected.

Source code in src/cjtrade/pkgs/models/event.py
103
104
105
def is_rejected(self) -> bool:
    """Return True if the order is now rejected."""
    return self.new_status == OrderStatus.REJECTED

to_dict()

Return the event as a JSON-friendly dict, without order and broker_raw_data.

Source code in src/cjtrade/pkgs/models/event.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def to_dict(self) -> Dict[str, Any]:
    """Return the event as a JSON-friendly dict, without ``order`` and ``broker_raw_data``."""
    return {
        "event_type": self.event_type.value if hasattr(self.event_type, 'value') else self.event_type,
        "timestamp": self.timestamp.isoformat(),
        "order_id": self.order_id,
        "symbol": self.symbol,
        "action": self.action.value if hasattr(self.action, 'value') else self.action,
        "quantity": self.quantity,
        "price": self.price,
        "old_status": self.old_status.value if hasattr(self.old_status, 'value') else self.old_status,
        "new_status": self.new_status.value if hasattr(self.new_status, 'value') else self.new_status,
        "filled_quantity": self.filled_quantity,
        "filled_price": self.filled_price,
        "filled_value": self.filled_value,
        "message": self.message,
    }

FillEvent(timestamp, order_id, symbol, action, filled_quantity, filled_price, filled_value, total_filled_quantity, remaining_quantity, order_status, fill_sequence=1, deal_id=None, order=None, broker_raw_data=dict()) dataclass

One fill (deal) of an order.

Attributes:

Name Type Description
timestamp datetime

When the fill happened.

order_id, symbol str

The order and its ticker.

action OrderAction

BUY or SELL.

filled_quantity int

Quantity of this fill.

filled_price float

Price of this fill.

filled_value float

Value of this fill.

total_filled_quantity int

Quantity filled so far, including this fill.

remaining_quantity int

Quantity still unfilled.

order_status OrderStatus

PARTIAL or FILLED.

fill_sequence int

Index of this fill within the order, starting at 1.

deal_id (str, optional)

Broker deal id.

order (Order, optional)

The order itself.

broker_raw_data (dict, optional)

Raw broker payload.

Examples:

def on_fill(event: FillEvent):
    print(f"✅ {event.action} {event.filled_quantity} {event.symbol} @ {event.filled_price}")

    if event.symbol == "0050" and event.filled_quantity >= 100:
        hedge_order = create_hedge_order(event)
        client.place_order(hedge_order)

client.register_fill_callback(on_fill)

is_complete_fill()

Return True if this fill completes the order.

Source code in src/cjtrade/pkgs/models/event.py
194
195
196
def is_complete_fill(self) -> bool:
    """Return True if this fill completes the order."""
    return self.order_status == OrderStatus.FILLED

to_dict()

Return the event as a JSON-friendly dict, without order and broker_raw_data.

Source code in src/cjtrade/pkgs/models/event.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def to_dict(self) -> Dict[str, Any]:
    """Return the event as a JSON-friendly dict, without ``order`` and ``broker_raw_data``."""
    return {
        "timestamp": self.timestamp.isoformat(),
        "order_id": self.order_id,
        "symbol": self.symbol,
        "action": self.action.value if hasattr(self.action, 'value') else self.action,
        "filled_quantity": self.filled_quantity,
        "filled_price": self.filled_price,
        "filled_value": self.filled_value,
        "total_filled_quantity": self.total_filled_quantity,
        "remaining_quantity": self.remaining_quantity,
        "order_status": self.order_status.value if hasattr(self.order_status, 'value') else self.order_status,
        "fill_sequence": self.fill_sequence,
        "deal_id": self.deal_id,
    }

PriceEvent(timestamp, symbol, current_price, previous_price=None, condition_type='', threshold=None, price_change=None, price_change_percent=None, volume=None, bid_price=None, ask_price=None, broker_raw_data=dict()) dataclass

A price condition on a symbol was met.

Attributes:

Name Type Description
timestamp datetime

When the condition was met.

symbol str

Ticker.

current_price float

Latest price.

previous_price (float, optional)

Price before the change.

condition_type str

"ABOVE", "BELOW", "CHANGE_PERCENT" or "TIME_INTERVAL".

threshold (float, optional)

Threshold of the condition.

price_change, price_change_percent (float, optional)

Change from previous_price.

volume (int, optional)

Volume.

bid_price, ask_price (float, optional)

Best bid and ask.

broker_raw_data (dict, optional)

Raw broker payload.

Examples:

def on_price_alert(event: PriceEvent):
    if event.symbol == "2330" and event.current_price > event.threshold:
        print(f"⚠️ {event.symbol} over {event.threshold}!")
        order = create_breakout_order(event.symbol)
        client.place_order(order)

client.register_price_callback(on_price_alert, symbol="2330", threshold=600)

to_dict()

Return the event as a JSON-friendly dict, without broker_raw_data.

Source code in src/cjtrade/pkgs/models/event.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def to_dict(self) -> Dict[str, Any]:
    """Return the event as a JSON-friendly dict, without ``broker_raw_data``."""
    return {
        "timestamp": self.timestamp.isoformat(),
        "symbol": self.symbol,
        "current_price": self.current_price,
        "previous_price": self.previous_price,
        "condition_type": self.condition_type,
        "threshold": self.threshold,
        "price_change": self.price_change,
        "price_change_percent": self.price_change_percent,
        "volume": self.volume,
        "bid_price": self.bid_price,
        "ask_price": self.ask_price,
    }

TickEvent(timestamp, symbol, price, volume, tick_type='', broker_raw_data=dict()) dataclass

One tick (trade print) of a symbol.

Attributes:

Name Type Description
timestamp datetime

Time of the tick.

symbol str

Ticker.

price float

Trade price.

volume int

Trade volume.

tick_type str

"BUY", "SELL" or "NEUTRAL".

broker_raw_data (dict, optional)

Raw broker payload.

Examples:

tick_buffer = []

def on_tick(event: TickEvent):
    tick_buffer.append(event)

    if len(tick_buffer) >= 10:
        avg_price = sum(t.price for t in tick_buffer) / 10
        print(f"10 avg: {avg_price}")
        tick_buffer.clear()

client.register_tick_callback(on_tick, symbol="0050")

to_dict()

Return the event as a JSON-friendly dict, without broker_raw_data.

Source code in src/cjtrade/pkgs/models/event.py
333
334
335
336
337
338
339
340
341
def to_dict(self) -> Dict[str, Any]:
    """Return the event as a JSON-friendly dict, without ``broker_raw_data``."""
    return {
        "timestamp": self.timestamp.isoformat(),
        "symbol": self.symbol,
        "price": self.price,
        "volume": self.volume,
        "tick_type": self.tick_type,
    }

cjtrade.pkgs.models.backtest

RoundTrip(symbol, entry_time, entry_price, exit_time, exit_price, quantity, pnl, holding_days) dataclass

A matched entry / exit pair for one symbol.

Supports partial exits (e.g. DCA stacking): each RoundTrip represents the FIFO matching of one entry lot against one exit lot.

Attributes:

Name Type Description
symbol str

Stock ticker.

entry_time str

ISO timestamp of the entry fill.

entry_price float

Fill price of the entry.

exit_time str

ISO timestamp of the exit fill.

exit_price float

Fill price of the exit.

quantity int

Number of shares matched in this pair.

pnl float

(exit_price - entry_price) * quantity (long only).

holding_days int

Calendar days between entry and exit.

BacktestResult(initial_balance, final_balance, equity_curve, fill_history, session_id=None, start_time=None, final_equity=None, provenance=None) dataclass

Immutable snapshot of a completed backtest session.

Attributes:

Name Type Description
initial_balance float

Starting cash before any trades.

final_balance float

Remaining cash at session end (excludes unrealised position value).

equity_curve list[dict]

Minute-resolution portfolio value recorded by the client. Each entry: {"time": "2024-06-14T09:01:00", "value": 1_234_567.0}

fill_history list[dict]

Every executed trade, already filtered to this session by the client. Each entry: {"time", "symbol", "action", "quantity", "price", "session_id", ...}

session_id (str, optional)

Opaque identifier the client stamped on every order it placed. Used to isolate this run's fills from the server's global fill_history.

start_time (str, optional)

ISO timestamp of when the client started this backtest session.

final_equity (float, optional)

Final portfolio equity (cash + position values) at session end. Used to calculate true PnL including unrealised gains/losses.

provenance (dict, optional)

Who produced this result and under what assumptions: which execution path, interval, symbols, window, strategy and parameters. Carried on the result because the two paths that produce one do NOT agree -- the oneshot engine fills a signal in the same bar at the signal's own price, while the trading engine places a limit order that fills only when a later close crosses it. The same strategy and parameters therefore give different numbers, so a report read without knowing which path produced it is not interpretable.

Defaults to None, which is what every result pickled before this field existed will report.

to_equity_series()

Return equity_curve as a minute-resolution pd.Series.

Source code in src/cjtrade/pkgs/models/backtest.py
105
106
107
108
109
110
111
def to_equity_series(self) -> "pd.Series":
    """Return equity_curve as a minute-resolution pd.Series."""
    if not self.equity_curve:
        return pd.Series(dtype=float)
    idx = pd.to_datetime([e["time"] for e in self.equity_curve])
    vals = [e["value"] for e in self.equity_curve]
    return pd.Series(vals, index=idx, name="equity")

to_daily_equity()

Resample minute equity to daily (last value of each trading day).

Source code in src/cjtrade/pkgs/models/backtest.py
113
114
115
116
117
118
def to_daily_equity(self) -> "pd.Series":
    """Resample minute equity to daily (last value of each trading day)."""
    minute_eq = self.to_equity_series()
    if minute_eq.empty:
        return minute_eq
    return minute_eq.resample("1D").last().dropna()

to_returns()

Return the returns as a pd.Series suitable for quantstats.

Uses daily returns when the backtest spans multiple calendar days. Falls back to minute-level returns (annualised at 252 trading days × 270 minutes/day) for single-day or intraday backtests.

Source code in src/cjtrade/pkgs/models/backtest.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def to_returns(self) -> "pd.Series":
    """Return the returns as a pd.Series suitable for quantstats.

    Uses daily returns when the backtest spans multiple calendar days.
    Falls back to minute-level returns (annualised at 252 trading days ×
    270 minutes/day) for single-day or intraday backtests.
    """
    daily = self.to_daily_equity()
    if len(daily) >= 2:
        return daily.pct_change().dropna()
    # Single-day fallback: use minute resolution
    minute_eq = self.to_equity_series()
    if minute_eq.empty:
        return minute_eq
    return minute_eq.pct_change().dropna()

to_quantstats()

Run the quantstats full report. Requires quantstats to be installed.

Raises:

Type Description
ImportError

If quantstats is not installed.

ValueError

If equity_curve is empty.

Source code in src/cjtrade/pkgs/models/backtest.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def to_quantstats(self):
    """Run the quantstats full report.  Requires ``quantstats`` to be installed.

    Raises
    ------
    ImportError
        If quantstats is not installed.
    ValueError
        If ``equity_curve`` is empty.
    """
    try:
        import quantstats as qs
    except ImportError:
        raise ImportError("pip install quantstats")
    returns = self.to_returns()
    if returns.empty:
        raise ValueError("equity_curve is empty – did the backtest run to completion?")
    qs.reports.full(returns, periods_per_year=self._returns_periods_per_year)

sharpe()

Return the Sharpe ratio of to_returns via quantstats.

Source code in src/cjtrade/pkgs/models/backtest.py
166
167
168
169
def sharpe(self) -> float:
    """Return the Sharpe ratio of `to_returns` via quantstats."""
    import quantstats as qs
    return qs.stats.sharpe(self.to_returns(), periods=self._returns_periods_per_year)

annual_return()

Return the annual growth rate (CAGR) of to_returns via quantstats.

Source code in src/cjtrade/pkgs/models/backtest.py
171
172
173
174
175
176
def annual_return(self) -> float:
    """Return the annual growth rate (CAGR) of `to_returns` via quantstats."""
    import quantstats as qs
    # quantstats.stats.cagr() accepts 'periods' for annualisation in some versions
    # prefer 'periods' to remain compatible across quantstats versions
    return qs.stats.cagr(self.to_returns(), periods=self._returns_periods_per_year)

max_drawdown()

Return the maximum drawdown of to_returns via quantstats.

Source code in src/cjtrade/pkgs/models/backtest.py
178
179
180
181
def max_drawdown(self) -> float:
    """Return the maximum drawdown of `to_returns` via quantstats."""
    import quantstats as qs
    return qs.stats.max_drawdown(self.to_returns())

compute_round_trips()

Match BUY fills against SELL fills using FIFO per symbol.

Works for both non-stacking (one BUY per SELL) and stacking strategies (multiple BUYs partially matched by each SELL). Only long trades are supported (BUY first, then SELL).

Returns:

Type Description
list[RoundTrip]

Sorted by entry_time ascending.

Source code in src/cjtrade/pkgs/models/backtest.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def compute_round_trips(self) -> List[RoundTrip]:
    """Match BUY fills against SELL fills using FIFO per symbol.

    Works for both non-stacking (one BUY per SELL) and stacking
    strategies (multiple BUYs partially matched by each SELL).
    Only long trades are supported (BUY first, then SELL).

    Returns
    -------
    list[RoundTrip]
        Sorted by entry_time ascending.
    """
    from collections import deque
    from datetime import datetime as _dt

    # Group fills by symbol, sorted by time
    by_symbol: Dict[str, list] = defaultdict(list)
    for f in sorted(self.fill_history, key=lambda x: x.get("time", "")):
        by_symbol[f["symbol"]].append(f)

    round_trips: List[RoundTrip] = []

    for symbol, fills in by_symbol.items():
        buy_queue: deque = deque()   # each item: [price, qty, time]

        for f in fills:
            qty = abs(f["quantity"])
            action = f["action"]
            price = float(f["price"])
            ts = f["time"]

            # TODO: support short-first trades
            # 新增一個 sell_queue (deque) 對稱 buy_queue:
            # 遇到 SELL 且 buy_queue 為空時,push 到 sell_queue(開空);
            # 遇到 BUY 且 sell_queue 非空時,從 sell_queue 頭端 FIFO 配對(平空),
            # pnl = (entry_price - exit_price) * matched(方向相反)。
            if action == "BUY":
                buy_queue.append([price, qty, ts])
            elif action == "SELL":
                remaining = qty
                while remaining > 0 and buy_queue:
                    buy_price, buy_qty, buy_ts = buy_queue[0]
                    matched = min(remaining, buy_qty)

                    try:
                        entry_dt = _dt.fromisoformat(buy_ts)
                        exit_dt  = _dt.fromisoformat(ts)
                        holding_days = (exit_dt.date() - entry_dt.date()).days
                    except Exception:
                        holding_days = 0

                    round_trips.append(RoundTrip(
                        symbol=symbol,
                        entry_time=buy_ts,
                        entry_price=buy_price,
                        exit_time=ts,
                        exit_price=price,
                        quantity=matched,
                        pnl=round((price - buy_price) * matched, 2),
                        holding_days=holding_days,
                    ))

                    if matched >= buy_qty:
                        buy_queue.popleft()
                    else:
                        buy_queue[0][1] -= matched
                    remaining -= matched

    round_trips.sort(key=lambda rt: rt.entry_time)
    return round_trips

trades_on(date)

Return all fills that occurred on date (e.g. '2024-06-14').

Source code in src/cjtrade/pkgs/models/backtest.py
257
258
259
def trades_on(self, date: str) -> List[Dict]:
    """Return all fills that occurred on ``date`` (e.g. '2024-06-14')."""
    return [f for f in self.fill_history if f.get("time", "").startswith(date)]

daily_summary()

DataFrame with one row per calendar day.

Returns:

Type Description
DataFrame

Columns: date, equity, daily_return, n_trades, traded_value.

Source code in src/cjtrade/pkgs/models/backtest.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def daily_summary(self) -> "pd.DataFrame":
    """DataFrame with one row per calendar day.

    Returns
    -------
    pandas.DataFrame
        Columns: date, equity, daily_return, n_trades, traded_value.
    """
    daily_eq = self.to_daily_equity()
    daily_ret = daily_eq.pct_change()

    fills_df = pd.DataFrame(self.fill_history) if self.fill_history else pd.DataFrame()

    rows = []
    for ts, eq in daily_eq.items():
        date_str = ts.strftime("%Y-%m-%d")
        ret = daily_ret.get(ts, float("nan"))
        if not fills_df.empty and "time" in fills_df.columns:
            day_fills = fills_df[fills_df["time"].str.startswith(date_str)]
            n_trades = len(day_fills)
            traded_value = (day_fills["price"] * day_fills["quantity"].abs()).sum() \
                if not day_fills.empty else 0.0
        else:
            n_trades, traded_value = 0, 0.0
        rows.append({
            "date": date_str,
            "equity": eq,
            "daily_return": round(ret, 6) if ret == ret else None,
            "n_trades": n_trades,
            "traded_value": round(traded_value, 2),
        })
    return pd.DataFrame(rows)

save(path)

Serialise to a pickle file.

Parameters:

Name Type Description Default
path str

Destination file.

required
Warnings

Writes path, overwriting any existing file.

Source code in src/cjtrade/pkgs/models/backtest.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def save(self, path: str) -> None:
    """Serialise to a pickle file.

    Parameters
    ----------
    path : str
        Destination file.

    Warnings
    --------
    Writes `path`, overwriting any existing file.
    """
    import pickle
    with open(path, "wb") as f:
        pickle.dump(self, f)

load(path) staticmethod

Deserialise from a pickle file.

Parameters:

Name Type Description Default
path str

File written by save.

required

Returns:

Type Description
BacktestResult
Warnings

Unpickling can run arbitrary code; load only files you trust.

Source code in src/cjtrade/pkgs/models/backtest.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
@staticmethod
def load(path: str) -> "BacktestResult":
    """Deserialise from a pickle file.

    Parameters
    ----------
    path : str
        File written by `save`.

    Returns
    -------
    BacktestResult

    Warnings
    --------
    Unpickling can run arbitrary code; load only files you trust.
    """
    import pickle
    with open(path, "rb") as f:
        return pickle.load(f)