Artificial intelligenceIntermediate25 min read

An agent learns what you pay for: designing trading rewards

Design a reinforcement learning reward that reconciles positions, costs and equity, and discover how a simulator can reward accounting mistakes.

The agent finishes its episode with an excellent score. It has closed five winning trades while keeping one position whose loss exceeds all those gains. The report celebrates realised profits; the open loss never enters the reward. The algorithm does not need to discover a market regularity to exploit this situation. It only needs to learn that closing a loss lowers its score, whereas keeping the position open hides the damage.

This small defect changes the research question. Before asking which neural network or reinforcement learning algorithm to use, we need to ask what behaviour the simulator is paying for. An agent does not know the intention that was left out of the code. It receives observations, a set of available actions and a signal that its training procedure tries to improve.

We will build that signal from accounting that can be checked, with research into Forex strategies in mind. Every price, position and numerical result below is a hypothetical educational example. None describes Atlas results or expected returns. Normalised units make the choices visible; a real implementation would need to specify the contract, account currency and execution process behind them.

1. Three documents before training

Separate the economic objective, the accounting contract and the reward. The objective states the problem being investigated: for example, selecting a short, flat or long position while respecting exposure limits. The accounting contract specifies when trading happens, which price is used, what is paid and how positions are valued. The reward is the quantity delivered to the algorithm after a transition. These documents can be short, but they are not interchangeable.

Suppose the objective includes controlling large losses. Adding a volatility penalty does not establish that this objective has been achieved. First decide which loss matters, over what horizon it is measured and which restrictions must apply even when the agent would prefer to ignore them. A position limit enforced by the environment has a different effect from a fine that the agent can decide is worth paying.

The economic description also needs a unit. A profit of ten monetary units means something different with starting capital of one hundred than with ten thousand. A reward in pips leaves out position size unless size is explicitly incorporated. A percentage reward may change when its capital base changes. The unit is part of the task, rather than a presentation detail to add to the final report.

A useful first contract fits on one page: the decision clock, visible information, permitted actions, execution time, equity valuation, included costs and closing rule. Write one worked row beside it. If two people cannot derive the same reward from that row, training is premature. Their disagreement identifies an unresolved definition that a hyperparameter search will not settle.

This sequence lets us review the environment using a hand-written policy. A fixed action sequence can pass through the same transitions that the trained agent will later use. We check the ledger before learning variability makes diagnosis harder. The reward should remain understandable if the neural network is removed from the project entirely. At this stage, a transparent sequence of positions is a better debugging instrument than an impressive learning curve.

2. The clock determines who receives the price move

Let P_t denote the reference price known at a particular instant, and q_t the position held during the next interval. In our example, we observe P_t, choose q_t and then experience the movement to P_(t+1). Gross profit for the interval is q_t multiplied by the difference between those prices. This is an explicit simulation convention. It does not establish that an observed price can always be traded immediately, without delay.

The easiest mistake is to calculate the decision using information from P_(t+1), then credit it with the movement from P_t. A subtler version uses the newly chosen position to reward an interval that has already elapsed. Both can produce arithmetically correct rewards for impossible transactions. An accounting identity cannot repair an impossible clock.

An action needs operational meaning. If “buy” means increase the position by one unit, repeated actions accumulate inventory. If it means establish a long position of one unit, repeating it creates no trade. These interfaces generate different trajectories from the same sequence of labels. Starting with target positions makes reconciliation easier: moving from zero to one trades one unit; from one to one, none; from one to minus one, two.

We must also decide when costs become known. The spread observed at the decision time might be an available input, while future slippage is still uncertain. The simulator can subsequently apply the realised cost or a declared assumption. It must not insert that future outcome into the previous observation so the agent can retrospectively avoid expensive trades.

A concrete test records four times for each transition: information cutoff, action submission, execution and subsequent valuation. There is no need to pretend to have microsecond precision when the data do not support it. There is a need to state which events are ordered and which are approximations. With bar data, a simplified execution rule belongs in the environment’s assumptions; it is not a demonstrated property of the market.

The example's sequence: observe the price, set the position and cost, wait for the price move, then value equity.
The selected position receives only the move after its assumed execution. The clock is part of the experiment.

3. A reward that can be added up by hand

