Skip to content

Latest commit

 

History

History
354 lines (272 loc) · 16.7 KB

unfilled_orders.md

File metadata and controls

354 lines (272 loc) · 16.7 KB

Orders: topping up what didn't fill

When a limit order doesn't fill, or fills only in part, the account falls short of the strategy's target. This guide shows how to use finlab-online to buy only the shares still missing without doubling orders, how to give top-ups a price cap and a deadline, how to check those rules on a paper account that never reaches a broker, and what backtests can and cannot simulate.

It follows Orders: many strategies: you already update a target with PortfolioSyncManager every day and sync the account to it.

Three things to know before topping up

  1. The gap is target minus holdings. OrderExecutor.generate_orders() (and pm.sync()) subtracts the holdings your broker reports from the target. After a partial fill, recomputing buys only the rest. With a target of 300 shares, holdings of 100, 200 and 300 shares leave gaps of 200, 100 and 0.
  2. Open orders are not subtracted. The gap looks at holdings, not at orders still working. Recomputing while orders are open places the same quantity again, and calling execute_orders(..., cancel_orders=False) repeatedly keeps stacking orders. create_orders() and pm.sync() cancel every open order in the account before recomputing, but a cancel request is not a completed cancel, so the approach below cancels and recomputes in separate rounds. Cancelling covers every order in the account, so only this program should place orders in it.
  3. Top up to the live target. Use the target PortfolioSyncManager keeps: rebalances, stop-losses and take-profits are already applied, and several strategies are already merged. Don't buy back from report.position or a signal from days ago. With several strategies in one account, merge them into one target first; if each strategy compares itself with the account, it treats the other strategies' holdings as extra and sells them.

Top up, one round at a time

Save this as top_up_rules.py:

import datetime

from finlab.online import OrderStatus

OPEN = (OrderStatus.NEW, OrderStatus.PARTIALLY_FILLED)


def refresh_plan(plan, executor, today, max_up=0.03, days=2):
    """When a target quantity changes, record a new price cap and deadline from the current price; drop stocks no longer targeted"""
    goal = {}
    for p in executor.target_position.position:
        goal[p["stock_id"]] = goal.get(p["stock_id"], 0) + float(p["quantity"])
    for sid in [s for s in plan if s not in goal]:
        del plan[sid]
    changed = [s for s, q in goal.items() if plan.get(s, {}).get("target") != q]
    prices = executor.account.get_price(changed) if changed else {}
    until = datetime.date.fromisoformat(today) + datetime.timedelta(days=days)
    for sid in changed:
        plan[sid] = {
            "target": goal[sid],
            "max_price": round(float(prices[sid]) * (1 + max_up), 2),
            "until": until.isoformat(),
        }


def top_up(executor, plan, today, **kwargs):
    """If orders are still open, cancel them and place nothing this round; otherwise fill the gap to the target"""
    account = executor.account
    if any(o.status in OPEN for o in account.get_orders().values()):
        if not kwargs.get("view_only"):  # a preview cancels nothing
            executor.cancel_orders()
        print("Orders still open; nothing placed this round")
        return []
    orders = executor.generate_orders()
    buys = [o["stock_id"] for o in orders if o["quantity"] > 0]
    prices = account.get_price(buys) if buys else {}
    keep = []
    for o in orders:
        sid = o["stock_id"]
        if o["quantity"] > 0 and sid in plan:  # no limits on sells, or on covering stocks outside the target
            rule = plan[sid]
            if today > rule["until"]:
                print(f"{sid} past its deadline {rule['until']}; no more top-ups")
                continue
            if prices[sid] > rule["max_price"]:
                print(f"{sid} price {prices[sid]} above cap {rule['max_price']}; skipped this round")
                continue
        keep.append(o)
    return executor.execute_orders(keep, cancel_orders=False, **kwargs)

