Artificial Intelligence

Can You Safely Wire an LLM API Into a Trading Tool?

Ionut Claudiu Fratila · Published Nov 20, 2026 · 7 min read · —
AI IntegrationsLLM APIsStructured OutputsTool CallingPrompt InjectionTrading Automation
Green and blue fibre-optic strands spreading from a central light

Large language model (LLM) APIs are now easy to call from almost any trading tool. A few lines of code can ask a model to tag a headline or summarise an Expert Advisor (EA)‘s log file. The hard part is not the call. It is what happens when the response is malformed, refused, cut short, manipulated by the text it was given, or never arrives.

This article is not about whether a model can forecast markets. It looks at the engineering the main API providers and OWASP document for putting an LLM inside a tool, and at the checks we look for when reviewing these integrations, so that a bad response cannot quietly become a wrong action.

Valid JSON Is Not a Valid Request

OpenAI describes Structured Outputs as the evolution of JSON mode: both produce valid JSON, but only Structured Outputs ensures the response follows your schema. The same page is clear about where that stops: “your application still needs to handle refusals, incomplete responses, and API errors, and validate any business rules that the schema does not express”. A safety refusal or hitting the token limit can produce output that doesn’t match the schema (OpenAI, Structured model outputs).

Anthropic documents the same edge cases. A refusal comes back with stop_reason: “refusal”, a 200 status code and billed tokens, and a response cut off at the token limit has stop_reason: “max_tokens”. The capitalisation of string enum values is not guaranteed, so they should be compared case-insensitively. Numerical constraints such as minimum, maximum and multipleOf are not supported in the schema; most of Anthropic’s SDK helpers move them into field descriptions and validate the response afterwards (Anthropic, Structured outputs).

So a volume of 0.013, a stop distance in the wrong units or “eurusd” instead of “EURUSD” can all arrive as perfectly valid JSON. The fields that matter need your own validation after parsing. In Python, Pydantic’s after validators run after its internal type validation and can reject a value before it goes any further (Pydantic, Validators). In MetaTrader 5, the model’s suggestion is just one more input to the normal pre-trade checks. OrderCheck() checks whether there is enough money for a trade operation (MQL5 Reference, OrderCheck), and a true return from OrderSend() is “not a sign of successful execution of a trade operation” (MQL5 Reference, OrderSend).

The Model Proposes, Your Code Acts

It is easy to read tool calling as the model doing things. It doesn’t. OpenAI describes a function definition as a way for the model “to pass data to your application, where your code can access data or take actions suggested by the model”. A response can contain several calls. OpenAI recommends always enabling strict mode, and setting parallel_tool_calls to false limits a turn to zero or one call (OpenAI, Function calling). Anthropic draws the same line: client tools run in your application, which receives tool_use blocks, runs the operation and returns a tool_result (Anthropic, Tool use with Claude).

So the order path, whether an EA, a broker API or a webhook, stays in deterministic code you control. The model proposes a structured request; your code checks it, then acts or refuses.

OWASP’s guidance on Excessive Agency adds the guard rails: offer the model only the tools it needs, avoid open-ended tools such as “run a shell command” or “fetch a URL”, minimise permissions, require human approval for high-impact actions, and enforce authorisation in downstream systems rather than leaving the model to decide what is allowed (OWASP, LLM06:2025 Excessive Agency). A read-only tool that explains a log file is a very different risk from one that can modify or send orders.

Text From Outside Is an Attack Surface

Trading tools often pass headlines, social posts or emails to a model. OWASP describes indirect prompt injection as what happens when an LLM accepts input from external sources, such as websites or files, and that content alters its behaviour. Listed impacts include unauthorised access to functions available to the LLM and manipulating critical decision-making. OWASP says it is “unclear if there are fool-proof methods of prevention”, so it offers ways to reduce the impact rather than a cure (OWASP, LLM01:2025 Prompt Injection).

In practice, a summariser fed with outside text should not hold any tool that can place an order, and its output deserves the same suspicion as any other untrusted input. OWASP’s Improper Output Handling entry says to treat the model “as any other user, adopting a zero-trust approach”, and names giving the LLM more privileges than end users, and insufficient logging of its outputs, as factors that raise the impact (OWASP, LLM05:2025 Improper Output Handling).

When the API Says No

An LLM API is a remote service with limits. Anthropic’s API returns 429 rate_limit_error, 500 api_error and 529 overloaded_error. Its official SDKs retry transient failures with exponential backoff, twice by default, honouring the retry-after header when present, while a spend-cap 429 has no retry-after and keeps failing until access resumes. Every response carries a unique request-id header (Anthropic, API errors). Limits use a token bucket that refills continuously rather than resetting at fixed intervals (Anthropic, Rate limits).

OpenAI’s advice for your own HTTP client is to follow Retry-After when present, otherwise use exponential backoff with jitter, and limit both attempts and total retry time; if you manage retries yourself, disable or count the SDK’s so nested loops don’t multiply requests (OpenAI, Rate limits). OWASP’s Unbounded Consumption entry covers the cost side, including “Denial of Wallet” on pay-per-use AI services (OWASP, LLM10:2025 Unbounded Consumption).

For anything time-sensitive, decide what the tool does when the model doesn’t answer: skip, queue or hand to a person. An unbounded retry loop is not an answer. Logging the request ID with the input, parsed output and your code’s decision makes investigation far easier.

Test It Like Software That Can Change

OpenAI notes that models “sometimes produce different output from the same input, which makes traditional software testing methods insufficient”, and describes evals as structured tests for this. The same page says its hosted Evals platform became read-only for existing users on 31 October 2026 and is scheduled to shut down on 30 November 2026 (OpenAI, Evaluation best practices). Anthropic recommends defining specific, measurable success criteria first, then building evaluations from exact-match checks to model-based grading (Anthropic, Define success criteria and build evaluations).

In a trading tool, that can be as plain as a version-controlled set of real log snippets or alert texts, each with the structured output you expect, rerun whenever the prompt, schema or model changes.

Decide What Data You Send

Decide what account or client data may leave your systems before you build. OpenAI states that, as of 1 March 2023, API data is not used to train its models unless you opt in, while abuse-monitoring logs, which can contain prompts and responses, are kept for up to 30 days by default; Zero Data Retention is available to approved customers (OpenAI, Data controls). Anthropic says structured outputs are eligible for zero data retention, but the JSON schema itself is cached for up to 24 hours after last use (Anthropic, Structured outputs). Keep identifiers out of schemas and, where possible, out of prompts.

Limits and Caveats

None of this makes a model’s judgement better, and nothing here suggests that adding an LLM will improve trading decisions. We make no performance claims. These patterns limit the damage a wrong, refused or manipulated response can do; they cannot make a response right.

Provider documentation changes often. The details above come from the official pages at the time of writing; check them again before relying on them.

Conclusion

Can you safely wire an LLM API into a trading tool? Yes, if the model is treated as an untrusted source of suggestions rather than a decision-maker. Validate every field your code depends on, keep the order path in deterministic code with its own authorisation, require human approval for high-impact actions, keep outside text away from tools that act, plan for refusals and rate limits, test with fixed cases, and decide what data leaves your systems.

This is the kind of work we do in our AI Integrations and Trading Automation services, and the same checks are part of our AI Code Rescue reviews.

Drafted with AI assistance; reviewed, edited and approved by Ionut Claudiu Fratila.