跳轉到

AccountClient

使用者唯一需要面對的券商 API。同一組呼叫可以用在 ArenaX 和永豐,用 BrokerType 選擇券商。

Danger

使用 BrokerType.SINOPAC 且 simulation=False 時,下單相關的方法會作用在真實帳戶上。

cjtrade.pkgs.brokers.account_client.AccountClient(broker_type, market=None, **config)

One account at one broker: balance, positions and orders.

Prices are a separate concern. client.market is the MarketData to read them from: the one passed as market, or else the broker's own (Sinopac and ArenaX serve prices; a broker that only takes orders does not, and then market is required for anything price-related).

Parameters:

Name Type Description Default
broker_type BrokerType

Which broker implementation to use.

required
market MarketData

Where prices come from. Defaults to the broker's own market data.

None
**config

Passed unchanged to the broker API constructor.

{}

Raises:

Type Description
ImportError

BrokerType.SINOPAC is chosen but the sinopac extra is not installed.

NotImplementedError

BrokerType.YUANTA or BrokerType.CATHAY is chosen.

ValueError

The broker type is not supported.

Source code in src/cjtrade/pkgs/brokers/account_client.py
83
84
85
86
87
88
def __init__(self, broker_type: BrokerType, market=None, **config):
    self.broker_type = broker_type
    self.broker_api = self._set_broker_api(broker_type, **config)
    self._market = market
    self.account_state = AccountState()
    self.broker_api_conn_keepalive = True  # For future use

market property

The MarketData prices come from, or None if there is none.

Returns:

Type Description
MarketData or None

The one given to the constructor, else the broker's own.

playback_speed property

Market seconds per real second. 1.0 for any live broker.

Use this to scale your own waiting, e.g. sleep(seconds / speed), rather than configuring the speed separately on both sides: the broker is the authority on how fast its own clock runs, so asking it is the only way the two cannot disagree.

Warnings

Calls get_market_time() each time; on ArenaX that is a network call.

control_plane property

Broker-server control plane, or None when there is nothing to control.

Not named simulation: that word is already taken in this codebase for Shioaji's sandbox flag (SIMULATION=y -> SinopacBrokerAPI.simulation), and the two are unrelated — a sinopac sandbox account is still a live broker with no clock to steer.

Deliberately NOT part of BrokerAPIBase either: freezing a clock, stepping a replay or restarting a backend are things only a simulated exchange can do, and declaring them there would force every adapter (yuanta, cathay, IBKR) to implement methods that have no meaning for a real broker.

It lives here so callers never reach through client.broker_api.middleware. Against a real broker it is None, which is an explicit check rather than an AttributeError two layers down.

Example::

if client.control_plane:
    client.control_plane.resume_time_progress()

current_broker_type property

The BrokerType this client was created with.

connect()

Connect to the broker. Call this before any other method.

Returns:

Type Description
bool

True if the connection succeeded.

Warnings

Makes a network call to the broker.

Source code in src/cjtrade/pkgs/brokers/account_client.py
141
142
143
144
145
146
147
148
149
150
151
152
153
def connect(self) -> bool:
    """Connect to the broker. Call this before any other method.

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

    Warnings
    --------
    Makes a network call to the broker.
    """
    return self.broker_api.connect()

disconnect()

Disconnect from the broker.

Warnings

Makes a network call to the broker.

Source code in src/cjtrade/pkgs/brokers/account_client.py
155
156
157
158
159
160
161
162
def disconnect(self) -> None:
    """Disconnect from the broker.

    Warnings
    --------
    Makes a network call to the broker.
    """
    self.broker_api.disconnect()

is_connected()

Return whether the broker session is open.

Returns:

Type Description
bool
Source code in src/cjtrade/pkgs/brokers/account_client.py
164
165
166
167
168
169
170
171
def is_connected(self) -> bool:
    """Return whether the broker session is open.

    Returns
    -------
    bool
    """
    return self.broker_api.is_connected()

get_positions()

Sync with the broker and return current positions.

Returns:

Type Description
List[Position]
Warnings

Runs a full sync (network calls for balance and positions) on every call. If not connected, it prints a message and returns the cached value.

Source code in src/cjtrade/pkgs/brokers/account_client.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def get_positions(self) -> List[Position]:
    """Sync with the broker and return current positions.

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

    Warnings
    --------
    Runs a full sync (network calls for balance and positions) on every call.
    If not connected, it prints a message and returns the cached value.
    """
    self._sync_all()  # will sync `account_state`
    return self.account_state.positions

