Tutorial: OpenAI Codex Multi-Agent Trading on Hyperliquid

This advanced tutorial walks through building a two-tier autonomous trading system using OpenAI Codex: a GPT-5.4-mini sub-agent polls live Hyperliquid positions every 30 seconds and packages them into a compact JSON digest, which a GPT-5.5 main agent reads to issue hold, hedge, or scale decisions. You'll configure the heartbeat loop, apply a STAND_DOWN safety gate, and test adaptive hedging and position scaling against live signals.


0

Building a Multi-Agent AI Trading Heartbeat on Hyperliquid

Feeding raw WebSocket data into a large model on every monitoring cycle burns tokens and kills loop latency — the wrong architecture for live position management. This tutorial walks you through a two-tier Codex system: a lightweight GPT-5.4-mini sub-agent that polls live Hyperliquid position data and packages it into a compact JSON digest, and a GPT-5.5 main agent that reads that digest, evaluates P&L against a defined goal, and issues a trading decision every 30 seconds. By the end, you’ll have a working autonomous heartbeat loop capable of holding, hedging, and scaling positions in response to live signals.

Full agent data-flow: the sub-agent polls WebSocket data, packages it into a heartbeat JSON, and feeds it to the main Codex decision agent
Full agent data-flow: the sub-agent polls WebSocket data, packages it into a heartbeat JSON, and feeds it to the main Codex decision agent
  1. Create a file named heartbeat_trade.md in your agent repo directory. This markdown file defines both agents — the main agent model (GPT-5.5 high), the sub-agent model (GPT-5.4-mini), the 30-second refresh cadence, the read-only constraint on the sub-agent, and the JSON digest format the main agent expects as input. This file is the single source of truth Codex reads on startup to configure the entire system.

  2. From your terminal, launch Codex in YOLO mode against your agent directory:

bash
codex --yolo

Codex initialises on GPT-5.5 high. Verify the sub-agent configuration immediately by asking: “Explain the sub-agent — what model is it running and what is its task?” Codex confirms the sub-agent is named trade_data_reporter, runs on GPT-5.4-mini, and is strictly read-only: it reports position facts but cannot queue trades, edit files, or call exchange APIs.

Warning: this step may differ from current official documentation — see the verified version below.

Launch Codex in YOLO mode against the hyperliq2 agent repo: `codex --yolo` with gpt-5.5 high gives the agent autonomous execution rights
Launch Codex in YOLO mode against the hyperliq2 agent repo: `codex –yolo` with gpt-5.5 high gives the agent autonomous execution rights
Hard capability boundary: the sub-agent reads 12+ data points but cannot edit files, queue trades, or call exchange APIs — the main agent owns all decisions
Hard capability boundary: the sub-agent reads 12+ data points but cannot edit files, queue trades, or call exchange APIs — the main agent owns all decisions
  1. Issue a natural-language trade command that includes instrument, margin, leverage, and a concrete profit goal:

“Set a $50 margin SP500 short, 10x leverage. Goal is $1 profit in 30 minutes.”

The goal is load-bearing: the main agent calibrates every heartbeat decision against it. A $1 target on $50 margin demands a different risk posture than a $10 target on the same position.

  1. Codex surfaces a STAND_DOWN safety gate before placing any order: “What is the maximum acceptable loss in dollars for this trade?” Provide your actual risk ceiling — $100 in the demo. The agent treats this as both a loss limit and a stop-placement reference and will not proceed without it.
STAND_DOWN safety gate: the agent requires an explicit max-loss dollar figure before placing any live order — it won't proceed without a defined risk ceiling
STAND_DOWN safety gate: the agent requires an explicit max-loss dollar figure before placing any live order — it won’t proceed without a defined risk ceiling
  1. The agent calculates position sizing against the live SP500 price (~7,595): $50 margin at 10x yields ~$500 notional, requiring a ~15.4-point move to hit the $1 take-profit. It reads risk_profile.py, sets initial stop placement, then writes a timestamped SP500 short intent to the queue and submits it via agent_execute.py. Hyperliquid confirms: 0.065 contracts short at entry 7,591.7, native reduce-only TP and stop orders in place.

  2. Immediately after confirming the live position, Codex spawns trade_data_reporter on GPT-5.4-mini. The sub-agent connects to the Hyperliquid WebSocket, reads position side, size, entry, mark price, P&L, liquidation distance, funding, and pending intents, then compacts everything into live_heartbeat.json.

Trade confirmed live and sub-agent spawned: short 0.065 SP500 at entry 7591.7 with native TP/stop in place — trade_data_reporter (gpt-5.4-mini) begins its 30-second monitoring loop
Trade confirmed live and sub-agent spawned: short 0.065 SP500 at entry 7591.7 with native TP/stop in place — trade_data_reporter (gpt-5.4-mini) begins its 30-second monitoring loop
  1. The main agent reads the JSON digest, validates data freshness, and issues its first heartbeat decision: P&L is +$0.10, distance to target is ~$0.90, native orders intact — hold. It calls agent_trade_control.py --decision hold --sleep-sec 30, logs {"ok": true, "logged": "hold"}, and the loop restarts.
