### Realtime Event Models: BidAsk Example Source: https://context7.com/finlab-python/order_executor/llms.txt Illustrates the `BidAsk` object, which represents a top-5 order book snapshot. Shows how to access bid and ask prices and volumes, and how to retrieve bid levels. ```python from finlab.online.core.realtime_models import ( Tick, BidAsk, BookLevel, OrderUpdate, Fill, BalanceUpdate, PositionUpdate, ConnectionState, ) import datetime # BidAsk — top-5 order book snapshot ba = BidAsk( stock_id='2330', bid_prices=[851.0, 850.0, 849.0], bid_volumes=[50, 120, 300], ask_prices=[852.0, 853.0, 854.0], ask_volumes=[30, 80, 200], time=datetime.datetime.now(), ) print(ba.bid_levels[0]) # BookLevel(price=851.0, volume=50) print(ba.bid_prices_top5) # [851.0, 850.0, 849.0, 0.0, 0.0] (padded to 5) ``` -------------------------------- ### Realtime Event Models: Fill Example Source: https://context7.com/finlab-python/order_executor/llms.txt Shows the structure of a `Fill` object, which confirms a single trade execution. Includes order ID, stock ID, action (BUY/SELL), price, quantity, and timestamp. ```python from finlab.online.core.realtime_models import ( Tick, BidAsk, BookLevel, OrderUpdate, Fill, BalanceUpdate, PositionUpdate, ConnectionState, ) import datetime # Fill — a single execution confirmation fill = Fill( order_id='ABC001', stock_id='2330', action=Action.BUY, price=852.0, quantity=2.0, time=datetime.datetime.now(), ) ``` -------------------------------- ### Run Integration Tests Source: https://github.com/finlab-python/order_executor/blob/main/README.md Execute integration tests which require actual broker credentials. Use the -s flag to see print statements during test execution. Refer to tests/README.md for credential setup. ```bash pytest tests/integration/ -v -s ``` -------------------------------- ### Realtime Event Models: Tick Example Source: https://context7.com/finlab-python/order_executor/llms.txt Demonstrates the structure of a `Tick` object, representing an individual trade. Includes fields for stock ID, price, volume, timestamps, and OHLC data. Shows how to access the calculated percentage change. ```python from finlab.online.core.realtime_models import ( Tick, BidAsk, BookLevel, OrderUpdate, Fill, BalanceUpdate, PositionUpdate, ConnectionState, ) import datetime # Tick — individual trade print tick = Tick( stock_id='2330', price=852.0, volume=10, total_volume=5000, time=datetime.datetime.now(), open=840.0, high=855.0, low=838.0, prev_close=845.0, # pct_change auto-calculated if not supplied ) print(tick.pct_change) # (852-845)/845 * 100 ≈ 0.828 ``` -------------------------------- ### Realtime Data Streaming with SinopacAccount Source: https://context7.com/finlab-python/order_executor/llms.txt Connects to realtime data streams using SinopacAccount and registers callbacks for various market events. Subscribe to specific symbols and handle backfilled data before starting live streaming. ```python from finlab.online.brokers import SinopacAccount from finlab.online.core.realtime_models import ( Tick, BidAsk, OrderUpdate, Fill, ConnectionState ) acc = SinopacAccount() acc.connect_realtime() # Register callbacks acc.on_tick(lambda tick: print(f"TICK {tick.stock_id} @ {tick.price}")) acc.on_bidask(lambda ba: print(f"BIDASK {ba.stock_id} bid={ba.bid_prices[0]}")) acc.on_order_update(lambda u: print(f"ORDER {u.order_id} → {u.status}")) acc.on_fill(lambda f: print(f"FILL {f.stock_id} qty={f.quantity} @ {f.price}")) acc.on_connection(lambda state, msg: print(f"CONN {state}: {msg}")) # Subscribe to tick and bid/ask streams for specific symbols acc.subscribe_ticks(['2330', '2317']) acc.subscribe_bidask(['2330', '2317']) # Backfill today's ticks then begin live streaming backfilled = acc.subscribe_ticks_with_backfill(['2330']) print(f"Backfilled {len(backfilled['2330'])} ticks for 2330") # Tear down acc.unsubscribe_ticks(['2330', '2317']) acc.disconnect_realtime() ``` -------------------------------- ### Two-Step Order Flow with generate_orders and execute_orders Source: https://context7.com/finlab-python/order_executor/llms.txt Separate order computation from execution for finer control. Use `generate_orders` to get a list of required orders, then `execute_orders` to submit them. This allows for inspection before committing and supports phased execution like sell-only followed by buy-only. ```python # Step 1: compute the required order list orders = oe.generate_orders() # [{'symbol': '2330', 'quantity': Decimal('2'), 'order_condition': CASH}, ...] # Step 2: execute with sell-only (useful for risk-off first pass) oe.execute_orders(orders, sell_only=True) # Then buy oe.execute_orders(orders, buy_only=True) # Get a full summary table of current vs target quantities + prices info = oe.get_order_info() # [{'symbol': '2330', 'price': 850.0, 'current_qty': 0.0, # 'target_qty': 2.0, 'order_qty': 2.0, 'order_condition': 'CASH'}, ...] ``` -------------------------------- ### Integrate with Broker Adapters (Fugle, Sinopac, Schwab) Source: https://context7.com/finlab-python/order_executor/llms.txt Import and instantiate broker adapters from `finlab.online.brokers` to connect to different financial services. Ensure necessary environment variables for API keys, secrets, and paths are configured for each adapter. ```python # Fugle / E.SUN (realtime: order events, fills, balance, position) import os from finlab.online.brokers import FugleAccount os.environ['FUGLE_CONFIG_PATH'] = './config.ini' os.environ['FUGLE_ACCOUNT_PASSWORD'] = 'YOUR_PASSWORD' os.environ['FUGLE_CERT_PASSWORD'] = 'YOUR_CERT_PASSWORD' os.environ['FUGLE_MARKET_API_KEY'] = 'YOUR_KEY' fugle = FugleAccount() # Sinopac / Shioaji (realtime: ticks, bid/ask, order events, fills, balance) from finlab.online.brokers import SinopacAccount os.environ['SHIOAJI_API_KEY'] = 'YOUR_API_KEY' os.environ['SHIOAJI_SECRET_KEY'] = 'YOUR_SECRET_KEY' os.environ['SHIOAJI_CERT_PERSON_ID'] = 'YOUR_ID' sinopac = SinopacAccount() # Charles Schwab — US equities (no real-time streaming) from finlab.online.brokers import SchwabAccount os.environ['SCHWAB_API_KEY'] = 'YOUR_KEY' os.environ['SCHWAB_APP_SECRET'] = 'YOUR_SECRET' os.environ['SCHWAB_TOKEN_PATH'] = '/path/to/token.json' schwab = SchwabAccount() ``` -------------------------------- ### Initialize Binance Account Source: https://context7.com/finlab-python/order_executor/llms.txt Initializes a Binance account connection. Ensure BINANCE_API_KEY and BINANCE_SECRET_KEY are set in your environment variables. ```python from finlab.online.brokers import BinanceAccount binance = BinanceAccount() # reads BINANCE_API_KEY / BINANCE_SECRET_KEY from env ``` -------------------------------- ### Run Unit Tests Source: https://github.com/finlab-python/order_executor/blob/main/README.md Execute fast, mocked unit tests for the finlab.online package. Ensure all changes pass these tests before contributing. ```bash pytest tests/unit/ -v ``` -------------------------------- ### Broker Adapters Source: https://context7.com/finlab-python/order_executor/llms.txt Information on available broker adapters, including Fugle, Sinopac, and Charles Schwab, detailing their real-time capabilities and required environment variables for initialization. ```APIDOC ## Broker Adapters Each broker adapter is imported from `finlab.online.brokers` or the legacy flat path. All adapters implement the `Account` interface, and those marked "Realtime" also implement `RealtimeProvider`. ```python # Fugle / E.SUN (realtime: order events, fills, balance, position) import os from finlab.online.brokers import FugleAccount os.environ['FUGLE_CONFIG_PATH'] = './config.ini' os.environ['FUGLE_ACCOUNT_PASSWORD'] = 'YOUR_PASSWORD' os.environ['FUGLE_CERT_PASSWORD'] = 'YOUR_CERT_PASSWORD' os.environ['FUGLE_MARKET_API_KEY'] = 'YOUR_KEY' fugle = FugleAccount() # Sinopac / Shioaji (realtime: ticks, bid/ask, order events, fills, balance) from finlab.online.brokers import SinopacAccount os.environ['SHIOAJI_API_KEY'] = 'YOUR_API_KEY' os.environ['SHIOAJI_SECRET_KEY'] = 'YOUR_SECRET_KEY' os.environ['SHIOAJI_CERT_PERSON_ID'] = 'YOUR_ID' sinopac = SinopacAccount() # Charles Schwab — US equities (no real-time streaming) from finlab.online.brokers import SchwabAccount os.environ['SCHWAB_API_KEY'] = 'YOUR_KEY' os.environ['SCHWAB_APP_SECRET'] = 'YOUR_SECRET' os.environ['SCHWAB_TOKEN_PATH'] = '/path/to/token.json' schwab = SchwabAccount() ``` ``` -------------------------------- ### Sync Account to Target Position with OrderExecutor Source: https://context7.com/finlab-python/order_executor/llms.txt Use OrderExecutor to calculate and place buy/sell orders to match a target position. Configure environment variables for broker authentication. Orders can be previewed, placed at last-traded price, or at market price with optional price chasing and partial execution. ```python from finlab.online import OrderExecutor, Position from finlab.online.brokers import FugleAccount import os os.environ['FUGLE_CONFIG_PATH'] = '/path/to/config.ini' os.environ['FUGLE_MARKET_API_KEY'] = 'YOUR_MARKET_API_KEY' account = FugleAccount() target = Position({'2330': 2, '1101': 5}) oe = OrderExecutor(target_position=target, account=account) # Preview orders without placing them preview = oe.create_orders(view_only=True) # BUY 2330 X 2 @ 850.0 CASH # BUY 1101 X 5 @ 34.5 CASH # Place real orders at last-traded price oe.create_orders() # Place orders at market price (limit-up for buy, limit-down for sell) oe.create_orders(market_order=True) # Add a 2 % price chase premium for buys / discount for sells oe.create_orders(extra_bid_pct=0.02) # Partial execution — place 30 % of the required lots this round oe.create_orders(progress=0.3) ``` -------------------------------- ### Query Live Quotes and Orders with Broker Adapters Source: https://context7.com/finlab-python/order_executor/llms.txt Use broker adapters like SinopacAccount to query live stock quotes, including last price and percentage change. You can also retrieve and inspect open orders, checking their symbol, action, and status. ```python from finlab.online.brokers import SinopacAccount import os os.environ['SHIOAJI_API_KEY'] = 'YOUR_API_KEY' os.environ['SHIOAJI_SECRET_KEY'] = 'YOUR_SECRET_KEY' os.environ['SHIOAJI_CERT_PERSON_ID'] = 'YOUR_ID' acc = SinopacAccount() stocks = acc.get_stocks(['2330', '2317']) print(stocks['2330'].close) # e.g. 850.0 print(stocks['2330'].pct_change) # e.g. 1.23 orders = acc.get_orders() for oid, o in orders.items(): print(oid, o.stock_id, o.action, o.status) ``` -------------------------------- ### Position: Constructing and Manipulating Portfolios Source: https://context7.com/finlab-python/order_executor/llms.txt Shows how to create and manipulate `Position` objects, which represent stock allocations. Supports building from stock-lot mappings, applying margin/short-selling flags, arithmetic operations, and serialization/deserialization. ```python from finlab.online import Position, OrderCondition # Build from a stock-id → lot-count mapping (cash, long only) p = Position({'2330': 2, '1101': 5}) print(p) # symbol quantity order_condition # 1101 5.0 CASH # 2330 2.0 CASH # Margin-long and short-selling flags p_margin = Position({'2330': 1}, margin_trading=True) p_short = Position({'2330': 1}, short_selling=True) # Arithmetic composition p1 = Position({'1101': 3}) p2 = Position({'2330': 1}) combined = p1 + p2 # [1101: 3 CASH, 2330: 1 CASH] # Scale down to 50 % half = combined * 0.5 # Serialise / deserialise combined.to_json('/tmp/position.json') restored = Position.from_json('/tmp/position.json') ``` -------------------------------- ### Set Fubon Integration Test Environment Variables Source: https://github.com/finlab-python/order_executor/blob/main/tests/README.md Configure the necessary environment variables for Fubon integration tests. These variables provide credentials and paths required to connect to Fubon APIs. ```bash export FUBON_NATIONAL_ID="..." export FUBON_ACCOUNT_PASS="..." export FUBON_CERT_PATH="/path/to/cert.pfx" # Optional: export FUBON_CERT_PASS="..." export FUBON_ACCOUNT="..." ``` -------------------------------- ### RealtimeProvider - Streaming Market Data and Events Source: https://context7.com/finlab-python/order_executor/llms.txt The RealtimeProvider is an abstract mixin that adds WebSocket/streaming capabilities to broker adapters. It enables event buses for ticks, bid/ask, order updates, fills, balances, positions, and connection states through a callback registration pattern. ```APIDOC ## `RealtimeProvider` — Streaming Market Data and Events `RealtimeProvider` is the abstract mixin that adds a WebSocket/streaming layer on top of broker adapters. It provides tick, bid/ask, order-update, fill, balance, position, and connection-state event buses via a callback registration pattern. ```python from finlab.online.brokers import SinopacAccount from finlab.online.core.realtime_models import ( Tick, BidAsk, OrderUpdate, Fill, ConnectionState ) acc = SinopacAccount() acc.connect_realtime() # Register callbacks acc.on_tick(lambda tick: print(f"TICK {tick.stock_id} @ {tick.price}")) acc.on_bidask(lambda ba: print(f"BIDASK {ba.stock_id} bid={ba.bid_prices[0]}")) acc.on_order_update(lambda u: print(f"ORDER {u.order_id} → {u.status}")) acc.on_fill(lambda f: print(f"FILL {f.stock_id} qty={f.quantity} @ {f.price}")) acc.on_connection(lambda state, msg: print(f"CONN {state}: {msg}")) # Subscribe to tick and bid/ask streams for specific symbols acc.subscribe_ticks(['2330', '2317']) acc.subscribe_bidask(['2330', '2317']) # Backfill today's ticks then begin live streaming backfilled = acc.subscribe_ticks_with_backfill(['2330']) print(f"Backfilled {len(backfilled['2330'])} ticks for 2330") # Tear down acc.unsubscribe_ticks(['2330', '2317']) acc.disconnect_realtime() ``` ``` -------------------------------- ### Position.from_report: Build from Backtest Report Source: https://context7.com/finlab-python/order_executor/llms.txt Translates a FinLab `Report` object into a live-tradeable `Position`. It automatically selects between `weights` and `next_weights` based on rebalancing timing and respects stop-loss/take-profit signals. ```python from finlab import backtest from finlab.online import Position report = backtest.sim( buy_condition, sell_condition, position=1.0, ) # Deploy TWD 1,000,000 against today's market prices position = Position.from_report(report, fund=1_000_000) # Combine two strategy allocations report2 = backtest.sim(buy2, sell2, position=1.0) pos2 = Position.from_report(report2, fund=1_000_000) total = position + pos2 # union of both strategies ``` -------------------------------- ### BalanceStreamMixin.subscribe_balances — Live Balance Updates Source: https://context7.com/finlab-python/order_executor/llms.txt Streams live updates for account balances. It polls `cash`, `settlement`, and `total_balance` at a configurable interval and emits `BalanceUpdate` events when changes are detected. ```APIDOC ## `BalanceStreamMixin.subscribe_balances` — Live Balance Updates Polls account balance fields (`cash`, `settlement`, `total_balance`) on a configurable interval and emits `BalanceUpdate` events whenever a change is detected. ```python from finlab.online.brokers import SinopacAccount from finlab.online.core.realtime_models import BalanceUpdate acc = SinopacAccount() acc.connect_realtime() def on_balance(update: BalanceUpdate) -> None: print( f"[{update.broker}] cash={update.cash:,.0f}" f" settlement={update.settlement:,.0f}" f" total={update.total_balance:,.0f}" ) acc.on_balance(on_balance) acc.subscribe_balances(poll_interval=3.0, emit_on_change=True) # Stop polling acc.unsubscribe_balances() ``` ``` -------------------------------- ### Live Position Updates with FugleAccount Source: https://context7.com/finlab-python/order_executor/llms.txt Subscribes to live position updates using FugleAccount. This stream seeds from `get_position()`, applies fill-driven deltas, and periodically reconciles by polling the broker. ```python from finlab.online.brokers import FugleAccount from finlab.online.core.realtime_models import PositionUpdate acc = FugleAccount() acc.connect_realtime() def on_position(update: PositionUpdate) -> None: print(f"[{update.source}] {update.broker} position updated at {update.time}") print(update.position) acc.on_position(on_position) # Start streaming; reconcile every 30 s (respects Fugle's 10-s rate limit) acc.subscribe_positions(poll_interval=30.0) # ... trading activity ... acc.unsubscribe_positions() ``` -------------------------------- ### Position.from_weight: Weight-Based Allocation Source: https://context7.com/finlab-python/order_executor/llms.txt Converts percentage weights and a fund size into discrete lot counts using a greedy allocation algorithm. Supports odd-lot precision and leverage options, utilizing market reference prices or provided price history. ```python from finlab.online import Position # Allocate TWD 1,000,000 equally between two stocks pos = Position.from_weight( weights={'1101': 0.5, '2330': 0.5}, fund=1_000_000, # price=None → uses market reference price automatically ) # [{'stock_id': '1101', 'quantity': 13, 'order_condition': CASH}, # {'stock_id': '2330', 'quantity': 1, 'order_condition': CASH}] # With odd-lot precision (fractional lots), margin leverage pos_leverage = Position.from_weight( weights={'2330': 0.6, '2317': 0.4}, fund=2_000_000, odd_lot=True, # precision down to 0.001 張 leverage=1.5, # 1.5× leverage; lowest-vol stocks assigned to margin price_history=price_df, # pd.DataFrame of close prices (≥252 rows) ) ``` -------------------------------- ### Account Abstract Interface Source: https://context7.com/finlab-python/order_executor/llms.txt The abstract base class for all broker adapters, defining the contract for order management, fetching quotes, holdings, cash, and balance. ```APIDOC ## `Account` Abstract Interface `Account` is the abstract base class all broker adapters implement. It defines the contract for creating, updating, cancelling, and querying orders, as well as fetching live stock quotes, current holdings, cash, settlements, and net asset value. ```python from finlab.online.core.account import Account, Order, Stock from finlab.online import Action, OrderCondition # All broker adapters expose the same interface: # account.create_order(action, stock_id, quantity, price, ...) # account.update_order(order_id, price=..., quantity=...) # account.cancel_order(order_id) # account.get_orders() → dict[str, Order] # account.get_stocks(['2330', '1101']) → dict[str, Stock] # account.get_position() → Position # account.get_cash() → int # account.get_settlement() → int # account.get_total_balance() → int # Example: manually query live quotes from finlab.online.brokers import SinopacAccount import os os.environ['SHIOAJI_API_KEY'] = 'YOUR_API_KEY' os.environ['SHIOAJI_SECRET_KEY'] = 'YOUR_SECRET_KEY' os.environ['SHIOAJI_CERT_PERSON_ID'] = 'YOUR_ID' acc = SinopacAccount() stocks = acc.get_stocks(['2330', '2317']) print(stocks['2330'].close) # e.g. 850.0 print(stocks['2330'].pct_change) # e.g. 1.23 orders = acc.get_orders() for oid, o in orders.items(): print(oid, o.stock_id, o.action, o.status) ``` ``` -------------------------------- ### Chase Unfilled Orders with update_order_price and cancel_orders Source: https://context7.com/finlab-python/order_executor/llms.txt Manage open orders by re-pricing them to the latest traded price, optionally with a premium to improve fill probability using `update_order_price`. Use `cancel_orders` to close all outstanding orders, or selectively cancel buys or sells. ```python import time oe.create_orders() time.sleep(60) # wait one minute # Re-price unfilled orders, adding 3 % premium oe.update_order_price(extra_bid_pct=0.03) # Cancel all outstanding orders oe.cancel_orders() # Cancel only buys or only sells oe.cancel_orders(buy_only=True) oe.cancel_orders(sell_only=True) ``` -------------------------------- ### Import OrderExecutor and Position Source: https://github.com/finlab-python/order_executor/blob/main/README.md Import necessary classes for order execution and position management. Refer to the official documentation for comprehensive API details. ```python from finlab.online import OrderExecutor, Position # See https://doc.finlab.tw/details/order_api/ for full documentation. ``` -------------------------------- ### Core Enums: Action, OrderStatus, OrderCondition Source: https://context7.com/finlab-python/order_executor/llms.txt Demonstrates the usage of core integer enums for order direction, status, and trading conditions. These enums are fundamental for defining and tracking orders within the system. ```python from finlab.online import Action, OrderStatus, OrderCondition # Action: BUY=1, SELL=2 print(Action.BUY) # Action.BUY print(Action.SELL) # Action.SELL # OrderStatus: NEW, PARTIALLY_FILLED, FILLED, CANCEL print(OrderStatus.NEW) # OrderStatus.NEW print(OrderStatus.FILLED) # OrderStatus.FILLED # OrderCondition: CASH, MARGIN_TRADING, SHORT_SELLING, # DAY_TRADING_LONG, DAY_TRADING_SHORT print(OrderCondition.CASH) # OrderCondition.CASH print(OrderCondition.MARGIN_TRADING) # OrderCondition.MARGIN_TRADING print(OrderCondition.SHORT_SELLING) # OrderCondition.SHORT_SELLING ``` -------------------------------- ### OrderExecutor - Sync Account to Target Position Source: https://context7.com/finlab-python/order_executor/llms.txt Computes the difference between a desired Position and the broker's current holdings, then places the requisite buy/sell orders. Supports previewing, placing real orders, market orders, price chasing, and partial execution. ```APIDOC ## `OrderExecutor` — Sync Account to Target Position `OrderExecutor` computes the difference between a desired `Position` and the broker's current holdings, then places the requisite buy/sell orders. ```python from finlab.online import OrderExecutor, Position from finlab.online.brokers import FugleAccount import os os.environ['FUGLE_CONFIG_PATH'] = '/path/to/config.ini' os.environ['FUGLE_MARKET_API_KEY'] = 'YOUR_MARKET_API_KEY' account = FugleAccount() target = Position({'2330': 2, '1101': 5}) oe = OrderExecutor(target_position=target, account=account) # Preview orders without placing them preview = oe.create_orders(view_only=True) # BUY 2330 X 2 @ 850.0 CASH # BUY 1101 X 5 @ 34.5 CASH # Place real orders at last-traded price oe.create_orders() # Place orders at market price (limit-up for buy, limit-down for sell) oe.create_orders(market_order=True) # Add a 2 % price chase premium for buys / discount for sells oe.create_orders(extra_bid_pct=0.02) # Partial execution — place 30 % of the required lots this round oe.create_orders(progress=0.3) ``` ``` -------------------------------- ### PositionStreamMixin.subscribe_positions — Live Position Updates Source: https://context7.com/finlab-python/order_executor/llms.txt Provides live updates for account positions. It seeds data from `get_position()`, applies fill-driven deltas for immediate updates, and periodically reconciles by polling the broker. ```APIDOC ## `PositionStreamMixin.subscribe_positions` — Live Position Updates Hybrid position streaming: immediately seeds from `get_position()`, applies fill-driven deltas for instant updates, and periodically reconciles by polling the broker. ```python from finlab.online.brokers import FugleAccount from finlab.online.core.realtime_models import PositionUpdate acc = FugleAccount() acc.connect_realtime() def on_position(update: PositionUpdate) -> None: print(f"[{update.source}] {update.broker} position updated at {update.time}") print(update.position) acc.on_position(on_position) # Start streaming; reconcile every 30 s (respects Fugle's 10-s rate limit) acc.subscribe_positions(poll_interval=30.0) # ... trading activity ... acc.unsubscribe_positions() ``` ``` -------------------------------- ### Check Warning Stocks with OrderExecutor Source: https://context7.com/finlab-python/order_executor/llms.txt Screens pending orders against TWSE credit-restricted and warning-stock registers. Requires OrderExecutor and a broker account adapter. ```python from finlab.online import OrderExecutor, Position from finlab.online.brokers import FugleAccount acc = FugleAccount() oe = OrderExecutor(Position({'1234': 5, '5678': 2}), acc) # Fetches TWSE warning-stock lists and prints any overlapping symbols oe.show_alerting_stocks() # 買入 1234 5 張 - 總價約 500,000.00 ``` -------------------------------- ### Calculate Price with Extra Bid Premium Source: https://context7.com/finlab-python/order_executor/llms.txt Adjusts a reference price by a fractional bid premium and snaps the result to the correct Taiwan Stock Exchange tick boundary. Useful for calculating buy or sell order prices with a premium. ```python from finlab.online import calculate_price_with_extra_bid # Add 3 % premium to a buy order at NT$100 → snapped to nearest tick buy_price = calculate_price_with_extra_bid(100.0, 0.03) # → 103.0 # Subtract 3 % from a sell order at NT$550 → snapped down sell_price = calculate_price_with_extra_bid(550.0, -0.03) # → 533.5 # 0 % → price unchanged unchanged = calculate_price_with_extra_bid(35.5, 0.0) # → 35.5 ``` -------------------------------- ### Live Balance Updates with SinopacAccount Source: https://context7.com/finlab-python/order_executor/llms.txt Subscribes to live balance updates using SinopacAccount. This function polls account balance fields and emits `BalanceUpdate` events when changes are detected. ```python from finlab.online.brokers import SinopacAccount from finlab.online.core.realtime_models import BalanceUpdate acc = SinopacAccount() acc.connect_realtime() def on_balance(update: BalanceUpdate) -> None: print( f"[{update.broker}] cash={update.cash:,.0f}" f" settlement={update.settlement:,.0f}" f" total={update.total_balance:,.0f}" ) acc.on_balance(on_balance) acc.subscribe_balances(poll_interval=3.0, emit_on_change=True) # Stop polling acc.unsubscribe_balances() ``` -------------------------------- ### OrderExecutor.generate_orders / execute_orders - Two-Step Order Flow Source: https://context7.com/finlab-python/order_executor/llms.txt Splits the diff-computation and submission steps for finer control or inspection before committing. Allows for executing sell-only or buy-only orders and retrieving order information. ```APIDOC ## `OrderExecutor.generate_orders` / `execute_orders` — Two-Step Order Flow Split the diff-computation and submission steps for finer control, or for inspection before committing. ```python # Step 1: compute the required order list orders = oe.generate_orders() # [{'symbol': '2330', 'quantity': Decimal('2'), 'order_condition': CASH}, ...] # Step 2: execute with sell-only (useful for risk-off first pass) oe.execute_orders(orders, sell_only=True) # Then buy oe.execute_orders(orders, buy_only=True) # Get a full summary table of current vs target quantities + prices info = oe.get_order_info() # [{'symbol': '2330', 'price': 850.0, 'current_qty': 0.0, # 'target_qty': 2.0, 'order_qty': 2.0, 'order_condition': 'CASH'}, ...] ``` ``` -------------------------------- ### calculate_price_with_extra_bid Source: https://context7.com/finlab-python/order_executor/llms.txt Adjusts a reference price by a fractional bid premium and snaps the result to the nearest Taiwan Stock Exchange tick boundary. ```APIDOC ## `calculate_price_with_extra_bid` — Tick-Aware Price Adjustment Adjusts a reference price by a fractional bid premium and snaps the result to the correct Taiwan Stock Exchange tick boundary (0.01 / 0.05 / 0.1 / 0.5 / 1 / 5 NT$ depending on the price tier). ```python from finlab.online import calculate_price_with_extra_bid # Add 3 % premium to a buy order at NT$100 → snapped to nearest tick buy_price = calculate_price_with_extra_bid(100.0, 0.03) # → 103.0 # Subtract 3 % from a sell order at NT$550 → snapped down sell_price = calculate_price_with_extra_bid(550.0, -0.03) # → 533.5 # 0 % → price unchanged unchanged = calculate_price_with_extra_bid(35.5, 0.0) # → 35.5 ``` ``` -------------------------------- ### Run Specific Test File or Method with Pytest Source: https://github.com/finlab-python/order_executor/blob/main/tests/README.md Execute a specific test file or a particular test method within a file. Useful for focused testing. ```bash pytest tests/unit/test_order_executor_unit.py -v ``` ```bash pytest tests/integration/test_fubon_account_integration.py::TestFubonAccountIntegration::test_get_cash -v -s ``` -------------------------------- ### OrderExecutor.show_alerting_stocks Source: https://context7.com/finlab-python/order_executor/llms.txt Screens pending orders against TWSE credit-restricted and warning-stock registers, printing estimated trade amounts for any matches. This method helps identify potential conflicts with regulatory stock restrictions. ```APIDOC ## `OrderExecutor.show_alerting_stocks` — Warning Stock Check Screens the pending order list against the Taiwan Stock Exchange's credit-restricted and warning-stock registers and prints estimated trade amounts for any matches. ```python from finlab.online import OrderExecutor, Position from finlab.online.brokers import FugleAccount acc = FugleAccount() oe = OrderExecutor(Position({'1234': 5, '5678': 2}), acc) # Fetches TWSE warning-stock lists and prints any overlapping symbols oe.show_alerting_stocks() # 買入 1234 5 張 - 總價約 500,000.00 ``` ``` -------------------------------- ### Filter Tests by Keyword with Pytest Source: https://github.com/finlab-python/order_executor/blob/main/tests/README.md Run tests that match a specific keyword. This helps in isolating tests related to a particular feature or functionality. ```bash pytest tests/ -k "price" -v ``` -------------------------------- ### OrderExecutor.update_order_price / cancel_orders Source: https://context7.com/finlab-python/order_executor/llms.txt Allows for re-pricing open orders to the latest traded price with an optional bid premium to improve fill probability. Also supports cancelling all outstanding orders or selectively cancelling buy or sell orders. ```APIDOC ## `OrderExecutor.update_order_price` — Chase Unfilled Orders Re-prices all open (NEW / PARTIALLY_FILLED) orders to the latest traded price, optionally with a bid premium to improve fill probability. ```python import time oe.create_orders() time.sleep(60) # wait one minute # Re-price unfilled orders, adding 3 % premium oe.update_order_price(extra_bid_pct=0.03) # Cancel all outstanding orders oe.cancel_orders() # Cancel only buys or only sells oe.cancel_orders(buy_only=True) oe.cancel_orders(sell_only=True) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.