Each round, top_up first checks the account for open orders:

  • Some are open: it cancels them and places nothing this round. It recomputes only in a round that starts with no open orders, so cancels and fills have time to be reported. If a cancel never takes effect, every round just cancels again; orders never stack.
  • None are open: it recomputes the gap with generate_orders() and buys only what is missing.

Buys must also pass two limits you choose, kept in plan:

  • Price cap: the price when the target was first seen × (1 + max_up), 3% in the example. Above it, nothing is bought this round; the top-up waits for the price to come back. The cap is compared with the current price; a positive extra_bid_pct places the order above it.
  • Deadline: days calendar days (weekends and holidays count) after the target was first seen, 2 in the example. After that, nothing more is bought; what wasn't bought stays in cash until a rebalance or a stop-loss changes the target.

When a target quantity changes (a rebalance, a strategy added or removed), refresh_plan records a new cap and deadline from the current price. When a stop-loss or a new signal drops a stock from the target, its plan is dropped too, the old top-up order in the account is cancelled, and what was already bought is sold to match the target.

Choose max_up and days for your strategy; finlab-online has no built-in setting for either. Other arguments to top_up go to execute_orders, for example top_up(executor, plan, today, extra_bid_pct=-0.01); view_only=True previews without cancelling or placing anything.

Connect it to PortfolioSyncManager

Keep running pm.update() and pm.to_local() every day as before. The top-up program only reads the target PM saved and replaces your pm.sync(account) call; it can run several times a day:

import datetime
import json
import os
from zoneinfo import ZoneInfo

import pandas as pd
from finlab.online.sinopac_account import SinopacAccount
from finlab.portfolio import PortfolioSyncManager
from top_up_rules import refresh_plan, top_up

PLAN = "top_up_plan.json"
now = datetime.datetime.now(ZoneInfo("Asia/Taipei"))
today = now.date().isoformat()

pm = PortfolioSyncManager.from_local()
account = SinopacAccount()  # other brokers: see "Orders: many strategies"
# the same target pm.sync(account) uses
executor = pm.create_order_executor(account, consider_margin_as_asset=True)

plan = {}
if os.path.exists(PLAN):
    with open(PLAN) as f:
        plan = json.load(f)
refresh_plan(plan, executor, today)
top_up(executor, plan, today)
with open(PLAN, "w") as f:
    json.dump(plan, f, indent=2)

# keep every order's state from this round for review
rows = [{k: getattr(v, "name", v) for k, v in vars(o).items() if k != "org_order"}
        for o in account.get_orders().values()]
pd.DataFrame(rows).to_csv(f"orders_{now:%Y%m%d_%H%M}.csv", index=False)

One top-up takes at least two rounds, one to cancel and one to place again; the time between rounds is how long an order stays working.

Check the rules on a paper account first

No broker, no real orders: PaperAccount implements the Account interface as a paper account where you trigger fills and failed cancels. Put it in the same folder as top_up_rules.py and run paper_check.py to try each case once: no fill, partial fill, an order still open, past the deadline, above the price cap, and a withdrawn target:

import datetime
import logging
from dataclasses import replace

from finlab.online import (
    Account,
    Action,
    Order,
    OrderCondition,
    OrderExecutor,
    OrderStatus,
    Position,
    Stock,
)
from top_up_rules import OPEN, refresh_plan, top_up

logging.getLogger("finlab_online").setLevel(logging.ERROR)  # the paper account has no price limits; silence that notice


