How the AutoHedge Class Manages the End-to-End Trading Workflow

The AutoHedge class orchestrates autonomous trading by initializing a conversation context, delegating tasks to a Director agent that coordinates four specialist agents via hand-offs, and returning formatted results.

The AutoHedge class in The-Swarm-Corporation/AutoHedge serves as the central coordinator for algorithmic trading operations. This Python-based trading workflow engine automates market analysis and order generation by managing a multi-agent conversation system. Understanding how this class structures its execution pipeline reveals the architecture behind autonomous quantitative trading systems.

AutoHedge Class Architecture

The trading workflow implementation resides primarily in autohedge/main.py, where the AutoHedge class defines three distinct operational stages. Each stage handles specific responsibilities ranging from setup to result formatting.

Initialization Phase

The __init__ method (lines 15-32) establishes the foundation for the trading workflow by storing configuration parameters including name, description, output format, and output paths. It creates a dedicated output directory and instantiates a Conversation object that tracks the complete dialogue history between the user and AI agents. This persistent context ensures auditability and continuity across trading cycles.

Execution Cycle

The public run(task, *args, **kwargs) method (lines 33-60) initiates the core trading workflow cycle. When invoked, this method appends the user-provided task to the conversation history, then triggers the Director Agent with the identical task payload. The Director parses the request, discovers relevant tickers using DIRECTOR_TICKER_DISCOVERY_PROMPT, and delegates work to specialized sub-agents via the hand-offs mechanism. Each sub-agent executes with max_loops=1, returning analyses to the Director for aggregation into a comprehensive trading thesis.

Output Formatting

Depending on the output_type specified during instantiation—either list, dict, or str—the run method converts the accumulated conversation history into the requested format before returning it to the caller (lines 52-60). This flexibility allows the trading workflow to integrate with downstream systems requiring different data structures for order management or logging.

The Director Agent and Hand-off Mechanism

The Director Agent, defined in autohedge/workers.py (lines 80-86), functions as the workflow orchestrator. Built using the gpt-4.1 model for high-quality reasoning, it receives a system prompt combining DIRECTOR_PROMPT with a timestamp suffix (_SYSTEM_SUFFIX) to establish temporal context.

The critical architectural feature is the handoffs parameter, which receives ALL_AGENTS—a collection containing the four specialist agents. When the Director processes a task, it sequentially delegates to the Sentiment Agent, Quant Analyst, Risk Manager, and Execution Agent. This hand-off mechanism ensures each specialized function executes independently while the Director maintains overarching coordination of the trading workflow.

Specialist Agent Pipeline

The autonomous trading system leverages four domain-specific agents defined in autohedge/workers.py (lines 26-77). Each agent utilizes the gpt-4.1 model except where noted, and all share the timestamp suffix for synchronized temporal awareness.

Sentiment Analysis Agent

The Sentiment Agent parses news and social media data to generate sentiment scores using the SENTIMENT_PROMPT template. It operates on the lightweight gpt-4o-mini model, optimizing cost-efficiency for high-volume text processing tasks within the trading workflow.

Quantitative Analyst

The Quant Analyst produces numerical metrics including technical scores and volatility measures. Powered by gpt-4.1 and guided by QUANT_PROMPT, this agent transforms raw market data into actionable quantitative insights.

Risk Management Agent

The Risk Manager calculates position sizing, potential drawdowns, and market exposure metrics using RISK_PROMPT. This safety-critical component ensures the trading workflow adheres to predefined risk parameters before execution.

Execution Agent

The Execution Agent translates analytical outputs into concrete trade orders, specifying entry points, stop-loss levels, take-profit targets, and order types via EXECUTION_PROMPT. This final specialist converts strategic decisions into executable commands.

Implementation Example

The following implementation demonstrates the complete cycle from initialization to result retrieval:

from autohedge.main import AutoHedge

# Initialize with dictionary output format

hedger = AutoHedge(output_type="dict")

# Execute complete trading cycle

result = hedger.run(
    "Identify bullish opportunities in the US technology sector and suggest execution parameters."
)

print(result)  # Returns full conversation history as dictionary

This example creates an AutoHedge instance, executes a single trading cycle including all agent hand-offs, and outputs the structured dialogue containing the Director's aggregated thesis and individual agent analyses.

Summary

  • The AutoHedge class in autohedge/main.py serves as the primary coordinator for autonomous trading operations, managing conversation state and output formatting.
  • The trading workflow executes through the run() method, which invokes the Director Agent to parse tasks and discover tickers before delegating to specialists.
  • Four specialized agents—Sentiment, Quant, Risk, and Execution—process distinct aspects of market analysis via the hand-off mechanism defined in autohedge/workers.py.
  • The Director Agent (gpt-4.1) aggregates individual agent outputs into a comprehensive trading thesis with defined entry, exit, and risk parameters.
  • Flexible output types (list, dict, str) allow seamless integration with external trading systems and databases.

Frequently Asked Questions

What triggers the specialist agents in the AutoHedge trading workflow?

The Director Agent triggers specialist agents through a hand-off mechanism when its run() method processes a user task. After discovering relevant tickers using DIRECTOR_TICKER_DISCOVERY_PROMPT, the Director sequentially delegates to the Sentiment, Quant, Risk, and Execution agents, each configured with max_loops=1 to ensure single-pass processing before returning results for aggregation.

How does AutoHedge maintain context across multiple trading cycles?

The class maintains persistent context through a Conversation object instantiated during __init__ in autohedge/main.py. This object records all user inputs and agent outputs throughout the session, enabling the Director to reference previous analyses and maintain continuity across iterative trading workflow cycles.

Which components define the behavior of individual trading agents?

Agent behaviors are defined in autohedge/workers.py through specific prompt templates (SENTIMENT_PROMPT, QUANT_PROMPT, RISK_PROMPT, EXECUTION_PROMPT) combined with a shared _SYSTEM_SUFFIX timestamp. The Director Agent additionally uses DIRECTOR_PROMPT with gpt-4.1 reasoning capabilities to coordinate the overall trading workflow.

Can AutoHedge integrate with live trading systems?

While the source code in autohedge/main.py handles analysis and order generation through the Execution Agent, the output_type parameter supports list, dict, or str formats, allowing programmatic extraction of structured trade orders. Implementation of actual broker API connections would extend the current workflow beyond the scope of the core repository files.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →