Preprint
Article

This version is not peer-reviewed.

Decomposable Reward Modeling and Realistic Environment Design for Reinforcement Learning-Based Forex Trading

Submitted:

29 October 2026

Posted:

30 October 2026

You are already at the latest version

Abstract
Reinforcement learning (RL) for foreign exchange (Forex) trading requires realistic execution modeling, interpretable reward design, and action spaces that respect market constraints. Existing approaches often simplify these aspects, limiting policy transparency and practical relevance. This paper presents a modular RL framework integrating three components: (1) a friction-aware execution engine enforcing anti-lookahead semantics—observations at closet, execution at opent+1, and mark-to-market at closet+1—while modeling spread, commission, slippage, rollover financing, and margin-triggered liq-uidation; (2) a decomposable 11-component reward architecture with fixed, pre-specified weights and per-step logging, enabling attribution, ablation, and auditability; and (3) a 10-action discrete interface supporting scaling, reduction, closure, and reversal, with legal-action masking enforcing margin-aware feasibility during training and evaluation. Empirical evaluation on EURUSD training-split data reveals non-monotonic interactions among reward components, demonstrating that additional penalties do not consistently improve performance. The full reward configuration achieves a terminal training Sharpe ratio of 0.765 and cumulative return of 57.09%. Comparing action spaces, the extended 10-action interface increases cumulative return but reduces Sharpe relative to a conservative 3-action variant, revealing a return–activity trade-off under a fixed training budget. Scaling-enabled strategies consistently reduce drawdowns, with the combined configuration delivering the strongest endpoint performance. Supplementary diagnostics on GBPUSD, USDJPY, and AUDUSD exhibit qualitatively similar trends. These findings demonstrate the framework’s diagnostic value and underscore the importance of controlled, interpretable design in RL-based financial systems.
Keywords: 
;  ;  ;  ;  ;  

1. Introduction

Reinforcement learning (RL) has emerged as a prominent paradigm for sequential decision-making in complex and uncertain environments, with successful applications ranging from games to continuous control in robotics (Mnih et al., 2015; Sutton & Barto, 2018). Financial trading is a demanding RL problem because decisions are sequential, outcomes are delayed, and market microstructure imposes strict feasibility constraints (Gould et al., 2013; Moody & Saffell, 2001; Zhang et al., 2020). Foreign exchange (Forex) trading is particularly challenging. It operates continuously (24/5), is typically leveraged, and is sensitive to transaction costs and financing frictions, while return distributions are heavy-tailed, noisy, and regime dependent (Cont, 2001). These properties increase gradient variance, complicate credit assignment, and make policy evaluation sensitive to execution assumptions.
Despite substantial recent activity in applied RL-for-trading research—such as predictive signal extraction (Deng et al., 2017), multi-asset portfolio allocation (Jiang et al., 2017), and raw return optimization (Meng & Khushi, 2019; Theate & Ernst, 2021)—three structural gaps continue to limit practical use. First, environment fidelity is often insufficient. Trading performance depends on execution mechanics that are difficult to simulate but essential in leveraged markets (Zhang et al., 2020). Many studies rely on simplified simulators that under-model or omit spread-embedded execution friction, dynamic financing costs, margin-based liquidation, and strict decision-execution timing (Carapuco et al., 2018; Rundo, 2019). Such simplifications widen the sim-to-real gap and can produce policies that are profitable only because the simulator is permissive.
Second, reward design opacity obscures the learning signal. Conventional approaches typically optimize a single scalar reward (for example, Profit and Loss (PnL), equity delta, or a risk-adjusted proxy such as the Sharpe ratio) (Moody & Saffell, 2001; Sharpe, 1994; Theate & Ernst, 2021). Although such objectives are easy to optimize, they make credit assignment less transparent and obscure whether observed gains arise from timing skill, reduced turnover, or leverage control. Without systematic decomposition and ablation, reward shaping remains difficult to analyze, tune, and reproduce (Ng et al., 1999).
Third, action-space granularity is often underspecified. Existing formulations frequently rely on coarse discrete spaces (for example, buy/sell/hold commands) (Theate & Ernst, 2021) or unconstrained continuous position sizing derived from deterministic policy gradients (Haarnoja et al., 2018; Jiang et al., 2017; Schulman et al., 2017). Coarse spaces do not represent practical operations such as scaling into positions, reducing exposure, or executing explicit reversals. Continuous formulations can express richer control, but they make hard feasibility constraints such as margin limits and position bounds less transparent unless they are enforced explicitly, for example through action masking in structured discrete domains (Huang & Ontañón, 2020).
To address these challenges, this paper presents a system-level, open-source framework rather than a new RL algorithm. The proposed system integrates: (i) a Gymnasium-compatible Forex environment with strict anti-lookahead execution, friction and rollover modeling, and margin-aware risk controls; (ii) an 11-component decomposable reward architecture with fixed aggregation, state-dependent clipping, and transparent per-step component logging; and (iii) a legal-action-masked 10-action discrete space with explicit primitives for pyramiding, martingale-style scaling, reduction, closure, and reversal. All experiments are driven through configuration-based protocols so that experimental variants can be generated without ad hoc code changes.

Contributions.

Our primary contributions are methodological and infrastructural rather than algorithmic:
  • System-level execution environment: We encode anti-lookahead timing, transaction frictions, rollover financing, margin constraints, and liquidation as simulator-enforced properties rather than post hoc corrections.
  • Reward and action interface design: We introduce an 11-component reward system and a 10-action legality-masked interface, enabling component-level attribution and explicit position-management primitives that are not available in coarse buy/sell/hold formulations.
  • Controlled experimental protocol: We demonstrate the framework through three experiment families (reward ablation, action-space comparison, and scaling analysis) on the EURUSD, with all variants generated via configuration rather than structural code changes.
  • Reproducibility infrastructure: We provide a complete pipeline for deterministic artifact generation under fixed seeds, resolved configurations, isolated outputs, and leakage-free feature processing.
The empirical emphasis of this work is methodological robustness rather than state-of-the-art performance benchmarking. Reproducibility and experimental scope, including seeding and evaluation partitioning, are detailed in Section 4; interpretations focus on system behavior and learning dynamics rather than stochastic performance variation, consistent with cautionary guidance in trading-RL evaluation (Zhang et al., 2020).

Research questions.

The empirical program is organized around three focused research questions:
RQ1. 
Which reward components contribute useful training signal, and does progressive penalty activation alter training-period risk-adjusted return relative to a profit-only baseline?
RQ2. 
Does increased action-space granularity change training efficiency and risk-adjusted learning relative to a coarse three-action discrete formulation?
RQ3. 
How do asymmetric position-scaling strategies (pyramiding vs. martingale-style scaling) influence training-period risk profiles, drawdown dynamics, and average scaling behavior?
See Section 4 for the canonical experimental setup, including evaluation partitioning and reproducibility controls.
The remainder of the paper is organized as follows. Section 2 situates the framework within existing RL trading literature and identifies the research gap. Section 3 details the environment, reward, and agent design. Section 4 describes the evaluation protocol and reproducibility controls. Section 5 presents the empirical findings, and Section 6 discusses implications. Section 7 then outlines limitations and forward directions before Section 8 concludes.

3. Methodology

This section formalizes the end-to-end research pipeline, from causal data preparation to environment transition mechanics and mask-aware value learning. The methodology is a system-level framework built around standard value-based learners rather than a new optimization algorithm. To improve reproducibility, we provide explicit algorithmic specifications for (i) execution and portfolio updates, (ii) compositional reward assembly, and (iii) training-loop optimization.

Reading guide.

The algorithms are presented in operational order rather than file-name order: the execution algorithm (Algorithm 1) constructs the transition, the reward algorithm (Algorithm 2) converts its trace into a learning signal, and the training algorithm (Algorithm 3) consumes that signal. Thus, the compiled numbering is Algorithm 1 for execution, Algorithm 2 for reward, and Algorithm 3 for training.
Algorithm 1:Execution and portfolio update with frictions.
1:
Input: portfolio state P t , action proposal a t , bars
2:
   ( close t , open t + 1 , close t + 1 ) , configuration Ω , legal mask m t
3:
Output: next portfolio state P t + 1 , realized/unrealized PnL,
4:
  cost trace, violation flag, and liquidation flag
5:
Recompute m t from current direction, free margin, and scaling-depth limits
6:
if m t [ a t ] = 0 then
7:
  Set executed action a ˜ t ← HOLD and raise constraint-violation flag
8:
else
9:
  Set a ˜ t ← a t
