Skip to content

ArenaX client

ArenaXBrokerAPI_v2 is the ArenaX adapter behind AccountClient. ArenaXMiddleWare is the HTTP client underneath it, also reachable as client.control_plane; it is how a replay driver moves the simulated clock.

Warning

Every method makes an HTTP call to the ArenaX server. Transport errors come back as None or an empty list rather than an exception.

cjtrade.pkgs.brokers.arenax.arenax_broker_api

Name: ArenaX Broker API v2 Description: User-side API that commnunicates with the ArenaX (Simulated Broker) via ArenaXMiddleWare. Usecase: Perform trading operations and account operations in the ArenaX simulated environment, such as placing/canceling orders, querying account cash balance, positions and market stock prices, etc.

Code quality check: - todo : 2026-05-01 - note : 2026-05-01 - code logic : 2026-05-01 - dead code : 2026-05-01

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,
    }

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
    }

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,
    }

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).

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.

OrderAction

Bases: str, Enum

Side of an order: BUY, SELL or CANCEL.

OrderStatus

Bases: str, Enum

Lifecycle status of an order.

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,
    }

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 (一般交易).

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,
    }

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,
    }

ArenaXBrokerAPI_v2(**config)

Bases: BrokerAPIBase

Broker API that communicates with the ArenaX standalone server via ArenaXMiddleWare.

For unit tests, inject a mock middleware via the middleware keyword argument: api = ArenaXBrokerAPI_v2(middleware=MockMiddleWare())

Parameters:

Name Type Description Default
**config Any

arenax_host (default 'localhost'), arenax_port (default $ARENAX_PORT or 8801), middleware, api_key (needed by connect()), username (default 'Ariana') and mirror_db_path.

{}
Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(self, **config: Any):
    super().__init__(**config)
    self.host = config.get('arenax_host', 'localhost')
    _default_port = int(os.environ.get('ARENAX_PORT', 8801))
    self.port = config.get('arenax_port', _default_port)
    self.middleware: ArenaXMiddleWare = config.get('middleware') or \
    ArenaXMiddleWare(
        host=self.host,
        port=self.port
    )
    self.config = config

    # db connection
    self.username = config.get('username', 'Ariana')
    self.db_path = config.get('mirror_db_path') or str(paths.mirror_db_path('arenax'))
    self.db = None

connect()

Connect to the ArenaX standalone server and set up the local SQLite mirror database.

Logs in via ArenaXMiddleWare.

Returns:

Type Description
bool

True if connection is successful, False otherwise.

Warnings

Makes a network call and opens (creating if needed) the mirror database file.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def connect(self) -> bool:
    """Connect to the ArenaX standalone server and set up the local SQLite mirror database.

    Logs in via ArenaXMiddleWare.

    Returns
    -------
    bool
        True if connection is successful, False otherwise.

    Warnings
    --------
    Makes a network call and opens (creating if needed) the mirror database file.
    """
    try:
        self.middleware.login(self.config['api_key'])
        self._connected = True
        self.db = connect_sqlite(database=self.db_path)
        prepare_cjtrade_tables(conn=self.db)
        log.info("connected")
        return True
    except Exception as e:
        log.error("connect failed: %s", e)
        self._connected = False
        return False

disconnect()

Log out of the server and close the mirror database.

Warnings

Makes a network call to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def disconnect(self) -> None:
    """Log out of the server and close the mirror database.

    Warnings
    --------
    Makes a network call to the ArenaX server.
    """
    if self._connected:
        try:
            self.middleware.logout()
            log.info("disconnected")
            self.db.close()
        except Exception as e:
            log.warning("disconnect err: %s", e)
        finally:
            self._connected = False

is_connected()

Return whether connect() succeeded and disconnect() has not been called.

Returns:

Type Description
bool
Warnings

Raises AttributeError if called before connect(); disconnect() does too.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
120
121
122
123
124
125
126
127
128
129
130
131
def is_connected(self) -> bool:
    """Return whether connect() succeeded and disconnect() has not been called.

    Returns
    -------
    bool

    Warnings
    --------
    Raises AttributeError if called before connect(); disconnect() does too.
    """
    return self._connected

market_data()

Return an ArenaXMarketData that shares this session.

Returns:

Type Description
ArenaXMarketData
Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
157
158
159
160
161
162
163
164
165
def market_data(self):
    """Return an ArenaXMarketData that shares this session.

    Returns
    -------
    ArenaXMarketData
    """
    from cjtrade.pkgs.marketdata.arenax import ArenaXMarketData
    return ArenaXMarketData(self)

get_positions()

Return current positions from the server.

Returns:

Type Description
List[Position]

Raises:

Type Description
ConnectionError

The server did not answer.

Warnings

Makes a network call to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def get_positions(self) -> List[Position]:
    """Return current positions from the server.

    Returns
    -------
    List[Position]

    Raises
    ------
    ConnectionError
        The server did not answer.

    Warnings
    --------
    Makes a network call to the ArenaX server.
    """
    pos = self._account_summary().get("positions")
    return [Position(**p) for p in (pos or [])]

get_balance()

Return the account balance from the server.

Returns:

Type Description
float

Raises:

Type Description
ConnectionError

The server did not answer or sent no balance.

Warnings

Makes a network call to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def get_balance(self) -> float:
    """Return the account balance from the server.

    Returns
    -------
    float

    Raises
    ------
    ConnectionError
        The server did not answer or sent no balance.

    Warnings
    --------
    Makes a network call to the ArenaX server.
    """
    balance = self._account_summary().get("balance")
    if balance is None:
        raise ConnectionError(
            f"ArenaX server at {self.host}:{self.port} answered "
            f"GET /api/v1/account with no balance")
    return float(balance)

get_bid_ask(product, intraday_odd=False)

Return a simulated five-level bid/ask quote for a product.

Parameters:

Name Type Description Default
product Product
required
intraday_odd bool

Accepted for interface compatibility; not used.