get_balance()

Sync with the broker and return the account balance.

Returns:

Type Description
float
Warnings

Runs a full sync (network calls for balance and positions) on every call. If not connected, it prints a message and returns the cached value.

Source code in src/cjtrade/pkgs/brokers/account_client.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def get_balance(self) -> float:
    """Sync with the broker and return the account balance.

    Returns
    -------
    float

    Warnings
    --------
    Runs a full sync (network calls for balance and positions) on every call.
    If not connected, it prints a message and returns the cached value.
    """
    self._sync_all()  # will sync `account_state`
    return self.account_state.balance

get_account_state()

Balance and positions from a single sync.

get_balance() and get_positions() each run a full _sync_all(), so asking for both costs two syncs and returns two views of the account taken a round-trip apart. A caller that needs them together -- anything reporting "here is your new balance and your new position" -- wants one consistent read, not two.

Warnings

Makes network calls to the broker. If not connected, it prints a message and returns the cached state.

Source code in src/cjtrade/pkgs/brokers/account_client.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def get_account_state(self) -> AccountState:
    """Balance and positions from a single sync.

    get_balance() and get_positions() each run a full `_sync_all()`, so
    asking for both costs two syncs and returns two views of the account
    taken a round-trip apart. A caller that needs them together -- anything
    reporting "here is your new balance and your new position" -- wants one
    consistent read, not two.

    Warnings
    --------
    Makes network calls to the broker. If not connected, it prints a
    message and returns the cached state.
    """
    self._sync_all()  # will sync `account_state`
    return self.account_state

get_bid_ask(product, intraday_odd=False)

Return the current bid/ask quote for a product.

Prefer client.market; this stays for existing callers. With a market passed to the constructor it reads from that, otherwise from the broker as before.

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 or None

Sinopac returns None if no quote arrives within 5 seconds.

Warnings

Makes a network call. On ArenaX the levels are simulated around the last close with random volumes, not real quotes.

Source code in src/cjtrade/pkgs/brokers/account_client.py
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
def get_bid_ask(self, product: Product, intraday_odd: bool = False) -> Dict[str, float]:
    """Return the current bid/ask quote for a product.

    Prefer ``client.market``; this stays for existing callers. With a
    `market` passed to the constructor it reads from that, otherwise from
    the broker as before.

    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 or None
        Sinopac returns None if no quote arrives within 5 seconds.

    Warnings
    --------
    Makes a network call. On ArenaX the levels are simulated around the
    last close with random volumes, not real quotes.
    """
    market = self._explicit_market()
    if market is not None:
        return market.get_bid_ask(product.symbol, intraday_odd)
    return self.broker_api.get_bid_ask(product, intraday_odd)

get_snapshots(products)

Return market snapshots for the given products.

Prefer client.market; this stays for existing callers. With a market passed to the constructor it reads from that, otherwise from the broker as before.

Parameters:

Name Type Description Default
products List[Product]
required

Returns:

Type Description
List[Snapshot]
Warnings

Makes a network call to the broker.

Source code in src/cjtrade/pkgs/brokers/account_client.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def get_snapshots(self, products: List[Product]) -> List[Snapshot]:
    """Return market snapshots for the given products.

    Prefer ``client.market``; this stays for existing callers. With a
    `market` passed to the constructor it reads from that, otherwise from
    the broker as before.

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

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

    Warnings
    --------
    Makes a network call to the broker.
    """
    market = self._explicit_market()
    if market is not None:
        return market.get_snapshots([p.symbol for p in products])
    return self.broker_api.get_snapshots(products)

register_order_callback(callback)

Register callback for order status changes (including fills).

Parameters:

Name Type Description Default
callback OrderCallback

Function(OrderEvent) -> None.

required

Examples:

def on_order_change(event: OrderEvent):
    print(f"{event.old_status} → {event.new_status}")
    if event.is_filled():
        # Handle fill
        update_position(event.symbol, event.filled_quantity)
Warnings

ArenaX raises NotImplementedError; poll sync_state() or list_orders() there.

Source code in src/cjtrade/pkgs/brokers/account_client.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def register_order_callback(self, callback: OrderCallback) -> None:
    """Register callback for order status changes (including fills).

    Parameters
    ----------
    callback : OrderCallback
        Function(OrderEvent) -> None.

    Examples
    --------
    ```python
    def on_order_change(event: OrderEvent):
        print(f"{event.old_status} → {event.new_status}")
        if event.is_filled():
            # Handle fill
            update_position(event.symbol, event.filled_quantity)
    ```

    Warnings
    --------
    ArenaX raises NotImplementedError; poll sync_state() or list_orders() there.
    """
    return self.broker_api.register_order_callback(callback)