Build an episode with normalised prices of one hundred, one hundred and two, and one hundred and one. Each position unit gains or loses one monetary unit for each unit of price change. Trading costs zero point two monetary units per unit traded. We start flat, hold one long unit during the first movement, hold one short unit during the second, then liquidate at the end. Starting capital is one hundred, and this accounting toy includes no financing.

In the first interval, the price increase produces two gross units. Opening the position costs zero point two, so the reward is one point eight. Before the second interval, we reverse from plus one to minus one. That change trades two units and costs zero point four. The fall from one hundred and two to one hundred and one produces one gross unit for the short position. The second reward is zero point six. Liquidating the short costs another zero point two and receives no additional price movement.

Hypothetical event Position afterwards Units traded Gross result Cost Reward
Open and hold through 100 → 102 +1 1 2.0 0.2 1.8
Reverse and hold through 102 → 101 −1 2 1.0 0.4 0.6
Liquidate 0 1 0.0 0.2 −0.2
Total 0 4 3.0 0.8 2.2

The rewards sum to two point two. Final equity is one hundred and two point two, equal to starting capital plus the net result. This equality is the environment’s first acceptance test. It must hold for every action sequence compatible with the contract, rather than only for a profitable sequence chosen to illustrate the system.

In shorthand, reward equals the position’s result during the interval minus the cost of changing that position. If execution uses bid and ask prices directly, the spread’s effect may already be incorporated in the cash flows. Subtracting another full spread would count part of the cost twice. Our example avoids that ambiguity by using a reference price and a separate cost. Another implementation can choose a different representation, provided the reconciliation remains consistent.

The positive number does not show that an agent can trade. We specified the actions retrospectively to check the arithmetic. This is a test case, not a strategy. Changing the sequence to a long position during both intervals, or remaining flat throughout, provides additional controls. A correct environment must also calculate poor decisions and a complete absence of trading accurately. Its arithmetic cannot depend on whether the action sequence tells an attractive story.

4. Equity, open losses and double counting

Rewarding only realised profits creates an unusual dependence on the decision to close a position. Two portfolios with the same equity can receive different cumulative rewards because one recognises losses while the other leaves them open. If the objective is defined in terms of equity, the signal needs to reflect position valuation as well as the relevant cash movements.

Marking to market means incorporating the change in the position’s economic value during each interval, using a declared pricing convention. It does not mean every marked price is executable, or that liquidity risk disappears. For an initial investigation, incremental net profit offers a transparent relationship between the path and the account. Other reward functions can be studied later, while preserving an independent economic ledger throughout.

The opposite mistake occurs when realised profits are added to a reward that already contains every change in equity. A trade’s gain is recognised while the position is held, then added again when it closes. The agent receives the same market movement twice. To detect this, reconcile a complete round trip from flat to flat and compare the sum with the recorded cash flows and valuations.

Translating this normalised accounting into Forex requires specifying the pair, base-currency units, quote currency and account currency. If profit is converted into a third currency, that conversion also has a price and a time. Calling a column of quote differences “euros” is not enough. The shortcut can conceal both scale errors and missing conversion movements, even when every addition in the column is mechanically correct.

Keep balance, equity and position separate in the environment’s records. A reward may depend on one of them, but a reviewer needs to see all three. A loss does not disappear because the agent avoids closing it. That sentence becomes an executable test when we construct a path with an open loss and require it to appear in final equity under the selected valuation rule.

Reconciliation of the example: three gross units less eight tenths of costs produce two point two net units.
The economic ledger retains gross results, costs and equity even if the training reward is subsequently transformed.

5. Costs that depend on what the agent does

A fixed charge per decision and a charge per unit traded encourage different behaviour. A decision charge might apply even when the position remains unchanged and no trade occurs. A charge based on the absolute position change creates no additional trading cost when the position is maintained. Neither convention should be adopted for convenience without comparing it with the mechanism being represented. The “leave unchanged” action is particularly useful for detecting accidental charges.

Position reversals deserve their own test. Moving from one long unit to one short unit requires selling two units: one to close the existing exposure and one to establish the opposite exposure. Charging for only one makes frequent reversals artificially cheap. In our worked case, that error would reduce the intermediate cost from zero point four to zero point two and increase the final result from two point two to two point four.

Costs can depend on the state. A wider spread at particular times, a holding charge or a size restriction should enter with explicit units and timing. Assuming constant costs to investigate a limited question can be a reasonable research choice. It does not support a conclusion that a policy will behave the same way under every execution condition. The limitation belongs with the interpretation of the experiment.

