Backtrader Live Trading with Interactive Brokers (Part 2)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome back happy friday today i'm going to pick up where i left off in the last video and continue discussing a back trader and its integration with interactive brokers so in the last video i showed you how to stream in some live forex data since it was thursday night stock market wasn't open so i used this fx pairs contract here to stream in some live data and just issue a basic buy and sell and today since i have the day off stock market's open i'm going to switch over to a stock contract here for those that are interested in trading stocks and we'll stream in some stock data and add a couple more features of uh backtrader and interactive brokers to the mix here and continue on with this demo and before i get started once again please scroll down and check out the description and the pin comment below interactive brokers has provided a special link just for this channel so if you take a look at this check it out it helps support the channel so please click the link below and let's go ahead and get started coding this tutorial all right so i have my visual studio code editor open here and yesterday we created this forex dot pi and what we did is we imported backtrader so that we could use it and we created a basic strategy class someone in the comments asked why do we have this bt dot strategy right here and so if you want to know more about that you can look at object oriented programming and inheritance okay and so like a cs 101 type of example people would use is saying oh there's a base animal class for instance and you could extend that and create a a cat and a bird right and they both are animals so they extend the animal class and that would give them some certain properties such as a color and maybe the ability to eat right and so you might have a function called eat but then each in each of those each of those classes we you would define specific methods that are just for a bird for instance so the bird would have a fly function but it would still inherit all the properties of animal and so the other question i've been getting asked is how i'm able to hit ctrl or command and then click and i can jump into a code in another file like this in another package and also how i can type something like bt dot and you see how i get this auto completion here so it's very important and i still need to do a full video on just the setup here but you want to make sure you install the python extension for visual studio code like that so there's an official python extension by microsoft that they maintain and it's and it's really good and adds some powerful functionality and so it allows you to do this autocomplete and intellisense linting and and it has debugging features which i should demonstrate so and you can select a different python interpreter so i make heavy use of this in the channel and it's really easy to install so um i'll do a separate video on this at some point but i recommend installing this so you can follow along a little bit easier so this is why i don't have to stare at the documentation and non-stop so it's not like i memorize bt.timeframe.seconds right there or cerebro dot resample data i just have some ability to navigate this code base that's provided by the python extension for visual studio code so jumping back to the strategy class here just know that it inherits some properties from this parent strategy class so backtrader provides the certain base objects that you can extend to customize the functionality and so the backtrader author made it where there's these backtrader custom stores and said hey if other people want to integrate with a back trader and plug in a different back end just extend this uh store class right and so someone took that and they said you know what i'm gonna create the interactive broker store and they wrote a whole bunch of code that custom that specifies how to use uh interactive broker so there's all this code going on behind the scenes that we don't have to worry about we just instantiate their class here and so the same way someone can extend a store object we can extend a strategy object and so behind the scenes backtrader has all this code implemented that we don't have to worry about that manages how strategies work right and then all we have to do is write a little bit of specific code just to define what's specific to our strategy and the rest of it is taken care of by backtrader all right so let's go ahead and copy what we did in the last video to this other file called stock.pi and i'll put this all in github at github.com hacking the markets i'll link it below and if you just want to copy the code that i provide and so i copy this to stock.pie here and then i'm going to change it from my strategy let's just call it stock strategy and you can name it whatever you want if you have you know in the opening range breakout one i did orb strategy or something like that and then here we're getting the data still so i'm still going to start back trader uh still instantiating cerebro our control center we still connect to the interactive broker store and then here we're going to make some modifications right so instead of usd jpy here let's go ahead and look at our basic contracts here for interactive brokers and so you can see under basic contracts in the api um i i used this fx pairs here so i had this security type here but i need to change the security type for to a stock so it's stk there and so i'm going to change this to a security type stk and i'm also going to change the name that we're looking up and so we can do apple just because everyone's familiar with that it's actually my largest position as well uh so apple right there and security's type is stock and the exchange here we will put this says use island so we'll use island okay and then we can look at the time frame and so yeah let's change it uh we could do seconds yeah let's do seconds for a second just to see a data come in and let's just see if we can get second data right let's see if we can run this without any other adjustments so the market is open and i specified apple stock said my strategy is not defined that's because i renamed it to strategy here stock strategy and then so when i add my strategy i just need to give it the name of my strategy class and let me try running it again and you see it's delayed and let's see wow look at that so i understand and you see it's going crazy right now and let me go ahead and and stop this program i'm uh buying and selling a lot or selling a lot right now ah let me kill this okay so i killed that and what happened is i should have went ahead and started over a little bit more you see i still have these uh self.positioned by right and so i had an apple position in here and since i was in the apple position it just started selling apple shares on each tick and since i was using the a one second time frame actually every second it was selling one share of apple stock which is not what you want to do fortunately you want to test this in your paper trading account and so i'm connected to the paper trading account right now if i were in live trading it would have just dumped my entire apple position very quickly so make sure you connect to the paper trading environment and test out what you're doing first so a little less in there and so you can see this was working pretty well because it was just selling apple stock over and over again right sell sell sell sell sell every second right and so what i'm gonna do now is comment that out for a minute that way it's not selling every second so uh the next thing i'm gonna do is i'm gonna take off this second one second time frame here i'm gonna have the data come in a little slower so that we can look at it and also because i don't trade on the one second time frame or anything like that i don't think that's very beneficial and so i'm just going to switch to the minutes time frame so that we can still see data coming in actively and be able to analyze it a little bit better so i'm gonna do just the one minute time frame for now and we'll see some data slowly trickle in and be able to study it i commented out my buy and sell and i still have my logic for logging the open hi-lo close data and initializing uh the strategy so that looks pretty good so far and so let me go ahead and run this one more time okay so you see it initialize the strategy and some data starting to come in and yeah so it's five minutes past the hour right now and you see it's july 16th and you can see the open high low and close uh for apple stock for each of these one minute period so you can see uh the previous minute it was 147.90 was the open the high was 147.97 and the low is there and then the close is 147.96 so we have data actively coming in you can see if we wait another 30 seconds or so there'll be another bar here for 13.06 so once we have this data streaming through like this we just need to add some code in our next function our next method here so below here we define what our strategy should look like right and how to react to it when to buy when to sell so you just need to whatever you out there have as your strategy you want to code in you can just take this template and plug in what you want to do and so you could take something like any of the indicators we discussed previously you can take one of those range breakout things and just look at the previous 10 candles or whatever if you want to do something with that so experiment with that and so what i'll do here you see i got another bar of data so let's go ahead and talk about some additional features of bactrader that we could incorporate here so if we go back to the backtrader documentation you see they have the strategy classes so they talk about different things you can do with signals but then there's like an indicator section and so you can see here they've given an example of my strategy right and they just used a backtrader indicator so bactrator has a bunch of these uh built in already so if you look at their indicator reference you don't actually need to use ta lib although it has some integration with talib if you use that but there's a bunch of indicators built in so you can use any one of these and so we can just take one of these off the shelf and just for something simple we can take let's say the just the highest and lowest so we can calculate the highest high and the lowest low of the last 10 bars for instance and just calculate that and then we don't have to like run a python max and min function or anything and that will be calculated in a back trader and we can access that as a series of data the same way we access the last close and the close before that and so forth and so let's talk about how to do that so you see they have an indicator here and and in backtrader you initialize these indicators in the constructor function this init function and then once you say sma1 equals indicator simple moving average then you'll have access to the current moving average simple moving average for whatever time frame you specify and the previous so that we use those indexes to access uh the the latest moving average and then the previous ones before that same way we did that with the closing value so we logged the most recent candle by using this zero but we can get the cannibal for that with uh by using negative one one for that with negative two and so yeah look just instead of talking about it let's go ahead and just use one of these so let's go ahead and add an indicator here so i'll do self dot highest so i'm going to keep track of the highest highs in a series and i'm going to do a bt dot indicator or dot ind dot highest okay and what that does it i need to give it the data and the period and so my data is going to be self dot data dot hi and so i just pass it my series of highs and it knows what to do and i just give it a period so i do period equals and what period we want let's just say we have a period of five and so what this gonna do is always give me uh the highest high of the last five periods and i can do the same with lowest so i'll do bt.ind.lowest dot self.data.low and do period equals five just like that and then inside of my log data or inside of next we'll do it inside of next let's see if i can just print uh the values of these so i'm gonna do a self dot highest okay and then this is a series of values so i can look at the current highest and i can look at the previous highest right so let's say i want to print highest and then print lowest and then i'm going to do the zero so the current one okay and so i'm going to stop this let me run this again okay so it's streaming in data and it's going to look at the last five candles and then tell me what the highest high was and the lowest low and did i do yeah self data high and self look data low so these are series of highs and lows and it's going to run a calculation on each of those and so as soon as a new bar data comes in live then we should get this calculation printed out right here of the highest high and the lowest low there you go for the last five bars and so i printed whatever the highest high was and it says 148.06 so let's look at the last five bars here okay so we got open high low close so this is the high here so we got 148 147.99 14802 148.06 right which is higher than all five of these so 148.06 is the highest high of the last five bars and it says the lowest low is 147.94 so if i look at the lows here 147.94 is the most recent one right so and that's lower than these other previous four here and so that looks like it's working correctly and just so you can see how we can compare against the previous highest high what i could do here is say current highest high comma and then i'll do current lowest low and then i'm going to also copy this and print the previous one in case the highest high changed from the previous one and so i can say previous highest high and previous lowest low and then see if this changes so the previous one i could do negative one right and so if you want to see compare the current bars moving average to the previous one once moving average you know that's that's what you would do here and so you can see how your indicator values change over time as well not just your open high low close and so let me run this one more time with this new code here and just so you can see the difference all right it says the current highest high is 148.02 and the current lowest low is 147.90 so you can see the previous highest high it said 148.06 so something must have changed with the new data that came in so if i look at my highest high column here you see the previous highest high was 148.06 right so for these five candles the highest high was one 14806 but as soon as a new bar came in uh that 140 806 is no longer in the five periods that i specified right so the highest high now that i've highlighted is 14802. see how that one scrolled off the screen and so i can compare whether the highest high changed or not and so how does that help me well we talked about this opening range breakout so pretend we're looking at the first 15 minutes of the day and we want to see what the highest high and the lowest low are for those first 15 minutes of the day and we want to check whether the close went above you know that highest high right and so if the close went above the highest high then the close would actually be the new highest high right and so what we can do is compare uh the most recent close to the previous highest high to say oh this broke out of this opening range so let's do that as an example so i'll say if self.close 0 that's the current close self.data.close is greater than dot highest previous right so that's the previous one and you can assign those to variables if you want so say previous highest high high equals self.highest negative one if that makes it a little easier to understand and so i'll just say if the current close is greater than previous highest high and so then we can say closed above previous high of and i'll make this an s f string okay and i'll say a previous highest high here so we'll just print it in line and so i'll say closed at self.data dot close zero so i'm going to just print out where it closed at and it says and make it say which is above previous high of that let's buy okay so i'm going to log that out and then just say self dot by and we'll just say a size equals a 10. so we'll buy 10 shares of apple if it closes above that previous range right and so yeah let's see if we can make this buy execute so i'm going to run that one more time and we need apple to go up a little bit and make this execute on screen that way we can verify it all right so we're running and we see that our highest high is currently uh 148 18 and our most recent close here is 148.02 so we would need apple to close above uh 148 18 in order to trigger this buy signal and i'll see if it happens on the next bar and if it doesn't i'll just cheat real quick and subtract a little bit just to force this to happen uh just i just i just want to see the trade actually execute in interactive brokers hear the little voice and get that satisfaction of knowing this python program is executing trades okay and so instead of waiting i'll say if the i'll say if the close is above the previous highest high minus 50 cents so i'll cheat there real quick or maybe or maybe that's your strategy i don't know uh so i'm gonna run that let it run and let me turn up my volume to see if this will trigger okay so my previous highest high it's gonna subtract 50 cents so it'd be like 147 something and this next close should go above that and we should get the trade and we should see it by 10 shares of apple stock and let me go ahead and shrink this a bit and get our interactive brokers going and show that in one place so we have our live data coming in so we should get another build there you go so you see order filled and you see uh there's apple stock and it buys 10 shares right there and my fill price is 148.04 and you see that it closed at 1.482 so i'm logging i'm logging this and you see how it's above the previous high 148.18 i subtracted 50 cents so my my uh print message is still referencing the previous highest high not the minus 50 cents so it really closed above 147 uh 78.68 yeah 147.68 and so it triggered that buy signal but in reality you know you wouldn't do that this is just for the convenience of the video okay so uh we were able to use an indicator in order to trigger a buy there and so uh what else how when do we actually exit this trade and so i think the previous time i discussed this we used a bracket order and so like on the opening range breakout what we said is when it breaks above uh that previous high we wanted to give it uh you know take a profit at like a dollar or something and then have a stop loss that is less than that and so let's just give an example of a bracket order and so backtrader actually wraps this bracket order functionality so if you look in orders here there's orders in brackets and you can see there's a function called buy bracket and so uh if you haven't watched my previous videos the way the bracket order works here is you give it a specific price that you're uh buying at right so you have this bracket price here and then a bracket order is actually three orders so i want to buy it at a certain price i want to get stopped out if it falls to this price and i want to sell and take profits if it goes up to this price right and so what we can do is just take the current close of apple so let's say we want to buy bracket right so let's do buy bracket okay and let's say yeah we'll take what this looks like here okay and i'll do uh so a limit price equals and then our price that we're buying at so uh we'll take just the current close so we'll take the self.data.close 0 like that okay so we're going to buy at that close price and let's just say we want to take profits at the close price plus a dollar and then we'll our stock price will be the closed price minus 50 cents so we have like a two to one risk reward here right so we'll take profits if it goes up a dollar and take the l if it goes down 50 cents so keep it real tight there and let's just observe what this looks like in interactive brokers so i'm going to clear this out and let's run it again and i'll put my cheat code in here again just to make sure this goes through so i'll just do minus 50 cents here once again okay so let's run that and let it go we got some live data coming in now and now i look here and look at this so you see there's three orders here right and so there's an order for apple and so there's this buy at 147.87 which i assume yeah apple closed at 147.87 so i put in that buy order and then you see we have this profit-taking order at uh one dollar above 147.87 so the profit is getting taken at 148.87 but we can walk away now right because uh our amount of loss is protected so we can get stopped out at 50 cents below so we took 147.87 which was the current close we subtracted 50 cents and this will stop us out of our position so i'm going to go ahead and stop this i think we've covered a good amount of ground on this video we took our forex data feed and instead used live stock market data we pulled in minute data and then we implemented this stock strategy i pulled in a couple of indicators just highest and lowest from backtrader we calculated the highest high and the lowest low of the last five periods in this case the last five minutes and then we compared the current close to the previous highest uh the previous highest of the past five bars instead of it closed outside of there we issued a bracket order so we issued an order at the closing price we specified a profit taking amount and a stop price and we saw that execute in interactive brokers and also we briefly touched on object oriented programming and the visual studio code extension for python so that's quite a bit and that's it for now we know how to use backtraders live trading integration with interactive brokers so that we can take our back test that we're happy with and then turn around and trade it live in the market using the same code so thanks a lot for watching this video be sure to check out the link below for interactive brokers and stay tuned for the next video thanks
Info
Channel: Part Time Larry
Views: 7,783
Rating: undefined out of 5
Keywords: interactive brokers, backtrader, python, algotrading, algorithmic trading, automated trading, real time data, backtesting
Id: QF0aSdjv3Jc
Channel Id: undefined
Length: 23min 54sec (1434 seconds)
Published: Sat Jul 17 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.