False

Returns:

Type Description
BidAsk

Raises:

Type Description
ConnectionError

Not connected.

Warnings

Not real quotes: prices are spaced 0.5 around the last close (100.0 if no snapshot), volumes are random, and the timestamp is the local wall clock.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
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
def get_bid_ask(self, product: Product, intraday_odd: bool = False) -> BidAsk:
    """Return a simulated five-level bid/ask quote for a product.

    Parameters
    ----------
    product : Product
    intraday_odd : bool, optional
        Accepted for interface compatibility; not used.

    Returns
    -------
    BidAsk

    Raises
    ------
    ConnectionError
        Not connected.

    Warnings
    --------
    Not real quotes: prices are spaced 0.5 around the last close (100.0 if
    no snapshot), volumes are random, and the timestamp is the local wall clock.
    """
    if not self._connected:
        raise ConnectionError("Not connected to broker")

    snapshot = self.middleware.snapshot(product.symbol)
    base_price = snapshot['close'] if snapshot else 100.0

    # TODO: Backend need to query the real bid/ask price rather than simulating one
    return BidAsk(
        symbol=product.symbol,
        datetime=datetime.now(),
        bid_price=[base_price - i*0.5 for i in range(5)],
        bid_volume=[random.randint(50, 500) for _ in range(5)],
        ask_price=[base_price + 0.5 + i*0.5 for i in range(5)],
        ask_volume=[random.randint(50, 500) for _ in range(5)]
    )

get_snapshots(products)

Return snapshots for the given products.

Products the server returns no snapshot for are skipped.

Parameters:

Name Type Description Default
products List[Product]
required

Returns:

Type Description
List[Snapshot]

Raises:

Type Description
ConnectionError

Not connected.

Warnings

Makes a network call to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def get_snapshots(self, products: List[Product]) -> List[Snapshot]:
    """Return snapshots for the given products.

    Products the server returns no snapshot for are skipped.

    Parameters
    ----------
    products : List[Product]

    Returns
    -------
    List[Snapshot]

    Raises
    ------
    ConnectionError
        Not connected.

    Warnings
    --------
    Makes a network call to the ArenaX server.
    """
    if not self._connected:
        raise ConnectionError("Not connected to broker")

    snapshots = []
    for product in products:
        snapshot = self.middleware.snapshot(product.symbol)
        snapshot = Snapshot.from_dict(snapshot) if snapshot else None
        if snapshot:
            snapshots.append(snapshot)

    return snapshots

get_kbars(product, start, end, interval='1m')

Return kbars for a product from the ArenaX server.

Does not require connect().

Parameters:

Name Type Description Default
product Product
required
start str

Start date.

required
end str

End date, exclusive.

required
interval str

'1m', '5m', '1h' or '1d'. Any other value prints a message and falls back to '1m'.

'1m'

Returns:

Type Description
List[Kbar]
Warnings

Makes a network call to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def get_kbars(self, product: Product, start: str, end: str, interval: str = "1m"):
    """Return kbars for a product from the ArenaX server.

    Does not require connect().

    Parameters
    ----------
    product : Product
    start : str
        Start date.
    end : str
        End date, exclusive.
    interval : str, optional
        '1m', '5m', '1h' or '1d'. Any other value prints a message and
        falls back to '1m'.

    Returns
    -------
    List[Kbar]

    Warnings
    --------
    Makes a network call to the ArenaX server.
    """
    # Note: kbar fetching is a read-only data operation and does not require
    # an authenticated trading session.  No _connected guard here.

    supported_intervals = ["1m", "5m", "1h", "1d"]
    if interval not in supported_intervals:
        log.warning("interval %r not supported by backend, using '1m'", interval)
        interval = "1m"

    # Server selects the data source automatically (price_db → real broker → yfinance).
    # No client-side availability check or fallback routing needed.
    kbars_raw = self.middleware.get_kbars(product.symbol, start, end, interval)

    def _parse_kbar(kr: dict) -> Kbar:
        ts = kr["timestamp"]
        if isinstance(ts, str):
            from datetime import datetime as _dt
            try:
                ts = _dt.fromisoformat(ts)
            except ValueError:
                ts = _dt.strptime(ts, "%a, %d %b %Y %H:%M:%S GMT")
        return Kbar(
            timestamp=ts,
            open=float(kr["open"]),
            high=float(kr["high"]),
            low=float(kr["low"]),
            close=float(kr["close"]),
            volume=int(kr["volume"]),
            # Server response has no code field; take it from the request.
            symbol=kr.get("symbol") or product.symbol,
        )

    kbars = [_parse_kbar(kr) for kr in kbars_raw] if kbars_raw else []

    return kbars

register_order_callback(callback)

Not implemented. Poll sync_state() or list_orders() instead.

A callback is a local function, so there is nothing to register with a REST server -- the server-side shape for this is an append-only event log the client tails:

GET /api/v1/events?after=<seq>  ->  {"events": [...], "last_seq": N}

and THIS method is where the callback illusion gets manufactured: store callback, run a daemon thread that tails the log, rebuild each OrderEvent and invoke it. The server would learn nothing about callbacks, and the backend would only append to the log from the two places that already own every transition -- _apply_fill() and the cancel path.

Warnings

Placeholder: always raises NotImplementedError.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def register_order_callback(self, callback: OrderCallback) -> None:
    """Not implemented. Poll sync_state() or list_orders() instead.

    A callback is a local function, so there is nothing to register with a
    REST server -- the server-side shape for this is an append-only event
    log the client tails:

        GET /api/v1/events?after=<seq>  ->  {"events": [...], "last_seq": N}

    and THIS method is where the callback illusion gets manufactured: store
    `callback`, run a daemon thread that tails the log, rebuild each
    OrderEvent and invoke it. The server would learn nothing about
    callbacks, and the backend would only append to the log from the two
    places that already own every transition -- _apply_fill() and the
    cancel path.

    Warnings
    --------
    Placeholder: always raises NotImplementedError.
    """
    raise NotImplementedError(
        "ArenaX has no push callback yet; poll sync_state() or list_orders()."
    )