10:
end if
11:
Perform pre-trade feasibility checks for a ˜ t (margin and leverage)
12:
if pre-trade feasibility fails then
13:
  Set a ˜ t ← HOLD and raise constraint-violation flag
14:
end if
15:
Set base execution anchor p base ← open t + 1
16:
Apply spread adjustment to obtain side-aware quoted price
17:
Apply deterministic slippage to obtain final fill price p fill
18:
Execute action semantics for a ˜ t (open, scale, reduce, close, reverse, or hold)
19:
Deduct commissions from cash according to traded volume
20:
if timestamp equals rollover time (22:00 UTC) then
21:
  Apply rollover financing (triple rollover on Wednesday)
22:
end if
23:
Mark open positions to close t + 1 and update unrealized and realized PnL
24:
Update cash, equity, used/free margin, utilization ratio, and drawdown statistics
25:
if equity below liquidation threshold or maintenance-margin rule violated then
26:
  Force-liquidate all open positions using configured liquidation convention
27:
  Set liquidation event flag and apply liquidation accounting effects
28:
end if
29:
Construct and return P t + 1 with per-step diagnostic traces
Algorithm 2:Per-step compositional reward computation.
1:
Input: transition trace τ t , component enable switches g i ∈ { 0 , 1 } ,
2:
  weights w i , clipping bounds [ r min , r max ]
3:
Output: clipped reward r t and component log dictionary L t
4:
Define fixed component order:
5:
  profit, holding, volatility, drawdown, transaction, overtrading,
6:
  pyramiding, martingale, margin-utilization, liquidation, constraint-violation
7:
for each component i in the fixed order do
8:
  if  g i = 1  then
9:
    Compute component value c i ( τ t )
10:
  else
11:
    Set c i ( τ t ) ← 0
12:
  end if
13:
  Compute weighted term u i ← w i c i ( τ t )
14:
  Append ( c i , w i , u i , g i ) to L t
15:
end for
16:
Compute raw reward r t raw ← ∑ i u i
17:
Compute clipped reward r t ← clip ( r t raw , r min , r max )
18:
Append ( r t raw , r t , ⊮ [ r t raw ≠ r t ] ) to L t
19:
Return ( r t , L t )
Algorithm 3:Mask-aware DQN/DDQN training with legal-action masking.
1:
Input:
2:
  Environment  & state: environment E ; state s t ; legal-action mask m t ∈ { 0 , 1 } | A | , where m t [ a ] = 1 iff a is legal in s t
3:
  Networks: online network Q θ ; target network Q θ −
4:
  Replay buffer:  D with capacity N
5:
  Training hyperparameters: batch size B; discount γ
6:
  Scheduling: learn-start t start ; learn frequency f learn ; target-sync interval f target ; evaluation interval f eval ; total steps T; evaluation budget K eval
7:
  Algorithm type:  DQN or DDQN
8:
Initialize θ randomly; set θ − ← θ ; initialize the ϵ schedule
9:
Reset E and observe ( s 0 , m 0 )
10:
for t = 0 to T − 1  do
11:
  Select a t by mask-aware ϵ -greedy on m t : with probability ϵ , sample a t ∼ Unif ( { a : m t [ a ] = 1 } ) ; otherwise a t ← arg max a : m t [ a ] = 1 Q θ ( s t , a )
12:
  Execute a t in E and observe ( s t ′ , r t , d t , info t , m t ′ )
13:
  Store ( s t , a t , r t , s t ′ , d t , m t , m t ′ ) in D
14:
  Update ( s t , m t ) ← ( s t ′ , m t ′ )
15:
  if  t ≥ t start and t mod f learn = 0 and | D | ≥ B  then
16:
    Sample minibatch { ( s i , a i , r i , s i ′ , d i , m i , m i ′ ) } i = 1 B from D
17:
    if algorithm type is DDQN then
18:
       a i ★ ← arg max a : m i ′ [ a ] = 1 Q θ ( s i ′ , a ) , ∀ i
19:
       y i ← r i + γ ( 1 − d i ) Q θ − ( s i ′ , a i ★ ) , ∀ i
20:
    else
21:
       y i ← r i + γ ( 1 − d i ) max a : m i ′ [ a ] = 1 Q θ − ( s i ′ , a ) , ∀ i
22:
    end if
23:
     L ← 1 B ∑ i = 1 B Huber Q θ ( s i , a i ) − y i
24:
    Update θ by gradient descent with gradient clipping
25:
  end if
26:
  if  t mod f target = 0  then
27:
    Hard-sync target network: θ − ← θ
28:
  end if
29:
  if  t mod f eval = 0  then
30:
    Evaluate the deterministic policy ( ϵ = 0 ) for K eval episodes and log all outputs
31:
  end if
32:
  Update ϵ
33:
end for
34:
Output: trained parameters θ , replay buffer state, and diagnostic artifacts

3.1. Design Principles and System Overview

The methodology is organized around three design principles: economic fidelity, temporal causality, and auditability. Economic fidelity is enforced through explicit transaction-cost and margin accounting; temporal causality is enforced through strict chronological processing and anti-lookahead execution timing; and auditability is enforced through deterministic component ordering, configuration snapshots, and structured logging artifacts. The resulting end-to-end pipeline (data ingestion → preprocessing → environment simulation → value-function learning → standardized evaluation export) is summarized in Figure 1.
Figure 1. System architecture of the RL trading framework, linking configuration, data processing, training, deterministic backtesting, and reproducibility logging in one end-to-end pipeline.
Figure 1. System architecture of the RL trading framework, linking configuration, data processing, training, deterministic backtesting, and reproducibility logging in one end-to-end pipeline.
Preprints 241217 g001

3.2. Data Pipeline, Temporal Partitioning, and Leakage Control

The dataset consists of hourly open-high-low-close-volume (OHLCV) bars for EURUSD, GBPUSD, USDJPY, and AUDUSD (summary in Table 5). Data are normalized to Coordinated Universal Time (UTC), validated for schema integrity, deduplicated using a last-occurrence retention policy, and processed with deterministic missing-value handling.

Chronological processing policy.

To preserve temporal causality, all experiments process data in strict chronological order with no shuffling. All evaluation metrics are computed exclusively on training trajectories and logged artifacts. No held-out or test split is used at any stage. This scope is deliberate: all reported results describe the training distribution, and no generalization or out-of-sample claims are made.

Scope and reproducibility.

Feature transformations, warm-up handling, periodic evaluation, and final evaluation use only training data and stored training artifacts. The manuscript therefore reports deterministic, training-artifact-level results rather than held-out performance; reproducibility and seeding details are centralized in Section 4.

Train-only transformations and warm-up handling.

Feature scaling parameters are estimated on the training data only and reused throughout. To initialize rolling indicators at the start of training, a warm-up lookback segment is prepended from the beginning of the training data, and warm-up rows are discarded from final training artifacts. These choices follow the scope and reproducibility policy above.

3.3. Feature Engineering and Observation Construction

Features are organized into deterministic namespaces so that all runs share a stable, auditable column ordering:
  • Technical indicators: simple and exponential moving averages (SMA/EMA; 10, 20, 50), relative strength index (RSI; 14), moving average convergence divergence (MACD; 12, 26, 9), Bollinger components (20, 2 σ ), one-bar log return, and rolling volatility.
  • Microstructure proxies: spread proxy ( H − L ) / C , short-horizon price-change proxy, realized volatility proxy, and UTC session label.
The canonical ordering improves reproducibility and prevents accidental feature-index drift across experiment variants.

Windowing and input dimensions.

Let L denote the observation lookback window ( L = 24 in release runs), d feat the number of engineered market features, d port = 10 the portfolio-state dimension, and n a the active action count ( n a ∈ { 3 , 10 } ). The flattened MLP input dimension is
d flat = L d feat + d port + n a .
where d flat denotes the flattened input width, L is the observation lookback window, d feat is the number of engineered market features, d port is the portfolio-state dimension, and n a is the active action count.
Equation 1 is used consistently across training and evaluation to guarantee that architecture instantiation matches the declared observation schema. The observation schema is summarized in Table 2.
Table 2. Observation schema and dimensions used by the Gymnasium environment.
Table 2. Observation schema and dimensions used by the Gymnasium environment.
Field Shape Role
market [ L , d feat ] Rolling market-feature window ( L = 24 )
portfolio [ d port ] Normalized account state ( d port = 10 )
mask [ n a ] Legal-action mask ( n a ∈ { 3 , 10 } )
flat [ L d feat + d port + n a ] Flattened vector for MLP agents

3.4. Trading Environment