First heartbeat decision loop complete: sub-agent reports +$0.10 PnL, main agent validates freshness and logs 'hold' — the 30-second autonomous cycle is live
First heartbeat decision loop complete: sub-agent reports +$0.10 PnL, main agent validates freshness and logs ‘hold’ — the 30-second autonomous cycle is live
  1. To test adaptive reasoning, send a hedge query: “How would you solve a hedge signal on the current trade with our goal in mind?” The agent rejects going long SP500 against a short SP500 position as self-cancelling. Instead it selects Nvidia as a correlated equity hedge at a 25% ratio and executes a 5x long Nvidia position on Hyperliquid.

  2. To test position scaling, instruct: “Exit the Nvidia hedge, double the margin on SP500 — signal is strong.” The agent closes the Nvidia long and opens an additional $50 same-side short on SP500 at 10x, bringing combined margin to ~$98. Issuing an exit-all command closes both legs and ends the demo cleanly.

How does this compare to the official docs?

The system runs end-to-end, but the YOLO execution flag, the model identifiers used throughout, and the Hyperliquid WebSocket integration pattern each warrant verification against current OpenAI Codex CLI and Hyperliquid API documentation — which is exactly where Act 2 picks up.

Here’s What the Official Docs Show

The video delivers a working architecture with the right structural instincts — the two-tier agent design and WebSocket data approach are both sound. These notes fill in two model identifiers that have drifted from their documented names and add one production-critical WebSocket requirement the tutorial’s polling loop leaves unaddressed.

Step 1 — Create heartbeat_trade.md

No official documentation was found for this step —
proceed using the video’s approach and verify independently.

OpenAI Agents SDK documentation page failed to load — no content retrievable
📄 OpenAI Agents SDK documentation page failed to load — no content retrievable

Step 2 — Launch Codex and verify agent configuration

The main/sub-agent model split the video recommends is architecturally correct. As of June 1, 2026, the correct identifier for the main agent is gpt-5.5 — the video’s GPT 5.5 high does not appear anywhere in the official model listing. The sub-agent model shown reflects a gpt-4.1-mini-style name that has since been superseded; the documented identifier for the lower-latency variant is gpt-5.4-mini. The OpenAI Models page states it plainly: “Start with gpt-5.5 for complex reasoning and coding, or choose gpt-5.4-mini and gpt-5.4-nano for lower-latency, lower-cost workloads” — the pairing logic maps perfectly, only the string values need updating in your config.

OpenAI Models page — Choosing a Model section recommending gpt-5.5 as flagship and gpt-5.4-mini / gpt-5.4-nano for lower-latency workloads
📄 OpenAI Models page — Choosing a Model section recommending gpt-5.5 as flagship and gpt-5.4-mini / gpt-5.4-nano for lower-latency workloads
OpenAI Models page — Frontier models section showing gpt-5.5 and gpt-5.4 model cards with capability guidance text
📄 OpenAI Models page — Frontier models section showing gpt-5.5 and gpt-5.4 model cards with capability guidance text

Steps 3–6 — Trade command, safety gate, position sizing, sub-agent spawn

No official documentation was found for these steps —
proceed using the video’s approach and verify independently.

Hyperliquid homepage — 'The Blockchain To House All Finance' hero with Start Trading and Start Building CTAs
📄 Hyperliquid homepage — ‘The Blockchain To House All Finance’ hero with Start Trading and Start Building CTAs

Step 7 — Heartbeat decision loop

The video’s approach here matches the current docs exactly on the core data-fetching mechanism: wss://api.hyperliquid.xyz/ws is the correct mainnet endpoint, and subscription-based streaming is the documented pattern for live position data. One production requirement the tutorial doesn’t surface: Hyperliquid’s WebSocket docs explicitly state that “all automated users should handle disconnects from the server side and gracefully reconnect,” with snapshot acknowledgment available to recover data missed during a dropped connection. Wrap your WebSocket client in reconnect logic before running this against real capital. Also note: the position-specific subscription types trade_data_reporter relies on are documented in the separate Subscriptions page, which was not captured here — verify those subscription schemas directly before deployment.

Hyperliquid WebSocket API docs — endpoint URLs for mainnet (wss://api.hyperliquid.xyz/ws) and testnet, with wscat connection example
📄 Hyperliquid WebSocket API docs — endpoint URLs for mainnet (wss://api.hyperliquid.xyz/ws) and testnet, with wscat connection example
Hyperliquid WebSocket docs — Connecting section showing disconnect/reconnect requirement and TypeScript/Python SDK availability
📄 Hyperliquid WebSocket docs — Connecting section showing disconnect/reconnect requirement and TypeScript/Python SDK availability

Steps 8–12 — Hedge query, position scaling, exit

No official documentation was found for these steps —
proceed using the video’s approach and verify independently.

  1. Models | OpenAI API — Official model listing confirming gpt-5.5 and gpt-5.4-mini as the current documented frontier model identifiers for the main agent and sub-agent respectively.
  2. Agents SDK | OpenAI API — OpenAI Agents SDK documentation covering orchestration patterns and Codex CLI configuration (page failed to load at capture time — verify directly at the source).
  3. Websocket | Hyperliquid Docs — Hyperliquid WebSocket API reference covering endpoint URLs, subscription protocol, and the mandatory disconnect/reconnect requirement for all automated clients.
  4. Hyper Foundation — Hyperliquid platform homepage with entry points to the live trading interface and the developer documentation hub.

Like it? Share with your friends!

0

What's Your Reaction?

hate hate
0
hate
confused confused
0
confused
fail fail
0
fail
fun fun
0
fun
geeky geeky
0
geeky
love love
0
love
lol lol
0
lol
omg omg
0
omg
win win
0
win

0 Comments

Your email address will not be published. Required fields are marked *