Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

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

--

And finally, here it is…

Hi and welcome (again)! In this tutorial, I’m going to reveal the complete source code and principles behind reinforcement learning software able to create and test profitable algorithmic trading strategies automatically.

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 (and other articles in this series of tutorials) 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.

First, we have a standard windows-designer-generated code for our interface (partial Form1 class):

And the other part that wraps everything up:

Looks like this:

There’s also a standard Program.cs class that loads the interface itself:

Once we select the CSV file with price data exported from MetaTrader 5 (MT5) trading terminal, DataManager class loads the file content and does preliminary calculations, checking data integrity, automatically recognizing chart timeframe, number of lines, CSV separator, the number of columns and loads the parsed data into Imported Price Data tab (DataTable format):

After preparing all the initial data points, we need to calculate indicator values correctly, among other things. PriceEngine class calculates Moving Average, Average True Range, Relative Strength Index, Daily OHLC, and other derivative values exactly like MetaTrader 5 (tested and verified), so the strategy created here will generate exactly the same trades in MetaTrader 5 strategy tester. All of this data is then loaded in Generated Price Data tab (DataTable format):

For more information on how to calculate technical indicator values the right way in your project, please, check this tutorial:

Next, there’s a Tester class that tests the trading logic on the historical price data generated by PriceEngine class and returns the hypothetical trading performance and statistics, we went through the Tester class in Part 2 of this tutorial series, here it is again, just in case:

Tester class uses a smaller JSON class to deserialize trading logic stored as JSON string into a dynamic object:

Then it iterates through the dynamic object generated by deserializing the JSON string in order to go through the trading logic and make trading decisions if entry/exit criteria are met. For more information on how to iterate through a dynamic object in C#, please check this tutorial:

Finally, we have the Builder class where our reinforcement learning logic resides and which builds trading strategies criterion-by-criterion:

Here’s a short version of how it works: Builder class adds entry criteria to buyLogic and sellLogic properties of Tester instance, runs the Tester and saves trading statistics.

Then it adds other criteria, runs the Tester once more, if current results are better than previous results, criteria are kept (and current trading statistics are saved for comparison), otherwise, they’re discarded (and previous trading statistics are loaded).

Again, new criteria are added to the existing list, tested, and kept or discarded based on whether they improve the results or not. Over and over.

There’s more to this, but I want to keep the length of this article reasonable, I tried my best to show you the most interesting parts. Feel free to check the previous tutorials for more insights, or just compile the code on your machine and start creating baby algorithmic strategies. Let me know in the comments what you think!

Thanks for reading and as always, you can check the links down below to get something free for your next project:

Disclaimer:

These contain affiliate links, and I may receive compensation if you use them

Hey again, would you like to know what I do for a living? I'm a Senior 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

Deploy your next app in seconds: Get $100 in cloud credits from DigitalOcean using this link: https://m.do.co/c/8c5a2698b1a2

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

10% Lifetime Discount on all trades from Binance: Binance is a cryptocurrency exchange that has the lowest fees in the world supporting by far the largest variety of ways you can trade or invest in crypto:

  • Spot Trading;
  • Peer to Peer (P2P) Trading;
  • Margin (up to 10x leverage) Trading;
  • Crypto Futures Trading;
  • Crypto Conversion and more…

You get an additional 10% discount on every trade you make when you register from this link.

Have an amazing day!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (3)

Write a response