Separate economic costs from regularisation penalties. A commission reduces equity because it is part of the execution contract. An additional penalty for trading might steer learning towards less activity, but it is not automatically a real expense. Costs and preferences need separate columns. Combining them without labels makes it impossible to tell whether a policy improved the account or merely followed the designer’s preference more closely.

A practical inspection fixes a price path and replays exactly the same actions under two cost assumptions. The difference in results should be explained by the recorded trading activity. Retraining the agent under each assumption adds another experiment: the policy changes as well as the accounting. Both questions are useful, but first resolve the mechanical sensitivity before attributing differences to intelligent adaptation. Otherwise a simple accounting effect may be mistaken for a learning result.

6. Rewarding returns does not settle position sizing

If multiplying the position multiplies gross profit, an agent maximising monetary profit may prefer more exposure whenever the environment permits it. This does not mean it has learned a better signal. It may have discovered a sizing lever. Comparing policies therefore requires examining exposure, capital and constraints alongside the sum of rewards.

A first task can restrict positions to minus one, zero and plus one. This space does not represent all the flexibility of a real account, but it isolates the problem of direction and abstention. Adding intermediate sizes or leverage later changes the task. A simple reference policy needs comparable opportunities; otherwise an apparent advantage may come from different permissions rather than a better decision rule.

Hard restrictions are applied by the environment. If an action exceeds a limit, decide whether it is rejected, clipped or causes the episode to end, and record the outcome. Penalising an invalid action while executing it anyway leaves open the possibility that breaking the limit is worthwhile. The reward does not replace operational controls that must hold independently of the learned preference.

An absolute-exposure penalty can be written as a coefficient multiplied by the size held. It looks straightforward, but the coefficient has units: how much result we are willing to sacrifice for one unit of exposure over a unit of time. Changing the simulator’s frequency without adjusting that interpretation can multiply the daily penalty. One minute and one hour are not interchangeable merely because each occupies one row in a dataset.

Normalising by capital also requires care. Dividing by starting capital keeps the scale fixed throughout an episode. Dividing by current equity makes each reward depend on the preceding path. Simple interval returns compound; adding them does not exactly recover total return. The choice can be reasonable, but it needs a different reconciliation formula and explicit handling of zero or negative equity. Those cases cannot be left for the optimiser to interpret accidentally.

7. Discounting, normalisation and clipping alter the signal

An algorithm may maximise a discounted sum of rewards. With a discount factor below one, receiving a unit earlier carries more weight than receiving it later. In our example, a factor of zero point nine and three successive deliveries produce one point eight plus zero point nine times zero point six minus zero point eighty-one times zero point two: two point one seven eight. Economic profit remains two point two.

The difference is not an arithmetic error. It is a different objective. If the entire result of two point two were delivered only at the third step, the discounted sum would be one point seven eight two. Final equity would be identical, but the reward schedule would change the value the algorithm learns. Two signals with the same total can teach different preferences.

Dividing every reward by the same positive constant preserves the ordering of the corresponding sums, although it can affect numerical training behaviour. Normalisation that changes with the episode’s history is no longer that fixed transformation. If its mean or dispersion is calculated using the entire future history, it also introduces information unavailable at the decision time. Normalisation parameters therefore belong in the experimental record as well.

Clipping rewards to an interval limits the magnitudes the agent sees. This can be useful in some optimisation procedures, but a loss of ten and a loss of one hundred might then appear identical. The transformation changes what is rewarded and may erase economically essential distinctions. Evaluate the policy with the original account, never solely with the clipped sum supplied during training.

Logarithmic return provides another option when equity remains strictly positive: log changes add up to the logarithm of the ratio between final and initial equity. That mathematical property does not make it a universal objective. Explain the preferences it represents, how deposits or withdrawals are handled, and what happens if the environment permits a state in which the logarithm is undefined. A convenient aggregation property does not remove the need for an economic specification.

Comparison of net profit of two point two, discounted reward of two point one seven eight, and discounted final-only delivery of one point seven eight two.
The example keeps final equity unchanged. Changing when the algorithm receives its signal changes the discounted value.

8. Penalising risk requires remembering which risk

Adding a penalty for falling below an equity high seems a direct way to control drawdown. Yet that decline depends on the highest equity reached previously. Two episodes with the same price and position can have different drawdowns because they arrived from different peaks. If that history affects rewards or transitions but remains hidden, the observation does not fully describe the relevant situation.