get_kbars(product, start, end, interval)

Return kbars for a product over [start, end); end is exclusive.

Prefer client.market; this stays for existing callers. With a market passed to the constructor it reads from that, otherwise from the broker as before.

Parameters:

Name Type Description Default
product Product

The product to fetch.

required
start str

Start date.

required
end str

End date, exclusive.

required
interval str

One of '1m', '3m', '5m', '10m', '15m', '20m', '30m', '45m', '1h', '90m', '2h', '1d', '1w', '1M'. Support depends on the broker.

required

Returns:

Type Description
List[Kbar]
Warnings

Makes a network call to the broker.

Source code in src/cjtrade/pkgs/brokers/account_client.py
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
def get_kbars(self, product: Product, start: str, end: str, interval: str):
    """Return kbars for a product over [start, end); end is exclusive.

    Prefer ``client.market``; this stays for existing callers. With a
    `market` passed to the constructor it reads from that, otherwise from
    the broker as before.

    Parameters
    ----------
    product : Product
        The product to fetch.
    start : str
        Start date.
    end : str
        End date, exclusive.
    interval : str
        One of '1m', '3m', '5m', '10m', '15m', '20m', '30m', '45m',
        '1h', '90m', '2h', '1d', '1w', '1M'. Support depends on the broker.

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

    Warnings
    --------
    Makes a network call to the broker.
    """
    # note that the range is [start,end), end is exclusive.
    # TODO: test each interval aggregation stability (especially edge cases)
    # interval: '1m', '3m', '5m', '10m', '15m', '20m', '30m', '45m',
    #           '1h', '90m', '2h', '1d', '1w', '1M'
    market = self._explicit_market()
    if market is not None:
        return market.get_kbars(product.symbol, start, end, interval)
    return self.broker_api.get_kbars(product, start, end, interval)

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

Return the top movers ranked by by.

Parameters:

Name Type Description Default
top_n int

Number of products to return.

10
by RankType

Ranking criterion.

PRICE_PERCENTAGE_CHANGE
ascending bool

Sort order.

True

Returns:

Type Description
dict or None

Sinopac maps product name to Snapshot; ArenaX returns None.

Warnings

Makes a network call. Not implemented on ArenaX.

Source code in src/cjtrade/pkgs/brokers/account_client.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def get_market_movers(self, top_n: int = 10, by: RankType = RankType.PRICE_PERCENTAGE_CHANGE, ascending: bool = True) -> Dict[str, float]:
    """Return the top movers ranked by `by`.

    Parameters
    ----------
    top_n : int, optional
        Number of products to return.
    by : RankType, optional
        Ranking criterion.
    ascending : bool, optional
        Sort order.

    Returns
    -------
    dict or None
        Sinopac maps product name to Snapshot; ArenaX returns None.

    Warnings
    --------
    Makes a network call. Not implemented on ArenaX.
    """
    return self.broker_api.get_market_movers(top_n, by, ascending)

place_order(order)

Place an order.

Parameters:

Name Type Description Default
order Order
required

Returns:

Type Description
OrderResult
Warnings

With BrokerType.SINOPAC this places a REAL order on a real account.

Source code in src/cjtrade/pkgs/brokers/account_client.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def place_order(self, order: Order) -> OrderResult:
    """Place an order.

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

    Returns
    -------
    OrderResult

    Warnings
    --------
    With BrokerType.SINOPAC this places a REAL order on a real account.
    """
    return self.broker_api.place_order(order)

sync_state()

Refresh order status from the broker.

Returns:

Type Description
List[OrderResult]
Warnings

Makes network calls. ArenaX and Sinopac write order status to the local mirror database.

Source code in src/cjtrade/pkgs/brokers/account_client.py
373
374
375
376
377
378
379
380
381
382
383
384
385
def sync_state(self) -> List[OrderResult]:
    """Refresh order status from the broker.

    Returns
    -------
    List[OrderResult]

    Warnings
    --------
    Makes network calls. ArenaX and Sinopac write order status to the local
    mirror database.
    """
    return self.broker_api.sync_state()

cancel_order(order_id)

Cancel an order.

Parameters:

Name Type Description Default
order_id str

The CJTrade order id.

required

Returns:

Type Description
OrderResult
Warnings

