Dedicated to the angels in my life, my mother, my wife Preshita and my two daughters Mihika and Anya. Last but not the least, my college professor, Dr Rajat Moona, who sowed the seeds of computer programming in my DNA.
Introduction to Trading Bot
Welcome to the world of automated trading! The fact that you are reading this book, suggests that you want to probably build your own bot which hopefully can make you some money whilst you are busy with your day job or like me want to experiment with the technology that goes into building such a bot using Java.
Automated trading has been around for a while, although it has largely been a preserve of big players such as banks and hedge funds.
This has however changed in the last few years. With many retail investors, able to trade on various platforms and exchanges directly, instead of using the services of a traditional broker on the phone, the demand has been growing to automate the task of placing orders, whilst these investors get on with their day jobs. As a first step in automating this process, many platforms such as OANDA, LMAX etc. provide APIs for various programming languages such as Java, Python, C#, PHP etc. so that the mundane tasks of watching the market, looking at charts, doing analysis can be automated.
On this journey, we will focus not only on the concepts of automated trading, but also on writing clean, test driven Java programs.
Towards the end, we would not only have a working trading bot, that would be ready to trade with any strategy but from a technical perspective, we would have also gained an appreciation into the event-driven, multithreaded world of java programming.
Warning:Trading foreign exchange on margin carries a high level of risk, and may not be suitable for all investors. Past performance is not indicative of future results. The high degree of leverage can work against you as well as for you. Before deciding to invest in foreign exchange you should carefully consider your investment objectives, level of experience, and risk appetite. The possibility exists that you could sustain a loss of some or all of your initial investment and therefore you should not invest money that you cannot afford to lose. You should be aware of all the risks associated with foreign exchange trading, and seek advice from an independent financial advisor if you have any doubts.
1.1 What is a Trading Bot?
In very simple language, a trading bot, is a computer program, that can automatically place orders to a market or exchange, without the need for human intervention. The simplest of bots could be a curlPOST to an OANDA REST API, such as
1
$curl
-
X
POST
-
d
"instrument=EUR_USD&units=2&side=sell&type=market"
"https://api-fxtrade.oanda.com/v1/accounts/12345/ord\
2
ers"
which can be setup on a unix cron to run every hour, during trading hours. It has no strategy, nor any external interface or dependencies. It is a one liner to place an order which has an equal probability to be in profit or in loss.
On the other end of the spectrum, it could be a complex program based on a distributed architecture, consuming lots of feeds from various sources, analysing them in realtime and then placing an order. It would be highly available with extremely low latency.
The scale and scope of the bot, as we can see is varied. To be effective, the bot should be able to accomplish the following tasks:
- Consume market data and/or ,external news events, social media feeds and distribute to interested components within the system.
- Have atleast one strategy which provides a trading signal.
- Based on a trading signal place Orders with the brokerage platform.
- Account management, i.e., have the ability to keep track of margin requirements, leverage, PNL, amount remaining etc. in order to curb trading if the amount available breaches a given threshold.
- Position Management i.e. keep track of all currently active positions of various instruments, units of such positions, average price etc.
- Have the ability to handle events which are triggered by the brokerage platform such as ORDER_FILLED, STOP_LOSS etc. and if required take appropriate decisions for such events.
- Some basic monitoring and alerting.
- Some basic risk management. For e.g. loss limitation by using stop losses for orders or making sure that risk is distributed between risky and safe haven instruments. These are just examples and by no means a comprehensive list of fully managing the risk.
1.2 Why do we need a Trading Bot?
I believe most of services provided by exchanges/platforms revolve around the following:
- Market data subscription for instruments of choice and dissemination.
- Place orders and trades.
- Account and position management.
- Historic market data.
- Heartbeating.
- Callbacks for trade, order and account events.
- Authentication
The trading bot is an attempt to generalise these tasks in a framework and provide an ability to provide the broker/exchange platform specific implementation at run time, using a dependency injection framework like Spring. Therefore, theoretically speaking, it would just be a change in the Spring configuration file, where we define our implementations for various interfaces that implement these services, and la voila, we should be able to support various broker/exchange platforms.
1.3 The capabilities of our Trading Bot
Our bot would have the following capabilities which would be discussed in detail, in later chapters:
- Account Management
- Integration with realtime market data feed
- Dissemination of market data
- Place orders
- Handle order/trade and account events
- Analysis of historic prices
- Integration with Twitter
- Strategies
1.4 Design Goals
- One of the key design goals, alluded to in the beginning of this chapter, is to have the ability to change the implementation of a broker/exchange platform at runtime through Spring configuration. This is possible, if we can create specifications for these platform API calls, very similar to the JDBC specification. For e.g. a sample specification/interface defining the position management requirements are
1
/**
2
* A provider of services for instrument positions. A position for an instrument
3
* is by definition aggregated trades for the instrument with an average price
4
* where all trades must all be a LONG or a SHORT. It is a useful service to
5
* project a summary of a given instrument and also if required close all trades
6
* for a given instrument, ideally using a single call.
7
*
8
* The implementation might choose to maintain an internal cache of positions in
9
* order to reduce latency. If this is the case then it must find means to
10
* either 1) hook into the event streaming and refresh the cache based on an
11
* order/trade event or 2) regularly refresh the cache after a given time
12
* period.
13
*
14
* @param