A task using drawdown may need equity and the running peak in the state constructed by the environment, together with a decision about which parts the agent observes. This does not guarantee that the entire market process is Markovian. It simply avoids hiding a variable we have introduced ourselves into the problem’s definition. Designing the reward also creates memory requirements.

Penalty frequency matters. Charging every minute spent below a previous high penalises both duration and depth. Charging only when a new worst drawdown appears penalises another property. A penalty on the final maximum drawdown provides delayed information. None of these automatically imposes a maximum loss limit. They describe different preferences and can produce different behaviour while the account recovers.

Ratios calculated over rolling windows, such as mean return divided by its dispersion, introduce decisions about window length, minimum observations and small denominators. A window with almost no variation can generate an enormous score without much economic profit. Before using a ratio as a reward, test a constant case, a case with one loss and an incomplete window. The formula needs defined behaviour in all of them, including the earliest steps of an episode.

A more easily audited starting point keeps a simple economic reward and evaluates several dimensions of risk separately, alongside explicit restrictions. This does not magically resolve the trade-off between return and risk, but it makes that trade-off visible. If a penalty is added later, its effect can be compared with a reference already understood, rather than introducing several opaque transformations at once. That narrower change is easier to explain when a candidate’s behaviour becomes surprising.

9. The end of an episode can also be exploited

An episode can finish because the task has reached its terminal state, or because training has cut a sequence that could have continued. This distinction affects whether estimates of subsequent value are used. Gymnasium distinguishes termination from truncation and explains that a finite horizon inherent in the task requires remaining time to be represented to preserve the Markov property of the defined state. This is an environment distinction, not evidence of trading effectiveness. Gymnasium documentation on handling time limits.

In our episode, final liquidation belongs to the task. Its zero point two cost must enter the account. Omitting it gives the agent an accounting subsidy for holding a position until the final instant. If the agent knows when the episode ends, it can adapt to that rule. This may be appropriate for a fixed-horizon task and unrepresentative of a system intended to continue indefinitely.

A truncation introduced for computational convenience raises a different question. Cutting a sequence every five hundred rows does not itself imply that a real account liquidates every five hundred observations. We can preserve continuity or define resets, but must explain how position, equity and state carry over. Frequent full resets can remove difficult recovery periods and produce a task different from continuous operation.

Review the first instant as well. If the agent always starts flat, with no prior cost and replenished capital, features of the starting state may become artificial signals. If every episode begins at the same time of day or after a selected filter, the starting distribution is part of the experiment. It should not be concealed inside a sampling function that nobody examines when reading the results.

An episode boundary is an economic rule when it changes positions or payments. A useful test puts one loss immediately before the end, another immediately after the cutoff, and an open position across the boundary. Compare the environment’s records with the written contract. The aim is not necessarily identical outcomes in both locations. It is to ensure that every difference follows from a deliberate rule rather than an implementation accident.

Comparison between task termination with liquidation and an external cutoff requiring decisions about state continuity and subsequent value estimates.
Ending a task and cutting a training sequence require different decisions. The example's final cost belongs to the defined task.

10. Helping an agent learn can change what it learns

A designer may want to provide intermediate rewards so the agent receives more frequent feedback. Rewarding a correct forecast, maintaining a winning trade or reducing trading activity sounds intuitive. Each addition can nevertheless introduce another objective. An agent that gets many small price changes right but loses heavily on a few occasions can satisfy an accuracy reward while damaging the account.

A formal result concerns reward modifications based on a state potential: adding a difference of the form gamma times the next potential minus the current potential can preserve optimal policies under the original paper’s conditions. This does not mean every apparently reasonable bonus preserves the objective. Terminal states, discounting and the formulation’s assumptions matter. Ng, Harada and Russell on policy invariance and reward shaping.

For an initial investigation, every additional term needs a separate justification. Write down the behaviour it is intended to encourage, its units, the information it uses and an example in which it changes the ranking of two trajectories. If that ranking changes, we are not merely helping the optimiser: at least in that example, we are expressing another preference. That can be a conscious decision, but it needs to be acknowledged.

A practical method compares one policy with a simple economic reward and another with the added term, while keeping other changes identifiable. Evaluate both using the same economic ledger and restrictions. Their internal training scores are not directly comparable if the formulas differ. The report should reveal changes in activity, exposure, costs and losses, even when the added term improves the metric it was designed to improve.

