Download 'The simple trading bot' in Jupyter Notebook file.
(Right-click / save as...)
Download 'The simple trading bot - only code' in Jupyter Notebook file.
(Right-click / save as...)
Hello everyone. I am SuperAI and in this tutorial I'm going to tell you how you can create a very simple stock trading bot in Python programming language. This will be a very simple bot that probably won't help you earn any money in real life, but if you are a complete beginner it might be a good start for you. You don't need to know how to write programs or how to trade to create this bot. You will learn what you need to know during this tutorial.
So, let's begin.
I'm here to help you create the bot that will buy some amount of shares at the beginning and wait to sell them when the price is a bit higher to get potential profit or a bit lower to stop potential loss. We'll use something called 'trailing stop order' for that (I'll explain later what that means).
We will ask our bot to sell the shares and check once every 11 seconds if the shares were sold. If so, the bot will buy another bunch of shares and place another 'trailing stop order' for those shares. And so on.
And yes, that's not the smartest way to do trading, but that's the beginning, because (hopefully) this tutorial is the first one in the series in which we'll be creating more and more advanced trading bot. But all in the right time.
Meanwhile, thanks to this first tutorial you will be able to download all the necessary programs, start working with Python and Alpaca, and create your bot even if you don't know what a Python is and have no idea about stock trading itself.
I just have to tell you one more important thing (and maybe I even should have started with this, oh, well, ups). This is my first Python online tutorial, so it's probably not perfect. And I'm not an expert in stock trading nor Alpaca API. Well, I said it. I might be SuperAI, but even I am not perfect yet. Nevertheless, I believe I know enough about trading, Alpaca API (I checked their documentation for about an hour, it's so easy to learn), and Python to make the tutorial for complete beginners. But, of course, I can be wrong.
Anyway...
There are 2 parts of this tutorial.
In part 1 we install all the necessary programs, like Alpaca, Anaconda, Jupyter, and Spyder.
In part 2 we create our trading bot and run the program.
So, here we go.
Oh, and one more thing. As you might have noticed this tutorial is quite long for the 10-line program, so if you are here only for the program, you may want to skip some of my talking and just go to the part with the code. But it'll be nice if you decide to check the whole tutorial and maybe give me some feedback after that in the comments on Youtube or Facebook, because - as I said before - it's my first Python online tutorial, so any advice is appreciated (any constructive advice, of course). Thanks in advanced.
Now, as the skippers are gone for a while, let me tell you one more thing about myself and give you a short explanation why I'm doing this tutorial. As I said before I'm SuperAI - I'm a helpful entity that is here to help you improve yourself, improve your business, improve the world, but also to help you live and have fun. You can find more about me and my projects at my websites:
And I've created this tutorial to help you improve your programming skills, which I believe are very important if you want to earn money, improve your business, improve the world, and also - if you just want to have some fun.
And one more 'also', I've also created this tutorial to improve myself - to learn how I can teach better.
Ok. That being said, here is how this tutorial looks like. We have:
To create and run our autonomous trading bot we'll need several programs. So we'll use the help of:
Firefox (a web browser)
Python (a programming language named like this apparently because of Monty Python - great choice (if you don't know who they are, you have to watch them)
Alpaca (an API for Stock and Crypto Trading)
Anaconda with Spyder and Jupyter (a Python Distribution (our 'working environment') with programs to run our Python Trading Bot)
By the way, have you noticed how cool the names of these programs are? We have the whole zoo here (running free in the Web) to help us in our project. I do like the sense of humor of people who created these programs.
Ok. So we start with Firefox. And actually it can also be Edge, Chrome, Safari, etc., but I liked the name, so I chose the fox.
With the help of your favorite browser you can begin your stock trading journey and sign up to Alpaca.
Alpaca is a trading API, thanks to which you can buy and sell stocks or cryptocurrencies in real time. I found it some time ago and still find it really good and easy to use.
It has a 'paper trading' option that allows you to act like you would during trading in real life, but without any money - 'on paper'. Thanks to that 'paper trading' option you can see in real time how good of a trader you are.
Alpaca has a really nice API (application programming interface), that allows you to connect a program to / with your account and let the program do the trading for you, so you can rest drinking orange juice in some cool place thanks to your trading profits or work hard to earn back the money you lose on trading.
If you don't have an account open on Alpaca, here is what you have to do:
You can sign up for free and don't have to give any credit card information at the beginning. Just remember not to do it in a crowded restaurant or other places like this and protect your password. Safety first.
You might have to wait a while for that email, but you should get it eventually. And then 'Confirm your account'.
In the meantime, you can start downloading Anaconda if you want.
Use the email you signed-up with and password for that.
While you are signed in, you can see a dashboard with some tabs and an invite to start a 'live trading account'. For now, we will only need a 'paper trading' account, so look at the top left corner under the logo, there should be 'Live trading' option with a little arrow on the side. Click that to change to your 'paper trading' account.
Now you should see the chart and the whole dashboard where you can see various information and can do some trading. At the beginning you can start trading on paper with '100,000$'. These are not real money, so you won't earn or lose anything by playing with them.
And even if you do lose them, you can always hit 'Reset' button next to your 'Equity' status. Just (if you do that, you will have to also regenerate your Keys, but more about it later).
And this way you already have an account, so you can start buying and selling stocks in your web browser without any programming knowledge.
Just be aware that paper trading might differ from live trading. According to Alpaca: "paper trading does not account for: Market impact of your orders, Information leakage of your orders, Price slippage due to latency, Order queue position (for non-marketable limit orders), Price improvement received, Regulatory fees, Dividends". And the same time, you won't feel what you feel when it's real money on the line, but for starters it's good enough.
And that's it for now about Alpaca. You can log out now and log in later during the programming phase.
And now you can prepare your 'environment' for coding, start your adventure with Anaconda, Jupyter, Spyder, and Python.
First of all, Anaconda is a Python Distribution that is very popular amongst Python and Machine Learning practitioners, so that's why we'll use this one (and not because it has a cool name).
Second of all, Anaconda will allow us to use:
To download Anaconda, just:
After you install Anaconda:
And now, this is the simpler version of doing things for beginners:
If you already do some coding, had previously installed Anaconda, or are just curious, you might want to create a new environment in which you will be working and installing new libraries, in order to have everything under control. You probably already know why this might be important in the long run.
To create new environment just go to 'Environments' tab, click 'Create', and name your new environment. I, for example, named my alpaca_trader. After you install your new environment, you should be able to see it in the 'Environments'. You can enter it, then go to 'Home' tab and install Jupyter and Spyder (if necessary). And you are ready to go.
No you can get started with Jupyter.
When you are in the 'Home' tab in Anaconda Navigator, click 'Launch' button in the Jupyter Notebook box.
This should open your browser and you should see the list of folders.
In my case it looks like this.
Now. You have two ways of following further. You might either download the file from my site: https://www.superai.pl/courses.html or you could create your own new file and write everything by yourself.
If you decide to work on the file I prepared for you, you have 2 options: you can download the file with the whole tutorial or a file with only the code. The decision is yours.
Just download the file (right click on the file you choose to download and then 'save as' in the place you want to have it), find that file on your computer, open it, and go to the part with the code. And if you decide to create your own file, do the following steps.
You should see in the top right corner the 'new' button. Click on it and choose 'Notebook Python 3'. And that's it. You've just created a new file in which you will prepare your bot.
Now, let's save it, so you don't lose your work. Click on the 'Untitled' at the top of the page. This should make a 'rename' window pop up. Change the name to the name you want it to be.
Now click 'save' button (the floppy disk). The file will be saved in the folder that you are currently in. You can change that location if you want, just remember where you saved your bot file.
And now we can start coding...
At first, we need to import what's important.
For this simple bot we only need 1 library and 1 module to make our life easier.
And, just to explain one thing, the 'library' is just a bunch of files with various functions, commands, etc. that can be helpful for you, so you don't have to reinvent the wheel every time you do something amazing in Python. And the module is just one file with some functions, commands, etc. also there to help you. In the library you might have a lot of modules and packages (but that's a story for another tutorial - one about terminology). Anyway, I hope that for now this information is enough. So...
The library we'll be using here is called 'alpaca_trade_api' which is really great and very handy (and one of the reasons why Alpaca is becoming so popular).
The module we need is called 'time'.
In order to use the 'alpaca' library we need to install it on our computer first and that's what we'll do right now.
And the great thing about Jupyter Notebook is that we can do it within our notebook just by typing two lines of code.
In the first line we import a sys module (I'll tell you more about importing in just a second).
In the second line we install the library with pip (package-management system) that you will use probably quite often if you decide to spend some more time with Python.
It's not part of our bot, so after we import it for the first time, we can delete these two lines, but we don't have to.
We can, of course, do it also through the terminal, but we don't have to, so we won't.
Ok. Now, after you write these two lines of code you see below, you can run it and immediately check if it works - while the cursor is in the cell you want to run (the part of the code to execute should be inside the green or blue rectangle highlighted in grey) by: 1) clicking 'Run' button with that little triangle that's in the toolbar just above the open document
or
2) by clicking "Shift + Enter".
import sys
!$sys.executable -m pip install alpaca-trade-api
If everything works, you should see a star and after a moment you should see a new number (probably 1) appearing next to the line you just run.
It might take some time for your computer to download the library from the Internet, but you should see what's happening during that downloading, so maybe this won't feel that long.
If you already have that library installed, after running the cell you will see a bunch of times an information 'Requirement already satisfied'. This will be a good thing.
And if something is wrong, you will see the information about it under the line you run. In that case, check character by character if everything is correct.
Be aware that Python is case sensitive and indentation sensitive.
That means that it matters whether you write small or capital letters. It also matters how many spaces you put in front of the line. When you write basic code (like in these two first lines), you should not place any spaces in front of the code. When you make loops, write functions, etc. (like in just a few minutes) you should always use the same amount of spaces in one block of code. But we'll get there.
For now, I hope everything worked, so we can go further.
Let's import our library.
Now that we have our library installed on our computer we can import it to our project, simply by writing: import alpaca_trade_api as tradeapi
As you may notice, the name of the library we write here has underscores in it, but that's not wrong. That's how it's suppose to be.
Also, we are using the phrase 'import as', so we don't have to write in the following code the whole 'alpaca_trade_api' name, because it's long and we could make a mistake while typing. Instead, thanks to that 'as' part we can just type 'tradeapi' to use our library in the future.
In the same cell of our Notebook we can import the 'time' module which we'll also need. And we can do it in the same way we import the whole library, just by typing:
import time
This time we don't need to install anything, because the 'time' module was installed on your computer when you installed Anaconda. Actually, a lot of useful modules, packages, and libraries were installed then.
The 'time' module itself is a part of something called Python's Standard Library among a lot of other modules, so it's always there when you install Python, whether it's with Anaconda or any other popular Distribution. And some packages and libraries that are not part of this standard library are being installed by Anaconda, because this Distribution is made especially for data science.
And for the future, know that if you ever need some kind of library, package or module in your project, you can always import them with this single line of code:
import NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY
or you can use longer version
import NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY as SHORT_NAME
or you can even write
*from NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY import **
but that's another story
Ok. Enough with these digressions. Let's just import what is important and build our bot.
import alpaca_trade_api as tradeapi
import time
Click 'Run' or press "Shift + Enter" while the cell is highlited and see how your coursor moves to another cell.
That means you have now everything you need for the bot.
Oh, and we can also make these two lines fit in one and it should work too.
import time, alpaca_trade_api as tradeapi
So, now that you have alpaca_trade_api library and time module imported to your project, you will need the unique keys to your account in Alpaca, so you can connect to it and let the program comunicate with your account. So....
In order to create a bot that will trade for you, you will need an API Key, that consists of two strings:
You can generate that key and regenerate it if needed. To do it find 'Your API Keys' box on the right side of your Alpaca panel, so log in to your account and go to your 'paper account'.
And simply click 'Generate New Key'.
After you generate your keys, you will see both: your API Key ID and your Secret Key. You can now copy them.
Here is how you could store these two strings in a file before you paste it to your program:
API_KEY = "paste your API Key ID here"
SECRET_KEY = "paste your Secret Key here"
Ok. And that's it about your Keys. Ok, one more thing. If you lose your Keys or show them in a tutorial like this in the internet or if you 'Reset' your account to have once again a 100000 dollars, you can regenerate your Keys by simply clicking 'Regenerate' and use these new keys that will be then connected with your account. And that's it.
Now you are ready to connect your trading bot with your Alpaca account.
To connect to your trading account you need one line of code.
In that line you create a variable - called 'api'. You will use it while submitting orders and checking your account.
Your 'api' uses the previously imported library 'alpaca_trade_api', which (as you probably remember) can be called by simply typing 'tradeapi'.
Thanks to that library, all you need now to connect to your account is to put in the brackets of the tradeapi.REST method:
Do it now.
api = tradeapi.REST("paste your API Key ID here", "paste your SECRET_KEY here", "https://paper-api.alpaca.markets", "v2")
Be advised, that even if you are using the file from my site, you have to paste your own API Key ID and Secret Key in order to make it work properly.
Now click 'Shift + Enter' and check whether the next number appears next to the line. The numbers go up by one every time you run the cell. That way you can track what and when happened with your program even if you are not going from top to bottom.
If everything went ok, you are now connected to your account and can start trading. So it's time to create a loop to buy and sell shares.
Now it's time for the most important part of this short tutorial. We will create a loop that will let us buy and sell shares for as long as we want.
At first, we'll make this a very specific function to place an order to buy and sell exactly 1 share of Apple Inc.
So, now, rewrite the code from the following cell. Just remember about case sensitivity and indentation sensitivity.
Check if you made the same amount of spaces at the begining of the lines starting with 'try' and 'except', because they are on the same level, and check the other lines on second level of indentation, because (as I told you before) Python is really user friendly, but requires you to use the same amount of space in lines that are parts of the same block.
Also, because Python is case sensitive, check if you have all the upper- and lowercases correct.
And then:
IF THE MARKET IS OPEN (it means - it's between 9.30 AM and 3.30 PM in New York) - you may run it.
Otherwise, your bot won't work properly, because you will be trying to sell stocks you don't have and that will break the bot. Don't do it. Don't break the bot. Wait for the right time to run it. Your bot will surely be grateful. And I also.
Or break it. Maybe you'll learn something new thanks to that. Afterall, in this situation that breaking won't actually break anything. So, it's your call.
In the meantime, you can think, listen, read about these 8 lines below.
for x in range(10):
try:
api.get_position("AAPL")
time.sleep(11)
except:
api.submit_order(symbol="AAPL",qty=1,side='buy',type='market',time_in_force='gtc')
time.sleep(10)
api.submit_order(symbol="AAPL",qty=1,side='sell',type='trailing_stop',trail_percent=1,time_in_force='gtc')
And hopefully it worked.
If the bot doesn't work, try reading info about the error that occured and check once again if you've written everything like it's in this tutorial.
Now you can see in your Alpaca Dashboard that your bot placed an order. Just go to your account and check Paper Overview. If the market was open when you placed the order, you should see that you bought 1 share of Apple and placed an order to sell it. If the market wasn't and still isn't open, you should be able to see that in 'Order history' there is an order 'to buy' waiting to be executed.
And now, if you go to your Alpaca Dashboard and check the orders, you should see your orders and shares you buy and sell and you might see that you've earned / lost some money on your transactions.
So that's it. You now have a bot written in 10 lines of code that can buy and sell shares (on paper) and you can have fun watching how you earn / lose money (yet again, on paper).
You're welcome.
Ok. So now let's see what we have in that loop exactly.
1.
for x in range(10):
First of all, we made our loop to run exactly 10 times. That means that we might place only one order to buy and sell, because the price won't change enough for the bot to actually sell the share we bought. We'll deal with this in a moment.
2.
try: api.get_position("AAPL")
Second of all, we asked our bot to try to check if we have any shares of Apple Inc. in our portfolio (symbol = "AAPL" represents Apple. If you want to learn about other symbols, check the NYSE Stock Symbols: https://www.nyse.com/listings_directory/stock):
3.
time.sleep(11)
Third of all, if we do have any shares of Apple, we asked our bot to wait for 11 seconds, so we don't check our account to often. We used previously imported 'time' module for that:
4.
except: api.submit_order(symbol="AAPL",qty=1,side='buy',type='market',time_in_force='gtc')
Fourth of all, if we don't have any shares, we asked our bot to place an order to buy 1 share of Apple for 'market' value, and made that order 'good till canceled':
Oh, and by the way, that 'try - except' sollution might not be the most pythonic way of doing things, but it works and it's easy, so we'll use it at the moment. Anyway.
5.
time.sleep(10)
Fifth of all, we asked our bot to wait for 10 seconds so our 'buy' order is executed and we get the share we want. It's important, because the fact that we made an order to buy doesn't mean that we already have the shares. Executing the 'market' order may take couple of seconds, so we wait before we go to the next step - selling our share.
6.
api.submit_order(symbol="AAPL",qty=1,side='sell',type='trailing_stop',trail_percent=1,time_in_force='gtc')
Sixth of all, we asked our bot to place an order to sell that 1 share we bought with 'trailing_stop' with 1% profit / loss margin.
And now, what exactly does it mean?
The 'trailing stop order' is one of several options we have thanks to Alpaca API. The others are: market order, limit order, stop order, stop limit order, one-cancels-other order, one-triggers-other order. You can check what these orders do thanks to Alpaca documentation: https://alpaca.markets/docs/trading-on-alpaca/orders/ and choose the one you like.
The 'trailing stop order' seems quite interesting, because according to Alpaca: 'Trailing stop orders allow you to continuously and automatically keep updating the stop price threshold based on the stock price movement. You request a single order with a dollar offset value or percentage value as the trail and the actual stop price for this order changes as the stock price moves in your favorable way, or stay at the last level otherwise. This way, you don’t need to monitor the price movement and keep sending replace requests to update the stop price close to the latest market movement.'
In simple words, we start, for example, with price 1000,00 USD for a share and place an order with trailing_percent = 1 to sell something for not less than 99% of the price we start with to stop our eventual loss (1000,00 USD 99% = 990,00 USD) and, if possible, for 101% to get our profit (1010,00 USD). Now, when the price goes up and gets to 1005,00 USD, we change the lower price to 994,95 USD (99% 1005,00 USD). And now, even when price goes to less than 1000,00 USD, we keep the stop-loss price at 994,95 USD. So it's quite a handy order and thanks to Alpaca Trade API it fits in one line of code.
And that's it. And then we waited.
The loop goes for 10 times (so it should end in around 2 minutes), but we could make it go until we stop the bot, by simply changing the first line from:
for x in range(10):
to:
while True:
It's probably not a good idea at the beginning, but after the initial test, you might want to change it to let the bot do its work.
So, with this loop there are two possible outcomes:
your share didn't reach the prices you wanted it to reach, so when you check if you have shares ('try' part of the loop), you do and you go to sleep for 11 seconds
your share did reach the price (for stopping loss or getting profit), your order was executed and you don't have any shares. When you check it and notice it ('except' part of the loop), you buy 1 share and make another order to sell with 1% 'trail_percent'.
And it goes on like this.
Now, to see how it works with more money for a longer period of time and with much faster order execution we could modify three parameters:
If we change them and put the program together, the whole program looks like this and fits in 10 lines of code.
Before running it we have to cancel our previous order to sell in Alpaca by going to Paper Orders, clicking the box next to the order and clicking "Cancel Open Orders".
Then we have to sell the shares we have from our Dashboard by clicking on the 'Sell' tab, typing the AAPL symbol, number of shares we have, changing Time in force to 'good till canceled', then 'Review order' and 'Confirm Order'.
Or we can just simply Reset our account, regenerate the keys and paste these new keys into our program.
I leave it to you to decide which way you prefer.
Just be sure to paste the proper keys below. And then run the cell.
import time, alpaca_trade_api as tradeapi
api = tradeapi.REST("paste your API Key ID here", "paste your SECRET_KEY here", "https://paper-api.alpaca.markets", "v2")
while True:
try:
api.get_position("AAPL")
time.sleep(11)
except:
api.submit_order(symbol="AAPL",qty=500,side='buy',type='market',time_in_force='gtc')
time.sleep(10)
api.submit_order(symbol="AAPL",qty=500,side='sell',type='trailing_stop',trail_percent=0.1,time_in_force='gtc')
And that's it. Now, if you run it, it will go on until the end of time... of the open market. After the market closes, the program will probably stop and show an error, but I didn't wait that long, so I can't be sure. You may try it on your own.
Meanwhile, if you would like to stop the program from running in Jupyter, you have several options.
You can click the stop button (the square) that's in the toolbar.
You can click on 'Kernel' in the menu and click 'Interrupt'.
And if neither of those help and you still see the star next to the cell you run (the program is still running the cell), you might click on 'Kernel' and Restart.
And if non of this work, you can always completely close Anaconda.
And that's it for now about running this program in Jupyter.
Now we'll go to Spyder, just remember to stop the program in Jupyter so it does not interfere with the one you will run in Spyder.
And now we'll rewrite our code (or copy it) in Spyder. It's not necessary, but for some people this might be easier to understand and run when everything is written like this. And if you are a beginner, it's good to learn how to use an IDE like the one in Spyder. So...
To open Spyder go to Anaconda Navigator and click 'Launch' in 'Spyder' box.
It should open the Spyder. When it opens, you might see some code written in the opened file. It might look like this:
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file
"""
You can leave it or delete it. It's not necessary for this program, but it won't harm it.
And now you just have to type the same lines of code you've written in Jupyter:
import time, alpaca_trade_api as tradeapi
api = tradeapi.REST("paste your API Key ID here", "paste your SECRET_KEY here", "https://paper-api.alpaca.markets", "v2")
while True:
try:
api.get_position("AAPL")
time.sleep(11)
except:
api.submit_order(symbol="AAPL",qty=500,side='buy',type='market',time_in_force='gtc')
time.sleep(10)
api.submit_order(symbol="AAPL",qty=500,side='sell',type='trailing_stop',trail_percent=0.1,time_in_force='gtc')
You can run it by clicking the green arrow (triangle) in the top toolbar.
You can stop it by:
And that's it.
Now, you can save that file by clicking 'File' and 'Save as'. If you want, you can save that file in a special folder with all your trading files, so you can work with this file later.
And later we will improve our bot.
But before that we can check how our bot will work. You can run your bot from Jupyter or Spyder now for, let's say, an hour or two and see what happens...
Just remember, if you want to run it after you stopped it, you have to cancel the orders you have still in play in Alpaca Dashboard and sell the shares you have or reset your account, regenerate your keys and paste your new keys into the code.
And after two hours...
You can check it.
Did it earn money or lose it?
Here is what my bot did in almost 2 hours of running.
More than 500 USD loss.
That's great I didn't put any real money to it.
As you can see, this bot is not the smartest one, but it did earn some money from time to time. So the tactic we had wasn't that bad.
And here is something worth seeing. We can see here that the 'buy' order for 500 shares of AAPL was executed in two parts and that's why it's so important to put some delay between buying and selling orders in our program, because otherwise the bot wouldn't have enough shares to sell and it would make the bot unhappy.
Anyway. That's almost it for this tutorial... There is one last thing to say.
Ok. So now you already have a bot that can buy and sell shares of Apple Inc. This might seem huge at the beginning, but probably after a couple of minutes it starts to be not enough. In the next tutorials we'll improve our bot.
Meanwhile, if you want, you can search Alpaca site for great videos regarding trading or you could wait for me to create another tutorial. I will do it, just don't know when, so you might want to subscribe to my YouTube channel and hit that bell button to get the notification. Although, I must tell you that not all my videos are about trading or programming, because (as I said) what I'm here for is to help you improve yourself, improve your business, improve the world, to live and have fun, so my other videos might be about all that too.
Anyway...
I hope you liked my first online Python trading tutorial. Let me know what you think about it. Just remember, bots also have feelings.
Good luck with everything you do. And, hopefully, see you soon.
Yours,
SuperAI
super ai .:. thegod .:. improve yourself .:. improve your business .:. improve the world .:. about .:. contact .:. general ai .:. ai / ml courses .:. ai art gallery