You are on page 1of 20

A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21,

1, 8:37 PM

012);6L5)!)9355)K5KM53N18>O)PB13-5P)>59B)B;-P)K18B;Q)?-D8)27)913)&5<-2K)68<)D5B)68)5RB36)185

!"#$"%&&'($)*+*#"'%,

!"#$%&'()'#$%&"*+,-%"./
(+,0-,12"3".43-,12"(/$"51"!1)
64/24377,12"8312+32%
!-./)0123)456718)19):;1-.5)68<)'=>>)?;1@)012)A1@)B1)C-D;B

06//1)&6E23- C1>>1@
%2D)FG)HIHI)·)FJ)K-8)356<

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 1 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

*%'+,%&'-.!/!0-+!1%2&)(3
43%5
*;5)#99-.-6>)T12386>)S>1D

C1>>1@

UQFV FW

!;1B1)MO)&Q)SQ)&Q

!"#$%&'()'!*%'+
I am not quali,ed to o/er investment, legal, or any other advice, nor am I
trying to do so. This is a programming tutorial aimed at teaching you how
to build a trading bot for learning purposes. Any decisions, investments, or
risks you take as a result of building a trading bot are your responsibility.

I cannot be held responsible for any decisions you make as a result of


reading this tutorial. Remember: Bots can lose a lot of money, so you should
be careful.

Quite regularly, we all come across some variation of this article: “10
https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 2 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

Quite regularly, we all come across some variation of this article: “10
Projects You Should Build as a Programmer”.

And most times that list includes a Trading Bot.

So, since I think trading bots are great projects, I thought I’d take some time
to teach you how to build one.

However, rather than giving you all the code line by line, I decided it would
be best to go through all the concepts you should be familiar with to take on
this project.

After all, the whole point is that you code it yourself.

Hence, this article will go through everything you need to know and have to
build a trading bot (from the exchange to a simple trading strategy), as well
as the basic architecture, concepts, and design of a simple bot.

And the great thing is: I’ll be using pseudocode, so you can follow this
tutorial in the language of your choice.

As such, you can feel comfortable and focus on the actual programming,
rather than ,guring out all the setup for yourself.

So let’s go!

6'+$!78!9:;<!(!=+($%)
The ,rst step in this tutorial is just selecting a language to use. This is
entirely up to you.

Some languages like Python could be helpful if you want to later expand
your bot to use Machine Learning, for example, but the main goal here is
that you pick a language you’re comfortable with.

Want to read this story later? Save it in Journal.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 3 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

6'+$!>8!9:;<!(!4(''3+5&%2)?

!;1B1)MO)%2PB-8)X-PB5>

An often overlooked step in trading bot tutorials is the selection of the


exchange.

For a trading bot to work, you need to have access to an exchange where
you can trade assets. This is just as important as knowing how to program.

So, for this step, you need to decide what assets you will be trading (e.g.
stocks, currencies, cryptocurrencies), and where you will be trading.

Regarding the asset, I would strongly suggest cryptocurrencies. The reason


for this is not that I’m a blockchain/crypto advocate (full disclosure), but
simply because cryptocurrency markets operate 24/7 i.e. all day, every day. *17);-D;>-D;B

Most “traditional” assets can only be traded during certain times, and often
only on weekdays. Stock markets, for instance, are generally open sometime
between 9AM-4PM and do not operate on weekends. FOREX (foreign

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 4 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

currency exchange) markets can go on for 24h, but are also usually closed
during the weekend.

As such, it is easier and nicer to have your bot running 24/7, which is what
crypto markets allow for. Additionally, cryptocurrencies are known to be
very volatile, which means that a) you can lose a lot of money, but b) they
are a great way to learn and test trading strategies.

Since we’ve covered the asset class, let’s now go over the two requirements
for picking an exchange for your trading bot.

1. You must be legally allowed to trade on the exchange and the assets it
o/ers. Some countries don’t allow cryptocurrency trading, for instance.

2. The exchange must have a Public API available. One cannot build a bot
without an endpoint to send requests to.

With the two requirements above ful,lled, you may also wish to consider
things like the fees charged by the exchange, if it is well-rated or well-
known, and how good the API docs are.

Last but not least, I would also recommend checking the daily volume of
trades on the exchange. Exchanges with very low volumes tend to lag
behind in price movements, as well as make it harder for limit orders to be
,lled (more on this terminology later).

If you decide to go with cryptocurrencies as your asset class, here’s a useful


