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

Besarion Turmanauli
Level Up Coding
Published in
8 min readMar 31, 2021

--

Let me start with a question: have you ever heard of Citadel LLC, Renaissance Technologies, Two Sigma, or, maybe, D. E. Shaw & Co.? In case you didn’t, the simplest way I can describe what they do is that these companies create automated trading strategies, AKA quantitative strategies, AKA quant strategies, AKA algorithmic strategies that manage investors' money by buying and selling different financial securities (currencies, stocks, indices, commodities, bonds, options, and others) for profit, automatically, without human intervention.

Before computers, there were traders making buy/sell decisions manually by analyzing charts, employing technical (historical price data) and fundamental (macroeconomic data, important market events, news, and so on…) analysis to predict future price movements, buying low and selling high, making profits along the way, and for those who knew what they were doing, it was relatively easy to consistently make money for investors and for themselves.

In 1998 United States Securities & Exchange Commission (SEC) authorized electronic exchanges opening doors for computerized High-Frequency Trading (HFT). What differentiates traders from investors is that traders rely on short-term predictions, usually buying and selling the same security in one day, holding positions for a few hours or a few minutes. As HFT became more widespread traders found themselves unable to beat computers making trading decisions in split-seconds and with higher accuracy, it became harder and harder for them to make money.

Manual trading can still be profitable today if you know very well what you’re doing, of course, the market you’re operating in, and either opt for longer-term (several days or weeks) positions or trade low liquidity high volatility markets like penny stocks, pink sheets, exotic currency pairs, or cryptocurrencies. One reason is that low liquidity means higher spread, slower order execution, and computers have more of an edge in higher liquidity markets where they’re able to buy and sell fast ideally with as much volume as they need.

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.

Just before you skip the disclaimer, please, understand that I actually mean every single word in it and it’s something I want you to take into careful consideration, moreover, artificial intelligence is very susceptible to making wrong decisions for a number of reasons ranging from a corrupt or insufficient amount of data, incorrect approach to the task at hand or just various bugs.

I personally take these principles into account when risking my own money knowing that I could lose it for a variety of accidental or partially predictable reasons and not only I could but I have. I learned a thing or two as a result but I also paid actual money for that education, however, for you this tutorial is free, let’s keep it this way!

Before we build an AI which builds trading robots (yet another frequently used name for automated/algorithmic strategies), we should first be able to build a trading robot ourselves, right?

For this, we need a trading platform or trading terminal which allows the creation and use of automated trading strategies, some of the most popular choices are:

  • Metatrader 5 (robots can be created in MQL5 language, based on C++)
  • Metatrader 4 (robots can be created in MQL4 language, based on C++)
  • JForex ( robots can be created in Java, using relevant libraries )
  • NinjaTrader ( NinjaScript programming language, based on C#)
  • Interactive Brokers’ Trading WorkStation ( TWS API + Python, Java, C#, C++ or VB)
  • Tradingview (PineScript programming language, similar to Python)

If the complexity of C++ scares you a little bit and you’ve already stumbled upon cases where you need some 500 lines of code to reliably do something you can do with just one line of code in C#, Visual Basic, Python, or PHP, don’t worry, I’m one of the most scared people I know when it comes to C++, I love maximum productivity and simplicity and although MQL5 and MQL4 are based on C++, they are as simple to use (if not more) as C#.

I’ve built dozens of algorithmic strategies and indicators over the years for all the platforms above and I’ve never found a trading platform as powerful as Metatrader 5 for developing, testing, and optimizing automated trading strategies, it gives you unmatched precision and power, far more than you’ll ever need, it’s also intuitive and simple to use.

As for the broker, I would recommend Roboforex, which provides the MT5 platform free of charge for its clients, you can open a demo (paper trading) account and if you meet the requirements listed below, you’ll also get $30 as a gift from the broker on a real/live account:

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

Once you open an account, download MetaTrader 5 (or MT5) from the Roboforex website and install it. MT5 comes with MetaEditor — an IDE for developing automated trading strategies, open it and let’s start directly by creating a simple strategy:

Got to File > New or CTRL+N and choose Expert Advisor (template), then click Next > :

By the way, in this platform, trading robots are called Expert Advisors.

Now choose a name for your robot and click Next > :

Click Next > again:

Click Finish.

A starting source code template will be generated, and it will look like this:

Let’s include main classes for opening/closing trades, retrieving order and position information:

Basic overview:OnInit function is called once when the robot is launched, OnDeinit function is called once when the robot is removed/stopped and OnTick function is called every time underlying security price changes.

Now let’s add a simple trading logic:

Click F7 or Compile button in MetaEditor to compile the strategy, and it’s ready (actually, it’s still far from ready, but we can test our trading logic on historical price data in Metatrader 5).

So, let’s open Metatrader 5, go to View > Strategy Tester or CTRL+R :

Click on Singleand choose everything as shown on the screenshot below, then click on the green start button at the lower right corner:

Once done, switch from Settings tab to Graph tab in order to visualize the profit curve over time:

It’s not perfect, but that’s OK for now, we’ll make it better!

If you’d like to learn MQL5 development in-depth, you can find excellent documentation here. However, learning MQL5 development is not required for this tutorial as we’re just demonstrating the best practices of building, improving, optimizing, and verifying trading strategies in order to replicate the same steps in an AI algorithm so that it’s able to do everything independently.

In the next part of the tutorial, we’ll refine our strategy, optimize and forward-test it to make sure it is consistent and reliable in different market environments.

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

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

Would you also like additional free stuff?

Get $100 in cloud credits from DigitalOcean when you register from this link: https://m.do.co/c/88f25eea9442

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:

When you invest in any cryptocurrency, you can make an additional risk-free passive income by allowing lending for margin (leveraged) trading, it comes with a powerful Online (web) platform, Windows, Mac, and Linux software, as well as Android and iOS apps + Binance API for software developers.

Binance doesn’t only have the lowest fees, but is one of the few platforms that support trading Dogecoin, and is the largest crypto exchange in terms of traded volume and cryptocurrencies allowed for trading in the world.

Deposit options include:

  • Direct crypto deposit of any listed cryptocurrency in your Binance wallet;
  • Buying cryptocurrency using your Credit/Debit card;
  • Deposit 35 different fiat currencies via Bank Transfer (SWIFT or SEN).

And you can now get a 10% commission cashback on any trades you make when you register from this link.

--

--