DEV Community

Cover image for How to Turn TradingAgents into a Real Trading API Workflow
Preecha
Preecha

Posted on

How to Turn TradingAgents into a Real Trading API Workflow

TL;DR / Quick Answer

The fastest practical way to use TradingAgents in a team workflow is to run it as a Python package, wrap it with a small FastAPI service, and test that service in Apidog. This gives you a repeatable way to trigger analysis, poll for results, document the request contract, and share the setup with frontend, QA, and platform teammates.

Try Apidog today

Introduction

TradingAgents is easy to run as a local research project, but the harder problem is operationalizing it.

Most teams do not want a repository that only one developer can run from a terminal. They need a predictable workflow:

  1. Submit a ticker and analysis date.
  2. Return a job ID immediately.
  3. Poll for status and results.
  4. Document the request and response contract.
  5. Share the workflow with teammates without requiring them to debug Python internals.

Because trading research can influence real-money decisions, it is also safer to wrap TradingAgents in a controlled, documented API instead of leaving it as a one-off script on someone’s laptop.

Apidog fits this workflow well. You can import the OpenAPI schema from FastAPI, save environments for local and remote deployments, extract variables from responses, chain polling requests into a scenario, and publish documentation for the rest of your team.

What TradingAgents Is and Is Not

Before writing code, define the tool correctly.

Image

TradingAgents is an open-source multi-agent trading framework. The repository describes specialized roles that mirror a trading firm structure:

  • fundamentals, sentiment, news, and technical analysts
  • bullish and bearish researchers
  • a trader agent
  • risk management roles
  • a portfolio manager for the final decision

Image

The repository also states that the framework is built with LangGraph and supports multiple model providers, including OpenAI, Google, Anthropic, xAI, OpenRouter, and Ollama.

In the public default config, the project currently uses values such as:

llm_provider = "openai"
deep_think_llm = "gpt-5.2"
quick_think_llm = "gpt-5-mini"
backend_url = "https://api.openai.com/v1"
max_debate_rounds = 1
Enter fullscreen mode Exit fullscreen mode

That means you are working with a configurable Python framework, not a drop-in hosted SaaS API.

The repository is also clear about scope: TradingAgents is a research framework, not financial advice. Keep that framing visible in your internal docs and product UX.

Step 1: Install TradingAgents

Start with the repository setup:

git clone https://github.com/TauricResearch/TradingAgents.git
cd TradingAgents

conda create -n tradingagents python=3.13
conda activate tradingagents

pip install .
Enter fullscreen mode Exit fullscreen mode

If you want to build the API wrapper in this tutorial, also install FastAPI and Uvicorn:

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

The TradingAgents repository includes an .env.example with provider variables such as:

OPENAI_API_KEY=
GOOGLE_API_KEY=
ANTHROPIC_API_KEY=
XAI_API_KEY=
OPENROUTER_API_KEY=
Enter fullscreen mode Exit fullscreen mode

Depending on your model and data choices, you may also need other vendor credentials, such as Alpha Vantage.

Use two rules from the beginning:

  • Store credentials in environment variables or a secrets manager.
  • Do not pass provider secrets through your public API request body.

That separation keeps your Apidog environments cleaner and your security model safer.

Step 2: Run TradingAgents in Python First

Before building an API wrapper, confirm that the framework runs locally.

The README shows this minimal usage pattern:

from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG

ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())
_, decision = ta.propagate("NVDA", "2026-01-15")

print(decision)
Enter fullscreen mode Exit fullscreen mode

This is your first checkpoint. It confirms that your machine, dependencies, model provider, and credentials can execute a TradingAgents run.

Next, verify that config overrides work:

from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG

config = DEFAULT_CONFIG.copy()
config["llm_provider"] = "openai"
config["deep_think_llm"] = "gpt-5.2"
config["quick_think_llm"] = "gpt-5-mini"
config["max_debate_rounds"] = 2

ta = TradingAgentsGraph(debug=True, config=config)
_, decision = ta.propagate("NVDA", "2026-01-15")

print(decision)
Enter fullscreen mode Exit fullscreen mode

This tells you which values are reasonable candidates for an API request:

  • ticker
  • analysis_date
  • llm_provider
  • deep_think_llm
  • quick_think_llm
  • research depth or debate rounds

