Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.
Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.
Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.
Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.

Building Profitable Algorithmic Trading Bots

MORITZ PUTZHAMMER

29 June 202117 min read

Table of contents

Let’s start off with the bad news first. Building profitable algorithmic trading bots won’t happen overnight. It’s a process, one that takes time, patience, and knowledge. And since it’s a fluid process, it also involves a fair bit of trial and error before you start to see consistently profitable results.

Now that wasn’t too painful, was it? Actually, it isn’t so much a question of bad news, but rather a matter of having a realistic understanding of what’s involved in algorithmic trading (or in any trading for that matter) and of how you can achieve proficiency in order to realize your trading goals.

The good news? Building algorithmic trading bots with Trality’s state-of-the-art technology is seamlessly intuitive and straightforward. Even if you can’t code, you can still build trading bots with our unique Rule Builder, a one-of-a-kind graphical user interface that allows you to construct your trading bot’s logic by simply dragging and dropping indicators and strategies.

↓ This is a quick walk-through of our state-of-the-art Rule Builder ↓

Algorithmic trading bots can give you a significant competitive advantage by ensuring emotionless trading and offering blazing-fast backtesting speeds, diversification, and trading discipline. All of which are crucial to becoming a successful trader.

In the following chapters, we’ll cover in detail all the steps and best practices when developing a consistent, standardized approach to algorithmic trading. From generating ideas and backtesting and validating those ideas to implementing the final algorithmic trading bot in live trading, we’ll walk you through each step while helping you to sidestep some of the common pitfalls that can beset traders.

Our goal here is to avoid ad hoc strategies (which aren’t really strategies) or short cuts by developing a foundational, rule-based approach that will serve as an objective basis for generating, testing, and implementing trading ideas in the future.

Let’s get started.

Chapter 1: Generating trading ideas

Generating trading ideas with Trality

It all starts with an idea.

This is the first step along the pathway of a rule-based trading strategy using an objective approach. While inspiration can come from many sources and strike at any time, generating trading ideas isn’t a random process. Rather, it’s one that traders can consciously do in a systematic way based on knowledge and experience, which you can supplement by reading widely (e.g. books, blog posts, research papers, and even purpose-built online courses) and learning from the experiences of tried-and-tested experts.

Below we will cover the main building blocks of strategy development, all of which are crucial to understand before creating a trading system.

  • Universe selection
  • Creating trading signals
  • Timeframe selection
  • Position sizing

At the end of this chapter, you’ll know exactly what trading ideas are worth focusing on, bringing you one step closer to pinpointing a winning trading system.

However, a rule of thumb applies, especially for beginners: keep it simple. Here Occam’s razor can provide some useful insight – simpler theories should be chosen over more complex ones because they are likely to be more testable and therefore more manageable.

Investment Universe (or Market selection)

Which assets do you want to trade? As a new trader, it’s perhaps one of the most important decisions that you’ll make. However, with over 4,000 cryptocurrencies to choose from, it’s not necessarily an easy decision.

Criteria for selecting cryptocurrencies

Assuming that you have a sound understanding of your trading goals, a good starting point when researching any digital asset is to look into its community, team and leadership, underlying technology, white paper, pricing history, and vision for the future. The information gleaned can provide insights into the credibility, viability, strengths, and weakness of a particular coin – in a word, its potential profitability. Crucially, you’ll want to consider a coin’s fundamental purpose or rationale: Why is it important/necessary/innovative/disruptive? If you find yourself unable to answer this question, then there’s a good chance that the coin might not be around too long, which means that it’s not worth the investment of your time and money.

With a coin’s fundamental rationale or purpose in mind, you’ll want to consider some other important metrics, such as its active users as well as the size and frequency of transactions.

A good starting point is actually checking coinmarketcap.com because it gives users info about volume, market cap and many other important information.

Cryptocurrency prices by market cap on www.coinmarketcap.com
Top 5 cryptocurrencies by Market Cap (as of 18.06.2021)

