Skip to content

Scale k-prefix hyperqliquid prices by 1000#5168

Merged
IvanIvanoff merged 1 commit into
masterfrom
add-decimals-to-k-hyperliquid
May 19, 2026
Merged

Scale k-prefix hyperqliquid prices by 1000#5168
IvanIvanoff merged 1 commit into
masterfrom
add-decimals-to-k-hyperliquid

Conversation

@IvanIvanoff
Copy link
Copy Markdown
Member

@IvanIvanoff IvanIvanoff commented May 19, 2026

Changes

Ticket

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • I have tried to find clearer solution before commenting hard-to-understand parts of code
  • I have added tests that prove my fix is effective or that my feature works

Summary by CodeRabbit

  • New Features

    • Asset-specific scaling applied to per-row bid/ask prices and volumes (assets with a lowercase "k" prefix are rescaled while others remain unchanged), preserving notional and mid/weighted-mid consistency
    • Added source-slug lookup to determine scaling rules
  • Tests

    • New tests verifying scaling behavior, preservation of notional, nil-handling, and prefix case sensitivity

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 19, 2026

📝 Walkthrough

Walkthrough

Adds source-slug lookup and per-asset scaling to Hyperliquid BBO timeseries: mapped slugs starting with "k" use factor 1000 to rescale bid/ask price and volume before mid and weighted-mid computations.

Changes

Hyperliquid BBO Scaling

Layer / File(s) Summary
Source slug lookup
lib/sanbase/project/source_slug_mapping.ex
New get_source_slug/2 performs an Ecto join to return the mapping slug for a project slug and source or nil.
BBO timeseries scaling implementation
lib/sanbase/hyperliquid/bbo/bbo_prices.ex
Module aliases SourceSlugMapping, sets @source, derives k_factor from the mapped slug, applies scale_price/2 and scale_volume/2 per row (k-prefixed => factor 1000), then computes mid_price and weighted_mid_price from scaled values.
Tests: k-prefix scaling
test/sanbase/hyperliquid/bbo/bbo_prices_test.exs
Adds Factory import and SourceSlugMapping seeding plus tests that verify scaling for lowercase k slugs, no scaling for non-k/uppercase K, and preservation of notional and nil sides.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I found a tiny "k" in a stream so wide,
I nudged the prices so mid-prices glide.
Thousandfold whisper, now numbers align,
carrots and code in a neat little line 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: scaling k-prefix Hyperliquid prices by a factor of 1000, which is the core functionality added across all modified files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add-decimals-to-k-hyperliquid

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
lib/sanbase/hyperliquid/bbo/bbo_prices.ex (2)

88-93: ⚡ Quick win

Use function-head pattern matching for scale/2.

This keeps the helper idiomatic and simpler.

Refactor
-  defp scale(value, divisor) do
-    case value do
-      nil -> nil
-      _ -> value / divisor
-    end
-  end
+  defp scale(nil, _divisor), do: nil
+  defp scale(value, divisor), do: value / divisor

As per coding guidelines, "Use pattern matching in function heads for control flow".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/sanbase/hyperliquid/bbo/bbo_prices.ex` around lines 88 - 93, Replace the
runtime case branch in scale/2 with function-head pattern matching: add a clause
scale(nil, _divisor) that returns nil and a second clause scale(value, divisor)
that returns value / divisor, keeping the exact semantics of the existing helper
(function name: scale/2).

68-80: ⚡ Quick win

Move this rationale to docs instead of inline comments.

Please place this explanation in @moduledoc/@doc rather than # comments.

As per coding guidelines, "Avoid adding comments to code".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/sanbase/hyperliquid/bbo/bbo_prices.ex` around lines 68 - 80, Move the
long inline comment about Hyperliquid "k" prefix handling out of the body
comments and into the module or function documentation: add this rationale to
the module `@moduledoc` (or the relevant `@doc` for the functions in the BboPrices
module that perform the 1/1000 adjustment) and remove the inlined # comment
block. Ensure the `@moduledoc/`@doc mentions the "k" prefix convention, the 1/1000
normalization rule, and why matching on name prefix is used (so readers and
generated docs retain the explanation), keeping the code files free of large
inline comments.
lib/sanbase/project/source_slug_mapping.ex (1)

56-59: ⚡ Quick win

Add an iex example to this public function doc.

The new public API is documented, but it still needs an example usage block.

Suggested doc update
   `@doc` ~s"""
   Return the source slug (as known to `source`) for the project identified by
   `project_slug` (Sanbase slug), or `nil` if no mapping exists.
+
+  ## Examples
+      iex> Sanbase.Project.SourceSlugMapping.get_source_slug("bitcoin", "hyperliquid")
+      "BTC"
   """