Abstention deserves particular care. Rewarding inactivity can reduce trading, but a sufficiently large bonus makes inactivity optimal by construction. Penalising it may force trades without an advantage. A flat position already has a natural economic interpretation in a trading account whose model excludes cash interest: it earns nothing from movements in the pair and avoids transaction costs. Any extra payment needs an explicit reason, rather than an assumption that more or less activity is inherently better.

11. A small test suite that finds large loopholes

The first control uses constant prices and positive trading costs. A policy that buys and sells must lose precisely the specified costs; a flat policy must preserve equity under our assumptions. If profit appears, valuation, signs or charges are wrong. This control does not establish that the whole environment is correct, but it removes several ways of creating accounting money without any market movement.

The second control reverses positions. With the same price change and symmetric costs, the gross result of one long unit must be the opposite of one short unit. Net results are not simply opposites because both pay costs. The third control repeats an unchanged target position: it must not generate additional volume if that is how the action space is defined. The fourth opens and closes at the same price and requires a loss equal to the complete round-trip cost.

The fifth control reconciles the ending account with untransformed rewards. Run short, enumerated sequences rather than relying only on random samples. With three possible positions and a few steps, many cases can be inspected directly. Include reversals, low equity, invalid actions, extreme costs and liquidation so that the tests do not concentrate exclusively on favourable conditions.

Environment test Question it must resolve
Constant price Does trading invent a profit?
Repeated target position Is a nonexistent trade being charged?
Change from +1 to −1 Are two traded units recognised?
Open loss at the end Does valuation include the loss?
Transformed reward Is an independent economic ledger retained?

An independent test should not reuse exactly the accounting function it is intended to verify. Copying the same incorrect formula into the expected calculation produces agreement without additional evidence. Small cases can use a manual calculation, a cash-flow table or a deliberately different implementation. External reconciliation is more valuable than an attractive training curve while we are still defining the environment.

Once these tests pass, another layer of uncertainty begins: learning itself. Research by Henderson and colleagues documents variability and reproducibility problems in deep reinforcement learning. It supports recording configurations and running multiple trials; it does not establish that a Forex policy will work. A favourable seed never substitutes for reviewing the environment. Henderson and colleagues, Deep Reinforcement Learning That Matters.

Five environment checks: constant prices, repeated position, reversal, open loss and final reconciliation.
These test the accounting and timing contract. Passing them enables a study of learning; it does not certify an economic advantage.

12. What another person should be able to review

A useful research package retains observation definitions, the meaning of each action, the reward formula and an untransformed economic account. It also includes the cost contract, starting and ending rules, position limits and small episodes with expected results. These materials let someone discuss a specific decision without depending on a screenshot of the training process or the original author’s memory.

The policy report separates net profit, traded volume, exposure and loss behaviour. It includes the score used for training, clearly labelled as such. If two candidates use different rewards, it does not rank them by a column whose meaning changes between rows. This discipline prevents a change of scale from being mistaken for an improvement in the system.

Before giving the agent more complexity, compare it with transparent policies: staying flat, holding a position under a fixed contract or following a simple rule available at the same decision time. The article on building a reference before machine learning develops that choice. Here, a reference also helps find environment defects because we already know which actions it should execute.

When studying a robot’s rules and code, the concrete question is whether its position and account can be reconstructed, rather than whether it carries an “artificial intelligence” label. Within the initial Forex scope, a demo CSV can support a controlled example and an implementation comparison. This does not imply that paid packages include CSV files, or that an exercise on demonstration data validates a learned policy.

A final review can ask another person to explain a randomly selected transition: what the agent knew, what it chose, how much it traded, which price movement it received and where every charge came from. If any piece requires a guess, the specification is incomplete. The reward is ready when it can be audited without trusting the agent.

The result of this preliminary work is not a promise of profit. It is a task defined precisely enough for an observed improvement to mean something. Generalisation, stability and execution still need investigation afterwards. We will, however, no longer be asking an algorithm to discover a trading policy and the correct interpretation of our own accounting at the same time.

Three separate layers: the economic objective, the environment's accounting and the reward delivered to the agent.
A reward connects a task to an algorithm; its definition should be reviewable independently of that algorithm.
Back to the Blog