Skip to content

Order generation & placement - #1

Merged
moconnell merged 9 commits into
masterfrom
dev
May 14, 2026
Merged

Order generation & placement#1
moconnell merged 9 commits into
masterfrom
dev

Conversation

@moconnell

@moconnell moconnell commented May 14, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Full order placement and execution implementation with automatic risk validation.
    • Wallet balance and holdings retrieval from exchange.
    • Order generation and submission integrated into main execution loop.
  • Improvements

    • Structured logging and tracing added throughout the application for better observability.
    • Environment configuration template provided with all required settings.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 14, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@moconnell has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 21 minutes and 46 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 044634cd-6dee-4238-9789-fb437538c3f7

📥 Commits

Reviewing files that changed from the base of the PR and between 5d4869e and e6c7fe2.

📒 Files selected for processing (8)
  • .env.example
  • README.md
  • src/config.rs
  • src/execution.rs
  • src/main.rs
  • src/order_state.rs
  • src/weights.rs
  • tests/hyperliquid_market_data.rs
📝 Walkthrough

Walkthrough

This PR implements a complete, event-driven order execution system that integrates market data, portfolio allocation, and exchange order submission. The architecture wires Hyperliquid API clients for wallet queries and order placement, generates buy orders proportional to dynamically-weighted portfolio allocations, validates orders against risk constraints, and executes them while maintaining structured observability throughout.

Changes

Event-Driven Order Execution System

Layer / File(s) Summary
Dependencies and Configuration
Cargo.toml, src/.env.example
Added rand for weight randomization and tracing/tracing-subscriber for structured JSON logging; environment template documents Hyperliquid API credentials, network flags, order limits, and logging configuration.
Wallet Holdings API
src/exchanges/hyperliquid/balances.rs, src/exchanges/hyperliquid/client.rs
New balances module exports get_wallet_holdings() to fetch wallet positions from Hyperliquid and convert them to WalletHolding instances; HyperliquidClient.get_wallet_holdings() now delegates to this module.
Order Placement API
src/exchanges/hyperliquid/orders.rs, src/exchanges/hyperliquid/client.rs
New orders module exports place_order() to validate order parameters, submit limit orders to Hyperliquid, and map exchange responses into internal OrderStatus values (including parsing fill prices and detecting rejections); HyperliquidClient.place_order() now delegates to this module.
Module Structure
src/exchanges/hyperliquid/mod.rs, src/lib.rs
Updated Hyperliquid module to declare and wire balances and orders submodules alongside the client; crate root exports new weights module.
Portfolio Weight Allocation
src/weights.rs
New module exports get_target_weights() to generate random, normalized per-symbol weights (summing to 1.0) and SymbolWeights type alias for allocation maps.
Order Generation Pipeline
src/order_state.rs
Complete implementation: periodic async task fetches weights, reads latest market data from watch receiver, generates buy orders sized as (max_order_usd * weight) / ask_price, publishes via watch sender; skips symbols with missing market data or non-positive weights; adds unit tests and expands OrderStatus derives to include Debug and PartialEq.
Execution & Validation
src/execution.rs
Replaced placeholder loop with event-driven async executor: watches for order changes, looks up market data, validates orders via risk module, submits to exchange client, logs outcomes; handles market data unavailability and risk rejection with structured warnings.
Observability & Tracing
src/main.rs, src/market_data.rs, src/risk.rs, src/exchanges/hyperliquid/market_data.rs
Added init_tracing() in main.rs to configure JSON structured logging from environment or config; market data subscription and message loops emit lifecycle logs; risk and order status enums now derive Debug for formatted output.

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant OrderState as Order State<br/>Generator
  participant Weights
  participant MarketData
  participant Execution
  participant RiskValidator
  participant Exchange
  participant Log
  
  App->>OrderState: spawn run()
  loop Every tick
    OrderState->>Weights: get_target_weights()
    Weights-->>OrderState: SymbolWeights (normalized)
    OrderState->>MarketData: borrow latest MarketState
    MarketData-->>OrderState: ask prices per symbol
    OrderState->>OrderState: generate orders<br/>(size = max_usd * weight / ask)
    OrderState->>Execution: send proposed order
    Execution->>MarketData: lookup symbol data
    Execution->>RiskValidator: validate_order()
    alt Validation passes
      RiskValidator-->>Execution: Accept
      Execution->>Exchange: place_order()
      Exchange-->>Execution: OrderStatus
      Execution->>Log: info! success
    else Validation fails
      RiskValidator-->>Execution: Reject
      Execution->>Log: warn! rejection
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Hops through the market with weighted grace,
Orders cascade at racing pace,
Weights and validation, logs galore,
Each trade now watched from core to store!
The pipeline's live—let execution soar!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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.
Title check ✅ Passed The title directly and concisely summarizes the main changes: implementing order generation and placement functionality across multiple modules.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dev

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR adds an initial end-to-end execution path: subscribe to market data, periodically generate target-weight-based proposed orders, validate them with basic risk checks, and (optionally) submit them to Hyperliquid. It also introduces structured logging via tracing and factors out Hyperliquid balance/order logic into dedicated modules.