The environment follows a Gym-style application programming interface (API), consistent with the OpenAI Gym design lineage (Brockman et al., 2016), and exposes dictionary observations together with deterministic transition diagnostics. This explicit state contract enables direct reproducibility checks across training and evaluation workflows.

3.4.1. Action Space and Legal Masking

The extended action interface contains 10 operations:
  • HOLD
  • OPEN_LONG, OPEN_SHORT
  • PYRAMID_LONG, PYRAMID_SHORT
  • MARTINGALE_LONG, MARTINGALE_SHORT
  • REDUCE
  • CLOSE
  • REVERSE
For controlled comparisons, a simplified 3-action adapter is used:
  • HOLD
  • TARGET_LONG
  • TARGET_SHORT
These are mapped to valid extended operations conditioned on the current position state.
Action legality is recomputed at every step using direction, margin availability, and scaling-depth constraints. The legal mask is stored with transitions in replay and reused for both exploratory sampling and masked argmax target computation. Although prior empirical evidence is reported primarily for policy-gradient settings (Huang & Ontañón, 2020), the same legality principle is applied here to value-based updates. Table 3 summarizes extended-action semantics.
Table 3. Extended action semantics and legality conditions (executed at o p e n t + 1 ).
Table 3. Extended action semantics and legality conditions (executed at o p e n t + 1 ).
ID Action Primary legality precondition Execution effect
0 HOLD Always legal Maintain current position; no new order submitted
1 OPEN_LONG Flat position and sufficient free margin Open long exposure at base lot size
2 OPEN_SHORT Flat position and sufficient free margin Open short exposure at base lot size
3 PYRAMID_LONG Existing long position, scaling depth below cap, margin available Add to long position using configured pyramid increment
4 PYRAMID_SHORT Existing short position, scaling depth below cap, margin available Add to short position using configured pyramid increment
5 MARTINGALE_LONG Existing long position, martingale depth below cap, margin available Add long exposure after adverse movement using martingale scaling rule
6 MARTINGALE_SHORT Existing short position, martingale depth below cap, margin available Add short exposure after adverse movement using martingale scaling rule
7 REDUCE Non-flat position Partially reduce current exposure (configured reduction fraction)
8 CLOSE Non-flat position Fully close current position
9 REVERSE Non-flat position and sufficient margin for opposite side Close current direction, then open opposite direction within one action

3.4.2. Execution Timing and Market Frictions

To prevent lookahead leakage, step timing is fixed as:
observe close t → decide a t → fill open t + 1 → mark close t + 1 .
where close t denotes the close price observed at step t, a t is the action selected after observing that close, open t + 1 is the next bar’s open used for execution, and close t + 1 is the next bar’s close used for mark-to-market.
The fill model applies spread, commission, and slippage in deterministic order; rollover financing is charged at 22:00 UTC with triple rollover on Wednesdays. Equation 2 is the causal timing contract summarized in Figure 2.
Figure 2. Causality-correct environment step timing: the environment emits s t , receives a t , execution is driven by market open t + 1 , portfolio state is marked at close t + 1 , reward engine returns only r t to the environment, and the environment emits the full transition ( s t , a t , r t , s t + 1 ) without any Reward→Agent bypass.
Figure 2. Causality-correct environment step timing: the environment emits s t , receives a t , execution is driven by market open t + 1 , portfolio state is marked at close t + 1 , reward engine returns only r t to the environment, and the environment emits the full transition ( s t , a t , r t , s t + 1 ) without any Reward→Agent bypass.
Preprints 241217 g002

3.4.3. Portfolio and Risk Accounting

The account model tracks cash, equity, realized and unrealized PnL, used/free margin, directional exposure, scaling depth, and drawdown. Core constraints include maximum leverage ( 30 × ), maintenance margin ( 50 % of initial margin requirement), bounded scaling depth, and forced liquidation at a fixed equity threshold. These controls are necessary to prevent value-function optimization from exploiting infeasible leverage trajectories.
The execution algorithm fixes the operational order of legality checks, fill construction, cost deduction, rollover financing, mark-to-market, margin updates, and forced liquidation. Making this order explicit is necessary for economic fidelity: the transition must reflect a single deterministic accounting sequence.
Algorithm 1 returns the next portfolio state together with realized and unrealized PnL, costs, and diagnostic flags. The transition trace is not yet a learning signal; it records realized PnL, costs, violation flags, and liquidation diagnostics that the reward algorithm converts into a scalar reward. This deliberate separation keeps execution accounting deterministic while leaving reward composition ready for ablation.

3.5. Compositional Reward Modeling

We model the reward as a weighted composition of components. Let c i ( s t , a t , s t + 1 ) denote component i with weight w i . The pre-normalized reward is:
R t raw = ∑ i = 1 11 w i c i ( s t , a t , s t + 1 ) .
where R t raw is the unbounded step reward, w i is the fixed weight assigned to component i, c i ( s t , a t , s t + 1 ) is the value of component i computed from the transition, and i indexes the 11 reward terms in Table 4.
Table 4. Reward component definitions, baseline weights, and intended behavioral effects.
Table 4. Reward component definitions, baseline weights, and intended behavioral effects.
Component Weight Primary purpose Typical trigger / penalty form
Profit (post-cost) 1.00 Core economic learning signal Step-wise post-cost equity return
Holding incentive 0.03 Reward sustained profitable exposure Small bonus when an open position remains profitable under contained drawdown
Volatility penalty 0.01 Discourage unstable equity trajectories Negative term proportional to short-horizon equity-return volatility
Drawdown penalty 0.05 Penalize peak-to-trough equity loss Incremental drawdown penalty with a stronger regime beyond the severe-drawdown threshold
Transaction burden 0.10 Reduce cost-driven churn Cost-normalized penalty for spread, slippage, commission, and rollover
Overtrading penalty 0.02 Suppress unnecessary repositioning Bounded penalty tied to elevated local trade frequency
Pyramiding penalty 0.05 Constrain aggressive winner-adding Depth-aware penalty for additional pyramid levels
Martingale penalty 0.12 Discourage averaging down under leverage Depth-aware penalty with a larger coefficient than pyramiding
Margin-utilization penalty 0.05 Avoid excessive leverage before liquidation Nonlinear penalty when utilization exceeds a conservative threshold
Liquidation penalty 2.00 Impose strong aversion to forced liquidation Large penalty on a forced-liquidation event
Constraint-violation penalty 0.10 Deter invalid action proposals Penalty when the policy attempts an invalid action
The final reward applies clipping:
R t = clip ( R t raw , r min , r max ) .
where R t is the clipped reward used for temporal-difference updates, r min and r max are the lower and upper clipping bounds, and clip ( · ) truncates its argument to the interval [ r min , r max ] . In the reward algorithm and training loop, this same clipped scalar is denoted by r t ; R t raw and R t are the prose/equation notation for the raw and clipped quantities, respectively.
Equation 3 defines deterministic component aggregation, and Equation 4 bounds temporal-difference target magnitude.

Clipping vs. running normalization.

Clipping bounds temporal-difference targets and stabilizes early training by limiting extreme updates. It preserves sign information and relative ordering within the unclipped region, but compresses large-magnitude rewards. In contrast, running normalization mitigates scale drift but introduces non-stationarity into the learning objective. We therefore adopt clipping as the default and use adaptive normalization only in sensitivity analyses.

Component structure and weighting.

The 11 components span four functional groups: (i) return, represented by post-cost profit; (ii) risk control, represented by volatility and drawdown penalties; (iii) trading frictions, represented by transaction burden and overtrading penalties; and (iv) constraints, represented by margin usage, liquidation, and rule-violation terms. The table below summarizes the exact weights and behavioral roles.
The economic and risk components have distinct roles. Profit is the primary economic signal and rewards post-cost equity growth. Holding incentive rewards sustained profitable exposure when the position remains favorable and drawdown is contained. Volatility and drawdown penalties discourage unstable equity trajectories and large peak-to-trough losses.
The friction and constraint components regulate how that exposure is obtained. Transaction burden and overtrading penalties reduce churn by discouraging spread, slippage, commission, rollover, and unnecessary re-entry. Pyramiding and martingale penalties distinguish controlled scale-in after favorable movement from averaging down into adverse movement; the martingale term is weighted more heavily because loss-averaging under leverage is riskier than adding exposure after gains. Margin-utilization, liquidation, and constraint-violation penalties encode broker-style feasibility limits and penalize states or actions that threaten forced exit. The weights are a calibrated baseline for these roles, not a universal optimum.
The baseline weights were fixed before the main experiments so that auxiliary terms regularize the policy without displacing profit as the dominant signal. This choice also makes the reward easier to interpret: the ablation family in Section 5 serves as a sensitivity check showing how changes in component activation alter the return–drawdown trade-off. The reported weights should therefore be read as a calibrated baseline rather than as a universally optimal setting.
The reward algorithm defines the deterministic reward-assembly pipeline: it applies component enable switches, a fixed component order, per-component weighting, clipping, and structured logging. The fixed order is the operational counterpart of the taxonomy summarized in Figure 3.
Figure 3. Reward taxonomy and computation flow for the RL trading environment, from agent–environment interaction through component aggregation and normalization to the final scalar reward.
Figure 3. Reward taxonomy and computation flow for the RL trading environment, from agent–environment interaction through component aggregation and normalization to the final scalar reward.
Preprints 241217 g003
The component dictionary is logged for every transition, while only the clipped scalar reward r t is passed to the learner. The component traces support diagnosis and ablation attribution without changing the signal consumed by the value update.

