Introduction To Algorithmic Trading
Introduction To Algorithmic Trading
of Contents
Preface 1.1
Disclaimer! 1.1.3
MACD 1.5.2
RSI 1.5.3
1
What you need to know about programming before we start 1.8
MetaTrader 1.12
Programming 1.13.4
Useful links and resources 1.14
Cryptocurrency exchanges 1.14.1
2
Preface
Preface
This book is being written entirely for free on the open web, "live", do what you will with it.
This is a work in progress and might contain mistakes, broken links, poorly written english or even empty chapters, please
feel free to feedback and contribute.
This is my first time writing, so please don't expect a masterpiece, I'll learn along the way and hopefully I'll be improving it
day by day...
***
When you find the content useful, please send tips my way ;")
BTC: 1767DuD8teMeeTV2DtPviqMYE1G13169x3
3
Who's this book for?
If you already have knowledge in one of these fields feel free to jump right in your interest area.
I'll explain subjects which i believe aren't covered on the internet in a simple way and give "modern" code
examples developed by myself.
People not interested in programming automated systems will learn key concepts and how to take better informed
decisions and make their own systems.
4
Why I'm writing this book
if you have a winning strategy why do you even bother to write a book? Why aren't you living your dream somewhere,
doing something you love to do in life while the robots take all the weight from your shoulders?
This was the first question i had in my head when i started looking into algorithm trading.
After a few months deep into research and learning, here I am, being the person in the other side of the question, the
person who wants to share some of the knowledge and pitfalls that were met during all this time.
One of the first clicks happened after i earned some money from trading and than gave it all away to the market. I got really
disappointed with myself, basically because i was already believing "that was my profit", but in reality i never spent that
money, so after giving away all that sense of "profiting" became simply imaginary, replaced by a void.
This void really put my down, so down i got really puzzled about "how to avoid this" and how to actually "don't give my
profits back" or even "how to earn consistently", this is a bloody hard challenge.
I spent many hours and nights awake reading and learning as much as i could and once i had some basic understanding i
actually turned it into learning and programming and by programming i mean programming trading strategies. I was coding
and testing whatever strategy i could put my hands on.
I did that day and night for countless months, way more than sex, believe me.
It took me ages until i had the "EUREKA", when i felt I connected all the floating parts.
Many backtests and live experiments later, i realised how much of this material is actually "hidden" from the web and really
just accessible for people that already have a background in finance and programming, but not really and introduction for
people who only have one of these skills.
5
Disclaimer!
Disclaimer!
None...
... of the sites linked in this book or even this book will make you rich in no time
By reading this book you have no guarantee that you will become a milionary and buy an island.
First you need to work out how the market works and how to have a profitable strategy.
Secondly the profits are proportional to your account size and You surely shouldn't be risking much if you still don't know
how to trade, so don't expect huge profits while you don't master your trading style, it will take some time.
Some...
... of the links on this book contains my referral id ( also know as affiliate link ).
If you use those links and one day decide to have a paid account the service will share a small piece of their profits with
me, which means you would be indirectly supporting this book at no cost.
If you really...
... learn how to trade the markets you will never have to look for a job again.
I know this sounds silly, but i must let you know upfront, it's all about being in a good state of mind. Having a plan helps not
loosing your hair and also guarantee you won't be under pressure when taking decisions.
It sounds easier than it is, but there are simple things you can do that will completely change how you feel. For instance if
you only use 1% of your account size, will you be as nervous as you would be if you traded 100% of it at once?
6
What you need to know about trading before we start
One thing i certainly know tough, is that when i knew nothing it would have been much better if someone had pointed Me
out to a few key topics.
I'll try to keep it as easy as possible, the idea here is to have an introduction basics and carry on. Not to get stuck on just
this topic just now!
Learning about markets is the most important thing You will be doing, so You will end up digging this much deeper later on
anyway.
undefined
7
Markets
- Markets
To be honest I'm by miles not the most qualified person to tell you what you need or don't need to know before trading the
markets, but certainly I would have appreciated if someone pointed me out to a few key links and subjects, and that's all I'll
try to achieve in this chapter.
There are many kind of markets markets and they can be totally different, for instance:
Trading Stocks
Trading Forex
Trading Options
Trading Commodities
Spread Betting
...
Trading Cryptocurrencies
All of this markets have their own ins and outs, their own reason and chaos so by no means I'll try to explain all of them.
- The market
It's important to say you don't need to be a market expert to read this book - surely that would help - but don't worry if you
just starting.
Ideally you know basic rules, for instance you want to buy a Stock or Currency when it's price is low and sell it when it's
high, therefore increasing your balance.
The opposite is also true, sometimes you want to sell it high and buy it low ( the opposite of buying low and selling high ),
that is also possible and it's called "shorting".
At first the market sound very complicated, but if you pretend you are a child about to learn the rules of a new game, it can
actually be quite enjoyable to learn.
8
Candle Sticks
Candle sticks
We won't go much go deeper than this on this part of the book, but for now would be cool if you knew how to read candle
sticks, there are a dozen of patterns and theories about them which you don't really need to think right now.
There are also written articles about candle sticks and patterns, you might find useful:
TODO
9
Order Book
Order book
The order book works like a two queues in different sides, one side wants to sell a stock and the other side wants to buy a
stock.
Naturally people on the buy want to buy it cheaper and people wanting to sell want to sell it at a higher price.
If you want to buy something cheaper than someone, you go to the end of the buying queue reversely if you want to sell it
more expensive you go to the end of the selling queue.
When people meet and agree on a price, that's the new price of the stock.
10
Position Sizing
Position Sizing
I can't emphasize enough how position sizing is the most importing ingredient when managing risk.
In plain words, if you want to be sure you won't blow your account, you must understanding position sizing and risk
management.
That is a common symptom caused by big position sizes, would you be nervous if you were risking less than 1% of your
captal?
The first time i learnt this concept was like a million doors opening in front of my eyes.
Enjoy.
11
Risk Reward Ratio
12
Stop Loss ( Limit ) Order
Introduction
A Stop Limit order is one of the most effective ways of limiting your risks and guaranteeing your profits.
It's Sunday afternoon, You are sitting on a park a guy using a suit comes and puts 100 USD in your hands and say:
-- For each degree Celsius the temperature go up I'll give you 20 USD extra and for each that goes down you have to give
me 20 USD. You also have the option of walking away now with 100 USD.
You suddenly realize you have absolutely no control or way of predicting the temperature and have to decide if you will go
home with 100 USD.
Let's say you wait and the temperature goes down by 1 degree, remember if it goes down by 6 degrees you will have to
pay him 20!
How long more can you stay? Hypothetically let's say it goes down even 1 more degree and you left with 60 USD and
decide to go home. That's would be a Stop Loss of 2 degrees !
What if temperature goes up by 1 degree, how long more will you stay before you decide to go home?
If it go up by 3 degrees and you decide to go home with 160 USD we could say you Took Profit at 3 degrees!
I hope the possibility of sitting there waiting the temperature to go down until you own some money didn't even appeared in
your mind.
You don't want to lose more money than you willing to risk, so be it! Do what you have to do to stick to your plan.
How it works
It's like an alarm, it will go off once the price hits a certain value.
When you alarm go off an order will be automatically placed for you at the rate ( price ) you specified.
Imagine the following situation, you buy 2 BTC worth of ETH and pay 0.0188 on each ETH because you believe the price
will go up about 10% and hit the 0.0206 mark.
But what if things don't go the way we planed, when will we jump ship? When do you know it's time to give up on that idea?
Once you decide the amount you willing to risk, it's time to set the alarm, so if things go against us an Order will be open
and hopefully our position will be closed.
In this example I decided I'll give up on the trade if the price hits 0.0184, which is about -2.2% loss.
I log into Poloniex and set my Alarm ( Stop ) to 0.184, once the alarm goes off I'll create an order.
13
Stop Loss ( Limit ) Order
The value of the order will be defined by Limit, which I'm setting to 0.0184, meaning that's the price I'll be willing to pay at
that moment.
( Note: If you really want to get you order filled, you can set limit to be lower than the alarm )
The Amount will be set to the same amount i have bought previously, effectively closing my position and giving up the
trade, "automatically"
Once i set:
14
Stop Loss ( Limit ) Order
Now theoretically you can loose just up to that 2.2% you have calculated, and unlimited gain possibility. Isn't that great ?
Now imagine the market goes in your favor and it hits the 0.0192 mark, you could now:
In theory now, you are safe and can't loose any money on this trade.
If You set a really tight stop, the market could go against you, trigger your stop order then move in your favor.
For complete documentation on Stop Orders on Poloniex, please check the Poloniex's documentation on Stop Limit
Orders!
15
What is Margin Trading?
Imagine now there is people around willing to lend you the same amount of money you have for a small fee.
Margin trading is the connection of this two "endpoints", one have a stash resting, the other needs to amplify his moves.
So one part borrows the money and buy double amount of shares, now his initial stash will be affected 2x, if the stock goes
up 5% his stash will grow 10% and vice-versa. That's called "leveraging".
The other part lends part of his stash and receives a "lending fee" together with his money. That's called "lending".
For a more detailed introduction, please check out "Margin Trading: Introduction" @ investopedia
16
Fees and Taxes
17
Trading on a demo account
Imagine you already know a certain market ( for instance BTC/ETH ) and you looking into diversifying your investment by
investing on Forex, Precious Metal, Commodities or even Equity
Wouldn't it be great if you could start playing around with other markets on a Demo account?
18
Registering on an exchange
Registering on an exchange
What if you could login into an exchange right now only using your facebook or google acount and start playing straight
away?
Once you're logged in you will have access to different markets, don't worry if you still feel like you don't understand
anything. You will get there.
In the meanwhile you can learn more clicking on the "Intro and Education" button on the bottom left of the page.
19
Buying and selling
Opening an order:
Closing an order:
For more information about how to use SimpleFX, you can have a look at SimpleFx Tips
20
Our first trade on a real account
In cryptocurrency exchanges anyone can open an account and start trading straight away, the fees are a small percentual
of your order.
This means your account balance literally doesn't matter, you can start right now with only 10 USD.
So far i have had a great experience poloniex but that doesn't mean they are secure.
Do your research about exchanges, many have been hacked in the past, so people are really cautious about which
exchange to use.
That's the main reason why it's recommended to keep coins you are not trading outside of exchanges.
- Next steps
I'm assuming by now you already got some bitcoins, if you don't please jump to "Bitcoin in a nutshell" chapter and get
some.
21
Registering on an exchange
Registering on an exchange
"An exchange is a marketplace in which securities, commodities, derivatives and other financial instruments are traded." (
Source: investopedia )
There are many exchanges you can choose, some of them are listed on the "Useful links and resources" chapter.
For the sake of simplicity we will be using one of the most well know cryptocurrency exchanges poloniex.com, there you will
be able to trade many cryptocurrencies.
It's free for registering and you don't need to send any proof of identity unless you plan to deposit or withdrawal more than
2000 USD/month.
Once you register and send some funds, you will be allowed to trade instantly!
22
Sending funds to the exchange
Once you find your deposit address, send some of your bitcoins into that address:
In case you still don't have bitcoins, please refer to "Bitcoin in a nutshell" chapter.
You will have to wait for a few minutes while all the needed confirmations for your transaction are verified, once that
happens, you are free to trade!
23
Buying and selling
24
What is lending ?
What is lending ?
TBD
25
How to "Margin Trade" ?
26
Buying on Margin
Buying on Margin
TBD
27
Selling on Margin
Selling on Margin
TBD
28
Technical Analysis
Technical Analysis
Really simple and well done video on Technical Analisys, this guy has loads of interesting ones:
29
Simple Moving Average
This one seems to be short enough and it involves a "blackboard" so should be easy to understand:
30
MACD
MACD
This is one of the most favoured indicators around, so much so that a lot of charts will draw MACD by default.
Without further do, go check Moving Average Convergence Divergence - MACD @ investopedia
31
RSI
RSI
Another really important indicator, check What is the 'Relative Strength Index - RSI'
32
Bollinger Bands
Bollinger Bands
Check Bollinger Band on investopedia ( as usual! )
There are also loads and loads of videos about Bolinger Bands strategies on Youtube, for instance this one hour long video
!
33
Ichimoku Cloud
Ichimoku Cloud
The list of indicators can go on and on, an infinite amount of indicators ( "classics" and "custom ones" ) can by found on the
internet.
It's important to remember: Becoming profitable is a matter of studying the market and finding it's rhythm.
You you just need a couple of simple indicators that are setup meaningfully.
A lot of indicators will "say the same thing" in slightly different ways, again: keep your chart simple so you understand where
the decision points happen and then how to make them profitable.
I would say "ichimoku Cloud" isn't exactly a "popular indicator" because it's surely not easy to understand and get your
head around, but i would classify as "2nd level of popularity" as it seems to be very common among intermediate /
advanced traders.
34
Developing your first strategy
35
Why Stop Loss is so necessary ?
What is the change one day you will be away from your screen and the market will go violently against your position?
Imagine you are on the blackboard, planning a strategy, how would you be able lay down a system if you never now how
much you willing to lose in each trade?
Now you are in the same blackboard, planning a strategy, you have a look at the charts and come to the conclusion:
Which one you think would be easier to predict and work out?
36
Buy and Sell signals
The most common way to generate signals is to analyzing values extracted from the charts and respond based on those
values.
A very simple example would be to buy and sell when Simple Moving Averages are crossing
It's not unusual to find people selling signals or publishing signals online as well, which is very common on stocks and forex
Some people like to mix a few different signals and only trade when they match and so on.
37
A Simple Example
A Simple Example
I know at first "developing a strategy" sounds scary and impossible for a beginner, so I'll play the cards early and hopefully
encourage you: It's surprising how simple a strategy can be and still make You some money.
And it's always surprise to discover that the technical aspect of the charts won't be the hardest hurdle for most, at least for
me, the discipline is by far the most challenging.
In order to constantly win you have to constantly play by the rules and by rules i mean the ones you have come up with,
your own rules -- your strategy !
Once you understand it's not about each trade, but actually about a combination of many, you will see how things starts to
be simpler.
Let's start with some sort of "home made" strategy, checkout what this lady has to show you, if the simplicity of this and the
audio quality of this video doesn't surprise, i don't know what will !
What will happen if i started doing this right now? You gonna loose all your money, surely!
If you don't believe a simple strategy can make you money or if you think this example was crap, don't worry, i got
something for you.. Go to tradingsetupsreview.com and have fun, there are tons and tons of strategies, from the most
simple to the most complicated. You can spend many sleepless night looking for them, anyway trus'me: start by loving a
simple one and move to the next step !
Research
Do you think a successful trader just walks around betting money on strategies they just heard of? Absolutely not, the
invest money where they see opportunities and when they believe the odds are favourable to their position.
If you've learnt a setup and you believe it could yield good results, you will have to evaluate it yourself - remember it's your
money you about to invest, naturally, nobody better than Yourself to check if an opportunity is a good as it looks like, that's
part of the secret source, believe in yourself and your judgement.
Sometimes the setup that worked for her on the afternoon on the 15 minutes chart of GBP/USD will work for you on the 2H
Chart of BTC/ETH, you never know, the possibilities are endless and that is the first important task you have to face is
Research
Look for the setup in different pairs, different time frames, make annotations, the possibilities are endless and if the setup
makes sense, it will actually happen in many different markets and time frames.
Annotate
Let's say you found a pair where the lady strategy works well on BTC/XMR, you zoom in to the 15 minutes chart and realize
every afternoon when the MACD crosses there is some movement in that direction.
38
A Simple Example
You then look for this setup multiple times, and take notes of the best cases and of the worst cases. Hoe much could you
have made on the best opportunity? What is the average variation of this setup, does the value goes up by 2% ? 5% ? 0.5
% ?
What were the worst losses? What would be a good "exit plan", eg: which stop size would be great to avoid horrendous
situations ?
How many times the setup were profitable when going long ( buy side ) vs how many times longing wasn't a good idea ?
Was it better than 50% of the times ?
How many times the setup were profitable when going short ( sell side ) vs how many betting it would go down wasn't the
best idea?
How many consecutive times you closed your position green in your best winning streak ?
How many consecutive times you closed your position red in your worst loosing streak ?
Sometimes a setup will work really well when on the buy side but not really when going short for instance. So might be a
good idea to just wait for when the trend becomes bullish!
Let's suppose have looked the 15 minutes MACD crossover and came to the conclusion the market will generally move 2%
up at best and at worst case it will cross back to red - forcing you to exit the position - at about 1% of the value, you also
notice sometimes it would go -5% those are the ones we will be avoiding by always having a stop loss set, remember:
From looking behind you can also see that if you use a trailing stop and move it to break even after it goes to 1% up you
can avoid loosing money 70% of the time.
You also noticed that if you take profit at 2% you will generally be in a good place, but sometimes there are spikes on about
4% up ( when the volume is increasing very fast ), so you might consider moving your stop loss higher to about 1% or 1.5%
instead of taking profits at 2%.
Play time
There is no better school than actually doing something with your own hands. Have the feeling of moving something and
see a consequence to your movement, that's when you really learn something.
In simple terms:
When the time comes, you won't be able to avoid it. Your mouth start bubbling, you are SURE you got a nice strategy in
your hands and you are looking so forward to f... find those crazy profits!
The best thing to do, is to see how the strategy plays in the real field, this will be a second "validation phase", where you
will try to play as close to "the real game" as possible.
This will show you real life problems, like trading fees you forgot to consider, dealing with anxiety, uncertainty, fear and all
the other challenges you will have to feel comfortable with.
Start with a demo account if you can't afford the real thing, but for those who really want to learn fast i suggest starting an
account with some small amount, like 50 or 100 USD and invest that money into gaining real experience, this will level up
your game immensely.
39
A Simple Example
You keep staring at the chart, your setup is happening right now, what should you do? Throw all your money into this
opportunity !!!!
Remember the chapters about "risk management" and "position sizing", that's what you want to be thinking about now.
For example, when your setup happens, you bet 1 USD on it. If it goes wrong ( your stop at -1% get hit ) you won't get hurt,
you will loose 1% of 1 USD which was 1% of your initial capital.
The next time, you "bet" the same, if it's go wrong and your 1% stop gets caught, you now at a loss of 2x 1% of 1USD.
That means, if the next time the setup happens you bet 1 USD again and it moves in your direction and gets your the 2%
target, you will be back at the start !
This also means, from every 3 trades if you hit your target 1 time, you are back at break even! The rest is profit!
Instead of going all in and getting all nervous, you now comfortable by knowing you betting a small amount and by betting
that amount with that stop loss you just need to hit the 1 of 3 times.
Imagine the opposite, every time you throw your whole cash at the setup: 100 USD, then you loose twice in a row, and
have only 98 USD. If the third time you hit the 2% profit, you won't be back at 0, because 2% profit on 98 USD won't take
you back to 100 USD !
Understand this and being able to clearly see this being applied to my strategies - as opposed to reading about this and
thinking that i understood - was one of my biggest EUREKA moments, and i hope the same happens to You.
The setups, the rules, it's all simple. The hard bit is to execute.
Now that you have your "parameters" together, it's time to work.
Work as in: punch the clock day in / day out, wait for your setup to happen, like a Fisher man waiting the fish to take the
bait.
Set your stop loss accordingly, you might also want to set your "take profit".
Learn the ins and outs, experience will tell you all the strong points and the weak ones.
At the beginning you might want to watch and and baby sit all your trades, but once the engine starts working and you
might feel comfortable by entering a position, setting your stop loss, take profit and simply walk away, fearless.
That's perfection, everything is going as planned, you know your maximun loss - and it's part of the plan - you ready to take
profits, and you not nervous because you not risking much.
Start small, game your game straight. Give it some time, so you sure you have constant results, if you don't, learn why you
don't.
40
A Simple Example
Make a journal about your trades, take notes on why you took the trade and when, how you were feeling, what you were
expecting, annotate the date, your balance. Then read it, read it, read it, learn from it. Learn from yourself, from your
mistakes. Taking notes ( on paper or digitally ) is the best way to learn and progress. Otherwise you might just forget all
your great ideas and will never understand what have gone wrong.
If a strategy don't work for 2 weeks, it doesn't mean it won't work in the next two and vice-versa, so don't give up once a few
bad trades happen.
In that case go back to the blackboard, read your journal, and find out, what is the next improvement.
Should you always add trailing stops to your gains? Should you increase your stop, is your balance moving too little ?
Only time and experience will tell, so take notes, be brave, face the work, hopefully the final reward will be proportional to
your efforts!
This is super badly viewed ( doubling / martingale / other strategies ), but for those who never thought about it. It's always
good to learn, so better ideas and better strategies might emerge from exploring different aspects of the game - for instance
going deeper into position sizing theory ( and buy a 400 USD book about it, lol ).
Let's say you have a pretty unlucky streak and get your stop loss caught 4x in a row, but you now feel confident you will
catch the next time. You can then bet 2 USD on the setup instead, so if you hit it, you will cover all your 4 losses. Worth
saying, if your stop gets caught again, you will now be 6 losses behind, and if you keep doubling you will blow your account
quickly.
, just because you have stabilished a stop loss and have analised historical data you are now in a much more
41
How Automated Trading works
Writing the code is actually the simplest part of this game, the difficult part is to write a good profitable strategy.
Before running your code with real money you will want to test the code using historical market data, that's called back-
testing.
This way you can see how your strategy would have performed in a certain period.
Once you happy with your backtest results then you should be able to run your strategy on a real money account.
42
Setting up your first robot
Setting up a robot
Let's imagine a situation, you just wrote the nicest strategy you ever could think of, you just backtested your script against
historical market data and now you are ready and confident you could use this script on a real money account.
Great! Now you just need a computer online 24/7 running your robot relentless.
You're right.
Developing a strategy, creating a backtest system, having a computer online all the time isn't something any human being
will enjoy learning and doing
Specially when they want to focus on trading markets, learning profitable strategies and whatnot.
Don't worry, for the sake of quick learning ( and fun ) we will start using a nice shortcut.
43
Backtesting your first strategy
This way we can start playing around without having to install or download any software, easy and effortless.
i kindly remind you of using the inline links on this book, some of them
contain my referral ids ( the ones i currently use myself ).
In this particular link i have written the whole link so you understand
the links actually have some extra information in it.
That's one of the onlys way i can make a penny out of this book
44
Running your first strategy
Luckily enough cryptotrader can also run our strategies and ensure the system will work as close as 24/7 as possible (
Disclaimer: i don't work for them ).
Surely that isn't something we want to be doing before even understanding how
Your robot will be there, restless working for you. That sounds cool, but also sounds like a lot of techy work, if you not into
these things there must be an easier way, right?
45
Drawing on the chart
46
What you need to know about programming before we start
Programming
First of all: If you have no clue about how programming works, don't worry.
I'm absolutely sure anyone with enough interest in automated trading will be able to learn enough to put a strategy together.
Actually, the good news are, you probably already know how to program you just don't know you know it. Programming is
pretty much like thinking, so if you are able to think you are already qualified to do the job.
How come?
A program is simply a sequential thoughts and conditions to be executed, pretty much like thoughts in your head.
This list of sequential commands ( in our analogy: our thoughts ) will deal with some information received - just like we
move numbers and possibilities in our heads - and then finally execute action.
This action might as simple as "instantly forget" or "do something with this glass".
If you never programmed before, i totally recommend this awesome, interactive, beautiful, short and fun online book.
You should be able to read this book in a few minutes, try out some code and if you never coded before, you surely will feel
like a different person.
If you prefer you can also learn as you go through this book examples.
47
Installing node.js
Installing node.js
If you are not familiar with command line i recommend going to node.js download page and downloading the installer.
If you are familiar with command line i recommend installing node.js using nvm so as time goes by you can easily switch
between node.js versions.
48
Running scripts from your terminal
49
Using Github and Git
Feel free to skip this page, you might get away for now while reading the book but surely if you want to be a prolific
programmer you better learn it.
50
Programming your first script from scratch
Some people will prefer using other languages, and that's completely fine.
For now using Coffee Script will be a good choice since we will also be using it when writing scripts to run at
cryptotrader.org
Coffee Script is a slightly different way of writing Javascript, it reminds me a lot of ruby and python. You can learn more at
coffeescript.org, if you already know Javascript or any other programming languages you will get it in no time.
In order to use coffee script you have to install node.js in your computer and also have basically knowledge on how to run
scripts from the terminal,
If you don't know how to do it, please refer to "Installing node.js" and "Running scripts from your terminal"
You will also have access to the sample code on this git repository, i'll try to keep it synchronized with the book, please let
me know if something is weird.
51
The exchange API and API Key
Poloniex has it's own API, you can read their full documentation here
Public API Methods which anyone can use to obtain data for whatever reason without providing any identification. For
instance: showing a ticker on your website
Trading API Methods like buy, sell or returnBalances which needs account identification.
It's a very good idea to keep the "enable withdrawal" checkbox unticked, this way if someone get access to your key they
won't be able to simply move the funds to their personal accounts.
Once you have your Key and Secret, keep then in a secret note, you will need in when writing your first script.
52
Your first script
$ mkdir my_project
$ cd my_project
$ npm init .
Download a package that will let us access poloniex methods pretty easily:
for more information please refer to this package reference and the poloniex api page
On this example we will simply fetch the current "Ticker" for BTC/ETH market, this method is available through the "Public
API" therefore we don't need any authentication.
$ coffee get_ticker.coffee
{ id: 148,
last: '0.02035216',
lowestAsk: '0.02035216',
highestBid: '0.02035001',
percentChange: '-0.02876367',
baseVolume: '18297.08372074',
quoteVolume: '888128.60751199',
isFrozen: '0',
high24hr: '0.02129990',
low24hr: '0.01991000' }
Congratulations, you just read the current ask/bid price of a market using an automated script!
53
Your first script
I'm sure you want to do something more exciting now, like buying or selling some crypto.
That sounds like a good idea, but before you will have to know your balance.
54
Knowing your balance
On this example we will simply fetch the current "Ticker" for BTC/ETH market, this method is available through the "Trading
API" therefore we will need our KEY and SECRET, if you still don't have one, please get back to "The exchange API and
API Key"
key = "YOUR_KEY"
secret = "YOUR_SECRET"
params =
key : key
secret: secret
if data.exchange?
console.log "You have some funds in your exchange account:"
if data.exchange.BTC
console.log " - #{data.exchange.BTC} BTC"
if data.margin?
console.log "You have some funds in your margin account:"
if data.margin.BTC
console.log " - #{data.margin.BTC} BTC"
$ coffee get_ticker.coffee
{ id: 148,
last: '0.02035216',
lowestAsk: '0.02035216',
highestBid: '0.02035001',
percentChange: '-0.02876367',
baseVolume: '18297.08372074',
quoteVolume: '888128.60751199',
isFrozen: '0',
high24hr: '0.02129990',
low24hr: '0.01991000' }
Congratulations, you just read the current ask/bid price of a market using an automated script!
55
Bitcoin in a nutshell
Bitcoin in a nutshell
- Nutshell
It's not possible to buy and sell bitcoins anywhere in the world
It's now possible to spend bitcoins in any store, online or offline as long as they accept debit cards
It's now possible to trade cryptocurrency markets
It's now possible to trade regular Stocks and forex markets using Bitcoin
If not the money of the future it is at least the first "well accepted" money of the future, the one that brought to light a
technological evolution as revolutionary as the e-mail.
- Basic concepts
If you not familiar with bitcoin, there is an infinite amount of resources online about it, this wikipedia entry is a great place to
start.
From a trader / regular person perspective, some of the most important aspects are the efficiency, speed and easy of use.
Believe me Bitcoin got to a point where it can fulfill this requirements very well.
Once you bought your coins, you can spend it anywhere in the world using services such as e-coin.io which is a pre-paid
debit card provider with a key difference:
- Buying bitcoins
I believe this is the biggest barrier for someone wanting to get into bitcoins, buying bitcoins it's not always easy.
Some cities will have bitcoins ATMs while others cities your only option will be to buy online.
You can easily find sellers online such as localbitcoins and use services like bittybot.co which supposedely find the
cheapest sellers.
You can alternatively use exchanges like kraken.com which will let you deposit EUR.
Programmers can also get some bitcoins by solving github issues, checkout gitmoney.
In order to receive bitcoins you will need a Bitcoin address - or a "wallet" - which you can easily create at [blockchain.info]
(http://blockchain.info
Once you have your bitcoins you can move your money to an exchange are you are ready to trade. Currently one of the
most popular ones is poloniex.com but there are many others.
You can easily find a list of exchanges and currencies pairs they offer at coinmarketcap.com and exchangewar.info
After opening an account on an exchange you will have a "deposit" address for Bitcoin - and other cryptos.
That's your "address" within your exchange account, which you will send your coins in order to trade.
When buying bitcoins you can also use that exchange address to receive the coins, but those addresses are subjected to
changing because they are assigned to you by the exchange.
56
Bitcoin in a nutshell
- Spending bitcoins
As previously stated there are many websites on the internet which will accept bitcoin directly, but for all other cases using
a pre paid card like the one provided by e-coin.io will allow you to shop anywhere in the web and if request a debit card,
they will send you which means you can use it in any physical store, pizza places, [...]
TODO:
57
More strategies and References
I'm putting together a few links around so you can have an idea of what people are doing:
Classic use of EMA/SMA combined with price action, very useful specially when trading manually.
58
MetaTrader
MetaTrader
I'm sure someone a lot of people will disagree but from my personal point of view it's a great platform for beginners to learn
and explore Automated Trading.
I must make clear that i don't believe MetaTrader to be the best tool for all tasks.
There are other brilliant tools like Ninjatrader that will outperform MetaTrader in some ways and surely there are many
more, like this one
One great thing about playing around with MetaTrader is that it has been around for very long, so naturally you can find a
lot of online content for free.
There are also "official websites" like mql5.com and mql4.com with more information than you can ever consume. You can
even automatically copy trades from other traders, crazy!
With MetaTrader you can use what they call an "Expert Advisor" which is basically a piece of code that can buy and sell in
your behalf.
They also have a "Strategy Tester" which allow you to do simple simulations using historical data.
You can find loads of examples online and MT also come with a couple of examples "out of the box".
You can learn a lot from reading other people's strategies, just remember to keep it simple! Don't fall into the trap of making
something complicated. Stick to strategies that are simple to understand and easy to backtest! - at least for now.
Very interesting feature : The Indicators on the chart can be edited in "code form", You can draw valuable information on
the screen that otherwise wouldn't be available in chart.
You will also notice that a lot of Brokers offers MT "for free", no surprise it's very popular among traders.
The quickest way to get a free demo account running in your desktop that i know is going to simplefx.com, you can easily
login with a Facebook or Google account and then go to their download page, they also have a version for Mac which is
very handy and not easily available around the web.
"MetaTrader 4" is also available for free on the App Stores, it comes with a Demo account and let you do some trades from
a very simplified interface.
Once you understand how it works you can easily change your broker ( for instance if you planning to trade Forex there will
be places with better spread than simplefx! ) and they will probably also have MetaTrader available for free, if they don't,
they will surely have other tool that will be great or at least that You will be able to compare with MetaTrader and start
having your own preferences.
Have phun!
Or watch some of the thousands of tutorials you will find on Youtube, like this tutorial !
59
MetaTrader
60
Backtesting on MetaTrader 4
Backtesting on MetaTrader 4
Very useful articles:
61
More Links and Tips
For instance you can search for "mql4 rsi alert" on google and you will find tons of versions, with sounds or email alerts,
etcs..
https://academy.tradingheroes.com/forex-trading-tools/
62
EUR/USD MACD / EMA system
63
Extras
Extras
64
Useful terms
Useful terms
Slippage
65
FAQ
FAQ
66
Other backtesting options
Install Software, download some data and run backtests on this software using the downloaded data OR
Write our own backtest tool
Since we still didn't write our backtest tool and don't want to be fiddling with software just yet, i recommend you to keep
playing around at cryptotrader.org and have a look into the other options later on, when you are more comfortable with the
whole jazz.
67
Programming
Programming
js2coffee.org It will convert Javascript to CoffeeScript - if you write Javascript on the left panel
It will convert CoffeeScript to JavaScript - if you write CoffeeScript on the right panel
codepen.io Perfect website for quick sketches and tests on your browser, supports CoffeeScript
68
Useful links and resources
69
Cryptocurrency exchanges
It also let's login using your facebook and trade online without installing any software using a demo account, this make
it really easy for beginners to start.
Some complain about their high "swap rate" and "spreads", other than that i never seen anyone complaining from
anything aside from the top banner that shows up when the platform loads - ha.
1broker.com Very interesting broker, let's you use Bitcoin to trade Indices, Stocks, Commodities, Forex and Crypto, the
website doesn't look very modern in the other hand it's simple and it works!
They provide an API and the spreads seems to be smaller compared simplefx spreads.
kraken.com Allows cash deposit, among other features like higher leverage than poloniex. Widely used, unfortunately i
still didn't have the opportunity to trade there.
exchangewar.info On this website you can find a very complete list of cryptocurrencies exchanges.
70
Platforms for online automated trading
Trading platforms
https://www.haasonline.com I got very surprised by some of the videos i seen, this platform seems pretty "advanced"
and "modular", definitely an amazing approach to trading. Check out what this guy can do! It's totally worth it!
cryptowat.ch Definitely the most pleasant interface to look at, hands down!
Every time i can look at a chart using cryptowat.ch i will ! I wish i could see any chart through their platform!
https://www.coinigy.com Interesting platform which allows you to trade on many different crypto exchanges from the
same interface. Very interesting they have an API which also allows you to interact with different markets therefore
saving you the time to integrate your system with different APIs
http://marginsoftware.de Another platform that let's you watch and trade different exchanges at the same time. They
also claim to have "automated strategies" but i fail to find out how to create your own strategy, etcs.. Seems promising
tough
71
Forex, Stocks, Precious Metals, Commodities, etcs
If you prefer to trade those markets with Fiat Currency ( USD / GBP / EUR / ... ) You will have to search for the broker that
meets all your requirements.
It's very common to hear about interactivebrokers.co.uk among programmers, Quantopian for instance, one of the coolest
online platforms for online automated trading can be linked to interactive brokers!
If you are in UK you might want to go the "spread betting" way, in that case i recommend you use ads-securities.co.uk they
have really tight spreads and really good customer service! Don't forget to use my code when registering "LDNRAFF16!",
this will pay bonus back for you and for me once you reach a certain Notional Value trading.
72
Further Reading
Further Reading
- General stuff
Modern Portfolio Theory Modern portfolio theory (MPT) is a theory on how risk-averse investors can construct
portfolios to optimize or maximize expected return based on a given level of market risk [...] Keep reading on
Investopedia
- Books
Technical Analysis for Dummies A great book for everyone getting into Technical Analysis, definitely an awesome
starting point for programmers and traders wanting to grasp the basics automated trading
Paul Wilmott on Quantitative Finance A classic in the area, super recommended "everywhere", not for everyone i
would say.
Mastering the trade I confess i still didn't finish reading this book i can tell this is definitely quality material, great to
understand better the mindset of a trader, which i believe to be as important as your programming skills, this can bring
great ideas and influences to your strategies
73
Online resources
Online resources
trading / charts
ChartSchool
Investopedia
Informed traders youtube channel
74
Bitcoin / Altcoins markets and news
TODO:
75