2020 started off good for crypto investors, with BTC prices increasing from levels of 7000USD to over 10,000USD in early February. Since then the disease COVID-19 has shook the markets to their cores and on top of that two of the three largest oil producers have engaged in an oil price war also dubbed “a collective suicide” by analysts. To the surprise of many, especially to strong believers in the independence of crypto assets from the traditional markets, Bitcoin portrayed a similar downtrend like equities over the course of February and especially in the first two weeks of March (see Figure 1), especially on Friday March 13th, where BTC dropped over 30% in one day.
Naturally, the important question that investors ask themselves in times like these is what they can do in order not to have to surrender to such terrible market conditions. Is there a way to avoid losing over 30% of your investment's worth in one single day? The short answer to this question is "yes, there can be a way": there are means and ways to trade successfully in this market and they rely on a technique called algorithmic trading.
Sounds complicated? Well it doesn't need to be! At Trality, our goal is to make professional-grade algorithmic trading available to private investors so that everyone can profit from it - not just the professionals. We do that with the help of trading bots! These are are technical vehicles for trading algorithms that control the automated buying and selling of (in this case: crypto-) assets. The algorithms use mathematical criteria based on assets' price or volume data to determine when a certain asset should be bought or sold. The trading bot forwards the resulting signals in the form of an order to a crypto exchange. Trading bots can help users to increase their profits in buying and selling assets by exploiting their volatility.
So how can even a simple version of algorithmic trading be used during a downward market environment such as the one starting mid-February? Let me give you a beginner-level example strategy, based on an indicators commonly used in technical analysis: an exponential moving average (EMA), specifically, the crossover of two EMAs.
See the Trality Documentation for a detailed explanation of the EMA crossover strategy. In short: An EMA is a type of moving average (MA) that places a greater weight and significance on the most recent data points. An exponentially weighted moving average reacts more significantly to recent price changes than a simple moving average (SMA). A crossover strategy applies two moving averages to a chart: one longer and one shorter. When the shorter-term MA crosses above the longer-term MA, it's a buy signal, as it indicates that the trend is shifting up. Meanwhile, when the shorter-term MA crosses below the longer-term MA, it's a sell signal, as it indicates that the trend is shifting down. (based on Investopedia)
We hence develop a strategy with two EMAs (20 and 40 candles look back period). The strategy trades on 1 hour candles, making it sensitive to mid- to short-term price movements. It moreover allocates always 80% of available base currency to each trade. We use the Trality Python code editor to craft this algorithm:
def crossed_upwards(short, lng): return short[-2] < lng[-2] and short[-1] > lng[-1] def crossed_downwards(short, lng): return short[-2] > lng[-2] and short[-1] < lng[-1] @schedule(interval="1h", symbol="BTCUSDT") def handler(state, data): # Basic indicators ema_long = data.ema(40) ema_short = data.ema(20) # Empty values check, e.g. maintenance windows, etc. if any(param is None for param in [ema_long.last, ema_short.last]): return # Whether we currently have an open position that's not dust has_position = has_open_position(data.symbol, truncated=True) # EMA conditions ema_crossed_upwards = crossed_upwards(ema_short['real'], ema_long['real']) ema_crossed_downwards = crossed_downwards(ema_short['real'], ema_long['real']) # Compute amount we want to buy (we use 80% of our portfolio here) balance_base = float(query_balance_free(data.base)) balance_quoted = float(query_balance_free(data.quoted)) buy_amount = balance_quoted * 0.80 / data.close_last # Check for buy and sell conditions and do allow one open position at a time if ema_crossed_upwards and not has_position: create_order(symbol=data.symbol,amount=buy_amount) elif ema_crossed_downwards and has_position: close_position(data.symbol)
By the way: if this seems like too much code for your liking, then you should try out our Trality Rule Builder, which lets you design simple strategies such as the one in this blog post based on boolean logic:
We subsequently use the Trality backtesting module to evaluate our strategy's returns:
Figure 3 displays the results of the aforementioned algorithm over a period from Feb 10 to March 31, 2020. Backtests on Trality always include exchange fees and can be modelled to account for slippage. As can be seen from the results, the strategy was backtested on a timeframe where the market significantly trended downwards and recovered only towards the end (see dark blue line). BTC lost over 34% of its value during that period. During the same period however our trading bot was able to amass a small profit of 2.71% by trading 14 times and thereby eliminating the large declines, which BTC would have otherwise been exposed to. Cumulated fees totaling 1.32% are deducted from the results, which can be seen depicted as the light blue line.
It is fair to argue at this point that this is only one backtest done over a short period of time and that backtests shouldn't be trusted as a sole measure for future success! While this is absolutely correct, the above above example nevertheless shows that even a trading bot as simple as based on an EMA crossover strategy can help to significantly cut ones losses during times of downturn - which it did in this particular case. For the sake of argument, however, let's take a look at a longer period of time and how our strategy might have performed during changing market environments.
As can be seen from Figure 4, over a 3-month period, the price of BTC initially rose significantly before enduring the aforementioned decline from mid-February to mid-March until finally climbing again to current levels. It becomes obvious that our simple EMA Crossover strategy is not as successful as above in all these varying market environments: It significantly under-performs the market in the first 1.5 months of our backtest, because a strong upward market doesn't result in enough trend reversals for the exponential moving averages to cross and hence result in trade signals. The algorithm unleashes its worth only in the second half of the backtest, where it ends up outperforming the market by a total of 34.71%.
Algorithmic trading isn't a "set it and forget it" type of operation!
This example trading bot and the two backtests go to show you that algorithmic trading isn't a "set it and forget it" type of operation. To be successful in the long-run, strategies need to be crafted meticulously, back- as well as forward tested and be flexibly adaptable to changing market environments. What does that mean in detail? The following key takeaways highlight some of the sophistication (not necessary complexity), which long-term trading algorithms should/could at least portray:
- they can be based on more sophisticated methods. Successful trading bots often include more than one indicator, they include personally developed indicators and they include additional methods such as statistics or machine learning. Remember though: this doesn't mean that the best algorithms are the most complex ones - often simplicity is the ultimate sophistication.
- testing your strategy on different intervals beforehand, can give you valuable insights on how dependent your strategy is on a given interval. Besides it could also be useful to include various time intervals. In order to be able to account for, both, short term price movements as well as long-term trends, good trading algorithms should be able to check conditions on various time intervals (candle sizes) and produce trading signals accordingly. The Trality schedule decorator allows for multiple intervals within one single trading bot.
- they can include multiple assets. As shown in one of our latest blog posts, certain market environments tend to result in high correlation among certain pairs, making certain asset combinations less attractive to successful bot trading. Sophisticated algorithms therefore compute information of multiple assets and produce trading signals accordingly. Remember though (again): also this is not always the case, so here as well testing with cross-validation across multiple assets is key and taking into account correlations among asset pairs can give you an indication if your strategy might work for multiple pairs or, alternatively, have negative results for multiple pairs.
- they should be tested over long periods of time, both back- as well as forward-tested (forward testing means practice trading with a bot in a real-life environment) and they should be tested in varying market environments. As mentioned before, they should be cross-validated along varying time-intervals and varying assets. Most importantly, they need to be based on a solid trading strategy and not solely be led by tests.
Over the next couple of months, we will continue to publish blog posts in this "strategies" series and we will discuss the above-mentioned and many more factors, which could lead to potentially well-performing trading bots for Trality users. Remember, all of the above strategy design is done in perfect hindsight about the situation and solely based on backtests. This series aims to go beyond this fact and provide our users different angles from which to analyze and optimize trading bots.
Disclaimer: Backtests are not indicative of future results, the above article is merely an opinion piece and does not represent any kind of trading advice or suggestions how trading bots or trading algorithms can or should be used.