Discover the Secret of Algorithmic Trading

Trading with shares or trading with the human psychology

Hrudhai Rajasekhar
krtrimaIQ Cognitive Solutions
8 min readSep 5, 2022

--

The stock market is a vast ocean of data with over a million trades being punched in every second, around the world. In this ocean, there are the whales — institutional investors, and the small fish — retail investors. The real direction of the market is driven primarily by the institutional investors, and the retail traders just follow this direction. But what makes us — the retail traders — just follow the market and not decide to go against it?

The answer to this question is two-fold. The volume of the money invested by retail trader is mere pennies compared to the investments by financial institutions. The second aspect is — human psychology. A trader’s mind will be hesitant to take a trade that is going in the opposite direction of what was expected initially. It takes discipline to stay in a trade during such situations.

The typical human impulse is to close the positions when the market is in the opposite direction and hold them when the market is favorable. On a daily basis, instances of a few candles going against a trader’s positions play with his psychology to protect the profits or minimize the losses by squaring off his trades. In reality, these candles are just a small correction and typically, the trend continues. Many retail traders fall into this trap and end up with either a loss or a smaller profit than what they could have made.

Is algorithmic trading the solution?

Algorithmic trading is the process of trading in the market using a computer program that follows a predefined set of rules taking in variables such as time, price, volume, and in certain situations, indicators as well. The simple principle behind algorithmic trading is that, if you have a strategy with a fixed set of rules for entry and exit, then you design a computer program that executes the trades as part of the strategy based on the rules without looking at the market sentiment. As long as the price action falls within the exit criteria band, the positions will be held irrespective of the actual market sentiment and price movement.

The biggest advantage of algorithmic trading is the ability to counter and tackle the fear arising from the human mind.

A robot must obey the orders given it by human beings, except where such laws would conflict with the First Law
- Isaac Asimov’s 2nd Law of Robotics

The use of algorithmic trading also reduces the trader’s screen time during market hours by allowing the bots to run automatically on a daily basis. This is particularly useful for retail traders who are looking for a secondary source of income in the market but do not have the time to observe the market and manually enter trades. Coupled with a dashboard to monitor strategies, this system could help traders manage their portfolios with minimal intervention.

Algorithmic trading is cool and all but how can anyone try it?

KPMG’s Pulse of Fintech H2’21 reports that 2021 has seen a record number of deals amounting to $210 billion, all around the world for investments in financial technology.

FinTech Investments. Source: Pulse of Fintech H2'21, KPMG

Start-ups and MNCs are now looking to leverage the potential of technology in the stock market. These companies are developing algorithmic trading bots with an aim to rope in retail traders. With the plethora of trading strategies defined by successful traders, the possibilities in algorithmic trading are endless. Most platforms charge a small subscription fee for each strategy, bundled with a platform fee for the analytics they provide.

Is there a DIY version of algorithmic trading? Yes, there is. While, getting into algorithmic trading is not as challenging as scaling Mount Everest, it does require some financial and technical knowledge.

Getting Started with Algorithmic Trading

In my experience, the most fundamental technical concepts that are required in developing algorithmic trading bots include — Python, REST APIs, and serverless cloud services. Before I explain how to do this, let me show you how algorithmic trading works.

It is a known fact that trades cannot be placed with stock exchanges directly but have to be placed through various exchange-approved brokers. So, how can we communicate to brokers and exchanges about our trades through a computer program?

A flowchart representing how a program consisting of a strategy logic communicates with the broker and the exchange
Program Interaction with Broker and the Exchange

When the program is initiated, the strategy logic starts running. A strategy logic typically comprises three components.

  • Entry: It handles entering of trades based on factors defined by the rules, like price action, indicators, and time
  • Monitoring System: This is used to track the existing positions, handle control mechanisms in case of order failures, trailing stoploss logic etc.
  • Exit: It squares off the positions as defined by the rules

Th strategy logic is responsible for communicating with the broker, to get the prices of instruments, existing positions, order details, and to place orders. The logic also computes values of other indicators as required by the rules. The broker in turn communicates with the exchange to retrieve prices, positions, and place orders. All this communication takes place through API calls between the components.

Most brokers provide Python, Java or R libraries or APIs that can be used for communication. The libraries provided are usually wrappers for API calls which can be used with ease in a Python program. When you subscribe to API access through a broker, they provide you with secret keys and API keys which are essential for any communication. They are used primarily for authentication of the API calls. In most cases, API keys and secret keys are used to generate an access token on signing in which are valid till the end of the day.