get_market_movers(top_n=10, by=RankType.PRICE_PERCENTAGE_CHANGE, ascending=True)

Not implemented; returns None.

Warnings

Placeholder: always returns None.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
374
375
376
377
378
379
380
381
382
383
384
385
def get_market_movers(self, top_n: int = 10,
                      by: RankType = RankType.PRICE_PERCENTAGE_CHANGE,
                      ascending: bool = True) -> Dict[str, Snapshot]:
    """Not implemented; returns None.

    Warnings
    --------
    Placeholder: always returns None.
    """
    # Mock implementation - return None for simplicity
    # Caller should handle None return value
    return None

place_order(order)

Place an order on the ArenaX server and record it in the mirror database.

Sets order.created_at to the current market time before sending.

Parameters:

Name Type Description Default
order Order
required

Returns:

Type Description
OrderResult

Raises:

Type Description
ConnectionError

Not connected, or the server did not answer.

ValueError

The server rejected the order.

Warnings

Makes a network call (simulated order, not a real one) and writes the order to the local mirror database.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
def place_order(self, order: Order) -> OrderResult:
    """Place an order on the ArenaX server and record it in the mirror database.

    Sets ``order.created_at`` to the current market time before sending.

    Parameters
    ----------
    order : Order

    Returns
    -------
    OrderResult

    Raises
    ------
    ConnectionError
        Not connected, or the server did not answer.
    ValueError
        The server rejected the order.

    Warnings
    --------
    Makes a network call (simulated order, not a real one) and writes the
    order to the local mirror database.
    """
    if not self._connected:
        raise ConnectionError("Not connected to broker")

    # Overwrite created_at (place ts is much more important than create ts)
    order.created_at = self.get_market_time()["mock_current_time"]

    res = self.middleware.place_order(order)

    insert_new_order_to_db(conn=self.db, username=self.username, order=order)
    # insert_new_order_to_db always writes 'PLACED'; update to actual status immediately
    update_order_status_to_db(conn=self.db, oid=order.id, status=res.status.value, updated_at=order.created_at)
    return res

cancel_order(order_id)

Cancel an order on the ArenaX server.

The mirror database is updated only when the result is CANCELLED.

Parameters:

Name Type Description Default
order_id str

The CJTrade order id.

required

Returns:

Type Description
OrderResult

Raises:

Type Description
ConnectionError

The server did not answer.

Warnings

Makes network calls and writes to the local mirror database.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
def cancel_order(self, order_id: str) -> OrderResult:
    """Cancel an order on the ArenaX server.

    The mirror database is updated only when the result is CANCELLED.

    Parameters
    ----------
    order_id : str
        The CJTrade order id.

    Returns
    -------
    OrderResult

    Raises
    ------
    ConnectionError
        The server did not answer.

    Warnings
    --------
    Makes network calls and writes to the local mirror database.
    """
    res = self.middleware.cancel_order(order_id=order_id)

    update_at = self.get_market_time()["mock_current_time"]

    if res.status == OrderStatus.CANCELLED:
        update_order_status_to_db(conn=self.db, oid=order_id, status="CANCELLED", updated_at=update_at)

    return res

sync_state()

Refresh status of all committed orders from the broker backend.

Returns:

Type Description
List[OrderResult]

One result per refreshed order. Per-order errors are printed and skipped.

Warnings

Makes network calls and writes order status to the local mirror database.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def sync_state(self) -> List[OrderResult]:
    """Refresh status of all committed orders from the broker backend.

    Returns
    -------
    List[OrderResult]
        One result per refreshed order. Per-order errors are printed and
        skipped.

    Warnings
    --------
    Makes network calls and writes order status to the local mirror database.
    """
    res = []
    orders = self.middleware.list_orders()
    committed_statuses = {OrderStatus.COMMITTED_WAIT_MATCHING.value, OrderStatus.COMMITTED_WAIT_MARKET_OPEN.value}
    committed_orders = [o for o in orders if o.get("status") in committed_statuses]
    for o in committed_orders:
        order_id = o.get("id") or o.get("order_id") or o.get("ordno")
        try:
            refreshed = self.middleware.sync_state(order_id)
            if refreshed:
                update_at = self.get_market_time()["mock_current_time"]
                update_order_status_to_db(conn=self.db, oid=order_id, status=refreshed.status.value, updated_at=update_at)
                res.append(refreshed)
        except Exception as e:
            log.warning("refresh order %s failed: %s", order_id, e)
    return res

list_orders()

Return the account's orders.

Returns:

Type Description
List[Trade]
Warnings

Makes a network call to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def list_orders(self) -> List[Trade]:
    """Return the account's orders.

    Returns
    -------
    List[Trade]

    Warnings
    --------
    Makes a network call to the ArenaX server.
    """
    # GET /api/v1/orders, not the whole account: this skips rebuilding and
    # re-pricing every position just to read the order list.
    return [Trade(**o) for o in self.middleware.list_orders()]

is_market_open()

Return whether the server's market time is on a weekday, 09:00-13:30.

Returns:

Type Description
bool
Warnings

Makes a network call. Holidays are not considered.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
506
507
508
509
510
511
512
513
514
515
516
517
def is_market_open(self) -> bool:
    """Return whether the server's market time is on a weekday, 09:00-13:30.

    Returns
    -------
    bool

    Warnings
    --------
    Makes a network call. Holidays are not considered.
    """
    return self.middleware.is_market_open()

get_broker_name()

Return 'arenax (<port>)'.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
520
521
522
def get_broker_name(self) -> str:
    """Return ``'arenax (<port>)'``."""
    return f"arenax ({self.port})"

get_system_time()

Deprecated alias for get_market_time().

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
525
526
527
def get_system_time(self) -> dict:
    """Deprecated alias for get_market_time()."""
    return self.get_market_time()