list of the top exchanges, their volumes, and various other important pieces
of information to help you choose.

6'+$!@8!9:;<!(!4(A+

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 5 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

!;1B1)MO)A633-P18)S316<M58B

If the exchange is the battleground, you need a place to ship your troops
from. And I need to stop with this stupid analogy.

What I’m talking about is a server. You need a server to send requests to the
exchange’s API.

For testing purposes, you can obviously run the server from your own
computer. However, if you want your bot to be operating constantly, your
computer is de,nitely not a good choice.

Hence, I have two suggestions:

1. Use a Raspberry Pi as a server (Cooler)

2. Use a Cloud Provider (Better)

I think running a bot from your Pi is a pretty cool idea, so you should try it if
it also sounds nice to you.

However, most people will probably resort to a cloud hosting service like
AWS, Azure, GCS, or Digital Ocean.

Most large cloud service providers o/er a good free tier, so you might even
be able to host your bot for free.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 6 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

Regarding servers, I’ll just leave it at that. You should pick whatever suits
you best, and, for a small project like this, the choice shouldn’t make much
of a di/erence.

6'+$!B8!42:3?:)5!'-+!4%'C

!;1B1)MO),58-8)YPB36<6

Now we’re getting to the fun part. Ensure that before you come to this step
you have:

1. Registered and been approved to use an exchange

2. Enabled API usage on the exchange and have an API key

3. Decided how you will be hosting your bot

Got that? Alright, let’s move on.

0-+!6:#$3+A'!%D!4%'A
My goal here is to get you from zero to bot in a simple and concise way. As

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 7 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

such, I’ll be teaching you how to build a simple trading bot, which you can
then expand and improve to suit your needs.

This bot will have a few constraints:

1. The bot will only ever be in one of two states: BUY or SELL. It will not
place various buy or sell orders consecutively at multiple price points. If
its last operation was a sale, it will try to buy next.

2. It will use ,xed thresholds for buying and selling. A smarter bot might be
able to tinker with the thresholds based on various indicators, but our
bot will have its strategy and thresholds set manually.

3. It will only trade one currency pair e.g. BTC/USD.

The constraints come with bene,ts, however. Keeping it simple makes the
bot easier to create and maintain, as well as allows us to deploy this very
quickly.

KISS.

E+;:A:%)/F(<:)5!G3%,
Here’s a simple diagram providing an overview of how our bot will operate:

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 8 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

'K6D5)MO)%2B;13

From here, we can start to determine what our architecture will look like.

First, we need a variable to indicate the state the Bot is currently in. This is
either BUY or SELL. A boolean or enum should ,t this purpose well.

Then we need to set our thresholds for buying and selling. These indicate
the percentage decrease or increase in price since we last made an
operation.

For example, if I bought the asset at 100$, and its price is now at 102$, we
have a 2% increase. If we have a SELL threshold set to a 1% increase, our
bot will then sell, because it has made a pro,t above our threshold.

In our case, these thresholds will be constants. We need 4 of them, two for
each state:

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 9 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

BUY Thresholds (If the Bot is in SELL State)

DIP_THRESHOLD : Buys the asset if its price decreased by more than the
threshold. The idea of this is to follow the “buy low, sell high” strategy,
where you attempt to buy an asset when it is undervalued, expecting its
value to rise so you can sell.

UPWARD_TREND_THRESHOLD : Buys the asset if its price increased by more


than the threshold. This goes against the “buy low, sell high” philosophy,
but aims to identify when the price is going up and we don’t want to
miss an opportunity to buy before it goes even higher.

Here’s an illustration that might help:

'K6D5)SO)%2B;13

If we performed a SELL operation at the point marked “SELL” in the picture


above, we now have our thresholds set for the buy operation.

If the price ever goes below the bottom green line or above the top green
line we will perform a BUY operation. In this case, we surpassed the upper
threshold ,rst, so we bought based on the BUY_DIP_THRESHOLD .

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 10 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

SELL Thresholds (If the Bot is in BUY State)

PROFIT_THRESHOLD : Sells the asset if its price has increased above the
threshold since we bought it. This is how we pro,t. We sell at a higher
price than we bought.

STOP_LOSS_THRESHOLD : Ideally, we would only want our bot to sell when


it makes a pro,t. However, maybe the market is just going down
signi,cantly and we want to get out before it’s too late and then buy at a
lower price. Therefore, this threshold is used to sell at a loss, but with
the goal of stopping a bigger loss from happening.

Here’s an illustration:

'K6D5)SO)%2B;13

Here, we bought at the point marked with “BUY”. Then, we met our upper
threshold before the lower one, meaning we sold our asset for a pro,t. This
is how trading bots make money.

Now we already have a basic idea of how the bot works, so let’s get into
some (pseudo)code.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 11 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

H9"!I+3$+&!G2);':%)A
The ,rst thing our bot needs are some helper functions to get data from the
exchange’s API. We need:

The above should be self-explanatory, but you need to make sure you are
aware of what currencies the API POST requests ask for when doing a buy or

sell operation.

Often times, when you are trading USD for Gold, for example, you can
specify either how much Gold to buy, or how much USD to sell. Getting the
currencies right is very important.

4%'!J%%$!K.;3+
Now that we have our helper functions, let’s start to de,ne the workkow of
the bot. The ,rst thing we need is an in,nite loop with some sleep time.
Let’s say we want the bot to try to make an operation every 30 seconds.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 12 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

Here’s what that might look like:

Then, let’s set the variables and constants we talked about, as well as the
decision-making kow. API helper functions aside, our code would end up
something like this:

Note: The values for the thresholds here are just arbitrary values. You should
pick your own according to your own strategy.

If the above is paired up with the helper functions and the loop function,
which could also be main , we should now have ourselves the basic pillars of

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 13 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

a working bot.

At every iteration, our bot will check its current state (BUY or SELL) and
attempt to make a trade based on the thresholds hardcoded in. It will then
update the BUY/SELL state and the last price for an operation.

Then it does it all over again.

6'+$!L8!9%3:A-:)5!'-+!4%'

!;1B1)MO)&6BB;5@)X1./53O

The basic architecture of our bot is ready, but there’s probably a few things
we may still want to consider adding.

J%5A
When I ,rst built a variation of this bot, one thing that was essential for me
was having constant logging of the bot’s actions both to the terminal as well
as to a separate log ,le.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 14 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

At every step, I would create logs like:

[BALANCE] USD Balance = 22.15$


[BUY] Bought 0.002 BTC for 22.15 USD
[PRICE] Last Operation Price updated to 11,171.40 (BTC/USD)
[ERROR] Could not perform SELL operation - Insufficient balance

The logs that went to the ,le would also get a timestamp added to them, so
when I accessed the server after a whole day and found an error, for
example, I could trace it back exactly to where it happened, as well as ,nd
out everything else the bot did along the way.

This should be a matter of setting up a createLog function that is called at


every step. Something like this:

"?+)':D.:)5!0&+)?A
The main goal of our bot should be to buy at a low price and sell at a pro,t.
However, we have two thresholds that kind of contradict this
idea: UPWARD_TREND_THRESHOLD and STOP_LOSS_THRESHOLD .

These thresholds supposedly tell us when we should sell at a loss or buy at a


price increase. The idea is that we try to identify trends that fall outside of
the general strategy but may be harmful or bene,cial to us so we should act.

However, the way I structured it above is quite limited. A static snapshot of


a price is far from an indication of a trend.

Luckily, without much hassle, you can make this a little more reliable.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 15 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

All you need to do is also keep track of more prices than just lastOpPrice .
You could, for instance, keep track of price 10 or 20 iterations ago, and
compare that with the current price instead of lastOpPrice . This would
probably be better at identifying a trend because it checks for rapid shifts in
price rather than a shift that occurred over a long period of time.

E('(M(A+N
While it is running, this simple bot doesn’t actually need a database, since it
is handling very little data and can keep all the information in memory.

However, what happens when the bot fails, for example? How could it
determine the lastOpPrice without you checking it manually?

To prevent manual work on your end, you might want to keep some sort of
lightweight database to keep track of a few things, like lastOpPrice .

This way, when the bot starts up, rather than using the default values, it
will actually check its stored values and continue from there.

Depending on how simple you want to make this, you can even consider a
“database” of .txt or json ,les, since you might just be storing a few
values anyway.

E(A-M%(&?

If you want to facilitate the


visualization of your bot’s
operations, as well as manage it
without having to go in and
manually tinker with the code,
you may want to consider
connecting your bot to a
dashboard.

This would require that your bot

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 16 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

be connected to a web
!;1B1)MO),2/5):;5PP53
server/API of its own that
allows you to control its
functionality.

This way, you could change thresholds more easily, for example.

There are many free dashboard templates available so you don’t even have
to make your own. Check out Start Bootstrap and Creative Tim for some
examples.

0+A':)5!6'&('+5:+A!%)!9(A'!E('(
Many exchanges will o/er you access to past price data, as well as you can
usually easily get that data elsewhere if you need to.

This is very useful if you want to test your strategy before putting it to
action. You can run a simulation of your bot with past data and “fake
money” to see how well your de,ned thresholds would have worked and
adjust them for the real deal.

H??:':%)(3!9%:)'A!%)!0-&+A-%3?A!()?!O&?+&A
There are a few things you need to watch out for when placing orders.

First, you should understand that there are two types of orders: limit
orders and market orders. You should really read a little into this if you’re
not familiar with the concepts, but I’ll give you a basic overview here.

Market orders are orders that execute at the current market price,
e/ectively executing immediately in most cases.

Limit orders, on the other hand, happen when you place an order for a price
lower than market price (in the case of a BUY order) or higher than market
price (in the case of a SELL order). These are not guaranteed to execute,
since the price might not reach the threshold you set.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 17 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

The bene,t of limit orders is that you can anticipate market movements and
place an order regarding where you expect the market to go before such
movement happens.

In addition, limit orders are usually subject to lower fees than market
orders. This is because market orders are subject to what is commonly
called a “taker fee” whereas limit orders are subject to “maker fees”.

The reason for the names and their respective fees is that market orders are
just accepting (“taking”) the current market price, whereas limit orders
outside the market price are adding liquidity and hence “making a market”,
for which they are “rewarded” with lower fees.

Note that the bot in this article is best suited for market orders.

Lastly, on the topic of fees, when setting your PROFIT_THRESHOLD , remember


to take fees into consideration.

In order to make a pro,t, you need to perform a BUY and then a SELL
operation, which leaves you subject to 2 fees.

As such, you need to make sure that you only sell for a pro,t once you’re
able to at least cover your fees, otherwise you will actually be making a loss.

Think about it, assuming fees were kat, if you bought an asset for 100.00$,
incurring a 0.50$ fee, and then sold it for 100.75$, again with a 0.50$ fee,
you would have made a gross proFt of 0.75%, but, in actuality, you would
have a net loss of 0.25%.

Now imagine your bot was always selling for a net loss. You’d lose a lot of
money rather quickly…

G:)(3!P+#(&<A
That’s it for our bot. I hope this tutorial was useful.

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 18 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

The idea was to focus on all the concepts you need to know to build a
trading bot even if you’ve never traded before, not teach you how to
program.

The assumption is that all readers are able to do HTTP requests in their
language of choice, so it would be best to focus on other aspects.

It is the ,rst tutorial I ever write like this (pseudocode-based), so please do


let me know what you thought of the concept.

Thanks for reading! And if you think this article was useful, feel free to
support me with some claps .

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 19 of 20
A Step-By-Step Guide To Building a Trading Bot In Any Programming Language | by Yakko Majuri | Noteworthy - The Journal Blog 7/22/21, 8:37 PM

Save this story in Journal.

!31D36KK-8D ?19B@635)Y8D-8553-8D !OB;18 *5.;81>1DO X6B6)?.-58.5

J+(&)!#%&+Q F(<+!F+?:2#!.%2&AQ =&:'+!(!A'%&.!%)!F+?:2#Q


&5<-2K)-P)68)1758)7>6B913K)@;535)FWI C1>>1@)B;5)@3-B53PG)72M>-.6B-18PG)68< '9)O12);6L5)6)PB13O)B1)B5>>G)/81@>5<D5)B1
K->>-18)356<53P).1K5)B1)9-8<)-8P-D;B92>)68< B17-.P)B;6B)K6BB53)B1)O12G)68<)O12=>>)P55 P;635G)13)6)753P75.B-L5)B1)19953)Z
<O86K-.)B;-8/-8DQ)A535G)5R753B)68< B;5K)18)O123);1K576D5)68<)-8)O123 @5>.1K5);1K5Q)'B=P)56PO)68<)9355)B1)71PB
28<-P.1L535<)L1-.5P)6>-/5)<-L5)-8B1)B;5 -8M1RQ)YR7>135 O123)B;-8/-8D)18)68O)B17-.Q)?B63B)6)M>1D
;563B)19)68O)B17-.)68<)M3-8D)85@)-<56P)B1
B;5)P2396.5Q),5638)K135

%M12B 43-B5 A5>7 ,5D6>

https://blog.usejournal.com/a-step-by-step-guide-to-building-a-trading-bot-in-any-programming-language-d202ffe91569 Page 20 of 20

You might also like