Logging and ablation protocol.

Component evaluation follows a fixed order, and each term is logged per step via the environment info dictionary and persisted reward traces. This enables direct attribution in ablation experiments (r1–r7), where individual components or weights are selectively modified. Because non-potential reward shaping can alter optimal policies (Ng et al., 1999), profit remains the primary signal, with auxiliary penalties introduced incrementally.
Figure 3 should therefore be read alongside Algorithm 2: it visualizes the same fixed component order and aggregation flow.

3.6. Agent Architectures

Both agents are value-based and share the same backbone: a feed-forward multilayer perceptron (MLP) with hidden dimensions [ 512 , 512 , 256 ] , ReLU activations, and a linear Q-value output head. Output dimensionality equals the active action-space size (3 in simplified mode, 10 in extended mode). The agents are Deep Q-Network (DQN) and Double Deep Q-Network (DDQN) variants, selected because they support explicit legality masking in discrete control.

3.6.1. DQN

DQN uses temporal-difference targets with periodic hard target-network synchronization (Mnih et al., 2015):
y t DQN = r t + γ ( 1 − d t ) max a ′ ∈ A legal ( s t + 1 ) Q θ − ( s t + 1 , a ′ ) .
where y t DQN is the temporal-difference target, r t is the clipped reward, γ is the discount factor, d t ∈ { 0 , 1 } is the terminal indicator, A legal ( s t + 1 ) is the legal-action set in state s t + 1 , and Q θ − is the target-network Q-function parameterized by θ − . Equation 5 masks invalid actions directly in target construction.

3.6.2. Double DQN

Double DQN decouples action selection and evaluation:
a * = arg max a ′ ∈ A legal ( s t + 1 ) Q θ ( s t + 1 , a ′ ) .
where a * is the legal greedy action selected by the online network, Q θ is the online Q-function, θ denotes the online-network parameters, and A legal ( s t + 1 ) is the legal-action set in state s t + 1 .
y t DDQN = r t + γ ( 1 − d t ) Q θ − ( s t + 1 , a * ) .
where y t DDQN is the temporal-difference target, r t is the clipped reward, γ is the discount factor, d t ∈ { 0 , 1 } is the terminal indicator, and Q θ − is the target-network evaluation at the selected action a * . Equations 6 and 7 separate online action selection from target-network evaluation, reducing value overestimation in volatile training regimes (van Hasselt et al., 2016).
Mask-aware exploration policy.
Exploration follows an ϵ -greedy policy defined on legal actions only: with probability ϵ , the agent samples uniformly from legal actions; otherwise, it selects the legal argmax action. The same legality constraints are applied during replay-based target computation, ensuring consistency between data collection and value updates.
Algorithmic variants outside release scope.
The architecture is compatible with dueling heads and distributional value estimation, which are relevant in heavy-tailed return settings (Bellemare et al., 2017; Wang et al., 2016). These variants are intentionally excluded from the main release protocol to isolate the effect of environment and reward design under DQN-family baselines.

3.7. Training Protocol

Core settings are fixed across experiment families unless explicitly overridden. For global reproducibility and side-by-side comparability, the exact training and environment values are consolidated in Table 6 within Section 4.
The training algorithm consolidates the mask-aware DQN/DDQN loop, including replay storage, learning gates, target synchronization, and evaluation cadence. In particular, the legal mask m t is stored in replay and reused during target construction, so exploration and backup share the same legality contract.
Algorithm 3 consumes the transition and reward outputs described above and returns trained parameters together with diagnostic artifacts. The subsequent figure is a schematic of this training algorithm, not a separate procedure.
Figure 4. Training-loop schematic with mask-aware interaction, complete transition construction, replay learning, and periodic target synchronization.
Figure 4. Training-loop schematic with mask-aware interaction, complete transition construction, replay learning, and periodic target synchronization.
Preprints 241217 g004

Rationale for optimization settings.

The 10 6 -step horizon improves coverage of diverse market regimes for off-policy replay. A 40K replay buffer balances decorrelation and recency under non-stationary financial dynamics. Batch size 128, Huber loss, gradient clipping (norm 10), and a learning rate of 2.5 × 10 − 4 were selected to stabilize updates without obscuring the effect of the environment and reward design. Detailed values are summarized in Table 6 and Appendix A.

Evaluation cadence and diagnostic logging.

Training logs include learning curves, loss, reward components, action distributions, turnover, and liquidation events. Periodic deterministic evaluation is performed during training (default interval: every 10,000 steps) using training episodes and stored trajectories. At the end of each run, a deterministic full-horizon evaluation is conducted on the training data. Reported metrics include cumulative and annualized returns, volatility, Sharpe (Sharpe, 1994), Sortino (Sortino & Price, 1994), maximum drawdown, win rate, turnover, liquidation statistics, and scaling utilization. These evaluations follow the scope stated above.

Determinism scope and methodological limitation.

The canonical seed and the remaining reproducibility details are reported in Section 4.

4. Experimental Design

This section specifies the controlled evaluation protocol used to answer RQ1–RQ3. We first define scope and invariants, then map each experiment family to a research question, and finally describe metrics and reproducibility controls.

4.1. Dataset Scope and Split Policy

The primary controlled families (Exp-01–Exp-03) are executed on hourly EURUSD training-split data with Double DQN (van Hasselt et al., 2016) to isolate component effects under a fixed optimization budget. We additionally report benchmark comparisons and cross-pair diagnostics from the same artifact generation pipeline to contextualize the primary findings; these are descriptive analyses rather than transfer benchmarks.
Table 5. Dataset statistics (raw hourly bars). The chronological 80/20 split is shown for completeness; all reported experiments use the training split only.
Table 5. Dataset statistics (raw hourly bars). The chronological 80/20 split is shown for completeness; all reported experiments use the training split only.
Pair N total N train N held - out
AUDUSD 25 000 20 000 5 000
EURUSD 25 000 20 000 5 000
GBPUSD 25 000 20 000 5 000
USDJPY 25 000 20 000 5 000
Pair Train period Held-out period†
AUDUSD 2022-01-01 – 2025-01-01 2025-01-01 – 2026-01-01
EURUSD 2022-01-01 – 2025-01-01 2025-01-01 – 2026-01-01
GBPUSD 2022-01-01 – 2025-01-01 2025-01-01 – 2026-01-01
USDJPY 2022-01-01 – 2025-01-01 2025-01-01 – 2026-01-01
†Held-out period reported for completeness only; not used in any reported experiment.
The dataset table clarifies that all pairs share an aligned chronological split policy, allowing pair-level comparisons without confounding differences in temporal coverage.

4.2. Experiment Families and Contextual Extensions

All studies are executed via configuration-only overrides using YAML files, with no structural code changes:
  • Exp-01Reward ablation: cumulative reward component schedule r1 to r7.
  • Exp-02Action space: simplified (3-action adapter) vs extended (10-action).
  • Exp-03Scaling analysis: no scaling, pyramid-only, martingale-only, both.
  • Context A (benchmark calibration): RL agents compared against random, buy-and-hold, momentum, and mean-reversion baselines under identical simulator semantics.
  • Context B (cross-pair diagnostics): DQN vs. Double DQN comparisons on GBPUSD, USDJPY, and AUDUSD using the full reward profile; these are descriptive observations under the same simulator semantics.
All families inherit the same anti-lookahead timing rule, transaction-friction model, and margin constraints, ensuring that observed differences arise from controlled design changes rather than simulator drift.

4.3. Protocol Invariants and Hyperparameter Budget

