while25 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. while25/__init__.py +341 -0
  2. while25/_costs/brokers/alpaca.json +96 -0
  3. while25/_costs/brokers/binance.json +34 -0
  4. while25/_costs/brokers/coinbase.json +34 -0
  5. while25/_costs/brokers/ibkr.json +39 -0
  6. while25/_costs/brokers/upstox.json +175 -0
  7. while25/_costs/brokers/zerodha.json +175 -0
  8. while25/_costs/crypto_alpaca.json +27 -0
  9. while25/_costs/global_crypto.json +18 -0
  10. while25/_costs/in_nse_equity.json +238 -0
  11. while25/_costs/in_nse_etf.json +352 -0
  12. while25/_costs/in_nse_fo.json +450 -0
  13. while25/_costs/us_crypto.json +18 -0
  14. while25/_costs/us_equity.json +175 -0
  15. while25/_costs/us_options.json +172 -0
  16. while25/_days.py +123 -0
  17. while25/_figures.py +233 -0
  18. while25/_runtime.py +49 -0
  19. while25/_universes/banknifty.json +80 -0
  20. while25/_universes/ndx100.json +520 -0
  21. while25/_universes/nifty50.json +260 -0
  22. while25/_universes/nifty500.json +2505 -0
  23. while25/_universes/sp500.json +2525 -0
  24. while25/assume.py +263 -0
  25. while25/backtest.py +881 -0
  26. while25/barline.py +160 -0
  27. while25/combo_legs.py +238 -0
  28. while25/errors.py +77 -0
  29. while25/fonts/IBMPlexMono-Regular.ttf +0 -0
  30. while25/fonts/IBMPlexMono-SemiBold.ttf +0 -0
  31. while25/fonts/Inter-Bold.ttf +0 -0
  32. while25/fonts/Inter-Regular.ttf +0 -0
  33. while25/fonts/Inter-SemiBold.ttf +0 -0
  34. while25/fonts/OFL-IBMPlexMono.txt +93 -0
  35. while25/fonts/OFL-Inter.txt +93 -0
  36. while25/future_pick.py +77 -0
  37. while25/inputs.py +215 -0
  38. while25/instruments.py +488 -0
  39. while25/modules.py +397 -0
  40. while25/money.py +24 -0
  41. while25/option_pick.py +221 -0
  42. while25/plots.py +147 -0
  43. while25/report.py +644 -0
  44. while25/ui.py +680 -0
  45. while25/universes.py +70 -0
  46. while25-0.1.0.dist-info/METADATA +3194 -0
  47. while25-0.1.0.dist-info/RECORD +50 -0
  48. while25-0.1.0.dist-info/WHEEL +5 -0
  49. while25-0.1.0.dist-info/licenses/LICENSE +201 -0
  50. while25-0.1.0.dist-info/top_level.txt +1 -0