get_market_time()

Return the server clock, with datetimes parsed from ISO 8601.

See BrokerAPIBase.get_market_time for the keys.

Returns:

Type Description
dict
Warnings

Makes a network call; the result depends on the server clock.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
def get_market_time(self) -> dict:
    """Return the server clock, with datetimes parsed from ISO 8601.

    See BrokerAPIBase.get_market_time for the keys.

    Returns
    -------
    dict

    Warnings
    --------
    Makes a network call; the result depends on the server clock.
    """
    # Server emits all datetime fields as ISO 8601 (naive Asia/Taipei).
    # Parse with fromisoformat(); no timezone conversion needed.
    #
    # playback_speed and paused are forwarded, not dropped: the server
    # already reports both, and a caller that wants to scale its own
    # waiting needs the speed. Dropping them here is what forced callers to
    # reach through to
    # middleware.get_config()['internal_config']['playback_speed'] instead.
    t = self.middleware.get_market_time()
    return {
        "mock_current_time": datetime.fromisoformat(t['mock_current_time']),
        "real_current_time": datetime.fromisoformat(t['real_current_time']),
        "mock_init_time":    datetime.fromisoformat(t['mock_init_time']),
        "real_init_time":    datetime.fromisoformat(t['real_init_time']),
        "playback_speed":    float(t.get('playback_speed', 1.0)),
        "paused":            bool(t.get('paused', False)),
    }

buy_stock(symbol, quantity, price, intraday_odd=True, opt_field=None)

Place a limit buy order for a stock.

Builds a TSE stock order with LMT price type and ROD order type and passes it to place_order().

Parameters:

Name Type Description Default
symbol str

Stock symbol, e.g. '2330'.

required
quantity int

Order quantity.

required
price float

Limit price.

required
intraday_odd bool

True for an intraday odd-lot order, False for a board-lot order.

True
opt_field dict

Extra fields attached to the order.

None

Returns:

Type Description
OrderResult
Warnings

Makes a network call (simulated order, not a real one) and writes the order to the local mirror database.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def buy_stock(self, symbol: str, quantity: int, price: float, intraday_odd: bool = True,
              opt_field: dict = None) -> OrderResult:
    """Place a limit buy order for a stock.

    Builds a TSE stock order with LMT price type and ROD order type and passes
    it to place_order().

    Parameters
    ----------
    symbol : str
        Stock symbol, e.g. ``'2330'``.
    quantity : int
        Order quantity.
    price : float
        Limit price.
    intraday_odd : bool, optional
        True for an intraday odd-lot order, False for a board-lot order.
    opt_field : dict, optional
        Extra fields attached to the order.

    Returns
    -------
    OrderResult

    Warnings
    --------
    Makes a network call (simulated order, not a real one) and writes the
    order to the local mirror database.
    """
    product = Product(
        type=ProductType.STOCK,
        exchange=Exchange.TSE,
        symbol=symbol
    )

    order = Order(
        product=product,
        action=OrderAction.BUY,
        price_type=PriceType.LMT,
        order_type=OrderType.ROD,
        order_lot=OrderLot.IntraDayOdd if intraday_odd else OrderLot.Common,
        quantity=quantity,
        price=price,
        opt_field=opt_field or {},
    )

    return self.place_order(order)

sell_stock(symbol, quantity, price, intraday_odd=True, opt_field=None)

Place a limit sell order for a stock.

Builds a TSE stock order with LMT price type and ROD order type and passes it to place_order().

Parameters:

Name Type Description Default
symbol str

Stock symbol, e.g. '2330'.

required
quantity int

Order quantity.

required
price float

Limit price.

required
intraday_odd bool

True for an intraday odd-lot order, False for a board-lot order.

True
opt_field dict

Extra fields attached to the order.

None

Returns:

Type Description
OrderResult
Warnings

Makes a network call (simulated order, not a real one) and writes the order to the local mirror database.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_broker_api.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
def sell_stock(self, symbol: str, quantity: int, price: float, intraday_odd: bool = True,
               opt_field: dict = None) -> OrderResult:
    """Place a limit sell order for a stock.

    Builds a TSE stock order with LMT price type and ROD order type and passes
    it to place_order().

    Parameters
    ----------
    symbol : str
        Stock symbol, e.g. ``'2330'``.
    quantity : int
        Order quantity.
    price : float
        Limit price.
    intraday_odd : bool, optional
        True for an intraday odd-lot order, False for a board-lot order.
    opt_field : dict, optional
        Extra fields attached to the order.

    Returns
    -------
    OrderResult

    Warnings
    --------
    Makes a network call (simulated order, not a real one) and writes the
    order to the local mirror database.
    """
    product = Product(
        type=ProductType.STOCK,
        exchange=Exchange.TSE,
        symbol=symbol
    )

    order = Order(
        product=product,
        action=OrderAction.SELL,
        price_type=PriceType.LMT,
        order_type=OrderType.ROD,
        order_lot=OrderLot.IntraDayOdd if intraday_odd else OrderLot.Common,
        quantity=quantity,
        price=price,
        opt_field=opt_field or {},
    )

    return self.place_order(order)

cjtrade.pkgs.brokers.arenax.arenax_middleware

Name: ArenaX Broker Middleware Description: Served as an abstraction layer between ArenaX server and ArenaX API, providing a clean interface for the API to interact with the server without worrying about the underlying communication details. It translates high-level API calls into specific HTTP requests. Usecase: Not directly used by end-users. It is an internal component of the ArenaX API implementation.

Code quality check: - todo : 2026-05-01 - note : 2026-05-01 - code logic : N/A - dead code : N/A

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
    }

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,
    }

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,
    }

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).

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,
    }

RankType

Bases: str, Enum

Criterion for ranking market movers: percentage change, price change or volume.

ArenaXMiddleWare(host='localhost', port=8801)

HTTP client for the ArenaX broker-side server.