To preserve comparability, core optimization and environment settings are held constant across families unless a specific family intentionally perturbs that axis. These shared values are summarized in Table 6.
Table 6. Core hyperparameters, interface dimensions, and environment settings used in release experiments.
Table 6. Core hyperparameters, interface dimensions, and environment settings used in release experiments.
Parameter Value Scope
Observation schema Dict:market/portfolio/mask/flat Environment
Observation window 24 bars Environment
Portfolio vector dimension 10 Environment
Action outputs ( n a ) 10 (extended) or 3 (simplified) Agent/Environment
Flat input dimension 24 d feat + 10 + n a Agent
Q-network architecture MLP [512, 512, 256] + ReLU + linear head Agent
Total timesteps 1,000,000 Training
Replay buffer size 40,000 Training
Batch size 128 Training
Learn start 10,000 steps Training
Learn frequency every 4 steps Training
γ 0.99 Training
Optimizer Adam (2.5e-4) Agent
Epsilon schedule 1.0→0.01 (30K) Agent
Target update interval 2,000 steps Agent
Gradient clip 10.0 Agent
Periodic diagnostic evaluation every 10,000 steps (default) Training
Automatic mixed precision (AMP) dtype fp16 Agent
Initial capital USD 100,000 Environment
Max leverage 30x Environment
Liquidation threshold 25% equity Environment
Commission USD 3.5 / lot (round trip) Environment
Base slippage 0.5 pips Environment
Seed See Section 4 Reproducibility
Temporal split 80/20 chronological Reproducibility
Fixing this budget is especially important when interpreting action-space and scaling effects, because it prevents confounding from unequal replay exposure or optimizer aggressiveness.

4.4. Research Questions

Each experiment family is explicitly tied to a research question that guides design choices and governs interpretation of outcomes:
RQ1 
(Reward Interactions): 
Do reward components interact non-monotonically, and does progressive penalty activation improve or degrade training-period risk-adjusted return compared to a bare profit signal? (Exp-01)
RQ2 
(Action Granularity): 
How does the extended 10-action interface change return, risk-adjusted performance, drawdown, and turnover relative to the 3-action coarse adapter? (Exp-02)
RQ3 
(Scaling Asymmetry): 
How does the 2.4 × martingale-to-pyramid penalty ratio relate to asymmetric position-management behavior, with pyramid-only variants outperforming martingale-only on drawdown? (Exp-03)
Context A and Context B are interpreted as calibration analyses rather than additional primary RQs; they are used to situate the main EURUSD findings against stronger baselines and pair variation.

4.5. Metrics and Statistical Testing

Evaluation captures profitability, risk, and behavior: cumulative return, annualized return/volatility, Sharpe (Sharpe, 1994), Sortino (Sortino & Price, 1994), maximum drawdown, win rate, turnover, liquidation metrics, and scaling utilization. For paired model comparisons, outcomes are reported descriptively; no inferential hypothesis testing is performed.
Because all reported values are endpoint artifacts, we emphasize effect patterns and relative trade-offs over formal claims of distributional superiority. See Section 4 for canonical seeding and evaluation scope, consistent with cautionary guidance in trading-RL evaluation practice (Zhang et al., 2020).

4.6. Reproducibility Protocol

Reproducibility controls include deterministic seeding across Python/NumPy/PyTorch/environment, resolved-config snapshots stored per run, canonical artifact paths, and strict chronological splitting. Numerical findings in this manuscript are therefore directly traceable to saved outputs. This protocol is aligned with reproducibility priorities emphasized in prior trading-RL benchmark literature (Liu et al., 2021; Zhang et al., 2020).

Important scope note.

This release reports single-seed outcomes (seed 42). Accordingly, we interpret differences as informative system-behavior evidence rather than definitive estimates of expected out-of-sample superiority.

5. Results

All values in this section are derived from training artifacts only (see Section 4). We report primary outcomes for Exp-01–Exp-03, then place them in context using benchmark comparisons and cross-pair diagnostics generated under the same simulator semantics. These latter analyses are descriptive and do not establish transfer performance.

5.1. Global Performance Dashboard

Before unpacking each experiment family, Figure 5 provides a compact multi-metric snapshot of profitability, risk, and behavior indicators used throughout this section.
Figure 5. Multi-panel dashboard of endpoint metrics across retained experiment families, summarizing return, drawdown, risk-adjusted performance, and activity.
Figure 5. Multi-panel dashboard of endpoint metrics across retained experiment families, summarizing return, drawdown, risk-adjusted performance, and activity.
Preprints 241217 g005
The dashboard suggests that no single configuration dominates all dimensions simultaneously: variants with stronger endpoint return often incur higher activity or weaker conservative risk summaries, reinforcing the need for objective-specific model selection.

5.2. Reward Component Ablation (Exp-01)

Objective.Exp-01 progressively enables reward components to identify constructive versus destructive interactions.
We first report endpoint statistics in Table 7, then use distributional and trajectory views to diagnose interaction nonlinearity.
Table 7. Reward ablation on EURUSD train split (Double DQN; see Section 4).
Table 7. Reward ablation on EURUSD train split (Double DQN; see Section 4).
Variant Sharpe Sortino Cum.Ret(%) MaxDD(%) WinRate(%) Turnover AvgPyr AvgMart
r1 0.412 0.573 27.79 10.48 35.18 1592.83 0.113 0.121
r2 0.237 0.353 12.20 8.60 31.85 1741.58 0.187 0.127
r3 0.638 0.979 41.20 5.44 31.53 1488.67 0.165 0.138
r4 0.687 1.029 43.21 5.68 30.99 1344.47 0.197 0.144
r5 0.589 0.822 41.74 4.12 31.07 1350.00 0.172 0.156
r6 0.410 0.539 24.58 7.70 27.38 1200.32 0.132 0.089
r7 0.765 1.117 57.09 2.31 33.15 1156.51 0.173 0.169
Endpoint values already indicate interaction effects: Sharpe and cumulative return do not improve monotonically with added penalties, and several intermediate variants underperform simpler compositions.
Figure 6 makes the non-monotonicity explicit: the sequence deteriorates from r1 to r2, recovers across r3–r5, softens at r6, and peaks at r7. The pattern is consistent with interaction effects among reward components rather than a strictly additive response to additional penalties.
Figure 6. Reward-ablation comparison for variants r1–r7 on EURUSD, showing a non-monotone profile with r7 as the strongest endpoint.
Figure 6. Reward-ablation comparison for variants r1–r7 on EURUSD, showing a non-monotone profile with r7 as the strongest endpoint.
Preprints 241217 g006
The trajectory view in Figure 7 corroborates the endpoint summary: the strongest terminal profile is not produced by the earliest penalty additions, but by the fully calibrated composition. This supports the claim that reward engineering is an empirical calibration task rather than a strictly additive design process.
Figure 7. Training equity trajectories for r1–r7, highlighting non-monotone intermediate behavior and the strongest endpoint for r7.
Figure 7. Training equity trajectories for r1–r7, highlighting non-monotone intermediate behavior and the strongest endpoint for r7.
Preprints 241217 g007

5.3. Action-Space Comparison (Exp-02)

Objective.Exp-02 compares the extended 10-action interface with the simplified 3-action adapter under matched training settings.
As shown in Table 8, the extended interface improves cumulative return while increasing turnover and reducing Sharpe relative to the conservative adapter, indicating a return–activity trade-off under the fixed training budget.
Table 8. Action-space comparison on the EURUSD (Double DQN).
Table 8. Action-space comparison on the EURUSD (Double DQN).
Action Space Sharpe Cum.Ret(%) MaxDD(%) WinRate(%) Turnover
Extended (10) 0.765 57.09 2.31 33.15 1156.51
Simplified (3) 2.433 33.21 0.29 68.13 528.65
To visualize how this trade-off accumulates over the episode rather than only at endpoint, Figure 8 contrasts the corresponding equity paths.
Figure 8. Equity-curve comparison of simplified (3-action) and extended (10-action) interfaces on EURUSD, showing a return–smoothness trade-off.
Figure 8. Equity-curve comparison of simplified (3-action) and extended (10-action) interfaces on EURUSD, showing a return–smoothness trade-off.
Preprints 241217 g008
The temporal separation in Figure 8 clarifies that action granularity changes policy behavior throughout training, not only final-point metrics: richer primitives increase opportunity capture but amplify path variability.

5.4. Scaling Strategy Analysis (Exp-03)

