⚡ Batch fetch kalshi markets in _sell_bet_positions to fix N+1 query issue - #5
⚡ Batch fetch kalshi markets in _sell_bet_positions to fix N+1 query issue#5j8asic wants to merge 1 commit into
Conversation
Replaces the N+1 query pattern inside the _sell_bet_positions loop with a single batched fetch using Kalshi's /markets?tickers= endpoint. This dramatically improves performance when selling multi-leg bets or when holding multiple positions. Co-authored-by: j8asic <10575972+j8asic@users.noreply.github.com>
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
💡 What: The optimization implemented
Replaced the
kalshi._get(f"/markets/{ticker}")loop inside_sell_bet_positionswith a single batched fetch using the Kalshi/markets?tickers=...endpoint before entering the ticker loop. We extract all potential tickers fromkalshi_ids, batch-fetch their current prices in one API call, store them in a dictionary, and then retrieve them natively from memory in the loop.🎯 Why: The performance problem it solves
The original code suffered from an N+1 query problem, making a separate HTTP request for every single market ticker and side pair we held a position in. With network delays, selling positions for a bet with multiple legs (or just multiple sides of the same ticker) sequentially introduces significant unnecessary latency, which is problematic when taking/exiting positions on a live order book where prices change quickly.
📊 Measured Improvement:
A baseline benchmark (
benchmark_sell_positions.py) was created to simulate holding positions in 5 tickers (across 2 sides, so 10 total checks).kalshi._getcalls simulated at 50ms each)kalshi._getcall simulated at 50ms)PR created automatically by Jules for task 7070254410738313747 started by @j8asic