Parameters:

Name Type Description Default
host str

Server host.

'localhost'
port int

Server port.

8801
Warnings

Every method makes a plain-HTTP request. Transport failures are logged and returned as None, not raised.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
42
43
44
45
def __init__(self, host: str = "localhost", port: int = 8801):
    self.host = host
    self.port = port
    self.base_url = f"http://{self.host}:{self.port}"

check_health(**kwargs)

Return the server's health response (GET health).

Returns:

Type Description
Any

Parsed JSON, or None if the request failed.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def check_health(self, **kwargs) -> bool:
    """Return the server's health response (GET health).

    Returns
    -------
    Any
        Parsed JSON, or None if the request failed.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    data = self._get("health")
    return data

get_market_time(**kwargs)

Raw clock dict from the server. See BrokerAPIBase.get_market_time.

Returns:

Type Description
dict or None

None if the server did not answer.

Warnings

Sends an HTTP request; the result depends on the server clock.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def get_market_time(self, **kwargs) -> dict:
    """Raw clock dict from the server. See BrokerAPIBase.get_market_time.

    Returns
    -------
    dict or None
        None if the server did not answer.

    Warnings
    --------
    Sends an HTTP request; the result depends on the server clock.
    """
    t = self._get("api/v1/clock")
    if t:
        return t
    else:
        log.error("get market time failed: no resp")
        return None

get_timeline(symbols, start, end, interval='1m')

The bar timestamps a replay of symbols over [start, end) steps through.

Not limited by the server clock, unlike get_kbars: a replay driver needs them before the clock gets there. Carries no prices.

Returns:

Type Description
list of datetime

Sorted union across symbols. Empty if the request failed.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def get_timeline(self, symbols, start: str, end: str, interval: str = "1m") -> list:
    """The bar timestamps a replay of `symbols` over ``[start, end)`` steps through.

    Not limited by the server clock, unlike get_kbars: a replay driver
    needs them before the clock gets there. Carries no prices.

    Returns
    -------
    list of datetime
        Sorted union across `symbols`. Empty if the request failed.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    from datetime import datetime
    res = self._get(f"api/v1/clock/timeline?symbols={','.join(symbols)}"
                    f"&start={start}&end={end}&interval={interval}")
    if res and res.get("ok"):
        return [datetime.fromisoformat(t) for t in res.get("result", [])]
    log.error("get timeline for %s failed: %s", symbols,
              res.get('error') if res else 'no resp')
    return []

get_system_time(**kwargs)

Deprecated alias for get_market_time().

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
168
169
170
def get_system_time(self, **kwargs) -> dict:
    """Deprecated alias for get_market_time()."""
    return self.get_market_time(**kwargs)

is_market_open(**kwargs)

Return whether the server's market time is on a weekday, 09:00-13:30.

Returns:

Type Description
bool
Warnings

Sends an HTTP request. Ignores holidays. Raises TypeError if the clock request fails, because get_market_time() then returns None.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def is_market_open(self, **kwargs) -> bool:
    """Return whether the server's market time is on a weekday, 09:00-13:30.

    Returns
    -------
    bool

    Warnings
    --------
    Sends an HTTP request. Ignores holidays. Raises TypeError if the clock
    request fails, because get_market_time() then returns None.
    """
    # mock_current_time is an ISO 8601 naive datetime (Asia/Taipei).
    # No timezone conversion — parse as-is.
    mct = self.get_market_time()["mock_current_time"]
    dt = datetime.fromisoformat(mct)
    return (
        dt.weekday() < 5 and
        dt_time(9, 0) <= dt.time() <= dt_time(13, 30)
    )

get_config(**kwargs)

