跳轉到

券商介面

BrokerAPIBase 是每個券商轉接層都要實作的介面。只有要新增券商時才需要它,其他情況一律透過 AccountClient。

cjtrade.pkgs.brokers.base_broker_api

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

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

An immutable tradable instrument (contract, 標的).

Attributes:

Name Type Description
symbol str

Ticker, e.g. "2330".

type ProductType

STOCK by default.

exchange Exchange

TSE by default.

category str

Category label; empty by default.

tags list of str

Free-form tags.

metadata dict

Free-form extra data.

to_dict()

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

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

OrderAction

Bases: str, Enum

Side of an order: BUY, SELL or CANCEL.

PriceType

Bases: str, Enum

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

OrderType

Bases: str, Enum

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

FOK = 'FOK' class-attribute instance-attribute

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

OrderLot

Bases: str, Enum

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

OrderStatus

Bases: str, Enum

Lifecycle status of an order.

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

A CJTrade order for one product.

Attributes:

Name Type Description
product Product

What to trade.

action OrderAction

BUY or SELL.

price float

Order price.

quantity int

Order quantity.

price_type PriceType

LMT or MKT.

order_type OrderType

Time in force, e.g. ROD.

order_lot OrderLot

Common or intraday odd lot.

id str

CJ order id; a random uuid4 hex by default.

created_at datetime

Creation time as a naive UTC+8 datetime.

broker str

Broker name, 'na' by default.

opt_field dict

Optional broker-specific fields.

Warnings

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

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

Result of an order operation reported by a broker client.

Attributes:

Name Type Description
status OrderStatus

Status after the operation.

message str

Human-readable message from the broker or engine.

metadata dict

Extra broker-specific detail.

linked_order str

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

id str

Result id; a random uuid4 hex by default.

to_dict()

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

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

Quote dataclass

Last price and volume of a symbol.

Attributes:

Name Type Description
symbol str

Ticker.

price float

Last price.

volume int

Volume.

timestamp str

Time of the quote.

Snapshot dataclass

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

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

Attributes:

Name Type Description
symbol str

Ticker.

exchange str

Exchange code, e.g. "TSE".

timestamp datetime

Time of the snapshot.

open, close, high, low float

Day prices; close is the latest price.

volume int

Volume.

average_price float

Average traded price.

action OrderAction

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

buy_price, sell_price float

Best bid and best ask.

buy_volume, sell_volume int

Volume at the best bid and best ask.

additional_note (str, optional)

Free-form note.

from_dict(d) classmethod

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

Parameters:

Name Type Description Default
d dict

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

required

Returns:

Type Description
Snapshot

Raises:

Type Description
KeyError

If a required field is missing.

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

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

    Returns
    -------
    Snapshot

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

to_dict()

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

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

BidAsk dataclass

Five-level order book of one symbol.

Attributes:

Name Type Description
symbol str

Ticker.

datetime datetime

Time of the book.

bid_price, ask_price list of float

Prices of the five bid and ask levels.

bid_volume, ask_volume list of int

Volumes of the five bid and ask levels.

to_dict()

Return the order book as a JSON-friendly dict.

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

BrokerAPIBase(**config)

Bases: ABC

A unified interface for different brokers: accounts and orders.

Market data is a separate concern (cjtrade.pkgs.marketdata). get_kbars, get_snapshots and get_bid_ask are optional here: a broker whose API only places orders leaves them unimplemented, and a broker that does serve prices also returns them from market_data().

All broker implementations must inherit from this class and implement all abstract methods.

Parameters:

Name Type Description Default
**config Any

Broker-specific settings, stored as self.config.

{}
Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
33
34
def __init__(self, **config: Any):
    self.config = config

connect() abstractmethod

Open the broker session.

Returns:

Type Description
bool

