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

This is the second article in a series of tutorials: Build AI for generating quant trading strategies automatically, for the previous article, please, check this link.We already wrote a basic strategy in Metatrader 5 trading terminal (MQL5 language) an…


This content originally appeared on Level Up Coding - Medium and was authored by Besarion Turmanauli

This is the second article in a series of tutorials: Build AI for generating quant trading strategies automatically, for the previous article, please, check this link.

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:

Optimization

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:

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:

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:

And a list:

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:

Let’s combine the two periods:

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;

RISK DISCLAIMER:

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:

$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

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

Requirements:

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

$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.

Have a great day!


Build AI for Generating Quant Trading Strategies in C# (Part 2) was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Besarion Turmanauli


Print Share Comment Cite Upload Translate Updates
APA

Besarion Turmanauli | Sciencx (2021-04-09T13:28:22+00:00) Build AI for Generating Quant Trading Strategies in C# (Part 2). Retrieved from https://www.scien.cx/2021/04/09/build-ai-for-generating-quant-trading-strategies-in-c-part-2/

MLA
" » Build AI for Generating Quant Trading Strategies in C# (Part 2)." Besarion Turmanauli | Sciencx - Friday April 9, 2021, https://www.scien.cx/2021/04/09/build-ai-for-generating-quant-trading-strategies-in-c-part-2/
HARVARD
Besarion Turmanauli | Sciencx Friday April 9, 2021 » Build AI for Generating Quant Trading Strategies in C# (Part 2)., viewed ,<https://www.scien.cx/2021/04/09/build-ai-for-generating-quant-trading-strategies-in-c-part-2/>
VANCOUVER
Besarion Turmanauli | Sciencx - » Build AI for Generating Quant Trading Strategies in C# (Part 2). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/09/build-ai-for-generating-quant-trading-strategies-in-c-part-2/
CHICAGO
" » Build AI for Generating Quant Trading Strategies in C# (Part 2)." Besarion Turmanauli | Sciencx - Accessed . https://www.scien.cx/2021/04/09/build-ai-for-generating-quant-trading-strategies-in-c-part-2/
IEEE
" » Build AI for Generating Quant Trading Strategies in C# (Part 2)." Besarion Turmanauli | Sciencx [Online]. Available: https://www.scien.cx/2021/04/09/build-ai-for-generating-quant-trading-strategies-in-c-part-2/. [Accessed: ]
rf:citation
» Build AI for Generating Quant Trading Strategies in C# (Part 2) | Besarion Turmanauli | Sciencx | https://www.scien.cx/2021/04/09/build-ai-for-generating-quant-trading-strategies-in-c-part-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.