Return the server configuration (GET api/v1/config).

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
193
194
195
196
197
198
199
200
def get_config(self, **kwargs):
    """Return the server configuration (GET api/v1/config).

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    return self._get("api/v1/config")

start_backend(**kwargs)

Start the server backend (PUT api/v1/backend).

Warnings

Sends an HTTP request that changes server state.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
202
203
204
205
206
207
208
209
210
def start_backend(self, **kwargs):
    """Start the server backend (PUT api/v1/backend).

    Warnings
    --------
    Sends an HTTP request that changes server state.
    """
    return self._put("api/v1/backend", {"running": True},
                     headers=kwargs.get("headers"))

stop_backend(**kwargs)

Stop the server backend (PUT api/v1/backend).

Warnings

Sends an HTTP request that changes server state.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
212
213
214
215
216
217
218
219
220
def stop_backend(self, **kwargs):
    """Stop the server backend (PUT api/v1/backend).

    Warnings
    --------
    Sends an HTTP request that changes server state.
    """
    return self._put("api/v1/backend", {"running": False},
                     headers=kwargs.get("headers"))

pause_time_progress(**kwargs)

Freeze the server market clock.

Warnings

Sends an HTTP request that changes server state.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
222
223
224
225
226
227
228
229
230
def pause_time_progress(self, **kwargs):
    """Freeze the server market clock.

    Warnings
    --------
    Sends an HTTP request that changes server state.
    """
    return self._patch("api/v1/clock", {"paused": True},
                       headers=kwargs.get("headers"))

resume_time_progress(**kwargs)

Resume the server market clock.

Warnings

Sends an HTTP request that changes server state.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
232
233
234
235
236
237
238
239
240
def resume_time_progress(self, **kwargs):
    """Resume the server market clock.

    Warnings
    --------
    Sends an HTTP request that changes server state.
    """
    return self._patch("api/v1/clock", {"paused": False},
                       headers=kwargs.get("headers"))

set_timeline_origin(mock_init_time, real_init_time=None, auto_start_progress=True, auto_preload_data=True, **kwargs)

Set where the simulated timeline BEGINS — not the current moment.

Snaps to 09:00 server-side and, unless both flags are turned off, also starts the clock and clears + refetches the price cache. To move the current moment within an existing timeline, use set_market_time().

Parameters:

Name Type Description Default
mock_init_time str

Start of the simulated timeline.

required
real_init_time str

Ignored; it is not sent to the server.

None
auto_start_progress bool

Start the clock after setting the origin.

True
auto_preload_data bool

Clear and refetch the price cache.

True
Warnings

Sends an HTTP request that resets the server clock and may clear its price cache.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def set_timeline_origin(self, mock_init_time: str, real_init_time: str = None, auto_start_progress: bool = True, auto_preload_data: bool = True, **kwargs):
    """Set where the simulated timeline BEGINS — not the current moment.

    Snaps to 09:00 server-side and, unless both flags are turned off, also
    starts the clock and clears + refetches the price cache. To move the
    current moment within an existing timeline, use set_market_time().

    Parameters
    ----------
    mock_init_time : str
        Start of the simulated timeline.
    real_init_time : str, optional
        Ignored; it is not sent to the server.
    auto_start_progress : bool, optional
        Start the clock after setting the origin.
    auto_preload_data : bool, optional
        Clear and refetch the price cache.

    Warnings
    --------
    Sends an HTTP request that resets the server clock and may clear its price cache.
    """
    data = {
        "mock_init_time": mock_init_time,
        # "real_init_time": real_init_time,
        "auto_start_progress": auto_start_progress,
        "auto_preload_data": auto_preload_data,
    }
    return self._put("api/v1/clock/origin", data, headers=kwargs.get("headers"))

set_system_time(*args, **kwargs)

Deprecated alias for set_timeline_origin().

The old name read as the setter-partner of get_system_time(), which it never was: that one reads the current moment, this one writes the timeline's start.

Warnings

Sends an HTTP request that changes server state.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
272
273
274
275
276
277
278
279
280
281
282
283
def set_system_time(self, *args, **kwargs):
    """Deprecated alias for set_timeline_origin().

    The old name read as the setter-partner of get_system_time(), which it
    never was: that one reads the current moment, this one writes the
    timeline's start.

    Warnings
    --------
    Sends an HTTP request that changes server state.
    """
    return self.set_timeline_origin(*args, **kwargs)

set_market_time(t, **kwargs)

Step the server's frozen clock to t. Repeatable and idempotent.

Unlike set_timeline_origin(), this neither snaps to 09:00 nor touches the preloaded data, so it is safe to call once per replayed bar.

Parameters:

Name Type Description Default
t datetime or str

New market time; datetimes are sent as ISO 8601.

required
Warnings

Sends an HTTP request that changes the server clock.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def set_market_time(self, t, **kwargs):
    """Step the server's frozen clock to `t`. Repeatable and idempotent.

    Unlike set_timeline_origin(), this neither snaps to 09:00 nor touches
    the preloaded data, so it is safe to call once per replayed bar.

    Parameters
    ----------
    t : datetime or str
        New market time; datetimes are sent as ISO 8601.

    Warnings
    --------
    Sends an HTTP request that changes the server clock.
    """
    iso = t.isoformat() if hasattr(t, "isoformat") else str(t)
    return self._patch("api/v1/clock", {"mock_current_time": iso},
                       headers=kwargs.get("headers"))

shift_market_time(hours, **kwargs)

Move the server clock by hours, keeping it paused or running as it was.

Returns:

Type Description
str or None

The new market time, ISO 8601; None if the server did not answer.

Warnings

Sends two HTTP requests and changes the server clock.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def shift_market_time(self, hours: float, **kwargs):
    """Move the server clock by `hours`, keeping it paused or running as it was.

    Returns
    -------
    str or None
        The new market time, ISO 8601; None if the server did not answer.

    Warnings
    --------
    Sends two HTTP requests and changes the server clock.
    """
    from datetime import datetime
    from datetime import timedelta
    now = self.get_market_time()
    if not now:
        return None
    target = datetime.fromisoformat(now["mock_current_time"]) + timedelta(hours=hours)
    res = self._patch("api/v1/clock", {"mock_current_time": target.isoformat(),
                                       "paused": bool(now.get("paused"))},
                      headers=kwargs.get("headers"))
    return (res or {}).get("mock_current_time")

get_price_from_exchange(symbol, **kwargs)

Latest price for symbol, as a Snapshot dict.

Used to have its own GET /control/get-price, which duplicated the snapshot route and answered with str(Snapshot) -- a Python repr, not JSON. Same data, one endpoint.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
327
328
329
330
331
332
333
334
335
336
337
338
def get_price_from_exchange(self, symbol: str, **kwargs):
    """Latest price for `symbol`, as a Snapshot dict.

    Used to have its own GET /control/get-price, which duplicated the
    snapshot route and answered with str(Snapshot) -- a Python repr, not
    JSON. Same data, one endpoint.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    return self.snapshot(symbol, **kwargs)

login(api_key, **kwargs)

Open a session on the server with an API key.

Parameters:

Name Type Description Default
api_key str
required

Returns:

Type Description
bool

Always True; failure raises.

Raises:

Type Description
ValueError

The server did not answer or did not confirm the login.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def login(self, api_key: str, **kwargs) -> bool:
    """Open a session on the server with an API key.

    Parameters
    ----------
    api_key : str

    Returns
    -------
    bool
        Always True; failure raises.

    Raises
    ------
    ValueError
        The server did not answer or did not confirm the login.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    data = {"api_key": api_key}
    response = self._post("api/v1/session", data, headers=kwargs.get("headers"))
    if response and response.get("ok") and response.get("message") == "Login successful":
        return True
    else:
        msg = None if response is None else response.get("message")
        raise ValueError(f"Login failed: {msg}")

logout(**kwargs)

Close the server session (DELETE api/v1/session).

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
369
370
371
372
373
374
375
376
def logout(self, **kwargs):
    """Close the server session (DELETE api/v1/session).

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    return self._delete("api/v1/session", headers=kwargs.get("headers"))

account_summary(**kwargs)

Balance, positions and orders from one read.

