veltrex-meteora 0.1.0__tar.gz

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.
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 VELTREX contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: veltrex-meteora
3
+ Version: 0.1.0
4
+ Summary: Read-only Meteora DLMM data, bin math and paper LP research simulator. No trading, no keys.
5
+ Keywords: solana,meteora,dlmm,liquidity,defi,research,backtest
6
+ Author: VELTREX contributors
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.13
10
+ Project-URL: Repository, https://github.com/infodhorvath-sudo/veltrex-meteora
11
+ Project-URL: Issues, https://github.com/infodhorvath-sudo/veltrex-meteora/issues
12
+ Description-Content-Type: text/markdown
13
+
14
+ # veltrex-meteora
15
+
16
+ [![tests](https://github.com/infodhorvath-sudo/veltrex-meteora/actions/workflows/tests.yml/badge.svg)](https://github.com/infodhorvath-sudo/veltrex-meteora/actions/workflows/tests.yml)
17
+
18
+ Read-only tooling for research on [Meteora](https://docs.meteora.ag/) DLMM (Solana) liquidity pools.
19
+ Pure Python standard library, no third-party runtime dependencies, Python 3.13+.
20
+
21
+ ## What it does
22
+
23
+ - Fetches public pool, OHLCV and volume data from the official Meteora DLMM Data API
24
+ (`https://dlmm.datapi.meteora.ag`, no key) and stores observations locally (append-only JSONL/JSON).
25
+ - DLMM bin math: bin id and price conversion, bin ranges.
26
+ - Pool scanner: gates and observed-vs-estimated-vs-scenario yield figures (no APR ranking).
27
+ - Data-quality audit of recorded history (coverage, gaps, reconciliation).
28
+ - Deterministic paper liquidity-provision simulator with rebalancing rules, fee model, optional
29
+ execution-cost and rent-aware accounting, and forward paper accounts with replay-checked journals.
30
+ - All money-like arithmetic uses `decimal.Decimal`.
31
+
32
+ Everything simulated is labelled as simulated and estimated. Results are descriptive, not forecasts
33
+ and not financial advice.
34
+
35
+ ## What it does not do
36
+
37
+ - It does not trade, sign, build or send transactions.
38
+ - It does not accept, store or read private keys, seed phrases or wallet connections. Address
39
+ validation rejects seed phrases and secret-key-sized strings.
40
+ - It does not read any environment variables or secret files.
41
+ - The only network access is HTTPS GET requests to the public Meteora Data API in `client.py`.
42
+
43
+ ## Layout
44
+
45
+ `src/veltrex_meteora/`: `addresses`, `bins`, `models`, `client`, `store`, `ingest`, `scanner`,
46
+ `data_quality`, `lp_market`, `lp_sim`, `lp_strategies`, `research`, `lp_paper`, `rent_accounting`.
47
+
48
+ ## Example
49
+
50
+ Replay three range strategies on the last 14 days of a pool (public data, needs network):
51
+
52
+ ```
53
+ PYTHONPATH=src python examples/simulate_range.py # SOL-USDC
54
+ PYTHONPATH=src python examples/simulate_range.py <POOL> 30 # any DLMM pool, 30 days
55
+ ```
56
+
57
+ It prints net return, return of simply holding the starting tokens, fees, costs, rebalances and
58
+ time in range for each strategy. All figures are simulated and estimated.
59
+
60
+ ## Tests
61
+
62
+ Tests are offline and use small recorded fixtures in `tests/fixtures/meteora`.
63
+
64
+ ```
65
+ uv run --group dev pytest
66
+ uv run --group dev ruff check .
67
+ ```
68
+
69
+ ## Data terms
70
+
71
+ Check the Meteora API and docs terms before redistributing data obtained through the client.
72
+
73
+ ## Licence
74
+
75
+ Apache-2.0, see `LICENSE`.
@@ -0,0 +1,62 @@
1
+ # veltrex-meteora
2
+
3
+ [![tests](https://github.com/infodhorvath-sudo/veltrex-meteora/actions/workflows/tests.yml/badge.svg)](https://github.com/infodhorvath-sudo/veltrex-meteora/actions/workflows/tests.yml)
4
+
5
+ Read-only tooling for research on [Meteora](https://docs.meteora.ag/) DLMM (Solana) liquidity pools.
6
+ Pure Python standard library, no third-party runtime dependencies, Python 3.13+.
7
+
8
+ ## What it does
9
+
10
+ - Fetches public pool, OHLCV and volume data from the official Meteora DLMM Data API
11
+ (`https://dlmm.datapi.meteora.ag`, no key) and stores observations locally (append-only JSONL/JSON).
12
+ - DLMM bin math: bin id and price conversion, bin ranges.
13
+ - Pool scanner: gates and observed-vs-estimated-vs-scenario yield figures (no APR ranking).
14
+ - Data-quality audit of recorded history (coverage, gaps, reconciliation).
15
+ - Deterministic paper liquidity-provision simulator with rebalancing rules, fee model, optional
16
+ execution-cost and rent-aware accounting, and forward paper accounts with replay-checked journals.
17
+ - All money-like arithmetic uses `decimal.Decimal`.
18
+
19
+ Everything simulated is labelled as simulated and estimated. Results are descriptive, not forecasts
20
+ and not financial advice.
21
+
22
+ ## What it does not do
23
+
24
+ - It does not trade, sign, build or send transactions.
25
+ - It does not accept, store or read private keys, seed phrases or wallet connections. Address
26
+ validation rejects seed phrases and secret-key-sized strings.
27
+ - It does not read any environment variables or secret files.
28
+ - The only network access is HTTPS GET requests to the public Meteora Data API in `client.py`.
29
+
30
+ ## Layout
31
+
32
+ `src/veltrex_meteora/`: `addresses`, `bins`, `models`, `client`, `store`, `ingest`, `scanner`,
33
+ `data_quality`, `lp_market`, `lp_sim`, `lp_strategies`, `research`, `lp_paper`, `rent_accounting`.
34
+
35
+ ## Example
36
+
37
+ Replay three range strategies on the last 14 days of a pool (public data, needs network):
38
+
39
+ ```
40
+ PYTHONPATH=src python examples/simulate_range.py # SOL-USDC
41
+ PYTHONPATH=src python examples/simulate_range.py <POOL> 30 # any DLMM pool, 30 days
42
+ ```
43
+
44
+ It prints net return, return of simply holding the starting tokens, fees, costs, rebalances and
45
+ time in range for each strategy. All figures are simulated and estimated.
46
+
47
+ ## Tests
48
+
49
+ Tests are offline and use small recorded fixtures in `tests/fixtures/meteora`.
50
+
51
+ ```
52
+ uv run --group dev pytest
53
+ uv run --group dev ruff check .
54
+ ```
55
+
56
+ ## Data terms
57
+
58
+ Check the Meteora API and docs terms before redistributing data obtained through the client.
59
+
60
+ ## Licence
61
+
62
+ Apache-2.0, see `LICENSE`.
@@ -0,0 +1,62 @@
1
+ [project]
2
+ name = "veltrex-meteora"
3
+ version = "0.1.0"
4
+ description = "Read-only Meteora DLMM data, bin math and paper LP research simulator. No trading, no keys."
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ dependencies = []
10
+ keywords = [
11
+ "solana",
12
+ "meteora",
13
+ "dlmm",
14
+ "liquidity",
15
+ "defi",
16
+ "research",
17
+ "backtest",
18
+ ]
19
+
20
+ [[project.authors]]
21
+ name = "VELTREX contributors"
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/infodhorvath-sudo/veltrex-meteora"
25
+ Issues = "https://github.com/infodhorvath-sudo/veltrex-meteora/issues"
26
+
27
+ [dependency-groups]
28
+ dev = [
29
+ "pytest>=8",
30
+ "ruff>=0.8",
31
+ ]
32
+
33
+ [build-system]
34
+ requires = ["uv_build>=0.9,<0.13"]
35
+ build-backend = "uv_build"
36
+
37
+ [tool.uv.build-backend]
38
+ module-name = "veltrex_meteora"
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ pythonpath = [
43
+ "src",
44
+ "tests",
45
+ ]
46
+ addopts = "-q --strict-markers"
47
+
48
+ [tool.ruff]
49
+ line-length = 100
50
+ target-version = "py313"
51
+
52
+ [tool.ruff.lint]
53
+ select = [
54
+ "E",
55
+ "F",
56
+ "W",
57
+ "I",
58
+ "B",
59
+ "UP",
60
+ "SIM",
61
+ "RUF",
62
+ ]
@@ -0,0 +1,37 @@
1
+ [project]
2
+ name = "veltrex-meteora"
3
+ version = "0.1.0"
4
+ description = "Read-only Meteora DLMM data, bin math and paper LP research simulator. No trading, no keys."
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "VELTREX contributors" }]
10
+ dependencies = []
11
+ keywords = ["solana", "meteora", "dlmm", "liquidity", "defi", "research", "backtest"]
12
+
13
+ [project.urls]
14
+ Repository = "https://github.com/infodhorvath-sudo/veltrex-meteora"
15
+ Issues = "https://github.com/infodhorvath-sudo/veltrex-meteora/issues"
16
+
17
+ [dependency-groups]
18
+ dev = ["pytest>=8", "ruff>=0.8"]
19
+
20
+ [build-system]
21
+ requires = ["uv_build>=0.9,<0.13"]
22
+ build-backend = "uv_build"
23
+
24
+ [tool.uv.build-backend]
25
+ module-name = "veltrex_meteora"
26
+
27
+ [tool.pytest.ini_options]
28
+ testpaths = ["tests"]
29
+ pythonpath = ["src", "tests"]
30
+ addopts = "-q --strict-markers"
31
+
32
+ [tool.ruff]
33
+ line-length = 100
34
+ target-version = "py313"
35
+
36
+ [tool.ruff.lint]
37
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF"]
@@ -0,0 +1,5 @@
1
+ """``veltrex_meteora`` -- Meteora DLMM liquidity intelligence. READ-ONLY and PAPER only.
2
+
3
+ No signing, no private keys, no seed phrases, no transaction is built for sending. Public wallet
4
+ addresses and the official Meteora Data API only.
5
+ """
@@ -0,0 +1,39 @@
1
+ """Solana public-key validation. Public addresses only: never a key, seed or signature.
2
+
3
+ A Solana address is the base58 encoding of exactly 32 bytes. Validating before a value is placed
4
+ in a URL path also keeps untrusted text out of requests.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ _ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
10
+ _INDEX = {c: i for i, c in enumerate(_ALPHABET)}
11
+
12
+
13
+ class InvalidAddressError(ValueError):
14
+ pass
15
+
16
+
17
+ def base58_decode(text: str) -> bytes:
18
+ number = 0
19
+ for char in text:
20
+ try:
21
+ number = number * 58 + _INDEX[char]
22
+ except KeyError:
23
+ raise InvalidAddressError(f"character {char!r} is not base58") from None
24
+ body = number.to_bytes((number.bit_length() + 7) // 8, "big")
25
+ leading_zeros = len(text) - len(text.lstrip("1"))
26
+ return b"\x00" * leading_zeros + body
27
+
28
+
29
+ def validate_public_key(text: str) -> str:
30
+ """Return ``text`` if it is a well-formed Solana public key, else raise ``InvalidAddressError``.
31
+
32
+ Seed phrases (words with spaces) and 64-byte secret keys (87-88 base58 characters) are rejected
33
+ by construction: only a 32-byte value passes.
34
+ """
35
+ if not isinstance(text, str) or not 32 <= len(text) <= 44:
36
+ raise InvalidAddressError("a Solana public key is 32-44 base58 characters")
37
+ if len(base58_decode(text)) != 32:
38
+ raise InvalidAddressError("not a 32-byte public key")
39
+ return text
@@ -0,0 +1,116 @@
1
+ """DLMM bin math, from the official formulas page.
2
+
3
+ Source: https://docs.meteora.ag/core-products/dlmm/formulas.md (DOCUMENTED).
4
+
5
+ P_i = (1 + bin_step / 10_000) ** i price of bin ``i``, raw units (Y lamports per X lamport)
6
+ UI price = P_i * 10 ** (decimals_x - decimals_y)
7
+
8
+ The program uses Q64.64 fixed point; here we use a 60-digit Decimal context, which is exact enough
9
+ that the round trip ``bin_id_from_price(bin_price(i)) == i`` holds for the whole program range
10
+ (verified in tests) -- but it is NOT bit-identical to the program's fixed-point result, so these
11
+ prices are DERIVED, never "the on-chain value".
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from decimal import ROUND_CEILING, ROUND_FLOOR, Context, Decimal
18
+
19
+ #: Bins per BinArray account (accounts.md).
20
+ MAX_BIN_PER_ARRAY = 70
21
+ BASIS_POINTS = Decimal(10_000)
22
+
23
+ _CTX = Context(prec=60)
24
+
25
+
26
+ def _base(bin_step: int) -> Decimal:
27
+ if bin_step <= 0:
28
+ raise ValueError(f"bin_step must be positive, got {bin_step}")
29
+ return _CTX.add(Decimal(1), _CTX.divide(Decimal(bin_step), BASIS_POINTS))
30
+
31
+
32
+ def decimals_scale(decimals_x: int, decimals_y: int) -> Decimal:
33
+ """Multiplier from raw price (Y lamports per X lamport) to UI price (Y per X)."""
34
+ return Decimal(10) ** (decimals_x - decimals_y)
35
+
36
+
37
+ def raw_bin_price(bin_id: int, bin_step: int) -> Decimal:
38
+ return _CTX.power(_base(bin_step), bin_id)
39
+
40
+
41
+ def bin_price(bin_id: int, bin_step: int, decimals_x: int, decimals_y: int) -> Decimal:
42
+ """UI price (token Y per token X) of ``bin_id``."""
43
+ return _CTX.multiply(raw_bin_price(bin_id, bin_step), decimals_scale(decimals_x, decimals_y))
44
+
45
+
46
+ def bin_id_from_price(
47
+ price: Decimal,
48
+ bin_step: int,
49
+ decimals_x: int,
50
+ decimals_y: int,
51
+ *,
52
+ rounding: str = ROUND_FLOOR,
53
+ ) -> int:
54
+ """Bin id at or below ``price`` (ROUND_FLOOR) or at or above it (ROUND_CEILING)."""
55
+ if price <= 0:
56
+ raise ValueError("price must be positive")
57
+ if rounding not in (ROUND_FLOOR, ROUND_CEILING):
58
+ raise ValueError("rounding must be ROUND_FLOOR or ROUND_CEILING")
59
+ raw = _CTX.divide(price, decimals_scale(decimals_x, decimals_y))
60
+ quotient = _CTX.divide(_CTX.ln(raw), _CTX.ln(_base(bin_step)))
61
+ estimate = int(quotient.to_integral_value(ROUND_FLOOR))
62
+ # Settle the boundary exactly: price(i) <= raw < price(i + 1) for the floor bin.
63
+ bin_id = estimate
64
+ while raw_bin_price(bin_id, bin_step) > raw:
65
+ bin_id -= 1
66
+ while raw_bin_price(bin_id + 1, bin_step) <= raw:
67
+ bin_id += 1
68
+ if rounding == ROUND_CEILING and raw_bin_price(bin_id, bin_step) < raw:
69
+ bin_id += 1
70
+ return bin_id
71
+
72
+
73
+ def bin_array_index(bin_id: int) -> int:
74
+ """Index of the BinArray covering ``bin_id`` (floor division, also for negative ids)."""
75
+ return bin_id // MAX_BIN_PER_ARRAY
76
+
77
+
78
+ def bins_in_range(lower_bin_id: int, upper_bin_id: int) -> int:
79
+ if upper_bin_id < lower_bin_id:
80
+ raise ValueError("upper_bin_id < lower_bin_id")
81
+ return upper_bin_id - lower_bin_id + 1
82
+
83
+
84
+ def width_pct(lower_bin_id: int, upper_bin_id: int, bin_step: int) -> Decimal:
85
+ """Price span of a bin range as a percentage of the lower bound (DERIVED)."""
86
+ span = _CTX.divide(raw_bin_price(upper_bin_id, bin_step), raw_bin_price(lower_bin_id, bin_step))
87
+ return _CTX.multiply(span - Decimal(1), Decimal(100))
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class BinRange:
92
+ lower_bin_id: int
93
+ upper_bin_id: int
94
+
95
+ def __post_init__(self) -> None:
96
+ if self.upper_bin_id < self.lower_bin_id:
97
+ raise ValueError("upper_bin_id < lower_bin_id")
98
+
99
+ @property
100
+ def count(self) -> int:
101
+ return self.upper_bin_id - self.lower_bin_id + 1
102
+
103
+ def contains(self, bin_id: int) -> bool:
104
+ return self.lower_bin_id <= bin_id <= self.upper_bin_id
105
+
106
+
107
+ def range_from_prices(
108
+ lower_price: Decimal, upper_price: Decimal, bin_step: int, decimals_x: int, decimals_y: int
109
+ ) -> BinRange:
110
+ """Smallest bin range whose prices cover [lower_price, upper_price] (UI prices)."""
111
+ if upper_price < lower_price:
112
+ raise ValueError("upper_price < lower_price")
113
+ return BinRange(
114
+ bin_id_from_price(lower_price, bin_step, decimals_x, decimals_y, rounding=ROUND_FLOOR),
115
+ bin_id_from_price(upper_price, bin_step, decimals_x, decimals_y, rounding=ROUND_CEILING),
116
+ )