Skip to content

fix(trade): paginate history_orders and accept zero-padded HK symbols - #627

Open
hogan-yuan wants to merge 4 commits into
mainfrom
fix/trade-history-pagination-and-symbol
Open

hogan-yuan wants to merge 4 commits into
mainfrom
fix/trade-history-pagination-and-symbol

Conversation

@hogan-yuan

@hogan-yuan hogan-yuan commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Fixes two defects in the trade APIs. Both fail silently, which is what makes them worth fixing together: neither surfaces an error, so a caller sees plausible-looking but wrong data.

Closes longbridge/developers#789. Addresses the first point of longbridge/developers#1210.

1. history_orders returned at most one page

The endpoint caps a response at 1000 records and reports the overflow in has_more, which the SDK dropped on the floor. A caller whose window held more than 1000 orders got a truncated list and no way to tell.

(The 1000 cap is not an assumption — the has_more row of the history-orders doc states it.)

history_executions already walks pages; history_orders now does the same: increment page, dedupe by order_id, stop when has_more is false or a page adds nothing new, bounded to 1000 pages.

The return type is unchanged (Vec<Order> and its per-language equivalents), so this is not a breaking change and no binding needed touching.

Why not expose has_more, as #1210 asked

Worth answering directly, because this repo already contains the alternative design and a reviewer will see the inconsistency:

API page returns who paginates
all_executions (/v3/trade/execution/all) public builder AllExecutionsResponse, with has_more the caller
history_executions (/v1/trade/execution/history) internal Vec<Execution> the SDK
history_orders (/v1/trade/order/history) internal (this PR) Vec<Order> the SDK

all_executions was built that way from the start: it already returns an envelope, so carrying has_more costs nothing. history_orders returns a bare Vec<Order>, so exposing has_more means changing the return type in six languages — a breaking change for every caller, to hand them a flag they would then have to write a pagination loop around.

Walking the pages gives them the complete result instead, which is what #1210 was after ("the response-envelope boundary is unavailable to Python clients" — the concern was not knowing the list was truncated). This also keeps history_orders consistent with its closest sibling, history_executions, which already works this way.

If a reviewer would rather have the explicit form, that is a deliberate breaking change and should be decided here, not inferred.

On the page parameter

The documentation asymmetry is worth stating plainly: history_executions documents page (1-based, 1000 cap, use together with has_more); history_orders does not document it at all.

Measured against the gateway:

query result
(none) has_more=false, 4 records
page=1 the same 4 records
page=2 0 records
page=abc HTTP 500, code 13

Two things follow. page=abc being rejected shows the value is parsed rather than ignored. More tellingly, page=2 returns nothing rather than the same 4 records — a parameter that was accepted but not applied would have returned the first page again. And sending page=1 is equivalent to sending no page at all, so the first request is unchanged.

What this does not establish is that page 2 of a >1000-record account returns records 1001–2000; the test account has 4 orders, so that case cannot be exercised here. The dedupe and the "a page added nothing new" exit make the loop safe either way: a gateway that silently ignored page would return page 1 again, add nothing, and the loop would stop.

Consequences worth reviewing

These are inherited from the history_executions implementation this mirrors, so they are not new to the codebase — but "consistent with what we already shipped" is not the same as "no downside", so:

  • Request count goes from 1 to up to 1000. The requests are sequential, not a burst.

  • Rate limiting is retried, which makes the worst case much slower than it looks. longbridge-httpcli retries an HTTP 429 five times with exponential backoff (100ms doubling to 1.6s, ~3.1s per request), and that budget is per request, so it applies to every page independently. If a long walk runs into sustained rate limiting, 1000 pages x 3.1s is ~52 minutes, and history_orders has no overall deadline. A caller running this inside a request handler can block for a long time.

    I had originally written here that there was no client-side rate-limit handling at all. That was wrong — I grepped for it, saw only what looked like a test name (rich_rate_limit_response_remains_retryable) and did not open the file. The retry is in request.rs:471.

  • Latency for a wide date range goes from one round trip to many.

  • Memory is no longer bounded by the 1000-record cap; everything is accumulated before returning.

  • Orders arriving mid-walk can shift records between pages. The dedupe prevents duplicates; a record could still be missed.