True if the connection succeeded.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
36
37
38
39
40
41
42
43
44
45
@abstractmethod
def connect(self) -> bool:
    """Open the broker session.

    Returns
    -------
    bool
        True if the connection succeeded.
    """
    pass

disconnect() abstractmethod

Close the broker session.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
47
48
49
50
@abstractmethod
def disconnect(self) -> None:
    """Close the broker session."""
    pass

is_connected() abstractmethod

Return whether the broker session is open.

Returns:

Type Description
bool
Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
52
53
54
55
56
57
58
59
60
@abstractmethod
def is_connected(self) -> bool:
    """Return whether the broker session is open.

    Returns
    -------
    bool
    """
    pass

market_data()

Return this broker's own MarketData, or None if it serves no prices.

Returns:

Type Description
MarketData or None

Shares this broker's session.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
62
63
64
65
66
67
68
69
70
def market_data(self):
    """Return this broker's own MarketData, or None if it serves no prices.

    Returns
    -------
    MarketData or None
        Shares this broker's session.
    """
    return None

get_positions() abstractmethod

Get current stock positions.

Returns:

Type Description
List[Position]
Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
72
73
74
75
76
77
78
79
80
@abstractmethod
def get_positions(self) -> List[Position]:
    """Get current stock positions.

    Returns
    -------
    List[Position]
    """
    pass

get_balance() abstractmethod

Get account balance.

Returns:

Type Description
float

Account balance.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
82
83
84
85
86
87
88
89
90
91
@abstractmethod
def get_balance(self) -> float:
    """Get account balance.

    Returns
    -------
    float
        Account balance.
    """
    pass

get_bid_ask(product, intraday_odd=False)

Return the current bid/ask quote for a product.

Parameters:

Name Type Description Default
product Product

The product to quote.

required
intraday_odd bool

Quote the intraday odd-lot book instead of the board-lot book.

False

Returns:

Type Description
BidAsk
Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def get_bid_ask(self, product: Product, intraday_odd: bool = False) -> BidAsk:
    """Return the current bid/ask quote for a product.

    Parameters
    ----------
    product : Product
        The product to quote.
    intraday_odd : bool, optional
        Quote the intraday odd-lot book instead of the board-lot book.

    Returns
    -------
    BidAsk
    """
    raise NotImplementedError(
        f"{type(self).__name__} does not serve market data; "
        "use a cjtrade.pkgs.marketdata.MarketData")

get_kbars(products, start, end, interval)

Return a list of Kbar, 1-min kbar by default.

Note that the range is [start, end), end is exclusive.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
111
112
113
114
115
116
117
118
def get_kbars(self, products: List[Product], start: str, end: str, interval: str) -> List[Kbar]:
    """Return a list of Kbar, 1-min kbar by default.

    Note that the range is [start, end), end is exclusive.
    """
    raise NotImplementedError(
        f"{type(self).__name__} does not serve market data; "
        "use a cjtrade.pkgs.marketdata.MarketData")

get_snapshots(products)

Get real-time market snapshots for given products. It must contain more detail than get_quotes()/ get_bid_ask() does. If broker's api does not provide some fields that required by Snapshot, broker must mention them in the additional_note.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
120
121
122
123
124
125
126
127
128
129
def get_snapshots(self, products: List[Product]) -> List[Snapshot]:
    """
    Get real-time market snapshots for given products.
    It must contain more detail than `get_quotes()`/ `get_bid_ask()` does.
    If broker's api does not provide some fields that required by `Snapshot`,
    broker must mention them in the `additional_note`.
    """
    raise NotImplementedError(
        f"{type(self).__name__} does not serve market data; "
        "use a cjtrade.pkgs.marketdata.MarketData")

register_price_callback()

Define what things to do when a certain price event happens.

Warnings

Placeholder: not abstract yet and does nothing.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
137
138
139
140
141
142
143
144
def register_price_callback():
    """Define what things to do when a certain price event happens.

    Warnings
    --------
    Placeholder: not abstract yet and does nothing.
    """
    pass