Cryptocurrencies with a high market cap provide us with a deep and liquid market. When there is liquidity, it’s easier to get in and out of trades. With a low-volume cryptocurrency, you’ll find it hard to get in at your entry point and even worse, you might be stuck in a trade when you want out.

Diversification

Whichever digital assets you ultimately choose, your universe should contain more than one star. Simply put, diversification is a risk management strategy that combines a wide array of assets in order to limit your exposure as a trader to any single asset or risk. Given their inherent volatility, crypto markets pose certain challenges that can be mitigated or offset by a diversified portfolio.

Although you’ve likely read or heard it a thousand times in relation to trading, the old saying “Don’t put all your eggs in one basket” certainly applies to crypto. The thinking goes that the risk of a balanced portfolio is less than the sum of the risks for all its individual assets. For a given expected return, the portfolio that exhibits the least amount of risk is deemed the most efficient. As Nobel laureate Harry Markowitz has already pointed out, “Diversification is the only free lunch in investing.”

However, diversity isn’t merely a matter of holding a number of different cryptocurrencies. If you have 10 or 15 different coins, but all produce the same signals, then diversity is a moot point since you’d be better off simply trading one coin. What we’re after are individual signals with a low correlation, so that we achieve diversified returns and a smoother equity curve.

Creating trading signals

Like so many things in life, timing is everything. Knowing when to enter and exit a trade is crucial, as a great entry can translate into nice profits, while a smart exit should be an important part of your risk management strategy.

All of this is to say that the core of your algorithmic trading bot strategy will be its trading signals. As their name suggests, signals simply initiate or “signal” buying or selling points for any given asset, signposting entry and exit positions for your trading algorithm.

Entry rules

For some people, entry rules can be one of the most empowering parts of designing a trading system. Just think about it: the period right before entry is really the only time you’ll likely feel in complete control. If the market doesn’t do x, y, and z, then you don’t enter. As soon as it does, you place a trade to enter, after which point things become increasingly complicated and, to a certain extent, beyond your control once trading has started. But you don’t want your entry rules to be overly complicated. If you have too many conditions that need to be met before a trade takes place, then you run the risk of finding it difficult, or even impossible, to get your trades off the ground.

So how will you actually enter a market? Many consider the following golden rule helpful when creating good entries: Use a single rule at first. If you want an entry with multiple conditions, first start out with just one condition. Then, slowly add new conditions only if they significantly improve performance. You will likely find that many entry conditions you thought were important or necessary really are not.

At Trality, you’ll find an ever increasing number of indicators and pre-defined strategies to help you get started easily and strategically. And since an educated trader makes the best trader, check out our “Signal Generator” section in Trality Docs for further particulars.

Exit rules

Many traders can overlook the importance of well-timed and well-executed exits. But exits can have a tremendous impact on your overall profitability, which is why you should devote a great deal of time and attention preparing proper exits. Just as with entries, the golden rule to creating good exits is to use a single rule at first.

The “job” of exit rules is to protect your capital so if a sell signal does not minimize the losses of your trading system then it should be discarded.

Timeframe selection

Another crucial piece of your trading strategy is the time frame(s) that you select. Again, there is no one-size-fits-all approach, as strategies will perform differently depending on the specified time frames, which is why it’s best to select a time frame that meets your objectives. Do you want to be in and out quickly? Maybe a 1-minute or 5-minute chart is best. Do you prefer long-term swing trading? If so, maybe a daily time frame is the best option for you. The point is to select a time frame that matches your interest.

Trading using short time frames (“scalping”) attempts to profit from small price changes during short time intervals, but requires strict adherence to a predefined exit strategy in order to avoid significant losses. Swing trading means that you hold an asset for a few days to several weeks in order to take advantage of short- to medium-term gains (i.e. profiting according to swings). And position trading, then, is staking a position for a longer period of time, usually for a period of weeks to months.