Changes:

  • Added a weights module to produce normalized target symbol weights.
  • Implemented an order producer (order_state::run) and a consumer/executor loop (execution::run_loop) with risk validation.
  • Added tracing initialization and replaced ad-hoc logging with structured tracing events; implemented Hyperliquid order placement and balance fetching helpers.

Reviewed changes

Copilot reviewed 14 out of 15 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/weights.rs New module to generate normalized per-symbol target weights.
src/order_state.rs Generates proposed orders from weights + market state and publishes them.
src/execution.rs Consumes proposed orders, validates with risk, and submits to the exchange client.
src/risk.rs Adds Debug derive for RiskReject to improve structured logging.
src/market_data.rs Uses tracing for lifecycle/error logging around subscription.
src/main.rs Initializes tracing and wires market data + order state + execution loop together.
src/lib.rs Exposes the new weights module.
src/exchanges/hyperliquid/orders.rs New Hyperliquid order placement implementation + response mapping.
src/exchanges/hyperliquid/balances.rs New helper for wallet holdings retrieval.
src/exchanges/hyperliquid/client.rs Routes holdings/orders through new helper modules; enables real order placement.
src/exchanges/hyperliquid/market_data.rs Adds structured logging around stream lifecycle and updates.
src/exchanges/hyperliquid/mod.rs Registers new balances and orders modules.
src/.env.example Adds an example environment configuration.
Cargo.toml / Cargo.lock Adds rand, tracing, and tracing-subscriber dependencies.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/order_state.rs Outdated
Comment thread src/weights.rs Outdated
Comment thread src/execution.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@src/order_state.rs`:
- Around line 118-128: The current use of a watch channel where you call
order_tx.send(OrderState { proposed_order: Some(order) }) can silently drop
intermediate orders under load because watch only keeps the latest value; change
the channel to an mpsc queue so each individual order is delivered. Replace the
watch sender/receiver types with tokio::sync::mpsc::Sender/Receiver (or bounded
channel) wherever order_tx and its receiver are created/used, update OrderState
usage so each message represents one order (e.g., send the order itself or
OrderState with a single order), and adjust the consumer logic to await recv()
in a loop instead of reading the watch; ensure backpressure/closure handling
mirrors the previous is_err() check.
🪄 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: ab32baef-5a95-4370-8680-167ffa0da9ce

📥 Commits

Reviewing files that changed from the base of the PR and between b6bc9af and 5d4869e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (14)
  • Cargo.toml
  • src/.env.example
  • src/exchanges/hyperliquid/balances.rs
  • src/exchanges/hyperliquid/client.rs
  • src/exchanges/hyperliquid/market_data.rs
  • src/exchanges/hyperliquid/mod.rs
  • src/exchanges/hyperliquid/orders.rs
  • src/execution.rs
  • src/lib.rs
  • src/main.rs
  • src/market_data.rs
  • src/order_state.rs
  • src/risk.rs
  • src/weights.rs

Comment thread src/order_state.rs Outdated
@socket-security

socket-security Bot commented May 14, 2026

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedtracing-subscriber@​0.3.239910093100100

View full report

@moconnell moconnell changed the title add implementation Order generation & placement May 14, 2026
@moconnell
moconnell merged commit f894a76 into master May 14, 2026
3 checks passed
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.

3 participants