class PaperAccount(Account):
    """A paper account with no broker: you trigger fills and failed cancels. Quantities to the executor are in lots"""

    def __init__(self, prices):
        self.prices = dict(prices)
        self.shares = {}  # shares held
        self.orders = {}
        self.cancel_works = True  # set to False: cancels never take effect

    def create_order(self, action, stock_id, quantity, price=None, odd_lot=False,
                     market_order=False, best_price_limit=False,
                     order_cond=OrderCondition.CASH):
        oid = str(len(self.orders) + 1)
        self.orders[oid] = Order(oid, stock_id, action, price, round(quantity * 1000), 0,
                                 OrderStatus.NEW, order_cond, datetime.datetime.now())
        return oid

    def fill(self, oid, shares):
        """Simulate the broker reporting a fill of `shares` shares"""
        o = self.orders[oid]
        o.filled_quantity += shares
        sign = 1 if o.action == Action.BUY else -1
        self.shares[o.stock_id] = self.shares.get(o.stock_id, 0) + sign * shares
        done = o.filled_quantity == o.quantity
        o.status = OrderStatus.FILLED if done else OrderStatus.PARTIALLY_FILLED

    def cancel_order(self, order_id):
        if self.cancel_works and self.orders[order_id].status in OPEN:
            self.orders[order_id].status = OrderStatus.CANCEL

    def update_order(self, order_id, price=None, quantity=None):
        raise NotImplementedError

    def get_orders(self):
        return {
            oid: replace(o, quantity=o.quantity / 1000, filled_quantity=o.filled_quantity / 1000)
            for oid, o in self.orders.items()
        }

    def get_stocks(self, stock_ids):
        return {s: Stock(s, *[self.prices[s]] * 5, 0, self.prices[s], 0) for s in stock_ids}

    def get_position(self):
        return Position({s: n / 1000 for s, n in self.shares.items()})

    def get_total_balance(self):
        return 0

    def get_cash(self):
        return 0

    def get_settlement(self):
        return 0

    def sep_odd_lot_order(self):
        return False  # one order per stock, so create_order always gets lots


def show(acc):
    pending = {}
    for o in acc.orders.values():
        if o.status in OPEN:
            pending[o.stock_id] = pending.get(o.stock_id, 0) + o.quantity - o.filled_quantity
    print(f"  held {acc.shares}, open {pending}")


def start(title, held=0):
    """Target: 300 shares of 2330 at 1,000; the first round places the order on Dec 1"""
    print(f"\n== {title}")
    acc = PaperAccount({"2330": 1000.0})
    if held:
        acc.shares["2330"] = held
    executor = OrderExecutor(Position({"2330": 0.3}), acc)
    plan = {}
    refresh_plan(plan, executor, "2026-12-01")
    top_up(executor, plan, "2026-12-01")
    show(acc)
    return acc, executor, plan


def next_rounds(executor, plan, today):
    """The next round cancels the old order, the one after recomputes and tops up"""
    for _ in range(2):
        refresh_plan(plan, executor, today)
        top_up(executor, plan, today)
    show(executor.account)


for held in (100, 200, 300):
    start(f"Already hold {held} shares", held)

acc, executor, plan = start("No fill: cancel, then place 300 again, never stacked")
next_rounds(executor, plan, "2026-12-01")

acc, executor, plan = start("100 filled: top up only 200")
acc.fill("1", 100)
next_rounds(executor, plan, "2026-12-01")

acc, executor, plan = start("Cancel not taking effect: no new order")
acc.cancel_works = False
next_rounds(executor, plan, "2026-12-01")

acc, executor, plan = start("Past the deadline: no more top-ups")
next_rounds(executor, plan, "2026-12-04")

acc, executor, plan = start("Above the price cap: skipped")
acc.prices["2330"] = 1040.0
next_rounds(executor, plan, "2026-12-01")

acc, executor, plan = start("Stop-loss after 100 filled: cancel the top-up, sell what was bought")
acc.fill("1", 100)
executor = OrderExecutor(Position({}), acc)
next_rounds(executor, plan, "2026-12-01")
print(f"  plan {plan}")

Output (finlab 2.3.17, finlab-online 1.2.0):

== Already hold 100 shares
BUY         2330       X 0.2        @ 1000.0       CASH
  held {'2330': 100}, open {'2330': 200}

== Already hold 200 shares
BUY         2330       X 0.1        @ 1000.0       CASH
  held {'2330': 200}, open {'2330': 100}

