How To Build A Trading Bot In Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi in this video I'm going to show you how you can automate your trading strategy using python in other words build your free trading bot that can automatically take trades on your behalf following a specific strategy and the code I will be using is available for download from the link in the description below so you can just follow the video for now and then download the file to use it as you like and what I will show you here in this video can work for any strategy that can fit in a python function and this might be the best way to test any strategy on a live market instead of Simply backtesting on past data if you want to test it on future data or on live data you can use whatever is presented in this video so this is our Jupiter notebook file I'm going to download some data some historical data first we're not going to use this data for the live trading it's mainly to test if our function or our signals are working so we need to test our signal functions first to see if they are working and I'm downloading from the Y Finance module the Euro US Dollar exchange data between two dates the starting and the end date and I'm using the 15 minutes time frame here something we should be aware of regarding this particular cell here is that when we are trying to download data for low time frames like the 15 minutes interval for example Yahoo finance only allows the last 60 days of data so we can't download more than 60 days at once and these have to be the last 60 days from the current date so in case you download the file and it's not working just pay attention to these particular dates here the start and the end date now we can test what we have just downloaded I'm going to comment these two lines we can see that this row here was downloaded now if I remove this minus one so we have the whole data frame and it's around 3973 rows as you can see we have the date time we have the Open high low close and the adjusted close prices the volumes are not provided for this data frame but we're not going to use these for this video this second part is to Define your signal generator so it's a function basically where you give your data frame current data frame because when we are streaming data live data for our trading bot we're going to acquire a data frame and then we can feed the data frame to this particular function and the function is going to return a signal is it a Buy Signal a selling signal or no signal no clear pattern in this example I'm using something very simple we're detecting only the engulfing patterns the candles engulfing patterns now this is not a full strategy but it serves for the purpose of this video please if you want to build a strategy this is where you can insert your signal generator strategy within this function so for example this function takes a data frame and we're going to read the open price the closing price of the current candle or the last candle of the data frame this is why I'm using the index -1 and the opening price and closing price of the previous scandal the one that comes before the last candle and this is how I'm going to test if the last couple of candles of my current data frame have the engulfing pattern and if it's happening as a bearish engulfing pattern these are the conditions to be used we are returning one the function is going to return one as a signal which has a selling signal and if it's a bullish engulfing pattern we're going to return two which is a buying signal if we don't have any of these two patterns we're going to return zero so how do I know that this function is working I'm going to test it in these couple of lines here and this is where we're going to use the historical data just to test this function I'm going to check first of all I'm going to create a list called signal and I'm going to append 0 for the first element of this list so we don't have a signal at first but then I'm going to Loop over all the data frame all the rows of the data frame and for each row I'm going to check if we have an engulfing candle using the function that we have just created the signal generator so I'm going to feed the data frame but not all the data frame like the last two rows of the data frame just to make sure that we are using the correct set of data and I'm going to append whatever the signal generator function returns into my signal list then I will add this as a new column into my testing data frame and I can print this print the whole data frame and I can see that I have an additional column here now all what I can see for the moment are zero signals but we can do a value count and we have 3617 0 meaning no signals buying signals we have 180 and selling signals we have 176 varish engulfing candles in the data sets that we presented okay so again this is simply a very simple example this is not a real strategy it's just to make sure that our bot is working correctly so now we can use it it's working I'm going to connect to the market and execute trades so first of all before you write a strategy and try to automate it you have to make sure that your broker supports an API connection and they have sufficient documentation to allow you to connect to their platform through Python and execute trades when does not the only one we have binance and other Brokers this is not an advertisement for owenda they didn't sponsor this video it simply happened that I've been using this broker and I have an account there and it's working fine for what I wanted to do so feel free to Simply jump to different Brokers and just read their documentation here I'm going to show you how I do it using wonder how I connect to their platform and for different Brokers it might be a very similar approach as well so I'm going to import all the libraries and the modules I'm going to use I don't think we are going to be using the candle collector we need to create an account account at the broker we're going to be using and you you don't have to create a real account a one that offers a demo account which is what I did for this video so when you create your account you can have an account ID on their platform and you have an API tab where you can create an access token it's just one button you click to create an access token you simply copy it and paste it so in my case I put these into a config file and this is why from my config file I'm importing the access token and the account ID just to keep these on a side but if you don't want to do this you don't want to include this line and put these into a config file you can simply put your access token as a variable here you can also put this as a global variable meaning you can put it outside of the function it works better so this way it is visible in all the program later on so now we can Define the first function which is the get candles because we need to acquire the candles from our Brokers platform so get candles is only a function that will go and grab the candles live now the current candles on the market and we will have the Open high low and closing price for each candle for the moment so we're going to get the last n candles for example going to grab the last three candles of the market and the way to do this is that I'm going to use the candle client of Wenda I'm going to provide the access token and the real value is equal to false because this is a is not a real account it's a practice account for the moment and then I'm going to define a collector variable which is the client dot get collector and the pair is going to be Euro US Dollars and the granularity is going to be M15 so you can find the list of these options on awenda's documentation if you need to change these to daily or four hours or the hourly bar charts the time frames so for the moment we're using the 15 minutes time frame and this is what we're going to use and then the candles are going to be equal to the collector dot grab the last and candles and is a parameter that we're going to provide for the get candles function so all of this is provided within the function and then the function Returns the candles so the candles are going to contain information about the opening price the closing price the high and the low prices for each candle and to make sure that this is working I'm going to Define candles outside here and call the function get candles to get the last three candles and for each candle within the candles that I just pulled from the market I'm going to print the opening price and to check if the opening price is above one and the reason I'm doing this is that you have to be careful what type is this variable candle dot bid price you can also provide the ask price dot o.open is a price type that is proper to owenda's platform but here we need to transform it into a string then to cast it into a float to be able to compare it with a numerical value which is one in this case so I'm going to print these and we can see that through through meaning the last three candles opening prices were above one so the Euro US dollar prices oh great now we have a function called get candles when we call this function it's going to provide us with the last three or n candles on the market so we can use it later on to cool the candles analyze the candles and check if we we will be passing any buying or selling positions on the market so now I'm going to Define another function called trading job because it's going to contain all my trading execution so first of all inside of the function we're going to call the get candles function we're going to get that the last three candles on the market we don't need any more candles the current candle meaning the last candle is not closed yet remember that the last candle is still moving so the closing price is fluctuating this is why we need three candles I'm going to make my test if I have an engulfing pattern on the previous couple of candles so those that already closed and we know the opening and closing prices we're going to call these three candles we're going to store the information in candles variable and then I'm going to create a DF stream and as data frame the open close high low prices and I'm going to fill the information of these candles for each candle with in candles I'm going to fill the information into the data frame and then we have to cast the types of the columns again into float otherwise it wouldn't work and then I'm calling the signal function and I'm providing the data frame that I've just downloaded live from the market so we're getting the candles putting these into a data frame and feeding this data frame into our signal generator function that we have just explained above and the signal generator function is going to read the last two closed candles check if we have an engulfing pattern buying or selling golfing patterns return this as a signal and we're going to use this signal in case we want to buy or sell but before that we need to Define our take profit and stop loss and this is done in this part of the code so we have the previous candles range I'm going to use something very simple here I'm going to look to the previous candles open minus close prices so this is the range of the candle and I'm going to use this as a stop loss distance for the moment from the current buying or selling price then the take profit is going to be twice because the stop loss take profit ratio or take profit stop loss ratio is going to be equal to 2 so it's multiplied by this ratio so that distance is multiplied by 2 for the moment to set our take profit prices so we have different prices whether it's a buying position or a selling position so for example we have the stop loss and the buying position is equal to the current opening price of the current candle minus whatever we defined as a stop loss distance and in the case of a selling position the stop loss is equal to this opening Price Plus to whatever we defined as a stop loss distance so anyway it's not very important as long as you know what you are doing and how you would like to set your stop loss and take profit values so you can set these right here and then I'm printing these whenever I'm calling the function just to make sure that the values are reasonable and then we have to define a client function with the API and provide the access token if the signal is equal to 1 then we're going to pass a selling position and the way we're going to do this is by checking the market order request function we're going to provide the instrument which is Euro US dollar and since it's a cell I'm going to sell a negative number of units so this is why we have minus 1000 here it's 1000 plus 1000 in case we are buying a take profit is equal to whatever the take profit distance is and this is the syntax to provide it to this function and the stop loss is equal to whatever the stop loss is in this case and this is the syntax we're going to use for buying positions it's the same only we provide positive units in this case because we are buying then we Define a new function I call that R here orders.orders create the account ID e and the data equal to mo.data so this is my market order data I'm going to pass it as a fund as a parameter for this function here at the end I'm going to call the client request function I'm going to print RV just to make sure that the order was passed because every time we haven't executed order we're going to have something on the screen so it's safer this way we can see at least that an order is executed so so far we have our signal generator function we have our get candles function to provide us our candles from the market then we have a trading job that's going to get the candles check the signal and see if we are going to pass any buying or selling positions provided that we are fixing our stop loss and take profit values now we have to execute all of this we have to call these functions at once we're going only to call actually the trading job function because this function call the other functions so in order to test if my function is working I'm going to override the signal value so inside of trading job function at this point I'm going to put for example signal equal to one so we have a selling signal we can run this and then I'm going to launch my function regardless of whether it's scheduled or not just to see if it's able to connect to my account and pass any trades on the market so this one didn't work because apparently we have a stop loss problem if the stop loss is not wide enough sometimes the order is canceled automatically by the API and instead we can extend the stop loss by choosing the high minus the close minus the low value instead of the opening and closing prices and I changed my signal to 2 so we're going to pass a buying signal a long position and now if I run this function and then the trading job function I'm going to have the details I can show you these because I will have to show you my token and the account ID but you'll get all the details printed Down Below in the Dual notebook regarding your order and we can also go and check how it looks like on the oanda account so this is my own account and this is the buying position with just the long position we just executed automatically from python so this is the web interface of Rwanda and we can see that it's working our python is correctly connected to the API and it is able to pass any automated trades stop loss and take profits also are set accordingly for one important note here is that any other platform you are using if you're using metatrader on your phone you can just check those trades on your phone wherever you are and this is a big Advantage you can also modify the stop loss and take profit of the trades and you can manage the trades even close these trades manually so you can interfere with your algorithm it's not something that I would recommend because if you have a winning strategy that you already back tested and it's working well you don't want to interfere with the algorithm however sometimes if you manage manually your trades it might increase your rewards so we can comment this line and then I'm going to Define my scheduler and I'm going to add job and then we can start the scheduler you only have to care about the parameters so this is the job we're going to be scheduling so add job my trading job this is the function to be called and I'm going to use a cron the days of the week are going to be Monday up to Friday hours zero zero up to 23 so 24 hours a day and I'm going to trade only on particular minutes of the hour so after 1 minute 16 31 and 46 the reason is because I'm using the 15 minutes time frame for this demo the start date doesn't really matter it's simply better to put it at 12 so we can start at a fixed hour and these minutes are going to be correct and the time zone also you can change it for whatever time zone you prefer it doesn't matter in this case because it's a cycle click scheduling so it's going to be 24 hours a day and testing every 15 minutes on the market so basically this is going to be downloading the last three candles every 15 minutes from the market applying all of this function checking take profit stop loss the signal and executing orders accordingly allowing many orders in parallel here so if one order is not closed it's okay we can allow a different order at the same time so just be careful for all these details in case you want to automate anything and that's all I had to show you for this one I hope you found the information helpful if so please support comment like And subscribe until our next video trade safe and see you next time
Info
Channel: CodeTrading
Views: 198,652
Rating: undefined out of 5
Keywords: python, python trading bot, trading, trading bot, algorithmic trading, python trading bot tutorial, python trading, build python trading bot, automated trading, trading algo, python programming for stock trading, trading bot python, python thrading, algo trading, how to create a crypto trading bot in python binance, how to create a crypto trading bot in python algovibes, how to code a trading bot in python, how to make a trading bot in python, trading strategies
Id: WcfKaZL4vpA
Channel Id: undefined
Length: 18min 46sec (1126 seconds)
Published: Thu Dec 08 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.