register_order_callback(callback) abstractmethod

Register callback for order status changes (including fills).

Callback receives OrderEvent with unified CJ abstraction layer format.

Parameters:

Name Type Description Default
callback callable

Function that takes OrderEvent as parameter.

required

Examples:

def on_order_change(event: OrderEvent):
    print(f"{event.old_status} → {event.new_status}")
    if event.is_filled():
        print(f"Filled: {event.filled_quantity} @ {event.filled_price}")
Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@abstractmethod
def register_order_callback(self, callback) -> None:
    """Register callback for order status changes (including fills).

    Callback receives OrderEvent with unified CJ abstraction layer format.

    Parameters
    ----------
    callback : callable
        Function that takes OrderEvent as parameter.

    Examples
    --------
    ```python
    def on_order_change(event: OrderEvent):
        print(f"{event.old_status} → {event.new_status}")
        if event.is_filled():
            print(f"Filled: {event.filled_quantity} @ {event.filled_price}")
    ```
    """
    pass

unregister_callback()

Unregister a previously registered callback.

Warnings

Placeholder: not abstract yet and does nothing.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
169
170
171
172
173
174
175
176
def unregister_callback():
    """Unregister a previously registered callback.

    Warnings
    --------
    Placeholder: not abstract yet and does nothing.
    """
    pass

place_order(order) abstractmethod

Submit an order to the broker.

Parameters:

Name Type Description Default
order Order

The order to place (symbol, action, quantity, price).

required

Returns:

Type Description
OrderResult
Warnings

On a live broker (Sinopac) this places a real order on a real account.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
@abstractmethod
def place_order(self, order: Order) -> OrderResult:
    """Submit an order to the broker.

    Parameters
    ----------
    order : Order
        The order to place (symbol, action, quantity, price).

    Returns
    -------
    OrderResult

    Warnings
    --------
    On a live broker (Sinopac) this places a real order on a real account.
    """
    pass

sync_state() abstractmethod

Synchronise the local order state with the broker's backend.

Replaces the old commit_order() whose name was misleading: sinopac has no staging area, so place_order() submits the order immediately. What the old method really did was call sj.update_status() to refresh the in-process order map. sync_state() makes that intent explicit.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
197
198
199
200
201
202
203
204
205
206
207
@abstractmethod
def sync_state(self) -> List[OrderResult]:
    """
    Synchronise the local order state with the broker's backend.

    Replaces the old `commit_order()` whose name was misleading: sinopac has
    no staging area, so `place_order()` submits the order immediately.  What
    the old method really did was call `sj.update_status()` to refresh the
    in-process order map.  `sync_state()` makes that intent explicit.
    """
    pass

cancel_order(order_id) abstractmethod

Cancel an order.

Parameters:

Name Type Description Default
order_id str

The CJTrade order id.

required

Returns:

Type Description
OrderResult
Warnings

On a live broker (Sinopac) this cancels a real order on a real account.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
@abstractmethod
def cancel_order(self, order_id: str) -> OrderResult:
    """Cancel an order.

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

    Returns
    -------
    OrderResult

    Warnings
    --------
    On a live broker (Sinopac) this cancels a real order on a real account.
    """
    pass

list_orders() abstractmethod

Return the account's orders.

Returns:

Type Description
List[Trade]
Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
228
229
230
231
232
233
234
235
236
@abstractmethod
def list_orders(self) -> List[Trade]:
    """Return the account's orders.

    Returns
    -------
    List[Trade]
    """
    pass

is_market_open() abstractmethod

Return whether the market is open at the broker's market time.

Returns:

Type Description
bool
Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
238
239
240
241
242
243
244
245
246
@abstractmethod
def is_market_open(self) -> bool:
    """Return whether the market is open at the broker's market time.

    Returns
    -------
    bool
    """
    pass

get_market_time()

What time it is on the market right now. Every broker answers this.