A simple flow for any algorithmic trading is shown in the diagram below.

A flowchart which depicts the typical flow of any algorithmic trading bot
Algorithmic Trading Flow
  1. The program sends the user to the broker login page for authenticating the user and generating an access token, valid till the end of the day
  2. On authentication of the user, an access token is sent back to the program
  3. This access token is further stored in the database, which can be reused throughout the day
  4. Based on the rules, the program triggers the strategy logic for entry, monitoring and exit
  5. For each trigger, the strategy logic can get the last traded price, list of orders and positions and place an order through the program to the broker
  6. The broker further communicates the same to the stock exchange and places the order. On confirmation of order placement, the exchange sends the order details back to the broker with the order ID
  7. This is sent back to the program which saves the order details in the database

Most algorithmic trading bots will follow a similar process with minor additions depending on the type of strategy and the rules defined.

The system architecture design needed to set up an algorithmic trading bot are as follows:

  1. A serverless backend on Python or Node.js like AWS Lambda or Google Cloud Function with a REST API attached to the function and a CRON job to set up automation
  2. A program that runs on a server or on serverless functions which contains the crux of the strategy logic
  3. An account with a broker and a subscription to their APIs (with the documentation)
  4. A database to store necessary details to ease order placement

With this, anyone having a basic knowledge of stock market and programming can create their own algorithmic trading bots.

What kind of strategies can I implement with algorithmic trading?

Any strategy having a fixed set of rules which can be defined through flowcharts can be programmed easily. Typically, strategies have predefined rules that are followed by traders. These strategies can be programmed easily. While some complex strategies might require additional programming knowledge, simple strategies can be developed with ease by anyone with basic knowledge.

Some of the popular strategies that can be used to start algorithmic trading are

  • Straddles
  • Strangles
  • Iron Fly
  • Iron Condor
  • Spreads

These strategies are mainly based on derivatives trading — but this does not restrict the scope of algorithmic trading.

Backtesting a Strategy

Most traders who have observed the market for years devise their own rule-based strategies and will want to test how these strategies work in the market. There may be some traders who take some of the popular strategies and add their own rules to them. If these strategies have fixed rules, they can also be programmed to simulate a live market based on historical data. This concept is called backtesting.

Initially, backtesting was done manually — by looking at charts and using Excel sheets. However, with the rise of algorithmic trading, most platforms provide backtesting services which run programmatically on historical data. A trader with access to this historical data, can develop their own backtesting program for any strategy.

It is important to keep in mind that while this backtesting may be accurate, it may not be able to accurately predict the outcome of the trades in the future. The main purpose of backtesting a strategy is to look at the statistics in terms of success rate, annual ROI, expectancy. These metrics will give an insight into how the strategy can be expected to perform.

Future of Algorithmic Trading

With the development of Machine Learning and Deep Learning, individuals and organizations are exploring the use of these concepts in trading. Predictive analysis is the simplest application of AI in the stock market. By using historical data to predict the direction of the market or the prices of instruments, trades can be executed, and strategies can be designed to maximize profits and minimize losses.

Sentiment analysis is another technology which is being tapped into within the financial domain. Tweets by Elon Musk, and about Ronaldo preferring water over Coca-Cola have impacted the share prices of Tesla and Coca-Cola respectively. With the use of sentiment analysis, tweets like these can help ascertain the direction of the market in general or of a particular instrument.

Conclusion

Algorithmic trading brings discipline and patience in the market. There may be drawdowns and big losses, but any tested and proven strategy will usually recover from them. Gone are the days when traders relied only on technical and fundamental analysis for their decisions. Rule-based disciplined trading or algorithmic trading are the in-demand technologies today.

We don’t have to be smarter than the rest. We have to be more disciplined than the rest

- Warren Buffet

krtrimaIQ Cognitive Solutions is an agile start-up with the attitude and power of an enterprise, focused on applying Data Science, Cognitive Science and NextGen BI to build the Intelligent Enterprise. In Sanskrit, “krtrima” means “artificial”, and “IQ” is the Intelligent Quotient.
To know more about what we do, check out our
website, and follow us on LinkedIn, and Twitter.

--

--

Hrudhai Rajasekhar
krtrimaIQ Cognitive Solutions

I am an MS in CS student at GeorgiaTech specializing in Machine Learning. I talk about all things LLM, GPT, and Algorithmic Trading