Objective.Exp-03 evaluates four scaling configurations: no scaling (s1), pyramid-only (s2), martingale-only (s3), and combined (s4).
Table 9 shows that all scaling-enabled variants improve over no scaling on drawdown, with distinct objective-dependent preferences across return and drawdown.
Table 9. Scaling-strategy analysis on the EURUSD (Double DQN).
Table 9. Scaling-strategy analysis on the EURUSD (Double DQN).
Variant Sharpe Cum.Ret(%) MaxDD(%) AvgPyr AvgMart Turnover
s1_no_scaling -1.568 -16.54 16.74 0.000 0.000 1440.09
s2_pyramid -0.136 -2.48 5.73 0.083 0.000 1394.52
s3_martingale 0.319 8.94 4.63 0.000 0.122 1273.71
s4_both 0.355 13.08 6.79 0.086 0.096 1483.55
The path-level evidence in Figure 9 suggests that enabling scaling alters drawdown dynamics over the full training horizon rather than merely shifting a single endpoint.
Figure 9. Training equity trajectories for scaling variants s1–s4 on EURUSD, where scaling-enabled variants reduce maximum drawdown versus no scaling.
Figure 9. Training equity trajectories for scaling variants s1–s4 on EURUSD, where scaling-enabled variants reduce maximum drawdown versus no scaling.
Preprints 241217 g009

5.5. Benchmark Calibration on EURUSD

Primary RQ findings are further calibrated against non-RL baselines and a DQN comparator. We first report headline endpoint metrics in Table 10, then inspect complementary risk diagnostics in Table 11.
Table 10. Benchmark comparison on the EURUSD training split. RL agents use full reward variant r7.
Table 10. Benchmark comparison on the EURUSD training split. RL agents use full reward variant r7.
Method Sharpe Cum.Ret(%) MaxDD(%) WinRate(%) Turnover
Random Policy -13.380 -34.58 34.70 25.99 2199.98
Buy-and-Hold -0.358 -1.05 2.08 0.00 0.11
Momentum -1.355 -3.82 4.05 23.62 186.28
Mean-Reversion -0.807 -1.67 2.34 24.64 157.67
DQN 0.369 24.56 8.72 34.12 1316.51
Double DQN 0.765 57.09 2.31 33.15 1156.51
Table 11. Benchmark risk diagnostics on the EURUSD (see Section 4).
Table 11. Benchmark risk diagnostics on the EURUSD (see Section 4).
Method Ann.Ret(%) Ann.Vol(%) Sortino Trades
Random Policy -12.11 0.96 -16.523 13728
Buy-and-Hold -0.32 0.89 -0.466 1
Momentum -1.18 0.87 -1.789 1715
Mean-Reversion -0.51 0.63 -0.772 1469
DQN 6.36 3.37 2.643 11240
Double DQN 14.82 4.11 4.771 8415
Taken together, the two tables show that RL improvements are not merely profit inflation: Double DQN remains favorable under risk-aware summaries and avoids liquidation events in this artifact view, while rule-based baselines underperform on cumulative return. These comparisons are training-split calibrations, not deployment claims.
Figure 10 reinforces that the learning-based agents maintain stronger growth profiles than benchmark heuristics under identical execution assumptions.
Figure 10. Equity trajectories for RL agents and benchmark strategies on EURUSD, with rule-based baselines as calibration anchors.
Figure 10. Equity trajectories for RL agents and benchmark strategies on EURUSD, with rule-based baselines as calibration anchors.
Preprints 241217 g010

5.6. Cross-Pair Generality Diagnostics

To assess whether the EURUSD pattern is idiosyncratic, Table 12 reports DQN-vs-DDQN outcomes on three additional pairs using the same full-reward configuration.
Table 12. Cross-pair DQN vs. Double DQN under the full-reward variant r7; results are descriptive diagnostics only.
Table 12. Cross-pair DQN vs. Double DQN under the full-reward variant r7; results are descriptive diagnostics only.
Pair Agent Sharpe Sortino Cum.Ret(%) MaxDD(%) WinRate(%)
EURUSD DQN 0.369 0.501 24.53 8.72 34.15
EURUSD DDQN 0.765 1.117 57.09 2.31 33.15
GBPUSD DQN 0.164 0.195 11.98 9.59 31.96
GBPUSD DDQN 0.759 0.969 83.19 3.14 31.90
USDJPY DQN 0.958 1.419 94.08 2.16 35.63
USDJPY DDQN 1.115 1.615 115.01 4.44 33.69
AUDUSD DQN 0.542 0.754 33.93 7.63 30.91
AUDUSD DDQN 0.811 1.222 52.98 4.91 32.16
These results are restricted to the experimental scope defined in Section 4; the directional trend across pairs is descriptive. Double DQN is generally stronger on return-oriented metrics, but the pair-specific drawdown behavior varies, so the table should not be read as a transfer benchmark.
Figure 11 illustrates that cross-pair behavior is heterogeneous in amplitude but consistent in qualitative ordering. This supports the use of pair-diverse diagnostics alongside the primary EURUSD-focused research questions, but it does not establish cross-market generalization.
Figure 11. Multi-pair equity trajectories (EURUSD, GBPUSD, USDJPY, AUDUSD) for value-based agents under aligned simulator and reward settings.
Figure 11. Multi-pair equity trajectories (EURUSD, GBPUSD, USDJPY, AUDUSD) for value-based agents under aligned simulator and reward settings.
Preprints 241217 g011

6. Discussion

This section interprets the empirical findings through the lens of design objectives introduced earlier: transparent reward construction, legality-aware action control, and causal simulation fidelity. We focus on what can be inferred from controlled experimental evidence (see Section 4) and explicitly separate methodological insights from broader deployment claims, aligning with the evaluation rigor advocated by (Zhang et al., 2020).

6.1. Reward Decomposition as an Experimental Instrument

The principal methodological insight of this manuscript is that reward engineering should be treated as controlled experimentation rather than iterative tuning. The 11-component architecture, together with deterministic per-step logging, enables direct attribution of behavioral changes to specific reward terms. In Exp-01, performance does not improve monotonically as components are added; instead, quality degrades and recovers across the schedule before peaking at r7. This pattern demonstrates interaction effects that are difficult to diagnose under monolithic scalar objectives, which are commonly used in trading RL to optimize raw return or equity delta (Meng & Khushi, 2019; Theate & Ernst, 2021). Unlike these conventional approaches, which obscure component-level attribution and complicate reward shaping analysis (Ng et al., 1999), our decomposable framework isolates the specific penalties that suppress excessive trading and the signals that improve entry timing. The fixed weights are therefore best interpreted as a calibrated baseline: profit remains dominant, but auxiliary terms regularize turnover, drawdown, and leverage usage. The ablation schedule shows that modest changes in component activation can materially shift the return–drawdown balance, which is precisely why the paper treats reward composition as an empirical design problem.

6.2. Behavioral Consequences of Action Granularity

Endpoint metrics in Table 8 suggest a return–activity trade-off, but the mechanism is clearer when inspecting action usage directly. Figure 12 reports aggregate action frequencies for the compared interfaces.
Figure 12. Aggregate action distributions across training runs, showing broader action usage and higher activity in the extended interface.
Figure 12. Aggregate action distributions across training runs, showing broader action usage and higher activity in the extended interface.
Preprints 241217 g012
The distribution shows that richer action semantics are not merely available but actively exploited: scaling, reduction, and reversal primitives contribute substantial policy mass. This explains why the extended interface captures more return opportunities while simultaneously increasing turnover and path volatility.

6.3. Scaling Mechanics Under Asymmetric Penalties

The scaling family (Exp-03) is best interpreted through both endpoint values (Table 9) and operational depth statistics. Figure 13 visualizes average pyramid and martingale utilization by variant.
Figure 13. Episode-level average pyramid depth (AvgPyr) and martingale depth (AvgMart) by scaling variant.
Figure 13. Episode-level average pyramid depth (AvgPyr) and martingale depth (AvgMart) by scaling variant.
Preprints 241217 g013
Two implications follow. First, the penalty asymmetry does shape behavior in the intended direction: enabling both mechanisms does not collapse into pure martingale usage. Second, utilization remains bounded, indicating that legality masks and margin controls are actively constraining excessive depth accumulation. The result is consistent with the design intent of making pyramiding relatively easier to sustain than martingale-style averaging down, rather than claiming that either mechanism is universally preferable.

6.4. Interpreting Endpoint Metrics

The retained results are intentionally restricted to the experimental scope defined in Section 4. Under this scope, endpoint metrics are informative about learning behavior but do not establish statistical dominance or deployment readiness. This distinction is central: the manuscript provides evidence about system dynamics, not definitive estimates of out-of-sample expected return. Consequently, directional claims should be interpreted as controlled observations that motivate multi-seed follow-up, in line with reproducibility concerns noted in prior surveys (Zhang et al., 2020).