This is the canonical name. "Market time" is the question callers actually have -- in a replay it is simulated time, live it is the wall clock -- and it matches ArenaX_Market.get_market_time() on the server side, so the same words mean the same thing at both ends.

Required keys: mock_current_time market time now real_current_time the broker host's wall clock, for diagnostics mock_init_time where the simulated timeline starts real_init_time wall clock when that timeline was anchored

Simulated brokers must also report how their clock is running, so a caller can pace itself without reaching into broker internals: playback_speed float market seconds per real second (1.0 = live) paused bool True when the clock is frozen

A live broker reports mock == real, playback_speed=1.0 and paused=False: real time is the degenerate case of the same contract, so callers never branch on the broker name.

Note there is deliberately no "system time" concept: the broker host's clock is just the real_* fields above, and a caller wanting its own machine's clock should call datetime.now() rather than ask the broker -- the two are different machines in general.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
248
249
250
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
def get_market_time(self) -> dict:
    """What time it is **on the market** right now. Every broker answers this.

    This is the canonical name. "Market time" is the question callers
    actually have -- in a replay it is simulated time, live it is the wall
    clock -- and it matches ArenaX_Market.get_market_time() on the server
    side, so the same words mean the same thing at both ends.

    Required keys:
        mock_current_time   market time now
        real_current_time   the broker host's wall clock, for diagnostics
        mock_init_time      where the simulated timeline starts
        real_init_time      wall clock when that timeline was anchored

    Simulated brokers must also report how their clock is running, so a
    caller can pace itself without reaching into broker internals:
        playback_speed  float  market seconds per real second (1.0 = live)
        paused          bool   True when the clock is frozen

    A live broker reports mock == real, playback_speed=1.0 and paused=False:
    real time is the degenerate case of the same contract, so callers never
    branch on the broker name.

    Note there is deliberately no "system time" concept: the broker host's
    clock is just the real_* fields above, and a caller wanting its own
    machine's clock should call datetime.now() rather than ask the broker --
    the two are different machines in general.
    """
    raise NotImplementedError(
        f"{type(self).__name__} does not implement get_market_time()"
    )

get_system_time()

Deprecated alias for get_market_time(). Prefer get_market_time().

Kept because "system time" was the original name here, but it reads as the setter-partner of set_timeline_origin() -- which writes the timeline origin, not the current moment -- and that false pairing is what made the two easy to confuse.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
280
281
282
283
284
285
286
287
288
def get_system_time(self) -> dict:
    """Deprecated alias for get_market_time(). Prefer get_market_time().

    Kept because "system time" was the original name here, but it reads as
    the setter-partner of set_timeline_origin() -- which writes the timeline
    origin, not the current moment -- and that false pairing is what made
    the two easy to confuse.
    """
    return self.get_market_time()

get_broker_name() abstractmethod

Return a short name identifying the broker.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
290
291
292
293
@abstractmethod
def get_broker_name(self) -> str:
    """Return a short name identifying the broker."""
    pass

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

Place a buy order for a stock.

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

On a live broker (Sinopac) this places a real order on a real account.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
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
@abstractmethod
def buy_stock(self, symbol: str, quantity: int, price: float, intraday_odd: bool = True,
              opt_field: dict = None) -> OrderResult:
    """Place a buy order for a stock.

    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
    --------
    On a live broker (Sinopac) this places a real order on a real account.
    """
    pass

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

Place a sell order for a stock.

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

On a live broker (Sinopac) this places a real order on a real account.

Source code in src/cjtrade/pkgs/brokers/base_broker_api.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
@abstractmethod
def sell_stock(self, symbol: str, quantity: int, price: float, intraday_odd: bool = True,
               opt_field: dict = None) -> OrderResult:
    """Place a sell order for a stock.

    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
    --------
    On a live broker (Sinopac) this places a real order on a real account.
    """
    pass