As per coding guidelines, "Include examples in documentation for public functions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/sanbase/project/source_slug_mapping.ex` around lines 56 - 59, Add an iex
doctest example to the public function's `@doc` for the SourceSlugMapping module:
update the docstring for the function (likely source_slug/1) to include an
"iex>" example that demonstrates calling
SourceSlugMapping.source_slug("project_slug") and shows the expected return (a
source slug string or nil) so the documentation contains a runnable usage
example and covers both a successful mapping and a nil result.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/sanbase/hyperliquid/bbo/bbo_prices.ex`:
- Around line 47-55: The current ClickhouseRepo.query_transform callback is
scaling both prices and volumes using divisor(slug), which incorrectly alters
book sizes; update the transform so only bid_price and ask_price are passed
through scale(divisor) and leave bid_volume and ask_volume unchanged (or apply
separate, explicit volume-normalization logic if needed); locate the transform
lambda used in ClickhouseRepo.query_transform and remove or replace the
scale(...) calls for bid_volume and ask_volume so only the price values are
scaled.

---

Nitpick comments:
In `@lib/sanbase/hyperliquid/bbo/bbo_prices.ex`:
- Around line 88-93: Replace the runtime case branch in scale/2 with
function-head pattern matching: add a clause scale(nil, _divisor) that returns
nil and a second clause scale(value, divisor) that returns value / divisor,
keeping the exact semantics of the existing helper (function name: scale/2).
- Around line 68-80: Move the long inline comment about Hyperliquid "k" prefix
handling out of the body comments and into the module or function documentation:
add this rationale to the module `@moduledoc` (or the relevant `@doc` for the
functions in the BboPrices module that perform the 1/1000 adjustment) and remove
the inlined # comment block. Ensure the `@moduledoc/`@doc mentions the "k" prefix
convention, the 1/1000 normalization rule, and why matching on name prefix is
used (so readers and generated docs retain the explanation), keeping the code
files free of large inline comments.

In `@lib/sanbase/project/source_slug_mapping.ex`:
- Around line 56-59: Add an iex doctest example to the public function's `@doc`
for the SourceSlugMapping module: update the docstring for the function (likely
source_slug/1) to include an "iex>" example that demonstrates calling
SourceSlugMapping.source_slug("project_slug") and shows the expected return (a
source slug string or nil) so the documentation contains a runnable usage
example and covers both a successful mapping and a nil result.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 59bcd0c1-90a4-4b18-b692-23192cab8488

📥 Commits

Reviewing files that changed from the base of the PR and between 9494222 and 2594f4b.

📒 Files selected for processing (2)
  • lib/sanbase/hyperliquid/bbo/bbo_prices.ex
  • lib/sanbase/project/source_slug_mapping.ex

Comment thread lib/sanbase/hyperliquid/bbo/bbo_prices.ex Outdated
@IvanIvanoff IvanIvanoff force-pushed the add-decimals-to-k-hyperliquid branch from c49909a to 1c8b45b Compare May 19, 2026 11:36
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
lib/sanbase/hyperliquid/bbo/bbo_prices.ex (1)

68-90: ⚡ Quick win

Move the long inline rationale out of code comments.

This block is valuable context, but it should live in tests/docs/PR notes rather than inline comments to stay consistent with repository standards.

Suggested minimal cleanup
-  # Hyperliquid quotes some low-priced assets per 1000 underlying tokens. The
-  # only signal is a lowercase "k" prefix on the coin name (e.g. "kPEPE",
-  # "kSHIB", "kBONK", "kLUNC", "kFLOKI"); the convention is "k" for kilo, so
-  # one quoted contract represents 1000 of the underlying. Raw fields from
-  # Hyperliquid are therefore:
-  #
-  #   * `px` — USD per 1000 underlying tokens
-  #   * `sz` — number of contracts (each = 1000 underlying tokens)
-  #
-  # To expose values in native-token units while preserving notional
-  # (`price * volume`), price is divided by 1000 and volume is multiplied by
-  # 1000 for k-prefixed coins.
-  #
-  # This convention is NOT formally documented in the Hyperliquid docs
-  # (perpetuals info endpoint, tick/lot size, contract specifications). The
-  # live `POST /info {"type":"meta"}` response exposes `name`, `szDecimals`,
-  # `maxLeverage`, `marginTableId`, `marginMode` per asset — none of which is
-  # a price/size multiplier. The encoding was verified empirically against
-  # `POST /info {"type":"l2Book","coin":"kPEPE"}`: a quoted `px=0.003691` with
-  # `sz=202527` gives notional `0.003691 * 202527 ≈ $748`, which only matches
-  # realistic order sizes if `px` is per 1000 PEPE and `sz` is in contracts.
-  # Matching on the name prefix is the only option short of hardcoding a list,
-  # which would go stale as Hyperliquid adds new k-assets.

As per coding guidelines: "Avoid adding comments to code."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/sanbase/hyperliquid/bbo/bbo_prices.ex` around lines 68 - 90, The long
rationale about Hyperliquid "k" (k-prefixed coins) currently embedded as a
multi-paragraph comment in bbo_prices.ex should be removed from the source and
relocated to an external doc or test/PR note (e.g., repository docs/ or test
fixtures) and replaced with a short one-line comment and a link/reference to
that external file; specifically, find the multi-line comment explaining px/sz
being per-1000 and the empirical verification and move that content to the
chosen doc, leaving a concise comment in the module (the existing k-prefixed
coins comment block) that points to the external doc for full rationale.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@lib/sanbase/hyperliquid/bbo/bbo_prices.ex`:
- Around line 68-90: The long rationale about Hyperliquid "k" (k-prefixed coins)
currently embedded as a multi-paragraph comment in bbo_prices.ex should be
removed from the source and relocated to an external doc or test/PR note (e.g.,
repository docs/ or test fixtures) and replaced with a short one-line comment
and a link/reference to that external file; specifically, find the multi-line
comment explaining px/sz being per-1000 and the empirical verification and move
that content to the chosen doc, leaving a concise comment in the module (the
existing k-prefixed coins comment block) that points to the external doc for
full rationale.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e0fad437-54ea-40a2-9878-f71a43138650

📥 Commits

Reviewing files that changed from the base of the PR and between 2594f4b and 1c8b45b.

📒 Files selected for processing (3)
  • lib/sanbase/hyperliquid/bbo/bbo_prices.ex
  • lib/sanbase/project/source_slug_mapping.ex
  • test/sanbase/hyperliquid/bbo/bbo_prices_test.exs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/sanbase/project/source_slug_mapping.ex

@IvanIvanoff IvanIvanoff merged commit f4ea04d into master May 19, 2026
3 checks passed
@IvanIvanoff IvanIvanoff deleted the add-decimals-to-k-hyperliquid branch May 19, 2026 11:53
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.

1 participant