Returns:

Type Description
dict or None

Keys balance, positions, orders; None if the request failed.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
def account_summary(self, **kwargs) -> dict:
    """Balance, positions and orders from one read.

    Returns
    -------
    dict or None
        Keys ``balance``, ``positions``, ``orders``; None if the request failed.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    summary = self._get("api/v1/account")
    if summary is None:
        return None
    else:
        res = {}
        res['balance'] = summary.get("balance")
        res['positions'] = summary.get("positions", [])
        res['orders'] = summary.get("orders", [])
        return res

list_orders(**kwargs)

Just the orders.

Cheaper than account_summary when that is all you want -- it skips rebuilding and re-pricing every position.

Returns:

Type Description
list

Order dicts; empty if the request failed.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def list_orders(self, **kwargs) -> list:
    """Just the orders.

    Cheaper than account_summary when that is all you
    want -- it skips rebuilding and re-pricing every position.

    Returns
    -------
    list
        Order dicts; empty if the request failed.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    res = self._get("api/v1/orders")
    if res and res.get("ok"):
        return res.get("orders", [])
    return []

get_backtest_state(session_id=None, **kwargs)

Fetch raw backtest data from the server.

Returns a dict with keys: initial_balance, final_balance, fill_history. equity_curve is NOT fetched from the server; the client (the CJTrade app) records it locally during the backtest run.

Parameters:

Name Type Description Default
session_id str

If provided, fill_history is filtered to only include entries that match this session_id. This allows clean isolation when the server has been running across multiple backtest sessions or manual operations.

None

Returns:

Type Description
dict or None

None if the request failed.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def get_backtest_state(self, session_id: str = None, **kwargs) -> dict:
    """Fetch raw backtest data from the server.

    Returns a dict with keys: initial_balance, final_balance, fill_history.
    equity_curve is NOT fetched from the server; the client (the CJTrade app)
    records it locally during the backtest run.

    Parameters
    ----------
    session_id : str, optional
        If provided, fill_history is filtered to only include
        entries that match this session_id.  This allows clean
        isolation when the server has been running across multiple
        backtest sessions or manual operations.

    Returns
    -------
    dict or None
        None if the request failed.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    # Ask the server to filter. fill_history only grows, so filtering here
    # meant downloading every other run's fills in order to throw them
    # away -- and this gets polled during a run.
    path = "api/v1/account/fills"
    if session_id is not None:
        path += f"?session_id={session_id}"
    res = self._get(path)
    if res and res.get("ok"):
        fill_history = res.get("fill_history", [])
        # Filtered again, deliberately. A server that predates the query
        # parameter ignores it and answers with everything, and silently
        # reporting another run's trades as this one's is worse than the
        # wasted bytes. Filtering an already-filtered list costs nothing.
        if session_id is not None:
            fill_history = [
                f for f in fill_history
                if f.get("session_id") == session_id
            ]
        return {
            "initial_balance": res.get("initial_balance", 0.0),
            "final_balance": res.get("final_balance", 0.0),
            "fill_history": fill_history,
        }
    return None

snapshot(symbol, **kwargs)

Return the latest Snapshot for symbol as a dict.

Returns:

Type Description
dict or None

None if the request failed.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def snapshot(self, symbol: str, **kwargs) -> dict:
    """Return the latest Snapshot for `symbol` as a dict.

    Returns
    -------
    dict or None
        None if the request failed.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    res = self._get(f"api/v1/market/{symbol}/snapshot")
    if res and res.get("ok"):
        return res.get("price")  # return Snapshot object
    else:
        log.error("get snapshot %s failed: %s", symbol, res.get('error') if res else 'no resp')
        return None

get_kbars(symbol, start, end, interval='1m', fallback=False)

Fetch historical kbars from the ArenaX server.

Parameters:

Name Type Description Default
symbol str

e.g. '2330'

required
start str

ISO date or datetime string, e.g. '2024-01-02'

required
end str

ISO date or datetime string, e.g. '2024-06-30'

required
interval str

e.g. '1m', '5m', '1d'

'1m'
fallback bool

Deprecated, ignored – the server now selects the data source automatically (price_db → real broker → yfinance).

False

Returns:

Type Description
list[dict]

Raw dicts with keys: timestamp, open, high, low, close, volume. Empty if the request failed.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def get_kbars(self, symbol: str, start: str, end: str,
              interval: str = "1m", fallback: bool = False) -> list:
    """Fetch historical kbars from the ArenaX server.

    Parameters
    ----------
    symbol : str
        e.g. '2330'
    start : str
        ISO date or datetime string, e.g. '2024-01-02'
    end : str
        ISO date or datetime string, e.g. '2024-06-30'
    interval : str, optional
        e.g. '1m', '5m', '1d'
    fallback : bool, optional
        Deprecated, ignored – the server now selects the data
        source automatically (price_db → real broker → yfinance).

    Returns
    -------
    list[dict]
        Raw dicts with keys: timestamp, open, high, low, close, volume.
        Empty if the request failed.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    res = self._get(
        f"api/v1/market/{symbol}/kbars?start={start}&end={end}&interval={interval}"
    )

    if res and res.get("ok"):
        return res.get("result", [])
    err = res.get("error") if res else "No response"
    log.error("get kbars %s failed: %s", symbol, err)
    return []

data_availability(**kwargs)

Which date range the real broker can serve, when one is attached.

Informational only. Do NOT use it to decide whether to call get_kbars: that route picks its own source (price_db -> real broker -> yfinance).

Replaces is_kbar_data_available(), which took start/end the server ignored and then read a response key the server never sent.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def data_availability(self, **kwargs) -> dict:
    """Which date range the real broker can serve, when one is attached.

    Informational only. Do NOT use it to decide whether to call get_kbars:
    that route picks its own source (price_db -> real broker -> yfinance).

    Replaces is_kbar_data_available(), which took start/end the server
    ignored and then read a response key the server never sent.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    return self._get("api/v1/market/data-availability")

