<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Edmondlubangakene on Medium]]></title>
        <description><![CDATA[Stories by Edmondlubangakene on Medium]]></description>
        <link>https://medium.com/@edmondlubangakene?source=rss-a9ea82fb7747------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H75u7yjq-5kd4CVKeR7orQ.jpeg</url>
            <title>Stories by Edmondlubangakene on Medium</title>
            <link>https://medium.com/@edmondlubangakene?source=rss-a9ea82fb7747------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:28:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edmondlubangakene/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Code to Cash: Building a Deep Neural Network-Powered Breakout Strategy in Python & MQL5]]></title>
            <link>https://medium.com/@edmondlubangakene/from-code-to-cash-building-a-deep-neural-network-powered-breakout-strategy-in-python-mql5-5ab18f692cb5?source=rss-a9ea82fb7747------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ab18f692cb5</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Edmondlubangakene]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 10:12:36 GMT</pubDate>
            <atom:updated>2026-11-23T10:35:23.871Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>From $10,000 to $152,824.69 in a backtest spanning 2022–2024. Can a deep learning model supercharge a classic breakout strategy?</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CZ0qsO88ZDhCCGyWN2i4A.png" /></figure><p>In this article, I’ll walk you through how I built a deep neural network-based trading algorithm to predict market direction for a breakout strategy on USD/JPY, integrated it with an MQL5 Expert Advisor in MetaTrader 5 for automated execution, and the results it achieved.</p><p>The goal was simple:</p><ul><li>Use a neural network to forecast the direction of the market over the next 4 hours.</li><li>Combine the prediction with a breakout trading framework to filter for higher-probability setups.</li><li>Backtest the system on historical data to evaluate its profitability.</li></ul><h3>Key Concepts &amp; Tools</h3><p>Before diving into the build, let’s clarify a few terms we’ll be using throughout the article.</p><h4>Breakout Strategy</h4><p>A breakout occurs when the price moves outside a defined support or resistance level, usually with increased volatility. Breakout strategies aim to capture these strong directional moves by entering trades once the price “breaks out” of a range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsHGRWGERry0kZqCQuGDSw.png" /><figcaption>Example of a price breakout from a range-bound market. Image source: <a href="https://www.ig.com/uk/learn-to-trade/ig-academy/breakout-trading/what-is-breakout-trading">IG Academy — What is Breakout Trading?</a></figcaption></figure><h4>MetaTrader 5 (MT5)</h4><p>MetaTrader 5 is one of the most popular trading platforms for retail traders. It provides advanced charting, backtesting, and automated trading capabilities.</p><h4>MQL5</h4><p>MQL5 is the programming language used to develop automated trading systems (Expert Advisors), custom indicators, and scripts for MetaTrader 5. In this project, I used MQL5 to:</p><ul><li>Place trades based on the neural network’s predictions</li><li>Backtest the strategy on historical market data</li><li>Manage risk and position sizing automatically</li></ul><p>By combining Python (for model training) with MQL5 (for execution), we get the best of both worlds: powerful machine learning predictions and robust real-time trade automation.</p><h3>Data Collection &amp; Preprocessing</h3><p>To train the model, I needed historical price data that captured both trends and volatility patterns. For this project, I used USD/JPY 4-hour (H4) historical data spanning 2010–2021.</p><p><strong>Why USD/JPY?</strong></p><ul><li>It’s one of the most liquid currency pairs.</li><li>It reacts strongly to global macroeconomic news, making it ideal for breakout strategies.</li><li>Its price action is relatively clean compared to some more volatile pairs.</li></ul><h4>Loading the Data</h4><p>The raw dataset was in MetaTrader 5 export format with columns for date, time, open, high, low, close, and volume.</p><pre>price_data = pd.read_csv(&quot;training/USDJPY_H4_201001040000_202112310000.csv&quot;, delimiter=&#39;\t&#39;)<br>price_data[&#39;datetime&#39;] = pd.to_datetime(price_data[&#39;&lt;DATE&gt;&#39;] + &#39; &#39; + price_data[&#39;&lt;TIME&gt;&#39;])<br>price_data.columns = price_data.columns.str.replace(&#39;&lt;&#39;, &#39;&#39;).str.replace(&#39;&gt;&#39;, &#39;&#39;).str.lower()<br>price_data.sort_values(by=&#39;date&#39;, inplace=True)<br><br>price_data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*WWaSIj5RzK658-3n6jSDYQ.png" /><figcaption>Sample of the dataset</figcaption></figure><h4>Feature Engineering</h4><p>To give the neural network something meaningful to learn from, I engineered a diverse set of features using technical indicators. These indicators help capture patterns in trend, momentum, volatility, and market strength and even intermarket relationships, all of which are critical for forecasting the next directional move in the market.</p><p><strong>Trend &amp; Moving Averages</strong></p><pre># Simple Moving Averages<br>price_data[&#39;ma_20&#39;] = price_data[&#39;close&#39;].rolling(window=20).mean()<br>price_data[&#39;ma_200&#39;] = price_data[&#39;close&#39;].rolling(window=200).mean()<br><br># Exponential Moving Averages<br>price_data[&#39;ema_6&#39;] = ta.ema(price_data[&#39;close&#39;], length=6)<br>price_data[&#39;ema_18&#39;] = ta.ema(price_data[&#39;close&#39;], length=18)<br><br># Crossover signal<br>price_data[&#39;ema6_18_x&#39;] = (price_data[&#39;ema_6&#39;] &gt; price_data[&#39;ema_18&#39;]).astype(int)<br><br># EMA slope as trend strength<br>price_data[&#39;slope_42&#39;] = price_data[&#39;ema_42&#39;].pct_change(1)</pre><p><strong>Momentum &amp; Volatility</strong></p><pre># RSI and MACD<br>price_data[&#39;rsi&#39;] = ta.rsi(price_data[&#39;close&#39;], length=14)<br>macd_data = ta.macd(price_data[&#39;close&#39;])<br>price_data[&#39;macd&#39;] = macd_data[&#39;MACD_12_26_9&#39;]<br>price_data[&#39;macd_signal&#39;] = macd_data[&#39;MACDs_12_26_9&#39;]<br><br># Average True Range<br>price_data[&#39;atr&#39;] = ta.atr(price_data[&#39;high&#39;], price_data[&#39;low&#39;], price_data[&#39;close&#39;], length=14)<br><br># Bollinger Bands<br>bbands = ta.bbands(price_data[&#39;close&#39;], length=20, std=2)<br>price_data[&#39;bb_upper&#39;] = bbands[&#39;BBU_20_2.0&#39;]<br>price_data[&#39;bb_lower&#39;] = bbands[&#39;BBL_20_2.0&#39;]</pre><p><strong>Candlestick Pattern Flags</strong></p><pre># TA-Lib candlestick patterns<br>price_data[&#39;hammer_flag&#39;] = (tb.CDLHAMMER(opn, hi, lo, cl) &gt; 0).astype(int)<br>price_data[&#39;engulfing_flag&#39;] = (tb.CDLENGULFING(opn, hi, lo, cl) &gt; 0).astype(int)<br>price_data[&#39;doji_flag&#39;] = (tb.CDLDOJI(opn, hi, lo, cl) &gt; 0).astype(int)</pre><p><strong>Intermarket Features</strong></p><pre>def load_h4_close(path, prefix):<br>    # parse the two fields into one &quot;datetime&quot;<br>    df = pd.read_csv(<br>        path, <br>        sep=&#39;\t&#39;,<br>        parse_dates={&#39;datetime&#39;: [&#39;&lt;DATE&gt;&#39;, &#39;&lt;TIME&gt;&#39;]}, <br>        infer_datetime_format=True<br>    )<br>    # normalize the column names<br>    df.columns = df.columns.str.replace(&#39;&lt;&#39;,&#39;&#39;, regex=False) \<br>                           .str.replace(&#39;&gt;&#39;,&#39;&#39;, regex=False) \<br>                           .str.lower()<br>    # set that rich datetime index<br>    df = df.set_index(&#39;datetime&#39;).sort_index()<br>    # keep only the one renamed close column<br>    return df[[&#39;close&#39;]].rename(columns={&#39;close&#39;: f&#39;{prefix}_close&#39;})<br><br>audjpy = load_h4_close(&#39;training/AUDJPY_H4_201001040000_202112310000.csv&#39;, &#39;audjpy&#39;)<br>audusd = load_h4_close(&#39;training/AUDUSD_H4_201001040000_202112310000.csv&#39;, &#39;audusd&#39;)<br>chfjpy = load_h4_close(&#39;training/CHFJPY_H4_201001040000_202112310000.csv&#39;, &#39;chfjpy&#39;)<br>eurjpy = load_h4_close(&#39;training/EURJPY_H4_201001040000_202112310000.csv&#39;, &#39;eurjpy&#39;)<br>eurusd = load_h4_close(&#39;training/EURUSD_H4_201001040000_202112310000.csv&#39;, &#39;eurusd&#39;)<br>gbpjpy = load_h4_close(&#39;training/GBPJPY_H4_201001040000_202112310000.csv&#39;, &#39;gbpjpy&#39;)<br>gbpusd = load_h4_close(&#39;training/GBPUSD_H4_201001040000_202112310000.csv&#39;, &#39;gbpusd&#39;)<br>nzdusd = load_h4_close(&#39;training/NZDUSD_H4_201001040000_202112310000.csv&#39;, &#39;nzdusd&#39;)<br>usdcad = load_h4_close(&#39;training/USDCAD_H4_201001040000_202112310000.csv&#39;, &#39;usdcad&#39;)<br>usdchf = load_h4_close(&#39;training/USDCHF_H4_201001040000_202112310000.csv&#39;, &#39;usdchf&#39;)<br>xauusd = load_h4_close(&#39;training/XAUUSD_H4_201001040000_202112310000.csv&#39;, &#39;xauusd&#39;)<br><br>aux = pd.concat([<br>    audjpy, audusd, chfjpy, eurjpy,<br>    eurusd, gbpjpy, gbpusd, nzdusd,<br>    usdcad, usdchf, xauusd<br>], axis=1)<br><br># one join, by index<br>price_data = price_data.join(aux, how=&#39;left&#39;)</pre><h4>Defining the Prediction Target</h4><p>The model’s goal was to predict whether the USD/JPY price would go up or down in the next 4-hour candle.</p><p>To define this target, I used a concept from quantitative finance called the log return.</p><p><strong>What is a Log Return?</strong></p><p>A logarithmic return (or log return) measures the percentage change in price on a logarithmic scale.<br> It is calculated by taking the natural logarithm of the ratio between the current price​ and the previous price.</p><p>This measures the percentage change in price between two periods, but unlike simple returns, log returns are time-additive, meaning the returns over multiple periods can be summed directly. This makes them very useful for modeling and forecasting.</p><p>Log returns also treat upward and downward moves symmetrically, which helps stabilize the variance in the data, an important property for training neural networks.</p><p>Here’s how the trend column (the model’s prediction target) was created:</p><pre># Calculate log return for each candle<br>price_data[&#39;log_return&#39;] = np.log(price_data[&#39;close&#39;] / price_data[&#39;close&#39;].shift(1))<br><br># Define the target as the direction of the next candle&#39;s return<br>price_data[&#39;next_candle_log_return&#39;] = price_data[&#39;log_return&#39;].shift(-1)<br>price_data[&#39;trend&#39;] = price_data[&#39;next_candle_log_return&#39;].apply(lambda x: 1 if x &gt; 0 else -1)<br><br># Clean up<br>price_data.dropna(subset=[&#39;next_candle_log_return&#39;], inplace=True)<br>price_data.drop(columns=[&#39;next_candle_log_return&#39;], inplace=True)</pre><h3>Selecting the Most Informative Features</h3><p>With over 50 features engineered, the next step was to figure out which of them contributed useful information to the model.</p><p>Rather than guessing, I used a two-pronged statistical approach to rank feature importance and select only the most predictive ones:</p><ul><li>Mutual Information (MI) — to measure how much each feature tells us about the target</li><li>Random Forest Importance — to estimate how much each feature contributes to classification accuracy</li></ul><h4>Encode the Target</h4><p>To prepare for both ranking methods, I first encoded the trend column as a binary target:</p><pre>from sklearn.preprocessing import LabelEncoder<br><br>le = LabelEncoder()<br>y = le.fit_transform(price_data[&#39;trend&#39;])  # 0 = down, 1 = up</pre><h4>Mutual Information Ranking</h4><p>Mutual Information measures how much knowing a feature reduces uncertainty about the target.</p><pre>from sklearn.feature_selection import mutual_info_classif<br><br>X = price_data.drop(columns=[&#39;trend&#39;, &#39;Target&#39;], errors=&#39;ignore&#39;).select_dtypes(include=[np.number]).fillna(0)<br>mi = mutual_info_classif(X, y, random_state=42)<br><br>mi_series = pd.Series(mi, index=X.columns).sort_values(ascending=False)</pre><h4>Random Forest Ranking</h4><p>A Random Forest classifier was also trained to assess how important each feature was for predicting the trend:</p><pre>from sklearn.ensemble import RandomForestClassifier<br><br>rf = RandomForestClassifier(n_estimators=200, random_state=42, n_jobs=-1)<br>rf.fit(X, y)<br><br>rf_importances = pd.Series(rf.feature_importances_, index=X.columns).sort_values(ascending=False)</pre><h4>Creating a Consensus</h4><p>When I compared the top features from both methods, there was noticeable <strong>disagreement</strong>. Some features ranked highly in MI but not in RF, and vice versa.</p><p>So instead of blindly trusting one approach, I combined them. The idea was to reward features that performed well in <em>both</em> rankings. Those are more likely to be genuinely useful across different modelling assumptions.</p><p>Each feature’s score was normalized to a 0–1 scale and summed to produce a consensus score:</p><pre>df_imp = pd.DataFrame({<br>    &#39;MI&#39;: mi_series,<br>    &#39;RF&#39;: rf_importances<br>}).fillna(0)<br><br>df_imp[&#39;MI_n&#39;] = df_imp[&#39;MI&#39;] / df_imp[&#39;MI&#39;].abs().max()<br>df_imp[&#39;RF_n&#39;] = df_imp[&#39;RF&#39;] / df_imp[&#39;RF&#39;].abs().max()<br>df_imp[&#39;consensus&#39;] = df_imp[&#39;MI_n&#39;] + df_imp[&#39;RF_n&#39;]</pre><h4>Final Feature Set</h4><p>The top 20 features selected from the consensus ranking were:</p><pre>consensus_feats = [&#39;williams_%r&#39;, &#39;log_return&#39;, &#39;stoch_%k&#39;, &#39;gbpusd_close&#39;, &#39;slope_42&#39;, &#39;close&#39;, &#39;nzdusd_close&#39;,<br>    &#39;macd_signal&#39;,&#39;macd_hist&#39;, &#39;stoch_%d&#39;, &#39;ema_6&#39;, &#39;adx_10&#39;, &#39;rsi&#39;,<br> &#39;low&#39;, &#39;eurusd_close&#39;, &#39;tickvol&#39;, &#39;std_dev&#39;, &#39;macd&#39;, &#39;gbpjpy_close&#39;, &#39;atr&#39;]</pre><h3>Model Architecture &amp; Training</h3><p>With the features selected and the target labels defined, it was time to train the model.</p><p>I opted for a fully connected deep neural network (also known as a feedforward network) using TensorFlow. The goal was to learn patterns from historical features that could predict whether USD/JPY would rise or fall in the next 4-hour candle.</p><h4>Data Preparation</h4><p>Before training, the data needed to be scaled and split:</p><pre>from sklearn.preprocessing import MinMaxScaler, LabelEncoder<br><br># Encode target: 1 = up, 0 = down<br>le = LabelEncoder()<br>y = le.fit_transform(price_data[&#39;trend&#39;])<br><br># Extract features from consensus list<br>X_consensus = price_data[consensus_feats]<br><br># Scale features to [0,1]<br>scaler_cons = MinMaxScaler()<br>Xc_scaled = scaler_cons.fit_transform(X_consensus)</pre><h4>Train-Test Split</h4><p>To simulate a realistic trading scenario, I used a time-series-aware split with no shuffling:</p><pre>from sklearn.model_selection import train_test_split<br><br>Xc_train, Xc_test, yc_train, yc_test = train_test_split(<br>    Xc_scaled, y, test_size=0.2, shuffle=False<br>)</pre><p>This ensures that the model is evaluated on future data it has never seen, which is critical for time-based forecasting.</p><h4>Model Architecture</h4><p>The final neural network consisted of two hidden layers, each with 128 neurons and ReLU activation. I used dropout and L2 regularization to prevent overfitting.</p><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, Dropout<br>from tensorflow.keras.optimizers import Adam<br>from tensorflow.keras.regularizers import l2<br><br>def build_best(input_dim, l2_strength=1e-4):<br>    model = Sequential([<br>        Dense(128, activation=&#39;relu&#39;, input_shape=(input_dim,), kernel_regularizer=l2(l2_strength)),<br>        Dropout(0.3),<br>        Dense(128, activation=&#39;relu&#39;, kernel_regularizer=l2(l2_strength)),<br>        Dropout(0.3),<br>        Dense(1, activation=&#39;sigmoid&#39;, kernel_regularizer=l2(l2_strength))<br>    ])<br>    model.compile(<br>        optimizer=Adam(1e-3),<br>        loss=&#39;binary_crossentropy&#39;,<br>        metrics=[&#39;accuracy&#39;]<br>    )<br>    return model<br><br>model_cons = build_best(len(consensus_feats))</pre><h4>Training the Model</h4><p>I trained the model using early stopping to avoid overfitting. Training was stopped automatically if the validation loss didn’t improve for 10 consecutive epochs.</p><pre>from tensorflow.keras.callbacks import EarlyStopping<br><br>es = EarlyStopping(monitor=&#39;val_loss&#39;, patience=10, restore_best_weights=True)<br><br>history_cons = model_cons.fit(<br>    Xc_train, yc_train,<br>    validation_data=(Xc_test, yc_test),<br>    epochs=100,<br>    batch_size=64,<br>    callbacks=[es],<br>    verbose=1<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*nhKFB_Sd9jRylC6knpsDRg.png" /><figcaption>A graph of the training and validation loss over time</figcaption></figure><p>The gap between the training and validation loss remained fairly small, suggesting that the model generalized well and avoided severe overfitting.</p><h4>Final Evaluation</h4><p>After training, I evaluated the model on the test set:</p><pre>loss_c, acc_c = model_cons.evaluate(Xc_test, yc_test, verbose=0)<br>print(f&quot;Test Accuracy: {acc_c:.4f}, Test Loss: {loss_c:.4f}&quot;)</pre><p>The final model reached a test accuracy of approximately 57%, which may not sound huge, but even a slight directional edge in forex trading can compound significantly when paired with proper execution logic and risk management.</p><h3>Out-of-Sample Testing (2022–2025)</h3><p>Once the model was trained and validated on historical data, I wanted to see how well it would generalize to<strong> </strong>completely unseen price action, without any retraining or tuning.</p><p>For this, I tested the model on a fresh dataset of USD/JPY 4-hour candles from January 2022 to May 2025, simulating what would have happened if the model had been deployed live during this period.</p><h4>Preparing the New Dataset</h4><p>The process for loading and preparing the new data followed the same pipeline as the training set:</p><ul><li>Loaded price data and auxiliary pairs like EUR/USD, GBP/JPY, and NZD/USD</li><li>Calculated all required features (e.g., MACD, RSI, Williams %R, EMA slope, volatility, etc.)</li><li>Joined all intermarket features</li><li>Scaled the features using the original scaler from the training phase to ensure consistency</li><li>Dropped any rows with missing values</li></ul><p>The target variable remained the same:</p><p>1 if the next candle’s return was positive, 0 otherwise.</p><h4><strong>Final Out-of-Sample Results</strong></h4><p>After preparing the data, I ran the model on this new period and evaluated its performance:</p><pre>Consensus model on NEW data →  Acc: 0.5860, Loss: 0.6773</pre><p>The accuracy of 58.6% may seem modest at first glance, but it’s both statistically significant and remarkably stable compared to the in-sample performance. This consistency suggests that the model learned generalizable patterns from historical data, rather than just noise.</p><p>As will be seen in the backtest, this edge is more than enough to be profitable when paired with:</p><ul><li>Tight execution logic (e.g., stop orders placed only in the predicted direction)</li><li>Controlled risk (1–3% per trade)</li><li>Clear stop-loss and take-profit mechanics</li></ul><h4>Exporting Predictions to MetaTrader 5</h4><p>After evaluating the model on unseen USD/JPY data from 2022 to 2025, the final step was to test how those predictions would perform in a real trading setup, specifically inside the MetaTrader 5 strategy tester.</p><p>Because MetaTrader 5 (and MQL5) doesn’t support running Python models directly, I needed a way to pass the predictions into the strategy logic. The solution?</p><p>Hardcode the model’s predictions directly into the MQL5 Expert Advisor.</p><h4>Generating the Predictions</h4><p>For each 4-hour candle in the test period, the model predicted whether the next candle would go up (buy) or down (sell). These predictions were:</p><ul><li>Shifted forward by one candle (to simulate making the decision before the bar closes)</li><li>Saved alongside the actual label and timestamp</li></ul><p>To embed these predictions into the EA, I generated a .txt file that defined three arrays in native MQL5 syntax:</p><pre>datetime times[] = {<br>    D&#39;2022.01.04 08:00:00&#39;, D&#39;2022.01.04 12:00:00&#39;, ...<br>};<br><br>string predictions[] = {<br>    &quot;buy&quot;, &quot;sell&quot;, &quot;sell&quot;, ...<br>};<br><br>string true_labels[] = {<br>    &quot;sell&quot;, &quot;sell&quot;, &quot;buy&quot;, ...<br>};</pre><p>These arrays were then copied directly into the MQL5 source code as global variables.</p><p><strong>Why Hardcode Them?</strong></p><p>By hardcoding the predictions:</p><ul><li>The EA could run fully offline with no dependency on external files or Python</li><li>It became possible to backtest hundreds of trades rapidly using MetaTrader 5’s built-in Strategy Tester</li><li>The model’s behavior was locked in and repeatable, ensuring an accurate evaluation</li></ul><p>This also mimics real-world deployment, where predictions are precomputed and then executed live on schedule.</p><h3>Strategy Logic: Executing Predictions in MetaTrader 5</h3><p>Once the model’s predictions were embedded into the MQL5 Expert Advisor (EA), I built a strategy that used those signals to enter trades only in the direction forecasted by the neural network.</p><p>The logic was implemented in MetaTrader 5 using MQL5 and followed a simple but robust breakout-style approach.</p><h4>Overview of the Strategy Logic</h4><p>For each 4-hour candle:</p><ol><li><strong>Prediction Check</strong>: The EA looks up the model’s prediction for the current time slot (&quot;buy&quot; or &quot;sell&quot;).</li><li><strong>Trade Window</strong>: Trades are only placed within a configurable time window (e.g., 08:00 to 20:00).</li><li><strong>Range Detection</strong>: The EA calculates the highest high and lowest low over the last N candles (default: 8 candles, or 32 hours).</li><li><strong>Trade Setup</strong>:</li></ol><ul><li>If the prediction is &quot;buy&quot;:</li><li><em>Place a buy stop at the high of the range</em></li><li><em>Stop loss below the low of the range</em></li><li><em>Take profit at a distance equal to the stop loss × a configurable risk-to-reward ratio (default: 3:1)</em></li><li>If the prediction is &quot;sell&quot;:</li><li><em>Place a sell stop at the low of the range</em></li><li><em>Stop loss above the high of the range</em></li><li><em>Take profit the same way</em></li></ul><p>5. <strong>Risk Management</strong>:</p><ul><li>Position sizing is based on either fixed volume or percentage risk of account balance</li><li>Optionally includes break-even protection once the trade is in profit</li></ul><h4>How It Works in Practice</h4><p>Let’s say the model predicted &quot;buy&quot; at 08:00:</p><ul><li>The EA calculates the highest high and lowest low over the last 8 candles (32 hours)</li><li>It places a buy stop at the high of the range</li><li>The stop loss is set at the low, and take profit is 3× that distance</li><li>If price breaks the high, the trade is triggered otherwise, the order expires</li></ul><p>The same applies in reverse for &quot;sell&quot; predictions.</p><p>This setup allows the strategy to:</p><ul><li>Avoid trading during low-volatility ranges</li><li>Only take positions when price shows signs of directional commitment</li><li>Align trade direction with the model’s prediction</li></ul><p>This structure allowed me to fully backtest the model-guided strategy in MetaTrader 5 using its built-in Strategy Tester.</p><h3>Backtest Results</h3><p>With the predictions embedded and the strategy logic implemented, I ran a full backtest in MetaTrader 5 using historical USD/JPY data from January 2022 to December 2024. The trading account was initialized with $10,000, and the model’s predictions were executed using the breakout strategy described earlier.</p><h4>Strategy Settings</h4><p>Here were the key parameters used during the backtest:</p><pre>| **Setting**          | **Value**                   |<br>| -------------------- | --------------------------- |<br>| Account Balance      | $10,000                     |<br>| Period               | Jan 2022 – Dec 2024         |<br>| Risk Per Trade       | 1% of account size          |<br>| Range Lookback       | 7 candles (28 hours)        |<br>| Risk-to-Reward Ratio | 3:1                         |<br>| Trading Hours        | 08:00 – 20:00 (broker time) |<br>| Break-Even           | Disabled                    |</pre><h4>Performance Summary</h4><pre>| **Metric**             | **Result**    |<br>| ---------------------- | ------------- |<br>|   Final Balance        | $152,824.69   |<br>|   Total Net Profit     | $142,824.69   |<br>|   Profit Factor        | 1.65          |<br>|   Recovery Factor      | 13.48         |<br>|   Drawdown (Max)       | 13.73%        |<br>|   Total Trades         | 687           |<br>|   Profitable Trades    | 41.48%        |<br>|   Average Profit Trade | $1,266.78     |<br>|   Average Loss Trade   | -$542.80      |<br>|   Sharpe Ratio         | 8.61          |</pre><p>Even with just 41.48% of trades being profitable, the strategy remained highly effective thanks to its tight risk control and strong risk-to-reward ratio. The takeaway? In trading, edge + proper money management &gt; high accuracy.</p><h4>Equity Curve</h4><p>Here’s the equity growth from $10,000 to over $152,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUhp5txBai5Ylp86IqTixg.png" /></figure><h4>Live Backtest Video</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05AtywA_E3y2uTDXnZGM1Q.gif" /></figure><p>To show the strategy in action, I’ve included a screen recording of the backtest as it ran live in MetaTrader 5. It demonstrates:</p><ul><li>The precise placement of buy/sell stop orders</li><li>Real-time trade execution based on predictions</li><li>Dynamic range calculation and position sizing</li></ul><h3>Conclusion</h3><p>This project set out to answer a simple but powerful question: <strong>Can deep learning be used to forecast Forex markets and trade profitably?</strong></p><p>The answer, based on this first prototype, is promising.</p><p>By combining solid <strong>feature engineering</strong>, a <strong>consensus-based feature selection strategy</strong>, and a well-regularized <strong>neural network</strong>, we built a model that generalized reasonably well to unseen data. Integrated into a breakout-style execution strategy coded in <strong>MQL5</strong>, the model was tested on <strong>MetaTrader 5</strong> using real historical tick data.</p><p>The results speak for themselves:</p><p>A $10,000 account grew to <strong>$152,824.69</strong> over nearly three years of testing with controlled drawdowns, robust risk-reward logic, and without curve-fitting.</p><p>But this is far from the end of the journey.</p><p>The algorithm is still evolving, with upcoming work focused on improving the model architecture, testing new markets, optimizing execution, and eventually deploying the system live.</p><p>If you’re interested in following the ongoing development of Code to Cash, you can:</p><ul><li>Visit the <a href="https://codetocash.lovable.app/">project website</a> for updates</li><li>Check out the <a href="https://github.com/LUBANGAKENE/Code-to-Cash/tree/main">GitHub repository</a> for the source code and research notes</li><li>Connect with me on <a href="https://www.linkedin.com/in/edmond-lubangakene-882350298">LinkedIn </a>to discuss ideas, feedback, or collaborations</li></ul><p>This is just the first step, and I’m excited to see where the next iterations take us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ab18f692cb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>