== Already hold 300 shares
  held {'2330': 300}, open {}

== No fill: cancel, then place 300 again, never stacked
BUY         2330       X 0.3        @ 1000.0       CASH
  held {}, open {'2330': 300}
Orders still open; nothing placed this round
BUY         2330       X 0.3        @ 1000.0       CASH
  held {}, open {'2330': 300}

== 100 filled: top up only 200
BUY         2330       X 0.3        @ 1000.0       CASH
  held {}, open {'2330': 300}
Orders still open; nothing placed this round
BUY         2330       X 0.2        @ 1000.0       CASH
  held {'2330': 100}, open {'2330': 200}

== Cancel not taking effect: no new order
BUY         2330       X 0.3        @ 1000.0       CASH
  held {}, open {'2330': 300}
Orders still open; nothing placed this round
Orders still open; nothing placed this round
  held {}, open {'2330': 300}

== Past the deadline: no more top-ups
BUY         2330       X 0.3        @ 1000.0       CASH
  held {}, open {'2330': 300}
Orders still open; nothing placed this round
2330 past its deadline 2026-12-03; no more top-ups
  held {}, open {}

== Above the price cap: skipped
BUY         2330       X 0.3        @ 1000.0       CASH
  held {}, open {'2330': 300}
Orders still open; nothing placed this round
2330 price 1040.0 above cap 1030.0; skipped this round
  held {}, open {}

== Stop-loss after 100 filled: cancel the top-up, sell what was bought
BUY         2330       X 0.3        @ 1000.0       CASH
  held {}, open {'2330': 300}
Orders still open; nothing placed this round
SELL        2330       X 0.1        @ 1000.0       CASH
  held {'2330': 100}, open {'2330': 100}
  plan {}

From "No fill" on, the first line of each case is the 300-share order from the first round on December 1. Whenever you change your own rules (cap, deadline, whole lots only), run it again and check every case does what you want before connecting a real account. After connecting, run a few days on your broker's paper account or with view_only=True first; while previewing, point PLAN at another file name and start live trading from an empty plan, so deadlines count from your first live day.

Keep the fills and review the top-ups

The script above saves an orders_*.csv every round: each order's price, quantity, filled quantity and status. To see how far your holdings are from the target and what the top-ups really earned, fetch the fills from your broker with TradeReview.from_account() after the close and compare them with the top-up target (account, plan and today come from the script above):

from finlab.portfolio import TradeReview

review = TradeReview.from_account(account, start="2026-12-01")
# plan targets are in lots; Taiwan stocks multiply by 1000 for shares
target = pd.DataFrame({s: [r["target"] * 1000] for s, r in plan.items()}, index=[today])
review.compare(target)  # diff is actual minus target; negative means shares still missing

For compare and the rest of the review, see Real-trade review from a broker account.

What backtests can and cannot simulate

You want to Use Limits
Top up only the gap in live trading top_up on this page (generate_orders() computes target minus holdings) Confirming cancels, the price cap and the deadline are rules in your program, not finlab-online settings
See orders go unfilled in a backtest sim(..., limit_up_down=True): no buy on a day locked at limit-up, sells delayed on a day locked at limit-down No unfilled ordinary limit orders, partial fills or odd-lot queues, and no automatic top-up the next day. A daily high or low touching your limit does not mean an odd-lot order would have filled
See the cost of worse prices Raise fee_ratio (for example 0.001425 + 0.003, 0.3% more on each buy and sell), or rerun with trade_at_price='open' Only raises costs or changes the trade price; every trade still fills in full, so it cannot show unfilled orders or idle cash
Check your top-up rules The paper account above; once live, TradeReview against the target A backtest cannot rebuild historical odd-lot queue fills, and does not promise that results after top-ups match the original backtest

How limit_up_down decides a stock is locked: Backtesting in the FinLab docs.

Next steps