If any of these are unacceptable for history_orders specifically, the alternative is the breaking has_more exposure, and it should be decided here rather than later.

2. Zero-padded HK symbols were silently ignored

The Longbridge apps display HK symbols with leading zeros (00700.HK). The quote subscription path already stripped them; the trade and asset paths did not. Measured against the gateway:

/v1/asset/stock?symbol=700.HK    -> 200, 1 position
/v1/asset/stock?symbol=00700.HK  -> 200, 0 positions

No error — a padded symbol reads as an empty account rather than as a mistake. That is the inconsistency reported in #789.

Symbols are now canonicalized on the way out for stock_positions, history_orders, today_orders, history_executions, today_executions, all_executions, cash_flow, margin_ratio, estimate_max_purchase_quantity and submit_order. normalize_symbol moves from quote::context to crate::types so both sides share one implementation, and it now leaves an all-zero code alone instead of trimming 000.HK down to a bare .HK.

Other markets are untouched, A-share codes included: 000001.SZ keeps its zeros.

Evidence boundary

The silent-empty behaviour was measured on read endpoints. submit_order and estimate_max_purchase_quantity are included for consistency, but I did not test an order submission with a padded symbol — I am not going to place test orders to find out. The change there can only rewrite 00700.HK into 700.HK, a form the gateway demonstrably accepts, so the risk is low; it is an inference rather than a measurement, and a reviewer may prefer to drop submit_order from the set.

A caller who passes 00700.HK now gets results whose symbol field reads 700.HK. That is better than the previous empty result, but code that string-compares the response against its own input will see a mismatch where it previously saw nothing at all.

Deliberately out of scope

  • Quote HTTP endpoints (~19 call sites) still send the symbol verbatim. The reporter states the padded form works there, and the quote REST routes answer 404000 on the test gateway, so I could not measure it either way and left behaviour I have not observed alone.
  • MultiLegOrderLeg and GetUSHistoryOrders are plain structs with public fields and no builder choke point. Both carry US symbols, where normalization is a no-op.
  • Fund positions take counter IDs, not market symbols.

Verification

End to end against the test gateway, through the SDK:

stock_positions(   700.HK) -> 1 position(s) ["700.HK"]
stock_positions( 00700.HK) -> 1 position(s) ["700.HK"]     <- was 0 before
history_orders()           -> 4 order(s)
history_orders(00700.HK)   -> 3 order(s)

New unit tests cover the serialized query for every normalized entry point, the owned/borrowed helper agreeing, and the all-zero edge case. Writing them is how I found that GetTodayExecutionsOptions lives in its own file and had been missed.

cargo test -p longbridge: 88 + 57 pass. cargo clippy --all --all-features: diffed against main line by line, zero new warnings.

🤖 Generated with Claude Code

hogan-yuan added a commit that referenced this pull request Nov 19, 2026
No workflow in this repo declares a `concurrency` group, so every push
to a pull request queues another full CI matrix and **the run it
replaced keeps its place in line**.

## What that looked like

Observed while iterating on #627 and #628:

```
全仓库最近 12 次运行:queued=6, completed=6
最近一次真正完成的运行:186 分钟前
最老的排队运行:187 分钟
```

Six runs queued at once; four were for commits that were no longer any
branch's HEAD. Nothing started for roughly three hours. Cancelling the
four obsolete runs by hand is what got the queue moving again:

```
44282677026  b18750b  superseded → cancelled
44266307848  b846aea  superseded → cancelled
44265659864  acc1c25  superseded → cancelled
44259650117  3e99304  superseded → cancelled
```

With nine jobs fanning out across a wide platform matrix, each obsolete
run is a lot of runner time spent on a commit nobody is waiting for.

## The change

```yaml
concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true
```

`github.head_ref` is set **only** for `pull_request` events, so:

- **a pull request** groups by its branch — a new commit cancels the run
for the commit it replaced
- **a push to main** falls back to `github.run_id`, which is unique per
run, so those get a group of their own: never cancelled, and never made
to queue behind each other either