Do this before HTTP. If you skip the local Python phase, you will make debugging much harder.

Step 3: Choose an Integration Pattern

You have three common ways to use TradingAgents.

Option 1: CLI Only

The repository includes an interactive CLI where you can choose ticker, date, provider, and research depth.

Use this when:

  • you are learning the project
  • you are running solo experiments
  • you do not need a stable contract for another app

Do not stop here if you need a frontend, admin tool, shared service, or QA workflow.

Option 2: Python Only

Calling TradingAgentsGraph directly from Python is useful for notebooks, local automation, or custom scripts.

Use this when:

  • you need programmatic control
  • one developer owns the workflow end to end
  • you do not need a shared HTTP contract

This still falls short when multiple teams need to consume the workflow.

Option 3: API Wrapper Plus Apidog

For teams, this is usually the most practical setup.

You keep TradingAgents as the execution engine, expose it through FastAPI, and use Apidog to test and document the contract.

Use this when:

  • a frontend needs to trigger analysis
  • QA needs repeatable request flows
  • you want environments, assertions, and docs in one place
  • the workflow may run long enough that polling is better than a synchronous request

For most teams, this is where “how to use TradingAgents” becomes an implementation-ready answer.

Step 4: Wrap TradingAgents in a FastAPI Service

Use a job-based API for the first wrapper.

A multi-agent analysis can take long enough that holding one HTTP request open is awkward. A better pattern is:

POST /analyses        -> returns analysis_id
GET /analyses/{id}   -> returns queued, running, completed, or failed
Enter fullscreen mode Exit fullscreen mode

This is easier for browsers, easier for QA, and easier to document in Apidog.

Minimal API Contract

Endpoint Purpose
GET /health Basic health check
POST /analyses Trigger a TradingAgents run
GET /analyses/{analysis_id} Fetch job status and final result

FastAPI Wrapper Example

Create app.py:

from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime
from uuid import uuid4

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

from tradingagents.default_config import DEFAULT_CONFIG
from tradingagents.graph.trading_graph import TradingAgentsGraph

app = FastAPI(title="TradingAgents API", version="0.1.0")

executor = ThreadPoolExecutor(max_workers=2)
jobs: dict[str, dict] = {}

class AnalysisRequest(BaseModel):
    ticker: str = Field(..., min_length=1, examples=["NVDA"])
    analysis_date: date
    llm_provider: str = Field(default="openai")
    deep_think_llm: str = Field(default="gpt-5.2")
    quick_think_llm: str = Field(default="gpt-5-mini")
    research_depth: int = Field(default=1, ge=1, le=5)

def run_analysis(job_id: str, payload: AnalysisRequest) -> None:
    jobs[job_id]["status"] = "running"
    jobs[job_id]["started_at"] = datetime.utcnow().isoformat()

    config = DEFAULT_CONFIG.copy()
    config["llm_provider"] = payload.llm_provider
    config["deep_think_llm"] = payload.deep_think_llm
    config["quick_think_llm"] = payload.quick_think_llm
    config["max_debate_rounds"] = payload.research_depth
    config["max_risk_discuss_rounds"] = payload.research_depth

    try:
        graph = TradingAgentsGraph(debug=False, config=config)
        _, decision = graph.propagate(
            payload.ticker,
            payload.analysis_date.isoformat(),
        )

        jobs[job_id].update(
            {
                "status": "completed",
                "finished_at": datetime.utcnow().isoformat(),
                "result": decision,
            }
        )

    except Exception as exc:
        jobs[job_id].update(
            {
                "status": "failed",
                "finished_at": datetime.utcnow().isoformat(),
                "error": str(exc),
            }
        )

@app.get("/health")
def health() -> dict:
    return {"status": "ok"}

@app.post("/analyses", status_code=202)
def create_analysis(payload: AnalysisRequest) -> dict:
    analysis_id = str(uuid4())

    jobs[analysis_id] = {
        "status": "queued",
        "ticker": payload.ticker,
        "analysis_date": payload.analysis_date.isoformat(),
        "created_at": datetime.utcnow().isoformat(),
    }

    executor.submit(run_analysis, analysis_id, payload)

    return {"analysis_id": analysis_id, "status": "queued"}

@app.get("/analyses/{analysis_id}")
def get_analysis(analysis_id: str) -> dict:
    job = jobs.get(analysis_id)

    if not job:
        raise HTTPException(status_code=404, detail="Analysis not found")

    return job
Enter fullscreen mode Exit fullscreen mode

Start the service:

uvicorn app:app --reload
Enter fullscreen mode Exit fullscreen mode

FastAPI will expose:

http://localhost:8000/docs
http://localhost:8000/openapi.json
Enter fullscreen mode Exit fullscreen mode

The OpenAPI URL is important because Apidog can import it directly.

Step 5: Use TradingAgents Through the API

Now you can use TradingAgents through a stable HTTP workflow.

Trigger an Analysis

Send:

POST /analyses
Enter fullscreen mode Exit fullscreen mode

Example body:

{
  "ticker": "NVDA",
  "analysis_date": "2026-03-26",
  "llm_provider": "openai",
  "deep_think_llm": "gpt-5.2",
  "quick_think_llm": "gpt-5-mini",
  "research_depth": 2
}
Enter fullscreen mode Exit fullscreen mode

Example response:

{
  "analysis_id": "88f9f0f5-7315-4c73-8ed5-d0a71f613d31",
  "status": "queued"
}
Enter fullscreen mode Exit fullscreen mode

This response should be fast. Your client does not need the final report immediately. It needs a stable handle for the run.

Poll for the Result

Use:

GET /analyses/{analysis_id}
Enter fullscreen mode Exit fullscreen mode

Example in-progress response:

{
  "status": "running",
  "ticker": "NVDA",
  "analysis_date": "2026-03-26",
  "created_at": "2026-03-26T06:00:00.000000",
  "started_at": "2026-03-26T06:00:01.000000"
}
Enter fullscreen mode Exit fullscreen mode

Example completed response:

{
  "status": "completed",
  "ticker": "NVDA",
  "analysis_date": "2026-03-26",
  "result": {
    "decision": "hold"
  }
}
Enter fullscreen mode Exit fullscreen mode

Example failed response:

{
  "status": "failed",
  "ticker": "NVDA",
  "analysis_date": "2026-03-26",
  "error": "Provider authentication failed"
}
Enter fullscreen mode Exit fullscreen mode

Return explicit failure states. Do not leave clients guessing when the agent workflow breaks.

Step 6: Import the API into Apidog

In Apidog, import the OpenAPI schema from:

http://localhost:8000/openapi.json
Enter fullscreen mode Exit fullscreen mode

After import, your endpoints should appear with their request and response structures.

This gives you immediate benefits:

  • docs match the FastAPI implementation
  • path parameters are generated correctly
  • request bodies stay aligned with your Pydantic models
  • teammates do not need to manually rebuild the collection

If you are moving from ad hoc cURL testing, this is a meaningful upgrade. If you are moving from a request-only client, Apidog also gives you design, testing, environments, and documentation in one workflow.

Step 7: Create an Apidog Environment

Create a local environment with variables like:

base_url = http://localhost:8000
analysis_id =
Enter fullscreen mode Exit fullscreen mode

If your wrapper uses authentication, add it as an environment variable too:

internal_api_key = your-local-dev-key
Enter fullscreen mode Exit fullscreen mode

Use variables in requests:

{{base_url}}/analyses
{{base_url}}/analyses/{{analysis_id}}
Enter fullscreen mode Exit fullscreen mode

This prevents common friction:

  • switching between local, staging, and production
  • rewriting URLs manually
  • sharing requests with teammates
  • keeping auth headers consistent

TradingAgents handles the analysis logic. Apidog handles the reusable workflow around it.

Step 8: Test the Full Workflow in Apidog

Test the API the same way a real client would use it.

Request 1: Create the Analysis

Configure:

  • method: POST
  • URL: {{base_url}}/analyses
  • body:
{
  "ticker": "NVDA",
  "analysis_date": "2026-03-26",
  "llm_provider": "openai",
  "deep_think_llm": "gpt-5.2",
  "quick_think_llm": "gpt-5-mini",
  "research_depth": 2
}
Enter fullscreen mode Exit fullscreen mode

Add a test script:

pm.test("Status is 202", function () {
  pm.response.to.have.status(202);
});

const data = pm.response.json();

pm.expect(data.analysis_id).to.exist;
pm.environment.set("analysis_id", data.analysis_id);
Enter fullscreen mode Exit fullscreen mode