place_order(order, **kwargs)

Send an order to the server (POST api/v1/orders).

Parameters:

Name Type Description Default
order Order
required

Returns:

Type Description
OrderResult

Status is UNKNOWN if the server returns an unrecognised status.

Raises:

Type Description
ConnectionError

The server did not answer.

ValueError

The server rejected the order or returned an empty result.

Warnings

Sends an HTTP request that places an order on the simulated exchange.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def place_order(self, order: Order, **kwargs) -> OrderResult:
    """Send an order to the server (POST api/v1/orders).

    Parameters
    ----------
    order : Order

    Returns
    -------
    OrderResult
        Status is UNKNOWN if the server returns an unrecognised status.

    Raises
    ------
    ConnectionError
        The server did not answer.
    ValueError
        The server rejected the order or returned an empty result.

    Warnings
    --------
    Sends an HTTP request that places an order on the simulated exchange.
    """
    # Serialize Order to JSON-serializable payload
    product = {
        "symbol": getattr(order.product, 'symbol', None),
        "exchange": getattr(order.product, 'exchange', None),
        "type": getattr(order.product, 'type', None).value if hasattr(getattr(order.product, 'type', None), 'value') else getattr(order.product, 'type', None),
    }

    data = {
        "product": product,
        "action": order.action.value if hasattr(order.action, 'value') else order.action,
        "price": float(order.price),
        "quantity": int(order.quantity),
        "price_type": order.price_type.value if hasattr(order.price_type, 'value') else order.price_type,
        "order_type": order.order_type.value if hasattr(order.order_type, 'value') else order.order_type,
        "order_lot": order.order_lot.value if hasattr(order.order_lot, 'value') else order.order_lot,
        "created_at": order.created_at.isoformat() if hasattr(order, 'created_at') else None,
        "id": order.id,
        "opt_field": order.opt_field,
    }

    res = self._post("api/v1/orders", data, headers=kwargs.get("headers"))

    if res is None:
        raise ConnectionError("No response from ArenaX broker-side server")
    if not res.get("ok", False):
        raise ValueError(f"Place order failed: {res.get('error')}")

    result = res.get("result")
    if result is None:
        raise ValueError("Unexpected empty result from broker server")

    # Map server result dict to local OrderResult dataclass
    status = result.get("status")
    try:
        status_enum = OrderStatus(status) if status is not None else OrderStatus.UNKNOWN
    except Exception:
        status_enum = OrderStatus.UNKNOWN

    order_result = OrderResult(
        status=status_enum,
        message=result.get("message", ""),
        metadata=result.get("metadata", {}),
        linked_order=result.get("linked_order", ""),
        id=result.get("id", result.get("order_id", order.id)),
    )
    return order_result

cancel_order(order_id, **kwargs)

Cancel an order on the server (DELETE api/v1/orders/{order_id}).

Parameters:

Name Type Description Default
order_id str
required

Returns:

Type Description
OrderResult

Status is UNKNOWN if the server returns an unrecognised status.

Raises:

Type Description
ConnectionError

The server did not answer.

Warnings

Sends an HTTP request that cancels an order on the simulated exchange.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def cancel_order(self, order_id: str, **kwargs) -> OrderResult:
    """Cancel an order on the server (DELETE api/v1/orders/{order_id}).

    Parameters
    ----------
    order_id : str

    Returns
    -------
    OrderResult
        Status is UNKNOWN if the server returns an unrecognised status.

    Raises
    ------
    ConnectionError
        The server did not answer.

    Warnings
    --------
    Sends an HTTP request that cancels an order on the simulated exchange.
    """
    res = self._delete(f"api/v1/orders/{order_id}", headers=kwargs.get("headers"))

    if res is None:
        raise ConnectionError("No response from ArenaX broker-side server")

    result_data = res.get("result", {})
    raw_status = result_data.get("status")
    try:
        status_enum = OrderStatus(raw_status) if raw_status is not None else OrderStatus.UNKNOWN
    except ValueError:
        status_enum = OrderStatus.UNKNOWN

    return OrderResult(
        linked_order=result_data.get("linked_order"),
        status=status_enum,
        message=result_data.get("message", ""),
        metadata=result_data.get("metadata", {}),
    )

sync_state(order_id, **kwargs)

Current status of one order, refreshed against the market.

A GET: the server re-runs the fill check and reports, it performs no transition of its own.

Parameters:

Name Type Description Default
order_id str
required

Returns:

Type Description
OrderResult or None

A single result despite the List annotation; None if the request failed or the server returned no result.

Raises:

Type Description
ValueError

The server answered with ok false.

Warnings

Sends an HTTP request to the ArenaX server.

Source code in src/cjtrade/pkgs/brokers/arenax/arenax_middleware.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
def sync_state(self, order_id: str, **kwargs) -> List[OrderResult]:
    """Current status of one order, refreshed against the market.

    A GET: the server re-runs the fill check and reports, it performs no
    transition of its own.

    Parameters
    ----------
    order_id : str

    Returns
    -------
    OrderResult or None
        A single result despite the ``List`` annotation; None if the
        request failed or the server returned no result.

    Raises
    ------
    ValueError
        The server answered with ``ok`` false.

    Warnings
    --------
    Sends an HTTP request to the ArenaX server.
    """
    res = self._get(f"api/v1/orders/{order_id}")
    if res is None:
        return None
    if not res.get("ok", False):
        raise ValueError(f"Order refresh failed: {res.get('error')}")

    r = res.get("result")
    if r is None:
        return None

    order_result = OrderResult(
        status=OrderStatus(r.get("status")) if r.get("status") in [s.value for s in OrderStatus] else OrderStatus.UNKNOWN,
        message=r.get("message", ""),
        metadata=r.get("metadata", {}),
        linked_order=r.get("linked_order", r.get("order_id", "")),
        id=r.get("id", r.get("order_id", "")),
    )
    return order_result