That second half matters. The naive `group: ${{ github.workflow }}-${{
github.ref }}` would put every main push in one group — either
cancelling a main run that a later commit supersedes, or serialising
them.

## Why only `ci.yml`

The other five workflows should not cancel, so they are untouched:

| workflow | trigger | why not |
|---|---|---|
| `release.yml` | push to `release` | publishes artifacts; aborting
halfway is worse than running twice |
| `docs.yml` | push to `release` | deploys docs; same |
| `check_docs.yml` | push to `main` | main only, infrequent |
| `close-slate-issues.yml` | weekly cron | nothing to supersede |
| `issue-notify.yml` | issue opened | nothing to supersede |

## Related, deliberately not bundled

- **longbridge-mcp** has no concurrency group in any of its four
workflows.
- **longbridge-terminal** has one in three of seven, but not in
`test.yml`.

Both are worth the same change, but neither has shown this backlog —
their CI is small where this one fans out — so they belong in their own
PRs rather than here.

## Honest note on how this came up

A good part of the backlog was self-inflicted: I pushed small follow-up
commits to #627 and #628 seven times while reviewing them, and in a repo
with no concurrency group each of those reset a full matrix. The fix is
worth having regardless, but the measurement above is as much a
description of my own push cadence as of the CI configuration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Two defects reported against the trade APIs, both of which fail silently.

history_orders returned at most one page. The endpoint caps a response at
1000 records and reports the overflow in `has_more`, which the SDK dropped
on the floor, so a caller whose window held more than 1000 orders got a
truncated list and no way to tell. Walk the `page` parameter until
`has_more` is false, deduping by `order_id` and stopping when a page adds
nothing new, exactly as `history_executions` already does. The return type
is unchanged, so this is not a breaking change for any binding.

The `page` parameter is undocumented for this endpoint. Checked against the
gateway: `page=1` and no page return the same records, `page=2` returns
none, and `page=abc` is rejected with code 13 — so it is parsed. The dedupe
and the "a page added nothing" exit make the loop safe even if a gateway
ignores it.

Trade and asset calls also rejected the zero-padded HK symbols the
Longbridge apps display. `/v1/asset/stock?symbol=00700.HK` answers 200 with
no positions rather than an error, so a padded symbol reads as an empty
account instead of a mistake, while the quote subscription path already
normalized it. Canonicalize the symbol on the way out for stock_positions,
history_orders, today_orders, history_executions, today_executions,
cash_flow, margin_ratio, estimate_max_purchase_quantity and submit_order.

normalize_symbol moves from quote::context to crate::types so both sides
share it, and now leaves an all-zero code alone instead of trimming it away
to a bare `.HK`. Other markets, A-share codes included, are untouched.

Verified against the test gateway: before, symbol=00700.HK returned 0
positions and 700.HK returned 1; after, both return the position, and
history_orders("00700.HK") returns its 3 orders.

Closes longbridge/developers#789
They were added after the last fmt run, so check-format caught them.
Formatting only; no behaviour change.
The doc comment on normalize_symbol said the quote endpoints accept the
padded symbol. That came from the issue report, not from anything checked
here -- the quote REST routes answer 404000 on the test gateway, which is
why this change deliberately leaves them alone. Say which part was measured
and which part is the reporter's observation.
…quests

Two gaps in the entries added by this branch.

The symbol-normalization entry listed nine APIs; the code normalizes ten.
`all_executions` was added to the code and to the PR description but not
here, so the list and the diff disagreed. Checked programmatically now:
the names in the entry and the call sites that use normalize_symbol_owned
are the same set.

The pagination entry said "no caller needs updating", which is true of the
type and misleading about the behaviour: the call goes from always one
request to one per page, so a wide window is slower and consumes more of
the caller's rate limit. Say that, and point at narrowing the date range
(the server defaults to 90 days when neither bound is set).
@hogan-yuan
hogan-yuan force-pushed the fix/trade-history-pagination-and-symbol branch from d9527b5 to 2df5195 Compare November 19, 2026 02:05

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

stock_positions 函数处理 symbol 时有问题

1 participant