Build AI for Generating Quant Trading Strategies in C# (Part 2) (2024)

This is the second article in a series of tutorials: Build AI for generating quant trading strategies automatically, you can check other articles below:

Building AI for Generating Quant Trading Strategies in C# (Part 1)Let me start with a question: have you ever heard of Citadel LLC, Renaissance Technologies, Two Sigma, or, maybe, D. E…levelup.gitconnected.com
Build AI for Generating Quant Trading Strategies in C# (Part 3)This is the third article in a series of tutorials: Build AI for generating quant trading strategies automatically, for…levelup.gitconnected.com

We already wrote a basic strategy in Metatrader 5 trading terminal (MQL5 language) and tested it on historical price data, now let’s dive deeper and go through all the best practices for refining and verifying the strategy for reliability. Right now the strategy is very basic, we need more data points and external input parameters to work with, let’s add some of them:

These external input parameters let us change/optimize the strategy settings without modifying the source code. On the right side, comments describe the meanings of each input, as you can see we have inputs for ATR, RSI, and MA indicators, let’s prepare some necessary variables for handling their values:

MQL4 language had a simpler way of getting an indicator value using a return value of a function, but the MQL5 method is more efficient and probably faster once everything’s set up, first we need to assign unique handles when the robot is launched, this happens in OnInit() function:

We also need to assign a unique Magic number to our CTrade object (trade), before or after assigning indicator handles, for that we’re using an input parameterMagicNumber that we created earlier, this way we can modify it externally without modifying the source code:

Right now indicator handles are set up, but we don’t process indicator values yet, for this we first need to access the indicator and copy all the values to the relevant buffer array, then set the buffer array as series, in order to avoid doing the same thing over and over again, I created a simple function that does just that in one line of code:

And some additional functions for handling routine stuff:

The last part is to use all this inside a trading logic (OnTick() function), let’s gather everything in order to make further access as simple as possible:

Let’s now define buy and sell criteria using some of these data points:

A complete source code looks like this:

Now click on F7 to compile the robot and we’ll do some more testing and optimization inside the MetaTrader 5 terminal…

The first backtest on the last 10 year period with default parameters looks like this:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (3)
Build AI for Generating Quant Trading Strategies in C# (Part 2) (4)

Optimization is trying different combinations of input parameters in order to find out potentially the most profitable combination. If done right, you can find the best settings for your automated strategy relatively quickly, if not, the robot could show great results on historical price data and terrible results on a demo (paper) or live account. If you’re familiar with statistics, you’re less likely to have common mistakes, but if you’re not here’s a basic checklist:

  • If you are testing your strategy on 10 years, always optimize it on the previous 9 or 8 years, leave recent/last 1–2 years or so just for verification, this is called forward testing.
  • Make sure you have at a minimum 500–1000 hypothetical trades (depending on a strategy), otherwise optimization is meaningless, a complete waste of time!
  • Once you find out the best settings for your strategy, you shall verify that these settings do work in the future, not only on an optimized time period. This is where 1 or 2 years (forward testing period) we kept untouched come in handy, test the robot on last 1–2 years with the best settings you just uncovered, the results you’ll get will be closest to the real trading results in the future.
  • The greater the similarity between the back and forward testing results, the better — more reliable your strategy is and shall, in theory, survive longer.

In order to optimize different inputs of your strategy, go to the strategy tester (CTRL+R) and change the last parameter (highlighted) like this:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (5)

Then go to the inputs tab, where your strategy’s inputs are, select the inputs you want to optimize, set a start value, step value, and stop value for each of them:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (6)

In this example, the start value is 0.7, it will be increased by step value till a value of 2 (Stop Value) is reached, generating 14 different settings per input.

The tester will test your strategy with 196 total combinations (14²) of those settings and show you the results, here’s what an optimization graph looks like:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (7)

And a list:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (8)

Let’s choose the one with the best Sharpe Ratio and test — right-click on it, then choose Run Single Test,here’s a backtest on the previous 9 years followed by a forward test of the last 1 year:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (9)

Let’s combine the two periods:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (10)

This strategy checks basically all the boxes and more:

  • Optimization results were successfully confirmed by forward testing;
  • Profitable on 10 year period, not only a few months or a few years;
  • Forward testing results are not only similar but way better than backtest results — a clear sign of robustness and big potential.
  • It’s simple, not over-optimized, and overcomplicated, will likely work on all brokers and account types, in all market conditions;

For the purposes of this tutorial, I’m not a qualified licensed investment advisor, nor do I provide personal investment advice, all information provided in this article is for informational and educational purposes only.

Conduct your own due diligence and consult a licensed financial advisor before making any and all investment decisions. Any investments, trades, speculations, or decisions made on the basis of any information found in this article, expressed or implied herein, are committed at your own risk, financial or otherwise.

Trading (both manual and algorithmic) involves substantial risk of loss and is not suitable for everyone. The valuation of financial securities may fluctuate, and, as a result, you may lose more than you original investment. The impact of seasonal and geopolitical events is already factored into market prices.

Leveraged trading means that small market movements will have a great impact on your trading account and this can work against you, leading to large losses or can work for you, leading to large gains.

If the market moves against you, you may sustain a total loss greater than the amount you deposited into your account.

If you enjoyed this article, please, hit that clap button, this way more people will be able to find it!

In order to avoid risking your own money, here’s a list of brokers who offer you a no-deposit bonus just for registration:

Build AI for Generating Quant Trading Strategies in C# (Part 2) (11)

$140 from FBS: regulated by IFSC, this broker is one of the oldest and most established institutions, operating since 2009.

Requirements:

Available Markets: Cryptocurrencies, Stocks, CFDs, Metals, Commodities, Foreign Exchange

Build AI for Generating Quant Trading Strategies in C# (Part 2) (12)

$30 from Tickmill: regulated by FSA, this broker operates since 2015.

Requirements:

Available Markets: Stock Indices, Oil, Precious Metals, Bonds, Foreign Exchange.

Build AI for Generating Quant Trading Strategies in C# (Part 2) (13)

$30 from Roboforex: regulated by CySEC and IFSC, Roboforex is operating since 2009 and is one of the most popular and trusted brokers among traders today.

Requirements:

  • Open an account and deposit $10 to verify your payment method (can be withdrawn at any time) and get $30 as a gift
  • Profits are withdrawable without limitations
  • If you trade the necessary number of lots, you can withdraw the $30 too

Available Markets: Stocks (all NYSE, NASDAQ, and AMEX shares + German and Chinese listed companies), Stock CFDs (on all stocks, $1.5 per trade fee on US-listed shares), Indices, ETFs, Commodities, Metals, Energy Commodities, Cryptocurrencies, Cryptoindices, Foreign Exchange.

Would you like to know what I do for a living? I’m a Senior Software Developer at the Proxify Network.

Right now Proxify is looking for new developers, so I wanted to share a few words about my experience here — compared to other things I’ve tried in my career:
1️⃣ The friendly and professional Proxify team and the amount of care they put into each candidate
2️⃣ The hiring process is quite simple and allows to show your skills in full
3️⃣ And, what’s most important, Proxify is the ideal way to find remote work with endless projects and companies to choose from.

Apply here to join me at Proxify: https://bit.ly/3hd64mN

Thank you and I hope I’ll see you in the next part of the tutorial:

Build AI for Generating Quant Trading Strategies in C# (Part 3)This is the third article in a series of tutorials: Build AI for generating quant trading strategies automatically, for…levelup.gitconnected.com

Have a great day!

Build AI for Generating Quant Trading Strategies in C# (Part 2) (2024)
Top Articles
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 5480

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.