Typically, shorter time frames lead to more trades, which is an important factor to keep in mind.  The higher the trade frequency, the more you’ll need to consider liquidity, bid-ask spread, and trading costs (low liquidity could yield an unprofitable strategy). This is why it’s best to avoid trading systems such as scalping as a novice trader. Even at this stage, it should be clear that algorithmic trading bots involve quite a number of moving parts, which can be a bit overwhelming for beginner traders. As a result, some traders tend to overlook one aspect of their trading strategy in particular, using a single time frame for trends as well as entry and exit signals. Instead, traders should consider becoming proficient in multiple time frame analysis (MTFA) in order to track how an asset performs within different time frames.

Position sizing

Finally, you need to figure out how much you’re going to trade (the position size) in order to complete your strategy. When we speak of position sizing, what we’re referring to is the size of your position for individual trades, which will depend on variables such as the size of your account, goals, and tolerance for risk. Position sizing revolves around the issue of capital allocation and there are various techniques that traders use (e.g. fixed dollar amount, equal percentage, risk based position sizing, etc.).

A small percentage means that there’s less of a chance of compromising your account since your losses will be small. However, the smaller percentage will necessarily result in smaller profits, if in fact your strategy is profitable, since you’ve invested only a small portion of your total balance. On the other hand, a higher percentage equates with increased risks, and where there are increased risks there are increased rewards.

In the end, it all depends on the kind of approach that you want to take. If you’re comfortable taking greater risks, you obviously stand to gain (or lose) more, while long(er)-term trading will involve a more conservative approach in order to trade profitably over the greater duration of time.

Chapter 2: Backtesting and validating strategies

Backtesting and validating strategies with Trality

Right. You’ve selected your universe; given careful thought to diversification; created trading signals; established your time frame(s); and calculated your position sizing. Congratulations, you’re on the right path toward building a profitable algorithmic trading bot. Now it’s time to backtest your trading strategy.

If we use a car racing analogy, then think of backtesting as practice laps on the racetrack, allowing the driver to test the car’s setup parameters and adjust them ex post facto in preparation for race day. The same principle applies to your crypto trading bot.

Backtesting allows you to evaluate your trading strategy based on historical market data, making it an ex-post simulation. And because it’s a simulation, it doesn’t require any actual capital, allowing you to test your strategy without risk or consequence. Good backtesting results can signal good results when you decide to begin live trading – although not always.

With the Trality Backtester tool, you can take advantage of commonly used statistics to evaluate algorithmic trading strategies in order to gauge performance (e.g. profit and loss; total return; average profit per winning trade), risk/return (e.g. volatility; Sharpe ratio), and runs (e.g. maximum drawdown; time under water).

Below we’ll cover best practices, out-of-sample testing, and which metrics to look at.

Backtesting - best practices

Overall, manual backtesting can be extremely complicated, time-consuming, and even frustrating. In keeping with Occam’s razor, which we mentioned earlier, it is generally considered best practice to select simpler strategies over more complex ones when deciding on optimizing parameters to estimate the amount of data required for backtesting. And in order to avoid inadvertent bias when backtesting, you should use blind or randomized data points so as to test, rather than reinforce, a hypothesis.

Overall, manual backtesting can be extremely complicated, time-consuming, and even frustrating. The Trality Backtester tool, however, is a real game-changer, as it allows traders using our Rule Builder or Code Editor to carry out comprehensive, customizable testing – literally in a matter of seconds. On the right side of your screen, simply select either a predefined scenario or choose a custom date to get started. For advanced settings, click the drop-down arrow to access additional options (i.e. fees, initial balance, and slippage).

Backtesting isn’t merely a one-off procedure, but something that you’ll do again and again before you forward test as well as when you’re live trading. When backtesting, you’ll also need to identify in advance key metrics, indicators and results before your actual test (more on this below).

Past performance does not guarantee future results, though. Let’s say that your backtest resulted in a healthy percentage increase in returns. The best parameters for any given time tend not to be the best results moving forward, a statistical phenomenon known as reversion to the mean.

In-sample and out-of-sample testing