With BrokerType.SINOPAC this cancels a REAL order on a real account.

Source code in src/cjtrade/pkgs/brokers/account_client.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def cancel_order(self, order_id: str) -> OrderResult:
    """Cancel an order.

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

    Returns
    -------
    OrderResult

    Warnings
    --------
    With BrokerType.SINOPAC this cancels a REAL order on a real account.
    """
    return self.broker_api.cancel_order(order_id)

list_orders()

Return the account's orders.

Returns:

Type Description
List[Trade]
Warnings

Makes a network call to the broker.

Source code in src/cjtrade/pkgs/brokers/account_client.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def list_orders(self) -> List[Trade]:
    """Return the account's orders.

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

    Warnings
    --------
    Makes a network call to the broker.
    """
    # Trade, not Dict: both implementations (arenax, sinopac) already return
    # Trade objects, and the annotation saying otherwise is what pushes
    # callers into subscripting them.
    return self.broker_api.list_orders()

is_market_open()

Return whether the market is open.

Returns:

Type Description
bool
Warnings

Sinopac checks the local wall clock; ArenaX checks the server's market time. Both use weekdays 09:00-13:30 only and ignore holidays.

Source code in src/cjtrade/pkgs/brokers/account_client.py
421
422
423
424
425
426
427
428
429
430
431
432
433
def is_market_open(self) -> bool:
    """Return whether the market is open.

    Returns
    -------
    bool

    Warnings
    --------
    Sinopac checks the local wall clock; ArenaX checks the server's market
    time. Both use weekdays 09:00-13:30 only and ignore holidays.
    """
    return self.broker_api.is_market_open()

get_market_time()

What time it is on the market now. Same keys for every broker.

See BrokerAPIBase.get_market_time for the key list. Includes playback_speed and paused, so a caller can pace itself against a simulated clock without knowing which broker it is talking to; a live broker reports 1.0 / False.

Warnings

Result depends on the current time. ArenaX makes a network call.

Source code in src/cjtrade/pkgs/brokers/account_client.py
435
436
437
438
439
440
441
442
443
444
445
446
447
def get_market_time(self) -> dict:
    """What time it is on the market now. Same keys for every broker.

    See BrokerAPIBase.get_market_time for the key list. Includes
    playback_speed and paused, so a caller can pace itself against a
    simulated clock without knowing which broker it is talking to; a live
    broker reports 1.0 / False.

    Warnings
    --------
    Result depends on the current time. ArenaX makes a network call.
    """
    return self.broker_api.get_market_time()

get_system_time()

Deprecated alias for get_market_time().

Source code in src/cjtrade/pkgs/brokers/account_client.py
449
450
451
def get_system_time(self) -> dict:
    """Deprecated alias for get_market_time()."""
    return self.get_market_time()

get_broker_name()

Return a short name identifying the broker.

Source code in src/cjtrade/pkgs/brokers/account_client.py
493
494
495
def get_broker_name(self) -> str:
    """Return a short name identifying the broker."""
    return self.broker_api.get_broker_name()

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

Place a limit 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

With BrokerType.SINOPAC this places a REAL order on a real account.

Source code in src/cjtrade/pkgs/brokers/account_client.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
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.

    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
    --------
    With BrokerType.SINOPAC this places a REAL order on a real account.
    """
    return self.broker_api.buy_stock(symbol, quantity, price, intraday_odd, opt_field=opt_field)

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

Place a limit 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

With BrokerType.SINOPAC this places a REAL order on a real account.

Source code in src/cjtrade/pkgs/brokers/account_client.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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.

    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
    --------
    With BrokerType.SINOPAC this places a REAL order on a real account.
    """
    return self.broker_api.sell_stock(symbol, quantity, price, intraday_odd, opt_field=opt_field)

cjtrade.pkgs.brokers.account_client.BrokerType

Bases: Enum

Supported broker backends.

Warnings

YUANTA and CATHAY are not implemented; AccountClient raises NotImplementedError for them. ArenaX is the simulated broker.

cjtrade.pkgs.brokers.account_client.AccountState()

Account data cached locally by AccountClient.

Warnings

pending_orders and order_history are never filled yet.

Source code in src/cjtrade/pkgs/brokers/account_client.py
42
43
44
45
46
47
def __init__(self):
    self.positions: List[Position] = []
    self.balance: float = 0.0
    self.last_sync_time: str = ""
    self.pending_orders: List[Order] = [] # Don't implement it for now, too complex.
    self.order_history: List[Order] = []  # Don't implement it for now, too complex.