Skip to content

Float safety: Kalshi normalizer mid-price (ask + bid) / 2 parseFloat arithmetic #286

@realfishsam

Description

@realfishsam

Risk Level

MEDIUM

Location

core/src/exchanges/kalshi/normalizer.ts:35

Code

} else if (market.yes_ask_dollars != null && market.yes_bid_dollars != null) {
    price = (parseFloat(market.yes_ask_dollars) + parseFloat(market.yes_bid_dollars)) / 2;

Problem

parseFloat converts the API's dollar strings to IEEE 754 floats, then addition and division by 2 compound the error. The derived price is stored as the market's current price and used for display and downstream routing comparisons.

Mid-point calculation is inherently imprecise with floats: (a + b) / 2 for two floats a and b can overflow the midpoint or produce a result outside [a, b] when the values are very close.

Example Failure

yes_ask_dollars = "0.5550", yes_bid_dollars = "0.5450"
parseFloat("0.5550") = 0.555
parseFloat("0.5450") = 0.545
(0.555 + 0.545) / 2 = 1.1 / 2 = 0.55  (exact here)

yes_ask_dollars = "0.3330", yes_bid_dollars = "0.3320"
(0.333 + 0.332) / 2 = 0.665 / 2 = 0.3325  (may drift: 0.33250000000000002)

Suggested Fix

import Decimal from 'decimal.js';
price = new Decimal(market.yes_ask_dollars).plus(market.yes_bid_dollars).dividedBy(2).toNumber();

Found by automated float safety audit

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions