0% found this document useful (0 votes)
248 views34 pages

Tradingbot Sample

Uploaded by

Mauricio Albini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
248 views34 pages

Tradingbot Sample

Uploaded by

Mauricio Albini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Developing a Trading Bot using Java

Shekhar Varshney
This book is for sale at http://leanpub.com/tradingbot

This version was published on 2016-03-06

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.

© 2015 - 2016 Shekhar Varshney


Tweet This Book!
Please help Shekhar Varshney by spreading the word about this book on Twitter!
The suggested tweet for this book is:
Develop your own trading bot in Java
The suggested hashtag for this book is #TRADINGBOTJAVA.
Find out what other people are saying about the book by clicking on this link to search for this
hashtag on Twitter:
https://twitter.com/search?q=#TRADINGBOTJAVA
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.
Contents

1. Introduction to Trading Bot 1


1.1 What is a Trading Bot? 2
1.2 Why do we need a Trading Bot? 3
1.3 The capabilities of our Trading Bot 4
1.4 Design Goals 5
1.5 Code Organisation and Software Stack Used 7
1.6 OANDA REST API as Reference Implementation 9
1.6.1 Opening an OANDA practice account 9
1.6.2 OANDA JSON Keys 15
1.6.3 Constructor Dependencies for OANDA implementations 17
1.7 Event Driven Architecture 19
1.7.1 Google EventBus 20
1.8 Provider Helper interface 23
1.9 TradingConfig class 25
1.10 Obtaining the source code 28
1.11 Try It Yourself section 29
1. 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
Introduction to Trading Bot 2

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
curl¹ POST 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\


2 /12345/orders"

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.

¹https://en.wikipedia.org/wiki/CURL
²https://en.wikipedia.org/wiki/Cron
Introduction to Trading Bot 3

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.
³https://en.wikipedia.org/wiki/Dependency_injection
Introduction to Trading Bot 4

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
Introduction to Trading Bot 5

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 <M>
15 * The type of instrumentId in class TradeableInstrument
16 * @param <N>
17 * the type of accountId
18 *
19 * @see TradeableInstrument
20 */
21 public interface PositionManagementProvider<M, N> {
22
23 /**
24 *
25 * @param accountId
26 * @param instrument
27 * @return Position<M> for a given instrument and accountId(may be null if
28 * all trades under a single account).
29 */
30 Position<M> getPositionForInstrument(N accountId, TradeableInstrument<M> instrument);
31
32 /**
33 *
34 * @param accountId
35 * @return Collection of Position<M> objects for a given accountId.
36 */
37 Collection<Position<M>> getPositionsForAccount(N accountId);
38
39 /**
40 * close the position for a given instrument and accountId. This is one shot
41 * way to close all trades for a given instrument in an account.
42 *
43 * @param accountId
44 * @param instrument
Introduction to Trading Bot 6

45 * @return if the operation was successful


46 */
47 boolean closePosition(N accountId, TradeableInstrument<M> instrument);
48
49 }

If we create such specifications/interfaces for each aspect of the platform interaction, we can in
theory create providers for these services and swap them as when required, through the Spring
configuration. From code organisation perspective, all these interfaces, therefore would go in a
project, that form part of the core api. This project would therefore be broker/exchange provider
agnostic and would comprise such interfaces and services.

• Write services that solve a single business problem or a collection of related problems. These
services lend themselves to easy unit testability and code reuse that eventually leads to better
software quality.
• Loosely couple services. This enables reducing system dependencies and as a result results
in more maintainable software. Our software would be continuously evolving as one might
decide to integrate more social media feeds or add more complex strategies. Writing loosley
coupled components ensures that we have little knock on effect on already working code.
• High unit test coverage. It is extremely important that we aim to have a high unit test
coverage. When used in a production environment where real money could be involved, a
large unit tests coverage will ensure that we catch regressions and bugs early on and prevent
the manifestation of bugs as much as possible in the production environment.
Introduction to Trading Bot 7

1.5 Code Organisation and Software Stack Used


Following on from our discussion of design goals in the previous sections, the code will be organised
in atleast 3 different projects ,i.e., atleast 3 jar files will be produced from the build. Why are we
saying atleast 3? Remember from our earlier discussion, that one of the key design goals is to be
able to switch provider implementation at runtime. Since we could have more than 1 provider from
which we can decide, there will be atleast 3 jar files. We are going to discuss only 1 implementation
in the book,i.e., the OANDA REST API implementation. Developers who would use the framework,
are encouraged to develop more provider implementations.

• trading-core is the core of the project. It comprises all the specifications/interfaces that must
be implemented. It also comprises all the generic services which make use of the core interfaces
and provide additional useful API methods.
• oanda-restapi is our reference implementation for the specification and will be discussed in
the book. You are more than welcome to swap this over with your own.
• tradingbot-app is the main application that uses Spring to inject the provider api at runtime.
It is also the project where we define our strategies and can implement app specific stuff.
Later in the book, we are going to talk about integration with social media, especially Twitter,
which we would implement in this project.
Introduction to Trading Bot 8

Java Projects

To build our bot we are going to use the following set of software and tools

• Java SDK 1.7+


• Spring Framework 4.1, Spring Social 1.1 (Dependency in tradingbot-app project only)
• Guava 18.0
• HttpClient 4.3
• Maven 3.2.5
• Eclipse IDE
Introduction to Trading Bot 9

1.6 OANDA REST API as Reference Implementation


Declaration- I have no current or past commercial relationship with OANDA and I have chosen
OANDA REST API as a reference implementation simply on it’s technical merit and the fact that it
is likely to have wider adoption as it is free to use. If there is something similar around, I would be
happy to give it a try as well.
I encountered the OANDA API by chance. At the time, I was looking for a broker who was offering
free API for trading (just in case i wanted to convert to a production account) and more importantly
supported the Java programming language. It was very easy to get started, as most of the examples
used curl to demonstrate various trading actions like getting a list of instruments, place an order
or get historical candle sticks data. I could just type the curl commands on my mac terminal and
fire away. I could easily see the json response received with each curl request fired. By seeing the
responses and data in realtime, I got a really good idea and appreciation of various APIs supporting
instruments, orders, rates, positions etc.
The curl command examples was a good starting point and I started to experiment writing equivalent
commands as test cases in Java described on the REST API⁴ page.

1.6.1 Opening an OANDA practice account


Before you can start using the API, you must signup for a free practice⁵ account. When you headup
there and click on open an account button, you will see a signup screen like below
⁴http://developer.oanda.com/rest-live/introduction/
⁵http://fxtrade.oanda.com
Introduction to Trading Bot 10

Oanda Account Signup

Once you have successfully signed up, you are now ready to sign into you practice account. You will
see the login screen below when you are ready to login.
Introduction to Trading Bot 11

Oanda Account Login

After a successful sign on, you would be taken to the account homepage which looks like the screen
below
Introduction to Trading Bot 12

Oanda Account Dashboard

In order to commence api trading, we need to first generate a personal API token, which will be
used by the OANDA platform to authenticate the request. You need to click on the link Manage API
Access, highlighted by a red arrow in the screen above. You will next be taken to the screen below
Introduction to Trading Bot 13

Oanda Generate API Token

When you click generate, the platform will generate a token with you, which must be included in
every request you make to the platform which hosts your practice account. The token generated will
be presented and you must take note of it.
Introduction to Trading Bot 14

Oanda Generated Token

Now you are ready to trade. OANDA provides a very useful web interface⁶ to test your REST requests
and see the responses in situ. You can also get a feeling of how the REST resource urls are organised
and which resource url to invoke, for fulfilling a given request.
The screen below demonstrates how we make a request to get a list of all instruments which can be
traded. The GET request requires an accountId to be passed in (this is the id that you can find on the
account page and for a practice account, comes loaded with 100,000 units of the account currency).
It is imperative to provide the header as well and can be specified as Bearer <Your API Token goes
here>
⁶http://developer.oanda.com/rest-live/console/??utm_source=oandaapi&utm_medium=link&utm_campaign=accesstoken_email
Introduction to Trading Bot 15

Oanda Dev API Console

Oanda Dev API Console-Headers Tab

1.6.2 OANDA JSON Keys


The OANDA json responses use a set of standard keys. For e.g. to denote a currency pair in a
response, the key instrument is used, whether it’s a streaming response for tick or candle stick
information. A tick in the live stream would look like

1 {"tick":{"instrument":"AUD_CAD","time":"1401919217201682","bid":1.01484,"ask":1.01502}}

whilst the response, when a trade is successfully modified would like


Introduction to Trading Bot 16

1 {
2 "id": 1800805337,
3 "units": 3000,
4 "side": "sell",
5 "instrument": "CHF_JPY",
6 "time": "2015-03-18T06:33:36.000000Z",
7 "price": 120.521,
8 "takeProfit": 110,
9 "stopLoss": 150,
10 "trailingStop": 0,
11 "trailingAmount": 0
12 }

From the 2 examples above, we can also see the key used for event date is time. Since the same keys
are used to denote a given attribute, we can create public static final String variables for
these keys. So therefore the concept of the class OandaJsonKeys was born. Instead of polluting the
code with lines below in many classes

1 String instrument = (String) instrumentJson.get("instrument");

it is much better practice to create a constant and use that instead. The same code snippet would
look like:

1 String instrument = (String) instrumentJson.get(OandaJsonKeys.instrument);

There are a lot of keys, but most of the keys that we use in our trading bot are captured in the
OandaJsonKeys class.

1 public class OandaJsonKeys {


2
3 private OandaJsonKeys() {
4 }
5
6 public static final String accounts = "accounts";
7 public static final String accountId = "accountId";
8 public static final String accountCurrency = "accountCurrency";
9 public static final String marginRate = "marginRate";
10 public static final String marginUsed = "marginUsed";
11 public static final String marginAvail = "marginAvail";
12 public static final String balance = "balance";
13 public static final String unrealizedPl = "unrealizedPl";
14 public static final String realizedPl = "realizedPl";
15 public static final String openTrades = "openTrades";
16 public static final String instruments = "instruments";
17 public static final String instrument = "instrument";
18 public static final String interestRate = "interestRate";
19 public static final String disconnect = "disconnect";
20 public static final String pip = "pip";
21 public static final String bid = "bid";
22 public static final String ask = "ask";
Introduction to Trading Bot 17

23 public static final String heartbeat = "heartbeat";


24 public static final String candles = "candles";
25 public static final String openMid = "openMid";
26 public static final String highMid = "highMid";
27 public static final String lowMid = "lowMid";
28 public static final String closeMid = "closeMid";
29 public static final String time = "time";
30 public static final String tick = "tick";
31 public static final String prices = "prices";
32 public static final String trades = "trades";
33 public static final String tradeId = "tradeId";
34 public static final String price = "price";
35 public static final String avgPrice = "avgPrice";
36 public static final String id = "id";
37 public static final String stopLoss = "stopLoss";
38 public static final String takeProfit = "takeProfit";
39 public static final String units = "units";
40 public static final String side = "side";
41 public static final String type = "type";
42 public static final String orders = "orders";
43 public static final String orderId = "orderId";
44 public static final String positions = "positions";
45 public static final String expiry = "expiry";
46 public static final String tradeOpened = "tradeOpened";
47 public static final String orderOpened = "orderOpened";
48 public static final String transaction = "transaction";
49 public static final String pl = "pl";
50 public static final String interest = "interest";
51 public static final String accountBalance = "accountBalance";
52 }

In all our OANDA API implementations, which will be discussed in the subsequent chapters, we
would be directly using this class and statically importing constants instead of hardcoding the string
literals for a given json key.

1.6.3 Constructor Dependencies for OANDA implementations


All OANDA implementations of the core api specifications have constructors which accept

• API url
• username
• access token

As we know, OANDA has different environments where we can run our bot, such as sandpit, practice
and live. These environments have different urls, access tokens and can have different usernames for
the same individual. These external configuration properties are passed in as constructor parameters
for various OANDA implementations. For e.g.
Introduction to Trading Bot 18

1 public OandaAccountDataProviderService(final String url, final String userName, final String accessToken) {
2 this.url = url;
3 this.userName = userName;
4 this.authHeader = OandaUtils.createAuthHeader(accessToken);
5 }

The parameters are passed to this implementation in the Spring configuration as seen below

1 <bean id="accountDataProvider" class="com.precioustech.fxtrading.oanda.restapi.account.OandaAccountDataProvide\


2 rService">
3 <constructor-arg index="0" value="${oanda.url}"/>
4 <constructor-arg index="1" value="${oanda.userName}"/>
5 <constructor-arg index="2" value="${oanda.accessToken}"/>
6 </bean>

Since these variables are provided in a property file, we can easily change them at runtime, without
having to do a new build or change code. It would be sufficient to just change the property file. We
would cover this topic in more detail in later chapters when we talk about configuration in detail.
Introduction to Trading Bot 19

1.7 Event Driven Architecture


The soul of any trading system, is it’s event driven architecture. The system must react to market
events, social media events, user events and maybe a plethora of other events coming from
external/internal sources. These events could further trigger a chain reaction of events, resulting
in state changes of various business/domain objects in the system. The real technical challenge is to
make sure that these state transitions happen in a thread safe way, backed by a transaction wherever
required.
At the heart of an event driven system are one or more event loops. These event loops typically run
in an infinite while loop and waiting on an event to come from a queue or a live stream. For an
Oanda market data tick event we have a event loop as following

1 this.streamThread = new Thread(new Runnable() {


2
3 @Override
4 public void run() {
5 CloseableHttpClient httpClient = getHttpClient();
6 try {
7 BufferedReader br = setUpStreamIfPossible(httpClient);
8 if (br != null) {
9 String line;
10 while ((line = br.readLine()) != null && serviceUp) {
11 Object obj = JSONValue.parse(line);
12 JSONObject instrumentTick = (JSONObject) obj;
13 ...
14 ...

In the code snippet above we have an infinite while loop that listens on new ticks being pushed on
to the live stream by the OANDA platform. When a tick json payload is received, it is parsed and
further disseminated via a queue or an event bus.

Typical Event Chain

The diagram depicts a typical chain of events, that might be triggered by a single event.
Introduction to Trading Bot 20

1. Tick event is received from the stream.


2. Event is parsed and sent to the EventBus.
3. The strategy component has a subscription for this event and gets a callback from the
EventBus.
4. The strategy component decides to generate a trading signal based on the latest tick data event
and places the signal on an OrderQueue.
5. The OrderExecutionService picks up this signal, creates a new order payload and posts it to
the platform.
6. The platform executes the order and sends an event down the order event loop.
7. This event can further trigger an update of say the trades cache.

This basically is the essence of an event driven architecture. Since we could have many components at
play at the same time, it is extremely important that we decouple components as much as possible, so
that new publishers and subscribers can be added with zero or minimal changes. This architecture
lends itself to take advantage of Java multithreaded programming capabilities. However, by the
same token, it dictates the developer to exercise great caution when performing state changes of
business objects present in caches, for e.g. the trades cache in our example. We must put adequate
synchronization and locking in place to make sure that the observed state of a shared object is always
consistent.

1.7.1 Google EventBus


Google EventBus⁷, which is part of the guava library, is an excellent broker to facilitate loose
coupling of our services and to allow publish-subscribe style communication between them. The
coolest feature about it, is the ability to add subscribers just by adding an annotation without having
the explicit need of knowing who the publisher is.
Lots of useful information is found on the wiki page of the EventBus but it would be worth discussing
how it is used in the trading bot ecosystem. Lets take the use case of disseminating market data event,
to one or multiple subscribers. Assuming a singleton EventBus has been created by the Spring DI
container,

• Register Subscribers automatically: Here we write a BeanBostProcessor to automatically


find beans which have methods annotated by @Subscribe annotation and call the event-
Bus.register method to register the subscribers.

⁷https://code.google.com/p/guava-libraries/wiki/EventBusExplained
Introduction to Trading Bot 21

1 public class FindEventBusSubscribers implements BeanPostProcessor {


2
3 @Autowired
4 private EventBus eventBus;
5 private static final Logger LOG = Logger.getLogger(FindEventBusSubscribers.class);
6
7 @Override
8 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
9 Method[] beanMethods = bean.getClass().getMethods();
10 for (Method beanMethod: beanMethods) {
11 if (beanMethod.isAnnotationPresent(Subscribe.class)) {
12 eventBus.register(bean);
13 LOG.info(
14 String.format("Found event bus subscriber class %s. Subscriber method name=%s",
15 bean.getClass().getSimpleName(), beanMethod.getName()));
16 break;
17 }
18 }
19 return bean;
20 }
21
22 @Override
23 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
24 return bean;
25 }
26
27 }

• Create Publisher: It is sufficient to just call the post(Object payload) to post it to the
EventBus.

1 public MarketEventHandlerImpl(EventBus eventBus) {


2 this.eventBus = eventBus;
3 }
4 public void onMarketEvent(TradeableInstrument < T > instrument, double bid, double ask, DateTime eventDate) {
5 MarketDataPayLoad < T > payload = new MarketDataPayLoad < T > (instrument, bid, ask, eventDate);
6 eventBus.post(payload);
7 }

• Consume Payload: The EventBus finds the appropriate subscriber by matching the method
signature based on the input type passed into the method and ofcourse annotated by the
@Subscribe annotation. This method must have one and only one input parameter. There is
a choice to go as fine grained or coarse grained as possible. In the case of coarse grained
subscription, we have the input parameter as an object which is the super class of all
known payloads in the system. The worst case being the payload java.lang.Object, in
which case the subscription is the most coarse grained. This method will be called for every
eventBus.post performed in the system. On the other hand, using individual subtypes
as input parameters to methods, make it extremely fine grained. In the example below
handleMarketDataEvent will only be called by the EventBus if the payload is of the type
MarketDataPayLoad or any of it’s subtypes.
Introduction to Trading Bot 22

1 @Subscribe
2 @AllowConcurrentEvents
3 public void handleMarketDataEvent(MarketDataPayLoad<T> marketDataPayLoad) {
4 if (instrumentRecentPricesCache.containsKey(marketDataPayLoad.getInstrument())) {
5 instrumentRecentPricesCache.get(
6 marketDataPayLoad.getInstrument())
7 .put(marketDataPayLoad.getEventDate(),marketDataPayLoad);
8 }
9 }
Introduction to Trading Bot 23

1.8 Provider Helper interface


Often different platform providers have different notations for denoting a currency pair. Cable can
be denoted in the variety of following ways

• GBP_USD
• GBPUSD
• GBP/USD
• GBP-USD

Similarly the act of buying a currency pair could be denoted by

• buy
• long
• +1 (or any other positive number)
• Platform specific enum, for e.g. TRADEACTION.BUY

In order to deal with such variances in notation provided by different providers, we need to create
an interface that provides methods to address these differences. It looks like

1 /**
2 *
3 * @param <T>
4 * The type of Long/Short notation
5 */
6 public interface ProviderHelper < T > {
7
8 /**
9 *
10 * @param instrument
11 * in ISO currency standard, such as GBPUSD
12 * @return currency pair denoted in the platform specific format
13 */
14 String fromIsoFormat(String instrument);
15
16 /**
17 *
18 * @param instrument
19 * in platform specific format such as GBP_USD
20 * @return currency pair denoted in ISO format
21 */
22 String toIsoFormat(String instrument);
23
24 /**
25 *
26 * @param instrument
27 * in a 7 character format, separated by an arbitrary separator
Introduction to Trading Bot 24

28 * character like -,/,_


29 * @return currency pair denoted in the platform specific format
30 */
31 String fromPairSeparatorFormat(String instrument);
32
33 /**
34 *
35 * @param instrument
36 * denoted as a hashtag, for e.g. #GBPUSD
37 * @return currency pair denoted in the platform specific format
38 */
39 String fromHashTagCurrency(String instrument);
40
41 /**
42 *
43 * @return T that denotes the action of Buying the currency pair on the
44 * platform
45 */
46 T getLongNotation();
47
48 /**
49 *
50 * @return T that denotes the action of Selling the currency pair on the
51 * platform
52 */
53 T getShortNotation();
54 }

The need for this interface was felt, when I was consuming data from external sources like Twitter
and sites which publish economic events. Various Twitter users and external sites had their own way
of denoting currency pairs and long/short trades. In order to deal with this plethora of conventions,
the need for such interface was strongly felt. I am pretty sure that there would be many more, which
need to be interpreted in the platform specific ways and should therefore be added to this interface.
Introduction to Trading Bot 25

1.9 TradingConfig class


The class TradingConfig holds all the parameters that are configured at runtime. These parameters
are required by various core apis. Some examples include

• Maximum value of an order to be placed.


• Maximum allowed contracts for a currency.

As different users may have different runtime values, these values form part of the external
configuration. These need to be configured in the Spring configuration (we will discuss it in detail
when we talk about Configuration and Deployment). It is strongly recommended to configure as
much as possible instead of hardcoding them inside various services.
Lets check out how the code looks like

1 public class TradingConfig extends BaseTradingConfig {


2
3 private String mailTo;
4 private int fadeTheMoveJumpReqdToTrade;
5 private int fadeTheMoveDistanceToTrade;
6 private int fadeTheMovePipsDesired;
7 private int fadeTheMovePriceExpiry;
8
9 public int getFadeTheMovePriceExpiry() {
10 return fadeTheMovePriceExpiry;
11 }
12
13 public void setFadeTheMovePriceExpiry(int fadeTheMovePriceExpiry) {
14 this.fadeTheMovePriceExpiry = fadeTheMovePriceExpiry;
15 }
16
17 public String getMailTo() {
18 return mailTo;
19 }
20
21 public void setMailTo(String mailTo) {
22 this.mailTo = mailTo;
23 }
24
25 public int getFadeTheMoveJumpReqdToTrade() {
26 return fadeTheMoveJumpReqdToTrade;
27 }
28
29 public void setFadeTheMoveJumpReqdToTrade(int fadeTheMoveJumpReqdToTrade) {
30 this.fadeTheMoveJumpReqdToTrade = fadeTheMoveJumpReqdToTrade;
31 }
32
33 public int getFadeTheMoveDistanceToTrade() {
34 return fadeTheMoveDistanceToTrade;
35 }
36
Introduction to Trading Bot 26

37 public void setFadeTheMoveDistanceToTrade(int fadeTheMoveDistanceToTrade) {


38 this.fadeTheMoveDistanceToTrade = fadeTheMoveDistanceToTrade;
39 }
40
41 public int getFadeTheMovePipsDesired() {
42 return fadeTheMovePipsDesired;
43 }
44
45 public void setFadeTheMovePipsDesired(int fadeTheMovePipsDesired) {
46 this.fadeTheMovePipsDesired = fadeTheMovePipsDesired;
47 }
48
49 }
50
51 public class BaseTradingConfig {
52 private double minReserveRatio;
53 private double minAmountRequired;
54
55 private int maxAllowedQuantity;
56 private int maxAllowedNetContracts;
57 private double max10yrWmaOffset;
58
59 public double getMinAmountRequired() {
60 return minAmountRequired;
61 }
62
63 public void setMinAmountRequired(double minAmountRequired) {
64 this.minAmountRequired = minAmountRequired;
65 }
66
67 public double getMax10yrWmaOffset() {
68 return max10yrWmaOffset;
69 }
70
71 public void setMax10yrWmaOffset(double max10yrWmaOffset) {
72 this.max10yrWmaOffset = max10yrWmaOffset;
73 }
74
75 public int getMaxAllowedNetContracts() {
76 return maxAllowedNetContracts;
77 }
78
79 public void setMaxAllowedNetContracts(int maxAllowedNetContracts) {
80 this.maxAllowedNetContracts = maxAllowedNetContracts;
81 }
82
83 public double getMinReserveRatio() {
84 return minReserveRatio;
85 }
86
87 public void setMinReserveRatio(double minReserveRatio) {
88 this.minReserveRatio = minReserveRatio;
89 }
90
91 public int getMaxAllowedQuantity() {
92 return maxAllowedQuantity;
Introduction to Trading Bot 27

93 }

Some of these member variables here may not make sense now but all will fall into place in later
chapters.
Introduction to Trading Bot 28

1.10 Obtaining the source code


All source code can be obtained at github. The following git command will clone the repository
locally on your machine

1 git clone https://github.com/shekharvarshney/book-code.git

We will discuss how this code can be built and run locally in later chapters.
Introduction to Trading Bot 29

1.11 Try It Yourself section


At the end of each chapter, we will include a small program/programs (wherever appropriate) that
demonstrates the concepts discussed in the chapter and for you to experiment and see the concepts
in action straightaway. These small standalone programs are for demonstration purpose only and
may not be part of the code that runs the bot eventually. This is to get a flavour of things that make
up a component of the bot.
We will run these programs inside the eclipse IDE so that if need be one can debug and see what is
happening inside the services used in the bot. These programs reside in a separate project tradingbot-
demo-programs, whose pom.xml file looks like the following

1 <project xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <modelVersion>4.0.0</modelVersion>
6 <groupId>com.precioustech</groupId>
7 <artifactId>tradingbot-demo-programs</artifactId>
8 <version>1.0</version>
9 <properties>
10 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
11 <spring.framework.version>4.1.1.RELEASE</spring.framework.version>
12 <spring.framework.social.version>1.1.0.RELEASE</spring.framework.social.version>
13 </properties>
14 <dependencies>
15 <dependency>
16 <groupId>com.precioustech</groupId>
17 <artifactId>tradingbot-core</artifactId>
18 <version>1.0</version>
19 </dependency>
20 <dependency>
21 <groupId>com.precioustech.fxtrading</groupId>
22 <artifactId>tradingbot-app</artifactId>
23 <version>1.0</version>
24 </dependency>
25 <dependency>
26 <groupId>com.precioustech</groupId>
27 <artifactId>oanda-restapi</artifactId>
28 <version>1.0</version>
29 </dependency>
30
31 </dependencies>
32 </project>

This demo project has a very simple dependency requirement on the 3 projects which comprise the
bot.

You might also like