Independent tests for AI-generated trading code
Design manual oracles, boundary cases and property tests to review AI-generated Forex code without repeating the same mistakes.

The AI delivers a function, adds twelve tests and shows that they all pass. You open one: its expected result is calculated by calling the same helper used by the main function. The program and its examiner share the formula. If that formula misinterprets the rule, both can make the same mistake and still display an impeccable result.
Asking for more tests does not make the problem disappear. You need some reason to believe the expected answer comes from a different path. It might be a calculation done by hand, a condition derived from the specification, a relation between runs or a sequence of events whose final state you can reconstruct.
A useful test needs a defensible expectation. Its independence does not require a different person to write every line. It requires examining where the expectation comes from and which shared error might invalidate it. Two tools may agree because they read the same ambiguity; one person can construct complementary checks by carefully separating their sources.
We will follow an original, hypothetical Forex example. The rules, prices, quantities and records are teaching materials, not Atlas robots or results. We will work without sending orders. Whenever we mention a CSV associated with the offer, we mean the demo exclusively; the small test datasets in this article are invented.
The purpose is to review an implementation you can read, run and modify with your AI. This allows you to study rules and code without knowing the private generator. Code passing its tests does not demonstrate that the strategy has an economic advantage. It demonstrates something more specific, whose scope depends on the tests actually performed.
Define what should happen
Before generating tests, write a small contract. In our exercise, a signal occurs when the close of a completed candle strictly exceeds the highest high of the three preceding completed candles. The current candle is excluded from that reference window. Sufficient history is required, and a new entry is not allowed when a position or a pending entry request already exists.
The contract does not yet say how the signal is executed. For this example, a request can only use a quote available after the close is known. Signal, request and execution must preserve separate identifiers. An implementation recording a purchase cannot justify it solely by saying that the indicator condition was true.
Words that change a decision deserve a case. “Preceding”, “strictly”, “completed” and “pending” delimit different behaviours. If a robot’s original description leaves any of those words unresolved, record the ambiguity. An AI can propose interpretations, but a proposal does not automatically become the authorised rule.
It also helps to distinguish valid inputs from invalid ones. Can a candle arrive without a high? Are duplicate records allowed? What happens with a negative quantity? The contract should state whether the input is rejected, the decision is postponed or a documented transformation applies. Allowing an automatic conversion to decide that behaviour conceals an important choice.
The first step ends with a brief page containing inputs, preconditions, outputs and unresolved cases. Software Carpentry presents preconditions, postconditions and internal checks as tools for expressing and reviewing program expectations. We adopt that general distinction; the Forex contract just defined is our own teaching construction. Defensive Programming.
Once the contract is written, save a version before inspecting the results. If you later change the definition, preserve the reason. Without that record, it becomes difficult to distinguish a code correction from a rule modification made to accommodate what the program already does.
Build an answer outside the program
A test oracle is the criterion used to decide whether an output is acceptable. Here we will construct a small one by hand. It does not attempt to explain every possible historical dataset: it fixes a checkable answer for a fragment that fits entirely on a work surface.
These four fictional candles have closing timestamps. The first three have highs of 1.1002, 1.1004 and 1.1003. The fourth, closed at 08:15, has a high of 1.1008 and a close of 1.1005. The reference maximum is 1.1004, calculated using only the three preceding candles. The close of 1.1005 therefore satisfies the strict comparison.
| Candle close time | High | Close | Role in the 08:15 decision |
|---|---|---|---|
| 08:00 | 1.1002 | 1.1000 | First preceding observation |
| 08:05 | 1.1004 | 1.1003 | Second preceding observation |
| 08:10 | 1.1003 | 1.1001 | Third preceding observation |
| 08:15 | 1.1008 | 1.1005 | Evaluated candle; excluded from the reference |
If a calculation mistakenly includes the current candle’s high, the reference becomes 1.1008 and the signal disappears. Observing the difference does not require thousands of trades. It is enough to check which three rows entered the window and write out the comparison that should have been made.
The manual calculation should preserve its reasoning. Saving only “true” as the expected answer makes the oracle itself harder to review. Also preserve the selected rows, the maximum obtained and the condition applied. Another person can then detect an error in the test even if the implementation agrees with it.
Choose a case that does not activate the condition as well. If the current close is exactly 1.1004, the strict comparison must fail. If only two preceding candles exist, history is insufficient. These cases prevent a function that always returns true from passing the small set by accident.
The manual oracle has deliberate limits. It does not yet verify execution, accounting or state transitions. Its value lies in isolating one decision. As the example grows, preserve those boundaries so you know which component explains a discrepancy.
Look for dependence between tests
Asking a second AI to review the first response can provide another reading, but does not automatically establish independence. If it receives the full code and derives expectations from its behaviour, it may turn an existing error into a convincing explanation. The useful question is which material it used to decide.
A circular test arises when the expected value is calculated using the same function, the same copied formula or the same preprocessing being verified. For example, comparing an optimised indicator with an identical helper moved into the test file does not add an independent check of the time shift.
Agreement between two implementations can preserve a shared error. Review the dependencies of both paths. If both sort the file using the same incorrect criterion before calculating, the indicator comparison can pass while the entire time sequence remains misinterpreted.
One alternative is to separate who or what receives each material. Implementation receives the contract. Case preparation receives the contract and small examples, without needing the implementation. The later review compares both outputs and may inspect the code to explain differences. This separation is a practical proposal, not a guarantee that reviewers will avoid mistakes.
Independence means diversity of checkable reasoning. A manual calculation provides one route; an algebraic relation provides another; an event-by-event reconstructed record provides a third. They are not votes added together to declare truth. Each route covers a different claim and can fail for its own reasons.
Some dependencies are legitimate. A test and a program can use the same standard number parser without making every comparison useless. You must decide whether that parser is part of the component under examination. If you are verifying it, you need original inputs and independent interpretation expectations; otherwise, you can declare it an assumed dependency and check it separately.
The deliverable at this stage can be a table connecting each claim to its oracle and dependencies. A cell without a supporting argument indicates unfinished work. The goal is not to eliminate every dependency in the world, but to prevent the check from inadvertently copying the error it was meant to discover.
Choose boundaries that change the result
Boundary tests sit where a small variation produces a different decision. In the example, equality with the preceding maximum separates a signal from no signal. Having two preceding candles or three separates insufficient history from a valid window. An empty position and a pending request separate availability from an occupied state.
You do not need to enumerate every possible price. You need to identify the contract’s decisions and present a case on either side. For the strict comparison, retain a close below the reference, one equal to it and one above it. For state, retain an account with no position, one with a position and one with an entry still pending.
Choose combinations deliberately. If you test only a higher close with an available state and a lower close with an occupied state, you do not know whether occupancy blocks anything. The price condition already explains the second result. You need a price that activates the signal combined with each relevant state.
A test must be able to fail for the reason it claims to check. This also applies to expected errors. If a file has an invalid quantity and an unreadable date, it may be rejected because of the date without ever reaching the quantity check. A red result or an exception is insufficient to claim coverage of the correct requirement.
The pytest documentation explains how to check values, approximate results and expected exceptions. Those tools let you express the expectation, but choosing the case and the appropriate error remains the test designer’s responsibility. Assertions in pytest.
Under our contract, an incomplete candle does not become complete because a field is missing. Prepare an input where the time looks correct but the completion state is false. This reveals whether the code uses the explicit input or an assumption based on the file format.
When you find a failure, reduce the example while preserving its cause. Remove irrelevant rows or fields until you can explain the case clearly. Save both the minimal fragment and the original case’s provenance. That reduction helps correct the appropriate component without losing the connection to the problem that appeared.
Check properties without guessing outputs
A manual case provides an answer for one input. A property expresses a condition that should hold across a domain of inputs. In a function calculating the maximum of three finite values, for example, the output must equal one of those values and must not be smaller than any of them. These are constraints derived from the calculation’s definition.
This does not mean any property is sufficient. A function that always returns the highest value permitted by the domain may satisfy an incomplete inequality. You need to combine conditions that exclude relevant incorrect behaviours. For a maximum, membership and comparison provide different checks.
Hypothesis can generate inputs through strategies and evaluate properties over them. Its documentation distinguishes the allowed domain from the distribution of generated examples. We use that separation to describe which inputs a test covers, without interpreting the generator’s failure frequency as a probability of failure in the market. Introduction to Hypothesis and domain and distribution.
The domain is part of the claim you are checking. If you exclude missing values, infinities or empty windows, your test says nothing about what the code will do with them. The exclusion may be correct if another test verifies that they are rejected before entering the function. It must be a visible decision.
In the example, you can generate three valid highs and a current close to check the rule. But you must also construct candle consistency when using all its fields: the high cannot be below the close in a valid OHLC representation. Generating inconsistent rows and demanding normal signals confuses program errors with generator errors.
Distinguish two families: valid inputs for studying behaviour and invalid inputs for studying rejection. The expected response differs. In the second family, an explicit refusal may be the correct outcome. Do not turn every exception into a defect if the contract required that input to be rejected.
Generated examples that reveal failures deserve to be preserved as readable regression cases. Automation broadens exploration; the reduced case explains the defect. Both materials serve different functions and should be retained without replacing one with the other.
Compare transformations through known relations
Sometimes you do not know the entire correct output, but you do know a relation that should hold when an input changes. The original work by Chen, Cheung and Yiu proposes generating additional cases through relations between runs, a foundation of metamorphic testing. Its usefulness depends on the chosen relation being valid for the problem. Metamorphic Testing.
For our signal function, we add the same constant to every high and close while keeping values valid. Comparing a close with the maximum of the three preceding values should produce the same sequence of true and false values. The common addition preserves that ordering. This property checks the logic of that function, not the economic outcome of an entire strategy.
Do not transfer the relation without examining its limits. If the program includes an absolute-price filter, adding a constant can legitimately change the signal. If you are studying monetary amounts or conversions, the transformation can change the data’s meaning. The property must state precisely which component and assumptions it preserves.
A second relation concerns the future. Run a causal function on a prefix of candles and preserve its signals. Then append later candles and run it again. The prefix’s signals should remain unchanged if the contract forbids retrospective revisions and the prior history is identical.
A test relation needs to justify what should remain unchanged and why. Prefix invariance can reveal normalisation performed over the whole series, but does not by itself prove that every input was available on time. An already contaminated field could remain the same in both runs. That question requires its provenance to be inspected.
You can also check that serialising and rereading a record preserves identifiers, units and values within a declared tolerance. This relation helps review a storage boundary. If the format deliberately rounds prices, the expectation must reflect that and identify the permitted loss.
Avoid attractive but false properties. Reversing candle order should not preserve the signals of a temporal rule. Splitting a trade into two does not necessarily preserve commissions when there is a minimum per order. The first task is to establish the relation on paper before asking the AI to automate it.
Test events and intermediate states
A function can be correct for each row while the robot mishandles a sequence. State matters: a pending request, a partial fill or a repeated confirmation changes which decisions are admissible next. The test must therefore observe transitions, not just final values.
We construct a fictional sequence. The system is available, receives a signal and records a request for 2,000 EUR. It then receives a fill of 1,000 EUR with identifier F1 and another fill of 1,000 EUR with identifier F2. The final position must be 2,000 EUR, rather than two independent full-size positions.
Now we repeat message F1. Under this contract, execution identifiers are unique and a repetition adds no quantity. The state remains at 2,000 EUR. If the program adds the fill again, the error appears even if the aggregate output of a simulation without duplicates was correct.
| Fictional event | Accumulated position | Pending entry |
|---|---|---|
| Request for 2,000 EUR | 0 EUR | 2,000 EUR |
| Fill F1 for 1,000 EUR | 1,000 EUR | 1,000 EUR |
| Fill F2 for 1,000 EUR | 2,000 EUR | 0 EUR |
| Repeated F1 | 2,000 EUR | 0 EUR |
Check state after every event. The same final value can conceal a duplication and a later correction. Preserve the position, pending quantity, processed identifiers and the reason for each transition. You do not need every internal variable: you need those that make the contract reviewable.
Separately, prepare cancellation of the remaining quantity after F1. In that second case, the position stays at 1,000 EUR and the pending quantity becomes zero. Cancelling what remains does not reverse a fill already received. Confusing the two effects would be a state defect, not a price discrepancy.
Do not claim that every platform sends the same events. These examples are teaching contracts for reviewing an adapter or simulator. A real implementation needs its interface documentation. If a cancellation arrives before a delayed confirmation, the correct behaviour depends on the identifiers and protocol; that sequence requires its own specification.
Reconcile quantities and money separately
After checking the signal and state, we construct an independent monetary oracle. We assume a complete purchase of 2,000 EUR at 1.1007 USD per EUR and a closing sale at 1.1002. Both figures are fictional executed prices. The account is denominated in USD and there are no additional conversions.
The price difference is minus 0.0005 USD per EUR. Multiplied by 2,000 EUR, it produces minus 1 USD. We assign an invented commission of 0.40 USD on each side, 0.80 in total. The net result is minus 1.80 USD. We assume no financing or other charges.
The test should compare components, not just the net result. An implementation could record a gross result of minus 0.50 and a commission of 1.30, coincidentally obtaining the same net result. Separating quantity, entry price, exit price and charges makes that offsetting error identifiable.
Units are part of the oracle too. A value of 2,000 can represent euros, contract units or a different size convention. The test case must declare the interpretation. Equality between two numbers without their units does not establish that the same quantity is being calculated.
For a second check, use twice the quantity while preserving prices and an explicitly defined proportional commission. Under those conditions, the gross result and charges should double. If the model’s commission is fixed per order, the net result will not follow that proportionality. The relation is required only when the contract justifies it.
Also separate numerical tolerance from economic tolerance. A small floating-point representation error may require an approximate comparison. That does not authorise accepting a material difference in price, quantity or commission. Define tolerance for each field and explain why it is compatible with the precision of the input and calculation.
The article on position size sensitivity develops how quantities change as size varies. Here we use that relationship to design bounded checks. The manual calculation does not validate a complete execution model, but helps detect reversed signs, omitted conversions and charges applied twice.
Separate clocks and availability
A test can verify the correct formula using information that did not yet exist. In our example, candle timestamps represent closing times and the 08:15 signal can only exist after that close is known. An earlier execution does not become admissible merely because the file is sorted.
We add a fictional quote timestamped 08:15:00.250. The execution test checks that the price used belongs to a quote admitted by the contract after the signal’s availability. If the program takes a quote from 08:14:59, the temporal incompatibility must be identified.
Do not assume that timestamps from two files use the same time zone or clock. Preserve both their meaning and the conversion applied. A string comparison can appear ordered while still combining times from different origins. The test needs comparable instants and documented conventions.
Check what was known, not just which date appears. An event’s time, its receipt time and a variable’s availability time may differ. In a simulation, those distinctions must become concrete rules governing when each input can participate.
To isolate the issue, create two inputs identical except for the availability of a quote. In one, it arrives after the signal; in the other, before. The expected response must show which execution is admissible. If the program delivers the same trade in both without justification, you have a discrepancy to investigate.
The prefix test mentioned earlier complements this review, but does not replace it. The first examines retrospective changes when future data is appended. This one examines whether fields and events respect their availability. Two tests can appear similar because both concern time, yet detect different errors.
When a candle contains only open, high, low and close, you also cannot invent its intrabar path to justify a sequence of fills. The article on OHLC candle limitations explains that ambiguity. A test must preserve it or apply a declared convention, rather than present an assumed path as an observation.
Check the tests with deliberate mistakes
A suite can execute many lines and fail to detect a relevant defect. Coverage.py distinguishes statement coverage from branch coverage and makes it possible to observe which alternatives of a decision were executed. That information helps locate unvisited areas; it does not establish that the expectations used are correct. Branch coverage measurement.
In our example, every line of the comparison could execute using only closes above the preceding maximum. Changing “greater than” to “greater than or equal to” would not affect those inputs. The equality case is what distinguishes the two implementations.
Introduce a small error whose effect you can predict. In a test copy, change the strict comparison, include the current candle in the window or apply commission twice. Run the checks and observe whether they fail for the expected reason. Then restore the implementation. The purpose is to study the suite’s sensitivity.
A test that misses the chosen defect needs review before serving as evidence against that defect. The appropriate case may be missing, the expectation may be wrong or the function you intended to test may not have run. The outcome does not require discarding the entire suite, but does require limiting its scope.
Not every deliberate modification changes behaviour. Some produce an equivalent implementation for the examined domain. If the test stays green, first determine whether an observable difference existed. Counting every surviving modification as a quality failure can lead to misleading conclusions.
Tests also need execution inspection. Check how many cases were discovered, which were skipped and which version was imported. A command can finish successfully because it did not execute the expected file or because a marker excluded precisely the critical cases. Preserve the summary and exact invocation alongside the result.
Closing this exercise does not require a universal coverage percentage. It requires connecting plausible errors to cases that actually distinguish them. A small list with those relationships made explicit provides a clearer review criterion than an isolated percentage accompanied by a confidence label.
Review changes without moving the expectation to suit them
When a test fails, an AI often offers several possible corrections. Some change the program; others change the expected value; others widen a tolerance. Before accepting a proposal, return to the contract and ask which component contains the error. A failure reveals disagreement between pieces, not which one is right.
If the manual expectation omitted a commission, it should be corrected. Independence does not make a human calculation infallible. Preserve the revision and the arithmetic that justifies it. The problematic action would be replacing the expectation with the current output solely to obtain a green result.
A correction should explain the discrepancy. If you included the current candle by mistake, the modification should change the relevant row selection. An additional condition that silences the specific case may leave the cause intact. That is why nearby cases should be repeated and the general relation involved should be checked.
Ask the AI for small changes accompanied by a verifiable explanation: which requirement was violated, which logical step changes and which case distinguishes the old version from the new one. This request organises the review, but the explanation remains material you must check against the file and tests.
Avoid giving the reviewer only a screenshot of the summary. Preserve minimal inputs, the code version, relevant dependencies and observed outputs. If behaviour involves randomness, record the conditions needed to reproduce the failure. An intermittent defect needs evidence of the sequence that triggers it.
After correcting it, incorporate the case into the regression set. Also examine whether the change affects a neighbouring decision: a time shift can correct a signal and alter warm-up; a quantity adjustment can change how partial fills accumulate. Review should follow the change’s real dependencies.
There is no need to repeat all the work indiscriminately after every edit. First run the affected component’s checks, then the relevant integrations. Expand when the change, a new failure or an unresolved dependency justifies it. The criterion is preserving sufficient evidence about the behaviour actually modified.
Prepare a review someone else can repeat
The verification package contains several small pieces. Include the contract, manual cases with reasoning, the fictional or authorised data used, the code version and a way to run the tests. Add a summary connecting requirements, checks and open limits.
Do not present “all tests pass” as the only result. A more useful formulation would be: the strict comparison was checked with equality and values on both sides; the window excludes the current candle in the stated cases; the accounting matches the manual calculation under the declared costs. Every claim points to reviewable evidence.
An open limit should keep its name. If a delayed cancellation has not been modelled, say so. If the test covers only a demo CSV reader with certain columns, do not extend it to every provider. If the real interface permits behaviours omitted by the simulator, that difference requires another investigation.
An external review can begin with a single requirement. Another person reconstructs the preceding maximum, calculates a trade’s result or checks a duplicate identifier. If they cannot reach the same conclusion with the supplied materials, identify what is missing: an input, a convention or an instruction.
That work can also be recorded in an experiment journal. The note should distinguish the defect found, the modification made and the subsequent evidence. Do not confuse the date of a correction with editorial approval or authorisation to send orders.
The conclusion should be as specific as the evidence you can provide. Independence becomes visible when a reviewer can follow an alternative path to an answer and understand why a different implementation would be wrong in that case.
At the end, also preserve the questions that survive a completely green suite. Execution realism, knowledge of the data or strategy evaluation may still be missing. These are different problems. Which plausible error might your implementation currently share with its tests, and which independent check would make it visible?