When backtesting your crypto bot, it’s quite important to divide the available period for the backtest into in-sample and out-of-sample data. Now the in-sample data is important because it’s used to optimise your strategy. Once everything looks good, then you use the out-of-sample data to validate your results, confirming that you didn’t produce an overfitted strategy that will perform poorly once deployed in live trading.  Since it creates a division of data into different sets, cross-validation is used to avoid overfitting. One set will be used to create your model, while the other set(s) will be used to validate the model's accuracy.

What does this mean for you as a trader? Let’s say that you have an idea and you want to test it based on historical data. The actual historical data that you use to test and optimize your idea is referred to as the “in-sample data” (you might also see this data referred to as “training data”). The second data set (sometimes referred to as the “test set”), then, is used to evaluate forecasting performance. And cross-validation provides a way to test the performance of a trading strategy by resembling real-life trading as much as possible by carrying out testing on new data.

A good rule of thumb for splitting in-sample and out-of-sample data is to use 2/3s of the data set for strategy optimization and the remaining data for out-of-sample validation.

How long should you backtest for?

Approximately one year is a common time frame used by seasoned traders for backtesting. By testing over an extended period of time such as twelve months, you get to see how the strategy performs during different market conditions. After all, what do you think would happen if you tested a trend following system in a trending market? Needless to say, you’d have an incomplete (and therefore inaccurate) picture of how well your strategy would be expected to perform in the future. On the other hand, testing your system in a choppy market can give you a much better idea about the extent of possible losses.

The longer the period that you test, the more accurate your data will be, since it will compensate for the limited insights provided by shorter, period-specific market conditions. By observing its behavior through both bearish and bullish markets, you get a fuller picture of your strategy’s effectiveness.

With its “quick select” option, the Trality Backtester tool allows traders to select a twelve-month time frame with just one mouse click, making backtesting quick, convenient, and precise.

Meet your metrics

Trality provides its users with a full suite of metrics to use when testing their strategy, with each one falling under one of three categories: 1) Performance, 2) Risk / Return, and 3) Runs. In our Trality Docs section, you can read all about the various tools and data at your disposal when backtesting your trading strategy, which is why we won’t offer a comprehensive breakdown of each one.

Instead, let’s take a look at the most important ones: Sharpe Ratio, Total Return, and Drawdown.

Sharpe Ratio

First created in 1966, the Sharpe ratio (named after William Sharpe) is one of the most popular risk/return measures used in trading, providing investors with a better understanding of the return of an investment compared to its risk. In fact, it’s probably the most famous risk-adjusted measure out there.

The Sharpe ratio measures the performance of an investment (e.g., an asset or portfolio) compared to a risk-free asset (e.g., US government treasuries and bonds), after adjusting for its risk, and is defined as the difference between the returns of the investment and the risk-free return, divided by the standard deviation of the investment (i.e. its volatility).

Formula and calculation of Sharpe Ratio
Formula and calculation of Sharpe Ratio

Generally speaking, the higher the ratio, the better the returns. An asset or portfolio with a ratio below 1 represents a poor investment, while anything above 2 suggests a great investment.

<1: sub-optimal or poor

1: acceptable to good

2: very good

3: excellent

Using the Sharpe ratio can give insights into your portfolio’s past performance using actual returns. Additionally, the Sharpe ratio can be useful in helping to explain if a portfolio’s excess returns were a result of excessive risk or a result of smart investment choices.

Total Return

A return is the amount of money made or lost over a period of time, or the absolute return on investment over the given time period. A further distinction can be made between nominal returns (i.e. the net profit or loss expressed in nominal terms) and real returns (i.e. adjustments are made to account for external factors such as inflation).

We are interested in Total Return, which is a performance statistic that represents the accumulated net profit or loss for a given time horizon in percent.

total return, crypto
The cumulative money-weighted return (MWR) or performance of your cryptocurrency portfolio over all time incorporating cash and crypto flows such as new deposits, reinvested proceeds, and withdrawals. (Source: Cointracker.io)

Despite the useful information that this metric provides in terms of net profitability, it shouldn’t be used in isolation, but rather in conjunction with other metrics, particularly since longer time horizons can make it difficult to interpret due to the compounding effect.

Maximum Drawdown (MDD)