6.5. Layered Safety and Causality Guarantees

Two cross-cutting properties remain robust across experiments. First, strict anti-lookahead timing is enforced by environment mechanics rather than documentation convention, reducing leakage risk at the API level (Zhang et al., 2020). Second, legality masks are applied consistently during both interaction and target computation, following prior invalid-action masking practice (Huang & Ontañón, 2020). Together with margin and liquidation controls, this yields a defense-in-depth design appropriate for high-risk financial RL experimentation.

6.6. Practical Interpretation

For practitioners, the key message is to align architecture choices with deployment objectives: decomposable rewards for auditability, action-space size for desired aggressiveness, and scaling configuration for explicit return–risk preferences, consistent with classical risk-return framing in portfolio analysis (Markowitz, 1952). The present study provides an internally consistent, reproducible baseline for that design process; broader claims require multi-seed and out-of-sample validation.

7. Future Work

The present manuscript establishes a controlled, reproducible baseline for Forex reinforcement learning, but several limitations naturally define the next research stage. This section outlines those limitations as concrete future-work priorities.

7.1. Limitations of the Current Study

All primary findings are training-split based (see Section 4 for canonical seeding and setup). As a result, the reported differences should be interpreted as directional evidence about system behavior rather than fully characterized performance distributions. Future studies should report multi-seed confidence intervals and wider temporal stress windows to quantify stability under regime variation.
The current experiments are pair-local: each environment instance models one currency pair at a time. This excludes cross-pair capital allocation, shared margin coupling, and correlation-aware portfolio control. The cross-pair diagnostics in Section 5 should therefore be read as descriptive observations, not as transfer or generalization evidence. Extending the framework to joint portfolio settings is required for full institutional realism.

7.2. Scalability and Algorithmic Extensions

Although the infrastructure is modular, scaling to larger instrument universes and longer histories will require more efficient replay management, distributed rollouts, and memory-aware training pipelines. From an algorithmic perspective, the release focuses on value-based baselines (DQN and DDQN) to isolate environment and reward effects. Future work should evaluate whether proximal policy optimization (PPO), soft actor-critic (SAC), and Rainbow-style extensions alter the observed reward and action-space trade-offs under identical simulator assumptions (Haarnoja et al., 2018; Hessel et al., 2018; Schulman et al., 2017).

7.3. Potential Methodological Improvements

Position management is currently discretized with fixed lot and rule-bounded scaling depth. A natural extension is hybrid control that preserves legality constraints while permitting continuous sizing and explicit risk-budget targets. Reward calibration can also be expanded by testing adaptive weighting schedules and regime-conditioned penalties, while retaining the same auditable per-component logging introduced in this paper.

7.4. Real-World Deployment Challenges

The current evaluation is simulation-only. It does not yet incorporate broker-specific routing behavior, execution latency, partial fills, quote outages, or production risk controls (for example, kill-switch policies and operational monitoring). Addressing these constraints requires a staged transition from historical simulation to paper trading and, eventually, limited-capital live pilots under strict governance.
In summary, future progress should combine broader uncertainty quantification, portfolio-level scaling, richer algorithmic baselines, and deployment-grade execution modeling before making strong claims about operational readiness.

8. Conclusion

This paper presents a modular and reproducible system-level framework for reinforcement learning-based Forex trading, centered on three design priorities: economic realism, temporal causality, and auditability. The framework combines anti-lookahead execution semantics, friction-aware portfolio accounting, decomposable reward modeling, and legal-action masking within a unified DQN-family training pipeline. It is a methodological contribution built around standard value-based learners rather than a new RL algorithm.

Summary of principal findings.

Controlled experiments on EURUSD training artifacts yield three main outcomes (see Section 4 for canonical seeding and setup):
1.
Reward interactions are non-monotone. Progressive reward composition (r1–r7) does not produce linear improvement. The full specification (r7) attains the strongest endpoint profile (Sharpe 0.765 , cumulative return 57.09 % ), while intermediate variants exhibit both gains and regressions.
2.
Action granularity induces a measurable trade-off. The extended 10-action interface increases cumulative return and turnover, whereas the simplified 3-action adapter yields stronger conservative risk summaries (higher Sharpe and lower drawdown) in the same endpoint view.
3.
Scaling materially improves over no scaling. All scaling-enabled settings outperform the no-scaling baseline on drawdown. The combined configuration (s4) achieves the best endpoint return in this artifact view, while martingale-only (s3) attains the lowest drawdown among scaling-enabled variants.

Contributions revisited.

The core contribution is infrastructural: a research workflow in which reward decomposition, legality constraints, and anti-lookahead execution are encoded as enforceable system properties rather than informal conventions. This design improves reproducibility, supports component-level ablation, and enables more transparent diagnosis of trading-policy behavior. The contribution is therefore system-level rather than algorithmic.

Outlook.

As detailed in Section 7, the next stage is to combine multi-seed uncertainty quantification, broader algorithmic baselines, and deployment-grade execution modeling. These extensions are necessary to convert controlled training evidence into robust out-of-sample and operational claims. The cross-pair diagnostics reported in Section 5 remain descriptive and should not be interpreted as transfer guarantees.

Conflicts of Interest

The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.

A. Full Hyperparameter Configuration

This appendix records the core configuration used across the release experiments. Main-paper values are summarized in Table 6; this appendix clarifies which settings were held constant and which were varied by experiment-family YAML overrides.

A.1. Shared Training Settings

  • Total timesteps: 1,000,000
  • Replay buffer size: 40,000
  • Batch size: 128
  • Learn start: 10,000 steps
  • Learn frequency: every 4 environment steps
  • Discount factor: γ = 0.99
  • Optimizer: Adam ( 2.5 × 10 − 4 )
  • Gradient clip: 10.0
  • Epsilon schedule: 1.0 → 0.01 over 30,000 steps
  • Target update interval: 2,000 learning steps
  • Mixed precision: fp16

A.2. Environment and Risk Settings

  • Observation window: 24 bars
  • Initial capital: USD 100,000
  • Maximum leverage: 30x
  • Maintenance margin ratio: 50% of initial margin
  • Liquidation threshold: 25% of initial capital
  • Commission: USD 3.5 per lot (round trip equivalent)
  • Base deterministic slippage: 0.5 pips
  • Rollover timestamp: 22:00 UTC (triple rollover Wednesday)

A.3. Experiment-Family Overrides

  • Exp-01: reward-component enable/disable schedule (r1–r7)
  • Exp-02: action-mode switch (simplified vs extended)
  • Exp-03: scaling action availability (none, pyramid, martingale, both)

A.4. Determinism Scope

All reported runs in this manuscript used a fixed seed; see Section 4 for the canonical seed value and related reproducibility details. This setting ensures deterministic reproducibility of the presented artifact snapshots but does not capture between-seed uncertainty.

B. Resolved YAML Configuration Snapshots

This appendix provides representative resolved configurations for reproducibility. Full resolved files are stored in run artifacts under experiment output directories.

B.1. Ablation Variant r1 (Profit-Only Core)

experiment:
  family: 01_reward_ablation
  variant: r1_profit_only
agent:
  name: doubledqn
  model:
   hidden_dims: [512, 512, 256]
  training:
   total_timesteps: 1000000
   learn_start_steps: 10000
   learn_frequency: 4
reward:
  components:
   profit: {enabled: true, weight: 1.0}
   transaction: {enabled: false}
   drawdown: {enabled: false}
   volatility: {enabled: false}
   overtrading: {enabled: false}
   pyramid_penalty: {enabled: false}
   martingale_penalty: {enabled: false}
   holding: {enabled: false}
   margin: {enabled: false}
   liquidation: {enabled: false}
   constraint: {enabled: false}
training:
  random_seed: 42

B.2. Ablation Variant r7 (Full Reward)

experiment:
  family: 01_reward_ablation
  variant: r7_full
agent:
  name: doubledqn
reward:
  components:
   profit: {enabled: true, weight: 1.0}
   holding: {enabled: true, weight: 0.03}
   volatility: {enabled: true, weight: 0.01}
   drawdown: {enabled: true, weight: 0.05}
   transaction: {enabled: true, weight: 0.10}
   overtrading: {enabled: true, weight: 0.02}
   pyramid_penalty: {enabled: true, weight: 0.05}
   martingale_penalty: {enabled: true, weight: 0.12}
   margin: {enabled: true, weight: 0.05}
   liquidation: {enabled: true, weight: 2.0}
   constraint: {enabled: true, weight: 0.10}
  reward_normalization:
   mode: clip_only
   clip_min: -1.0
   clip_max: 1.0