while25/instruments.py ADDED
@@ -0,0 +1,488 @@
1
+ """One instrument's size and price rules (while25.data.instrument).
2
+
3
+ Mirrors the engine's venue rules: the same catalog
4
+ row, the same two checks (check_size / check_price), so a script can size an
5
+ order it already knows the engine will accept instead of discovering the rule
6
+ from a rejection. `check()` here is a LOCAL, ADVISORY re-implementation of
7
+ that C++ — the ENGINE re-checks every order regardless, and its verdict is the
8
+ one that counts; this exists so an author sizing a strategy does not need a
9
+ live round trip (and a rejection) to find a lot size.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ import numbers
15
+ from dataclasses import dataclass
16
+ from decimal import Decimal, InvalidOperation, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_EVEN
17
+ from typing import NamedTuple
18
+
19
+ from ._figures import _canon
20
+ from .money import Money
21
+
22
+
23
+ def _as_decimal(x, what: str = "price") -> Decimal:
24
+ """A price as an exact Decimal, for snapping — the ONE place a noisy float
25
+ is welcome. A float is read by its shortest round-trip form: the tape's
26
+ 100.05 (stored as 100.0499999999999971) reads back as 100.05, and a
27
+ computed 99.94999999999999 reads as exactly that, to be put on the tick
28
+ next. Nothing is rounded here; snap() does the rounding, on the venue's
29
+ tick, out loud. The shortest form comes from float.__repr__, not repr():
30
+ NumPy 2 prints a float64 (a float, and what pandas hands a script) as
31
+ "np.float64(100.05)", which is no decimal at all."""
32
+ if isinstance(x, Decimal):
33
+ return x
34
+ if isinstance(x, bool):
35
+ raise ValueError(f"{what} must be a number, not {x!r}")
36
+ if isinstance(x, numbers.Integral):
37
+ # An int, or a NumPy integer (not an int subclass, but Integral).
38
+ return Decimal(int(x))
39
+ if isinstance(x, float):
40
+ if not math.isfinite(x):
41
+ raise ValueError(f"{what} must be a finite number, not {x!r}")
42
+ return Decimal(float.__repr__(x))
43
+ if isinstance(x, str):
44
+ try:
45
+ return Decimal(x.strip())
46
+ except InvalidOperation:
47
+ raise ValueError(f"{what} is not a valid decimal: {x!r}") from None
48
+ raise ValueError(f"{what} must be a Decimal, int, float or str, not {type(x).__name__}")
49
+
50
+
51
+ class PriceStep(NamedTuple):
52
+ """One step of a price ladder (venue_rules.h PriceStep): from `from_price`
53
+ up to the next step's, prices move in steps of `increment`. Both exact
54
+ Decimals, as the wire states them."""
55
+ from_price: Decimal
56
+ increment: Decimal
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Instrument:
61
+ """The venue's own statement of one instrument's rules. Every figure is
62
+ Decimal | None — absent means the venue stated no rule, not zero — and
63
+ price_steps is () when it states no ladder."""
64
+ instrument_key: str
65
+ symbol: str
66
+ size_increment: "Decimal | None"
67
+ min_qty: "Decimal | None"
68
+ max_qty: "Decimal | None"
69
+ lot_multiple: "Decimal | None"
70
+ price_increment: "Decimal | None"
71
+ sub_band_price_increment: "Decimal | None"
72
+ price_band_floor: "Decimal | None"
73
+ multiplier: "Decimal | None"
74
+ min_notional: "Money | None"
75
+ quote_currency: str
76
+ settlement_currency: str
77
+ tradeable: bool
78
+ untradeable_reason: str
79
+ # The first rule the venue did not state ("size_increment", "min_qty",
80
+ # "lot_multiple", "price_increment", "multiplier", "currency"), or ""
81
+ # when every rule is on file. A gap does NOT make the row untradeable
82
+ # (decision 118): an order goes to the venue as typed, and the engine's
83
+ # reply names what it could not verify. notice() says the same locally.
84
+ rules_gap: str = ""
85
+ # What the engine's catalog and profile state about where it trades, ""
86
+ # where they state nothing (never guessed from the key): the exchange code
87
+ # ("NSE", "NFO", "NASDAQ", ...), the catalog's type ("EQ", "FUT", "OPT",
88
+ # "CRYPTO", ...), the market's country ("IN", "US", ...) and the
89
+ # execution broker's id. A cost lookup needs all four.
90
+ exchange: str = ""
91
+ instrument_type: str = ""
92
+ country_code: str = ""
93
+ broker_id: str = ""
94
+ # The tick by price where it changes with the price (IBKR's price rule for
95
+ # the contract), lowest first: each step's increment applies from its
96
+ # from_price up to the next step's. Non-empty, it governs every price in
97
+ # place of price_increment and the band, as VenueRules::tick_for reads
98
+ # it; () = the venue states none, and those govern.
99
+ price_steps: "tuple[PriceStep, ...]" = ()
100
+ # The venue's minimum order size and value apply to BUY orders only
101
+ # (Alpaca, 2026-11-08: "Sell orders do not have this validation, so you
102
+ # can close any open position"): a sell below them goes to the venue, and
103
+ # check(side="SELL") spares it. False = the minimum applies both ways.
104
+ minimum_buys_only: bool = False
105
+ # The venue states its least order value (min_notional) for an order sized
106
+ # by amount only (Coinbase's quote_min_size, 2026-11-08: stated for the
107
+ # quote asset alone): an order sized in units below it is sent, for the
108
+ # venue to answer. check() does not hold a quantity to min_notional where
109
+ # this is True, and notice() names it.
110
+ min_notional_amount_orders_only: bool = False
111
+
112
+ @property
113
+ def step(self) -> "Decimal | None":
114
+ """The size an order's quantity must sit on: the lot, else the plain
115
+ increment. Matches VenueRules::step() exactly."""
116
+ if self.lot_multiple is not None and self.lot_multiple > 0:
117
+ return self.lot_multiple
118
+ if self.size_increment is not None and self.size_increment > 0:
119
+ return self.size_increment
120
+ return None
121
+
122
+ def tick_for(self, price) -> "Decimal | None":
123
+ """The tick that governs THIS price. On a ladder (price_steps): the
124
+ increment of the last step whose from_price is at or below the price,
125
+ the lowest step's for a price below them all. Else band-aware: below
126
+ price_band_floor the finer sub_band_price_increment applies, when the
127
+ venue states both. Absent when the venue states no tick at all."""
128
+ return self._tick_at(Decimal(_canon(price, "price")))
129
+
130
+ def _tick_at(self, p: Decimal) -> "Decimal | None":
131
+ # THE tick-for-price rule, the engine's own: every
132
+ # price rule here reads its tick through this, or, walking a ladder's
133
+ # grid, picks its step with the same _step_at.
134
+ if self.price_steps:
135
+ ladder = self._ladder()
136
+ return None if ladder is None else ladder[_step_at(ladder, p)][1]
137
+ # A tick of 0 or below is no tick, as the engine's catalog reads it
138
+ # (it keeps only positive ones, so only a hand-built row can carry
139
+ # one): a finer band tick that is not positive is no band, and a main
140
+ # tick that is not positive is no grid at all. Never a "tick" that
141
+ # notice() would call stated while check() and snap() skip it.
142
+ # NaN and the infinities are not positive figures either: the wire
143
+ # text "NaN" decodes, and comparing it raised out of every caller.
144
+ sub = self.sub_band_price_increment
145
+ if (self.price_band_floor is not None and sub is not None
146
+ and sub.is_finite() and sub > 0 and p < self.price_band_floor):
147
+ return sub
148
+ tick = self.price_increment
149
+ return tick if tick is not None and tick.is_finite() and tick > 0 else None
150
+
151
+ def _ladder(self) -> "tuple | None":
152
+ """price_steps as the rows a ladder is read by: ((from_price,
153
+ increment), ...), each from_price above the last and the first one
154
+ None — that row also governs every price below the second's — with no
155
+ two neighbours on one increment. Read as the engine reads
156
+ its steps: lowest first (its catalog sorts them; a
157
+ hand-built row is sorted here), a from_price stated twice governed by
158
+ the later step.
159
+ None when any step is no step: a from_price or an increment that is
160
+ not a finite Decimal, or an increment not above 0. The engine never
161
+ sends one (its catalog keeps a venue's ladder whole or not at all),
162
+ so only a hand-built row or a garbled wire carries one, and a ladder
163
+ that cannot be read is no rule to judge by: no tick at any price,
164
+ never price_increment standing in for the steps the venue stated."""
165
+ steps = []
166
+ for start, inc in self.price_steps:
167
+ if not (isinstance(start, Decimal) and isinstance(inc, Decimal)
168
+ and start.is_finite() and inc.is_finite() and inc > 0):
169
+ return None
170
+ steps.append((start, inc))
171
+ steps.sort(key=lambda s: s[0]) # stable: a later twin stays later
172
+ rows = [(None, steps[0][1])]
173
+ for start, inc in steps:
174
+ if rows[-1][0] == start: # stated twice: the later one governs
175
+ rows.pop()
176
+ if rows[-1][1] != inc:
177
+ rows.append((start, inc))
178
+ return tuple(rows)
179
+
180
+ # ---- exactness at the point of use (decision 96) -------------------------
181
+ # Tape prices reach a script as floats and stay floats (indicators want
182
+ # them so, and converting every field of every tick would pay for maths
183
+ # done in a few lines). These three are those lines: they turn a float
184
+ # into the exact tick-grid Decimal ONCE, where a price becomes a decision
185
+ # or an order, so "two ticks below" and "how many ticks apart" are exact.
186
+
187
+ def snap(self, price, *, mode: str = "nearest") -> "Decimal | None":
188
+ """The tick-grid price for `price` (a float from the feed, a str, an
189
+ int or a Decimal), exact. `mode`: "nearest" (half to even — the
190
+ engine's own rounding), "down" (a buyer's limit), "up" (a seller's).
191
+ On a ladder (price_steps) the grid is every price on the tick that
192
+ governs it, so a price just under a step edge may snap onto the edge.
193
+ None when the venue states no tick for this price: there is no grid
194
+ to snap to. Raises ValueError for a non-finite or unreadable price."""
195
+ p = _as_decimal(price)
196
+ if self.price_steps:
197
+ return self._snap_on_ladder(p, mode)
198
+ tick = self._tick_at(p)
199
+ if tick is None or tick <= 0:
200
+ return None
201
+ steps = p / tick
202
+ if mode == "nearest":
203
+ n = steps.to_integral_value(rounding=ROUND_HALF_EVEN)
204
+ elif mode == "down":
205
+ n = steps.to_integral_value(rounding=ROUND_FLOOR)
206
+ elif mode == "up":
207
+ n = steps.to_integral_value(rounding=ROUND_CEILING)
208
+ else:
209
+ raise ValueError(f"snap mode {mode!r}: use 'nearest', 'down' or 'up'")
210
+ return (n * tick).quantize(tick)
211
+
212
+ def _snap_on_ladder(self, p: Decimal, mode: str) -> "Decimal | None":
213
+ # p's two neighbours on the grid, found step by step (an edge need not
214
+ # sit on either step's grid): "down" is the highest grid price at or
215
+ # below p, "up" the lowest at or above it. Where each edge sits on
216
+ # both steps' grids, that is the price the tick at p snaps to, the
217
+ # half-to-even tie included.
218
+ ladder = self._ladder()
219
+ if ladder is None:
220
+ return None
221
+ if mode not in ("nearest", "down", "up"):
222
+ raise ValueError(f"snap mode {mode!r}: use 'nearest', 'down' or 'up'")
223
+ if not p.is_finite():
224
+ raise ValueError(f"price must be a finite number, not {p!r}")
225
+ i = _step_at(ladder, p)
226
+ below = _grid_down(ladder, i, p, False) if mode != "up" else None
227
+ above = _grid_up(ladder, i, p, False) if mode != "down" else None
228
+ if below is None or above is None:
229
+ row, out = below or above
230
+ elif p - below[1] != above[1] - p:
231
+ row, out = below if p - below[1] < above[1] - p else above
232
+ else:
233
+ # Halfway: the side half to even on the tick at p takes.
234
+ tick = ladder[i][1]
235
+ half = (p / tick).to_integral_value(rounding=ROUND_HALF_EVEN) * tick
236
+ row, out = below if half < p else above
237
+ return out.quantize(ladder[row][1])
238
+
239
+ def offset(self, price, ticks: int) -> "Decimal | None":
240
+ """`ticks` ticks above (positive) or below (negative) `price`, exact,
241
+ from the snapped price. None when the venue states no tick.
242
+ On a ladder (price_steps) a tick is one step along the venue's grid —
243
+ the prices that sit on the tick governing them — so the move changes
244
+ increment AT a step edge: on a 0 -> 0.05 / 3 -> 0.10 ladder
245
+ offset(2.95, 2) is 3.10 (2.95, 3.00, 3.10) and offset(3.10, -2) is
246
+ 2.95, never the 2.90 a 0.10 step down from 3.00 would reach. Without
247
+ one, the move is ticks x the tick AT `price`; a move that crosses a
248
+ band floor is the caller's to re-snap if it cares.
249
+ `ticks` must be a whole number (an int, or a NumPy integer): 2.7 ticks
250
+ is no move a venue can make, so it raises ValueError rather than
251
+ quietly moving 2."""
252
+ # bool is an int subclass; refused first, as _canon refuses it.
253
+ if isinstance(ticks, bool) or not isinstance(ticks, numbers.Integral):
254
+ raise ValueError(f"ticks must be a whole number of ticks, not {ticks!r}")
255
+ base = self.snap(price)
256
+ if base is None:
257
+ return None
258
+ if self.price_steps:
259
+ ladder = self._ladder()
260
+ row, out = _walk(ladder, base, int(ticks))
261
+ return out.quantize(ladder[row][1])
262
+ tick = self._tick_at(base)
263
+ return (base + tick * int(ticks)).quantize(tick)
264
+
265
+ def ticks_between(self, a, b) -> "int | None":
266
+ """Whole ticks from `a` to `b` (negative when b is below a), exact,
267
+ between the snapped prices. On a ladder (price_steps) they are counted
268
+ along the grid as offset() walks it: 2.95 to 3.10 on a 0 -> 0.05 /
269
+ 3 -> 0.10 ladder is 2. None when the venue states no tick, or, without
270
+ a ladder, when the two prices are governed by different ticks (across
271
+ a band floor): that distance is not one number of one tick."""
272
+ pa = self.snap(a)
273
+ pb = self.snap(b)
274
+ if pa is None or pb is None:
275
+ return None
276
+ if self.price_steps:
277
+ ladder = self._ladder()
278
+ return _count(ladder, pa, pb) if pa <= pb else -_count(ladder, pb, pa)
279
+ ta = self._tick_at(pa)
280
+ tb = self._tick_at(pb)
281
+ if ta != tb:
282
+ return None
283
+ return int((pb - pa) / ta)
284
+
285
+ def notice(self, *, quantity=None, price=None) -> "str | None":
286
+ """What the engine will NOT be able to verify about this order, in
287
+ the engine's own words (decision 118), or None when every rule the
288
+ order touches is on file. EVERY gap is named, size first and then
289
+ price, joined the way the engine's size check joins them: naming
290
+ only the first would hide a later one. An order with a notice is
291
+ still sent, as typed, for the venue to judge; the engine's placement
292
+ reply carries the same notice. Named here so a script can log it
293
+ before sending.
294
+ """
295
+ key = self.instrument_key or self.symbol
296
+ gaps = []
297
+ if quantity is not None:
298
+ if self.step is None:
299
+ gaps.append(f"the venue states no size step for {key}; the "
300
+ f"quantity is sent as typed for the venue to judge.")
301
+ elif self.min_qty is None:
302
+ gaps.append(f"the venue states no minimum size for {key}; the "
303
+ f"quantity is sent as typed for the venue to judge.")
304
+ # A floor in another currency than the order's value: check()
305
+ # does not compare it (no FX conversion), so it is the venue's.
306
+ # Needs a price, as check() does, to be an order value at all.
307
+ if (price is not None and self.min_notional is not None
308
+ and self.min_notional.currency != self.quote_currency):
309
+ gaps.append(
310
+ f"the venue's minimum order value is stated in "
311
+ f"{self.min_notional.currency} and the order value in "
312
+ f"{self.quote_currency or 'an unknown currency'}; the "
313
+ f"floor is the venue's to judge.")
314
+ # A least value the venue states for orders by amount only: a
315
+ # quantity below it is the venue's to judge, as check() leaves it.
316
+ if (price is not None and self.min_notional is not None
317
+ and self.min_notional_amount_orders_only
318
+ and self.min_notional.currency == self.quote_currency):
319
+ q = Decimal(_canon(quantity, "quantity"))
320
+ p = Decimal(_canon(price, "price"))
321
+ mult = self.multiplier if self.multiplier is not None else Decimal(1)
322
+ if q * p * mult < self.min_notional.value:
323
+ gaps.append(
324
+ f"the venue states its least order value "
325
+ f"{self.min_notional.value} {self.min_notional.currency} "
326
+ f"for an order sized by amount; whether it holds an order "
327
+ f"of {q * p * mult} {self.quote_currency} sized in units is "
328
+ f"the venue's to judge.")
329
+ if price is not None:
330
+ p = Decimal(_canon(price, "price"))
331
+ if self._tick_at(p) is None:
332
+ gaps.append(f"the venue states no tick for {key}; the price is "
333
+ f"sent as typed for the venue to judge.")
334
+ return " ".join(gaps) if gaps else None
335
+
336
+ def check(self, *, quantity=None, price=None, side=None) -> "str | None":
337
+ """A local pre-check, mirroring check_size / check_price. Returns a
338
+ refusal message, or None when the order would pass every rule this
339
+ can judge. ADVISORY ONLY — the engine re-checks and its answer is
340
+ authoritative; this exists so a script can size an order without a
341
+ round trip and a rejection first.
342
+
343
+ Only a rule the venue STATED is judged (decision 118): a size step
344
+ or minimum the venue does not publish refuses nothing, and neither
345
+ does a min_notional stated in another currency than the order's
346
+ value (no FX conversion) — the order is sent as typed for the venue
347
+ to judge, and notice() names the gap.
348
+ Checked, in order, when `quantity` is given: positive; on-step, when
349
+ the venue states a step; at or above the minimum, when it states
350
+ one; at or below the maximum, when it states one; at or above
351
+ min_notional, when the venue states one in the order's own currency
352
+ AND a `price` is also given (min_notional needs a price to turn a
353
+ quantity into a value), unless the venue states that value for
354
+ orders by amount only (min_notional_amount_orders_only, Coinbase's
355
+ quote_min_size): a quantity is then not held to it, goes to the
356
+ venue, and notice() names it. Where the venue states its minimum for buys
357
+ only (minimum_buys_only, Alpaca), `side="SELL"` is spared the minimum
358
+ size and value: such a sell goes to the venue, which answers. An
359
+ order sized by `amount=` is not checked here: the venue sizes it.
360
+ Checked, when `price` is given: on the tick that governs it
361
+ (tick_for: the ladder's step, else the band's), when the venue
362
+ states one.
363
+ """
364
+ q = Decimal(_canon(quantity, "quantity")) if quantity is not None else None
365
+ p = Decimal(_canon(price, "price")) if price is not None else None
366
+ # A minimum the venue states for buys only is not judged on a sell.
367
+ minimum_judged = not (self.minimum_buys_only
368
+ and str(side or "").upper() == "SELL")
369
+
370
+ if q is not None:
371
+ step = self.step
372
+ if q <= 0:
373
+ return f"quantity {q} is not positive"
374
+ if step is not None and q % step != 0:
375
+ return f"quantity {q} is not a multiple of lot size {step}"
376
+ if minimum_judged and self.min_qty is not None and q < self.min_qty:
377
+ return f"quantity {q} is below the venue minimum {self.min_qty}"
378
+ if self.max_qty is not None and q > self.max_qty:
379
+ return f"quantity {q} is above the venue maximum {self.max_qty}"
380
+ # A floor in another currency is not compared and never
381
+ # converted: the engine's size check passes the order
382
+ # unverified and the venue judges it; notice() names it.
383
+ if (minimum_judged and self.min_notional is not None and p is not None
384
+ and not self.min_notional_amount_orders_only
385
+ and self.min_notional.currency == self.quote_currency):
386
+ mult = self.multiplier if self.multiplier is not None else Decimal(1)
387
+ notional_value = q * p * mult
388
+ if notional_value < self.min_notional.value:
389
+ return (
390
+ f"order value {notional_value} {self.quote_currency} "
391
+ f"is below the venue minimum {self.min_notional.value} "
392
+ f"{self.min_notional.currency}")
393
+
394
+ if p is not None:
395
+ tick = self.tick_for(p)
396
+ if tick is not None and tick > 0 and p % tick != 0:
397
+ return f"price {p} is not a multiple of tick size {tick}"
398
+
399
+ return None
400
+
401
+
402
+ # ---- a ladder's grid ------------------------------------------------------------
403
+ # The rows are Instrument._ladder()'s: ((from_price, increment), ...), the
404
+ # first from_price None. The grid is every price that sits on the increment
405
+ # of the row it falls in. A row is crossed in one step wherever it can be, so
406
+ # even a move of 10**20 ticks costs one pass over the rows, never 10**20.
407
+
408
+ def _step_at(ladder: tuple, p: Decimal) -> int:
409
+ """The row that governs price `p`: the last whose from_price is at or
410
+ below it, the first for every price below the second's — VenueRules::
411
+ tick_for's loop, row for row."""
412
+ at = 0
413
+ for i in range(1, len(ladder)):
414
+ if p < ladder[i][0]:
415
+ break
416
+ at = i
417
+ return at
418
+
419
+
420
+ def _grid_down(ladder: tuple, i: int, x: Decimal, strict: bool) -> tuple:
421
+ """(row, price): the highest grid price at or below `x` (below it, when
422
+ `strict`), looking from row i down. A row holding no multiple of its
423
+ increment between its from_price and `x` is passed for the row under it."""
424
+ while True:
425
+ start, inc = ladder[i]
426
+ q = x / inc
427
+ n = (q.to_integral_value(rounding=ROUND_CEILING) - 1 if strict
428
+ else q.to_integral_value(rounding=ROUND_FLOOR))
429
+ if start is None or n * inc >= start:
430
+ return i, n * inc
431
+ i, x, strict = i - 1, start, True
432
+
433
+
434
+ def _grid_up(ladder: tuple, i: int, x: Decimal, strict: bool) -> tuple:
435
+ """(row, price): the lowest grid price at or above `x` (above it, when
436
+ `strict`), looking from row i up. A row holding no multiple of its
437
+ increment between `x` and the next row's from_price is passed for that
438
+ next row."""
439
+ while True:
440
+ inc = ladder[i][1]
441
+ q = x / inc
442
+ n = (q.to_integral_value(rounding=ROUND_FLOOR) + 1 if strict
443
+ else q.to_integral_value(rounding=ROUND_CEILING))
444
+ end = ladder[i + 1][0] if i + 1 < len(ladder) else None
445
+ if end is None or n * inc < end:
446
+ return i, n * inc
447
+ i, x, strict = i + 1, end, False
448
+
449
+
450
+ def _walk(ladder: tuple, p: Decimal, n: int) -> tuple:
451
+ """(row, price): grid price `p` moved `n` grid prices, up for n > 0."""
452
+ i = _step_at(ladder, p)
453
+ while n > 0:
454
+ inc = ladder[i][1]
455
+ end = ladder[i + 1][0] if i + 1 < len(ladder) else None
456
+ if end is None:
457
+ return i, p + inc * n
458
+ # The grid prices left in this row above p: multiples of inc below end.
459
+ room = int(((end - p) / inc).to_integral_value(rounding=ROUND_CEILING)) - 1
460
+ if n <= room:
461
+ return i, p + inc * n
462
+ i, p = _grid_up(ladder, i, p + inc * room, True)
463
+ n -= room + 1
464
+ while n < 0:
465
+ start, inc = ladder[i]
466
+ if start is None:
467
+ return i, p + inc * n
468
+ # The grid prices left in this row below p: multiples of inc from start.
469
+ room = int(((p - start) / inc).to_integral_value(rounding=ROUND_FLOOR))
470
+ if -n <= room:
471
+ return i, p + inc * n
472
+ i, p = _grid_down(ladder, i, p - inc * room, True)
473
+ n += room + 1
474
+ return i, p
475
+
476
+
477
+ def _count(ladder: tuple, a: Decimal, b: Decimal) -> int:
478
+ """How many grid prices from grid price `a` up to grid price `b` (a <= b):
479
+ _walk read backwards."""
480
+ i, n = _step_at(ladder, a), 0
481
+ while True:
482
+ inc = ladder[i][1]
483
+ end = ladder[i + 1][0] if i + 1 < len(ladder) else None
484
+ if end is None or b < end:
485
+ return n + int((b - a) / inc)
486
+ room = int(((end - a) / inc).to_integral_value(rounding=ROUND_CEILING)) - 1
487
+ i, a = _grid_up(ladder, i, a + inc * room, True)
488
+ n += room + 1