Request 2: Poll the Analysis

Configure:

  • method: GET
  • URL: {{base_url}}/analyses/{{analysis_id}}

Add an assertion:

pm.test("Analysis has a valid status", function () {
  const data = pm.response.json();

  pm.expect(["queued", "running", "completed", "failed"]).to.include(data.status);
});
Enter fullscreen mode Exit fullscreen mode

Add a success-path check:

pm.test("Completed jobs include a result", function () {
  const data = pm.response.json();

  if (data.status === "completed") {
    pm.expect(data.result).to.exist;
  }
});
Enter fullscreen mode Exit fullscreen mode

Chain Both Requests into a Scenario

Create a scenario that:

  1. Sends POST /analyses.
  2. Saves analysis_id.
  3. Waits a few seconds.
  4. Sends GET /analyses/{{analysis_id}}.
  5. Verifies that the status is valid.
  6. Optionally checks that completed jobs include a result.

This gives QA and engineering a reproducible lifecycle test instead of a one-off endpoint check.

Step 9: Publish Internal Docs

After the requests work, publish documentation for the team.

Document:

  • allowed providers
  • supported model names
  • what research_depth means in your deployment
  • expected status values
  • expected runtime behavior
  • retryable and non-retryable errors
  • where the research-only disclaimer applies

This is critical. TradingAgents may be powerful, but any framework becomes a bottleneck when the contract exists only in one developer’s head.

Common Mistakes When Using TradingAgents This Way

Treating the Framework Like a Hosted API

TradingAgents is not a ready-made public service. It is a Python framework. Build the HTTP contract your team needs.

Passing Secrets Through Request Bodies

Keep provider keys in environment variables or a secrets manager. Do not expose them in frontend calls, examples, screenshots, or shared request bodies.

Returning One Long Synchronous Response

For a multi-step agent workflow, a job-based API is usually easier to manage than a long blocking request.

Exposing Too Many Config Knobs

The repository has many configuration options, but your first API does not need to expose everything. Start with a small stable contract.

A reasonable first set is:

  • ticker
  • analysis date
  • provider
  • model choices
  • research depth

Expand only when there is a real use case.

Keeping Results Only in Memory

The tutorial uses an in-memory dictionary because it is simple.

For production, use durable storage such as Redis, Postgres, or another backend suitable for job state and results.

Hiding the Research Disclaimer

If your service wraps TradingAgents, keep the project’s framing visible. It is for research and experimentation, not financial or investment advice.

Conclusion

The best way to use TradingAgents depends on your goal.

If you are exploring alone, the CLI and Python package are enough. If you need a stable team workflow, wrap TradingAgents in a small API and use Apidog to test, document, and share it.

A practical path looks like this:

  1. Install TradingAgents.
  2. Confirm TradingAgentsGraph works locally.
  3. Add POST /analyses.
  4. Add GET /analyses/{analysis_id}.
  5. Import openapi.json into Apidog.
  6. Create an environment.
  7. Build one end-to-end scenario.

That is easier to maintain than terminal commands, screenshots, and tribal knowledge.

FAQ

How do you use TradingAgents for the first time?

Install the repository, set the model provider environment variables, and run the Python example with TradingAgentsGraph. Once that works, decide whether the CLI is enough or whether you need an API wrapper.

Does TradingAgents come with an official REST API?

Not from the public repository materials reviewed on March 26, 2026. The project is presented as a CLI and Python package, which is why many teams may want to add a thin FastAPI layer.

What is the easiest way to use TradingAgents in a frontend app?

Do not call the Python framework directly from the frontend. Expose it through a backend API that returns an analysis_id, then let the frontend poll for results.

Why use Apidog with TradingAgents?

Apidog gives you a place to import the OpenAPI schema, save environment values, store example requests, add assertions, build scenarios, and share documentation with teammates.

Which TradingAgents settings are worth exposing in an API?

Start with ticker, analysis date, provider, model choices, and research depth. Add more settings later only when the use case is clear.

Can I keep the example job state in memory?

Only for learning or prototyping. In production, store job state and results in a durable backend so a service restart does not wipe active analyses.

Is TradingAgents suitable for live financial decisions?

The public project materials describe it as a research framework and explicitly say it is not financial or investment advice. Treat it as a research and experimentation system unless you add your own controls, validation, and governance.

Top comments (0)