training:
  random_seed: 42

B.3. Action-Space Variants

# simplified
environment:
  actions:
   mode: simplified
# extended
environment:
  actions:
   mode: extended

C. Anti-Lookahead Test Specification

This appendix formalizes the anti-lookahead guarantee enforced by the environment and summarizes corresponding validation tests.

C.1. Formal Timing Rule

Definition 
(Decision–Execution Separation). At step t, the agent receives observations built from bars up to and including close t , where close t denotes the close price of bar t. The chosen action a t is executed at open t + 1 , where a t denotes the action selected after observing close t and open t + 1 denotes the next bar’s open used for execution. Reward and equity marking for that step are computed using information available at close t + 1 , where close t + 1 denotes the next bar’s close used for mark-to-market, without access to bar t + 2 or later.

C.2. Validation Test Cases

Test 1: Feature staleness check.

Inject a sentinel value into a future bar and verify that the step-t observation tensor does not expose this sentinel.

Test 2: Fill-price rule check.

For deterministic synthetic bars, verify execution at open t + 1 (not close t and not close t + 1 ).

Test 3: Reward-timing check.

Verify that reward at step t depends on costs and marks from bar t + 1 only.

Test 4: Scaler leakage check.

Verify that feature scaling parameters are fitted on the train split only and, if a held-out split is instantiated, reused unchanged during held-out transformation.

Test 5: Mask-timing check.

Verify that legal-action masks are computed from current state/margin before action dispatch, and that illegal-action coercion/penalty is logged without future leakage.

C.3. Interpretation

Passing these tests does not guarantee real-market validity, but it materially reduces a major source of optimistic bias in trading RL backtests: unintended access to future information through timing or preprocessing pathways.

D. Data and Code Availability

The implementation code and relevant configuration files used to reproduce the experiments in this manuscript are available in a public GitHub repository: https://github.com/NabeelAhmadSaidd/frl_trading_framework.

References

  1. Bellemare, M. G., W. Dabney, and R. Munos. 2017. A distributional perspective on reinforcement learning. In Proceedings of the 34th international conference on machine learning. pp. 449–458. [Google Scholar] [CrossRef]
  2. Bertoluzzo, F., and M. Corazza. 2012. Testing different reinforcement learning configurations for financial trading: Introduction and applications. Procedia Economics and Finance 3: 68–77. [Google Scholar] [CrossRef]
  3. Brockman, G., V. Cheung, L. Pettersson, J. Schneider, J. Schulman, J. Tang, and W. Zaremba. 2016. OpenAI Gym. In arXiv. [Google Scholar] [CrossRef]
  4. Carapuco, J., R. Neves, and N. Horta. 2018. Reinforcement learning applied to forex trading. Applied Soft Computing 73: 783–794. [Google Scholar] [CrossRef]
  5. Cont, R. 2001. Empirical properties of asset returns: Stylized facts and statistical issues. Quantitative Finance 1, 2: 223–236. [Google Scholar] [CrossRef]
  6. Deng, Y., F. Bao, Y. Kong, Z. Ren, and Q. Dai. 2017. Deep direct reinforcement learning for financial signal representation and trading. IEEE Transactions on Neural Networks and Learning Systems 28, 3: 653–664. [Google Scholar] [CrossRef]
  7. Fischer, T., and C. Krauss. 2018. Deep learning with long short-term memory networks for financial market predictions. European Journal of Operational Research 270, 2: 654–669. [Google Scholar] [CrossRef]
  8. Gould, M. D., M. A. Porter, S. Williams, M. McDonald, D. J. Fenn, and S. D. Howison. 2013. Limit order books. Quantitative Finance 13, 11: 1709–1742. [Google Scholar] [CrossRef]
  9. Haarnoja, T., A. Zhou, P. Abbeel, and S. Levine. 2018. Soft actor-critic: Off-policy maximum entropy deep reinforcement learning with a stochastic actor. In Proceedings of the 35th international conference on machine learning. pp. 1861–1870. [Google Scholar] [CrossRef]
  10. Hessel, M., J. Modayil, H. van Hasselt, T. Schaul, G. Ostrovski, W. Dabney, D. Horgan, B. Piot, M. G. Azar, and D. Silver. 2018. Rainbow: Combining improvements in deep reinforcement learning. In Proceedings of the 32nd aaai conference on artificial intelligence. Vol. 32, pp. 3215–3222. [Google Scholar] [CrossRef]
  11. Huang, S., and S. Ontañón. 2020. A closer look at invalid action masking in policy gradient algorithms. arXiv arXiv:2006.14171. [Google Scholar] [CrossRef]
  12. Jiang, Z., D. Xu, and J. Liang. 2017. A deep reinforcement learning framework for the financial portfolio management problem. arXiv arXiv:1706.10059. [Google Scholar] [CrossRef]
  13. Liu, X.-Y., H. Yang, J. Gao, and C. D. Wang. 2021. FinRL: Deep reinforcement learning framework to automate trading in quantitative finance. In Proceedings of the 2nd acm international conference on ai in finance. pp. 1–8. [Google Scholar] [CrossRef]
  14. Markowitz, H. 1952. Portfolio selection. Journal of Finance 7, 1: 77–91. [Google Scholar] [CrossRef]
  15. Meng, T. L., and M. Khushi. 2019. Reinforcement learning in financial markets. Data 4, 3: 110. [Google Scholar] [CrossRef]
  16. Mnih, V., K. Kavukcuoglu, D. Silver, and A. A. Rusu. 2015. Human-level control through deep reinforcement learning. Nature 518, 7540: 529–533. [Google Scholar] [CrossRef] [PubMed]
  17. Moody, J., and M. Saffell. 2001. Learning to trade via direct reinforcement. IEEE Transactions on Neural Networks 12, 4: 875–889. [Google Scholar] [CrossRef]
  18. Ng, A. Y., D. Harada, and S. J. Russell. 1999. Policy invariance under reward transformations: Theory and application to shaped reward reinforcement learning. In Proceedings of the 16th international conference on machine learning. pp. 278–287. [Google Scholar]
  19. Rundo, F. 2019. Deep LSTM with reinforcement learning layer for financial trend prediction in FX high frequency trading systems. Applied Sciences 9, 20: 4460. [Google Scholar] [CrossRef]
  20. Schaul, T., J. Quan, I. Antonoglou, and D. Silver. 2016. Prioritized experience replay. Proceedings of the 4th international conference on learning representations. [Google Scholar] [CrossRef]
  21. Schulman, J., F. Wolski, P. Dhariwal, A. Radford, and O. Klimov. 2017. Proximal policy optimization algorithms. In arxiv, 1707.06347. [Google Scholar] [CrossRef]
  22. Sharpe, W. F. 1994. The Sharpe Ratio. Journal of Portfolio Management 21, 1: 49–58. [Google Scholar] [CrossRef]
  23. Sortino, F. A., and L. N. Price. 1994. Performance measurement in a downside risk framework. Journal of Investing 3, 3: 59–64. [Google Scholar] [CrossRef]
  24. Sutton, R. S., and A. G. Barto. 2018. Reinforcement learning: An introduction, 2nd ed. MIT Press. [Google Scholar]
  25. Theate, T., and D. Ernst. 2021. An application of deep reinforcement learning to algorithmic trading. Expert Systems with Applications 173: 114632. [Google Scholar] [CrossRef]
  26. van Hasselt, H., A. Guez, and D. Silver. 2016. Deep reinforcement learning with double Q-learning. In Proceedings of the aaai conference on artificial intelligence. Vol. 30, pp. 2094–2100. [Google Scholar] [CrossRef]
  27. Wang, Z., T. Schaul, M. Hessel, H. van Hasselt, M. Lanctot, and N. de Freitas. 2016. Dueling network architectures for deep reinforcement learning. In Proceedings of the 33rd international conference on machine learning. pp. 1995–2003. [Google Scholar] [CrossRef]
  28. Yang, H., X.-Y. Liu, S. Zhong, and A. Walid. 2020. Deep reinforcement learning for automated stock trading: An ensemble strategy. In Proceedings of the 1st acm international conference on ai in finance. pp. 1–8. [Google Scholar] [CrossRef]
  29. Zhang, Z., S. Zohren, and S. Roberts. 2020. Deep reinforcement learning for trading. Journal of Financial Data Science 2, 2: 25–40. [Google Scholar] [CrossRef]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.