A maximum drawdown (MDD) is the maximum observed loss of a portfolio from a peak to a trough, before a new peak is attained. As such, MDD is an indicator of downside risk over a specified time period. Rather than pinpointing the frequency of significant losses, MDD measures the size of the largest loss.

Mathematically, it can represented as the following formula:

maximum drawdown, crypto, MDD
Mathematical formula to determine Maximum Drawdown (MDD)

By considering the difference between an asset’s or portfolio’s peak and trough, maximum drawdown is a critical risk measure, providing valuable insights into potential maximum accumulated losses as well as the time it takes before recovery or recuperation. A low maximum drawdown is preferred, since this indicates that losses from the investment were small. Conversely, the higher the MDD, the greater the losses.

Your crypto trading portfolio will be allocated in certain ways depending on a number of factors, including your overall strategy as well as your expertise, experience, and level of risk aversion. Whichever configuration you choose, your overall strategy should be analyzed and optimized by consulting various metrics (e.g. measuring risk, measuring returns, measuring risk-adjusted returns), a number of which we’ll highlight below.

Chapter 3: Live trading

Live trading with Trality

By this point, you now possess the knowledge and insights to create a foundational, rule-based approach that will serve as an objective basis for generating, testing, and implementing trading ideas.

In fact, let’s say that you’ve created and tested your own algorithmic trading bot. You’re now ready to take your trading to the next level – live trading, right? Emotionless trading, 24/7, easy money.

Well, not quite. Just because you’ve pinpointed and optimized your strategy doesn’t mean that you can set your automated algorithmic trading bot and then forget it.

Can you trust yourself, for example, to follow your strategy exactly as tested, even under challenging market conditions when your emotions might bubble to the surface? Unnecessary expenditures of emotional capital can be costly when it comes to your financial capital, which is why a brief look at some best practices when live trading will help you stick to your strategy even when fear and doubt, or a series of losing trades, are whispering in your ear to abandon ship.

  • It’s automated, but not automatic. Once your bot has been deployed for live trading, it is very important to monitor it regularly to ensure that it runs as smoothly as it did in backtesting.
  • Know when to quit. Entry points are easy; the real difficulty lies in knowing when to exit. Maybe it’s X amount of consecutive losers in a row, or a matter of overall profit after X months. However you define your exit point, ensure that it’s solid and definitive and stick to it.
  • Going to the market. Trending markets, sideways markets, whip-sawing markets, volatile markets, and slow moving markets – markets are fluid and can change or move  in unpredictable ways. (See the first point.)
  • Losing is for winners. The entire point of this exercise is to develop a profitable strategy, but the simple fact is that you will lose on some trades. Embrace the fact that everyone experiences losing trades. Once you do, fear of failure dissipates and you can get on with the business of profitable trading.

Create your own algorithmic trading bot with Trality

Trality’s state-of-the-art platform empowers traders to create their bots and connect them to their favorite exchange via API keys. Once connected, your bot will run 24/7, making automated trades safely, securely, and reliably.

Just think of the alternative: manual trades, which are undisciplined, subjective, unreliable, and S-L-O-W. It’s like trading with one hand tied behind your back. With Trality’s automated crypto trading bots, however, there are no more missed trades or missed opportunities. You can buy, sell or hold assets in a timely, efficient, and automated manner day or night from anywhere in the world.

A step-by-step guide for creating, backtesting, and live-trading with a new trading bot on Trality

Casual traders will fall in love with the ease and simplicity of our unique drag-and-drop Rule Builder (no coding required!), while Python gurus can make the most of their quantitative skills and code sophisticated trading algorithms with our revolutionary Code Editor. And our powerful backtester ensures that the viability of your ideas is assessed quickly and comprehensively, empowering you with the information that you need to trade profitably.

The best part? With only a few clicks, you can sign up and start exploring our game-changing tech absolutely free of charge. You’ll also get an invite to join our awesome Discord community.

Ready to start? There’s no time like the present!

Check out the Trality Rule Builder, a state-of-the-art tool that allows you to create your own trading bots without writing any code.