Interactive Brokers API, TradingView Charts in Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so we have an onbar update event and what I'm doing is updating this chart with new bars of data and there you go you see it just happened this is the simplest condition here so this is actually buying Apple's stock right now so I'm gonna stop that so back in 2020 I created a popular series on how to subscribe to real-time financial data and visualize that data on lightweight charts which is an open source Library by trading View and this library is great it has tons of features uh you can stream your own data and connect to different events you can integrate whatever data you have and it works really well it's fast there's lots of styling and you get all these cool chart types so you get to ride on the coattails of trading view who are experts on creating these slick charts while at the same time you can integrate your own data create your own applications but one drawback to this is that a lot of people that watch this channel were like why did you switch from python to Java script I like to do everything in Python I don't have time to know multiple languages and so there are some libraries in Python like MPL finance and matplotlib where you can create some charts in Python but they're kind of ugly relative to the trading view charts and they're not quite as interactive and fast and smooth when you try to zoom and pan around it so the charts here they're just not on the same level as what you get in trading view wouldn't it be great if you could just instantiate these trading view charts from python with a few lines of code well it's on Reddit and this user suppressive OG looks like he goes by Lewis NW on a GitHub he posted about this package that he just released that's open source and what he did was wrap a trading view lightweight charts and combine it with a web View and looks like Pi QT and WX Python and made it where within a few lines of code here you can just import this chart object instantiate it you can pass it a data frame and boom you have a trading view chart just like this now in his examples here here he's just reading in a flat file so a CSV file containing open high low close and volume data and just displaying it on the chart and even the real time example here what it does is read two different CSV files and kind of simulates real-time data so it'll plot the initial rendering of the chart and then read the next pieces of price data from this other CSV file and render render them bar by bar so what I've done here is run with this Library a bit and create some actual Integrations with real-time data and so I've created five unique projects here that I will show you how to build in this video and let me talk about them and show you what we're building first so you can decide whether this is something of interest to you and there is a written version of this tutorial as well as source code on the website linked below if you want to follow along with what I'm saying here and so I wanted to demonstrate the power of this Library by creating some projects that you can follow along with and so I've created Five unique projects that you can create here and work through this with me and they get progressively more complex so I start simple with free data from Yahoo finance so dynamically fetching that data and then rendering it on a chart here and I also integrate pandas TA in case you want to plot different indicators this library has the power of taking a series of pandas data and plotting lines and other visualizations markers on this chart so that's project number one and we also put in watermark for what the chart is so this will render a chart for Microsoft and just to show you what that actually looks like when we run this I'm going to run this program that we're building and so you can see this chart is a lot nicer than what you get in Python you see I can move it around I have these crosshairs you can see the moving average indicator here follows my cursor around it's zoomable panable and so forth so not a lot nicer Slicker charts so that's the first example to get to understand the library then we get get more complicated the second project we're going to do is use callbacks to switch between symbols so you're going to be able to type control F or command F to switch between symbols on the chart and also have these little panels to switch between different time frames and what we're going to do is fetch different time frame data dynamically and different symbols and render them on this chart and respond to this UI and so this is going to be interacting with Trader workstation I do have a link to interactive brokers below if you want to follow along and help support the channel you can sign up using my special link down there and yeah you can follow along with what I'm doing here and what we're going to do let me show you what you get out of that so this static with callbacks example here we're actually interacting with IBN sync a library I covered in my interactive brokers API tutorial right here and so what we're doing is taking this open source Library this python Library someone created for charting I'm going to combine it with my interactive brokers API tutorial and we're going to request historical data we're going to display it on this chart and then we're going to implement some of these callback functions to dynamically switch between symbols and time frames and so let me run this one real quick and this is coming from the market right now so the market is open and there's an apple chart right there and you see I have these time frames here so this is the 15 minute time frame and then I can switch between this so this is being executed so this is being instantiated from like python code and I'm providing callbacks for it and so I'm switching to the hour time frame the daily time frame and this is actually fetching data from my Trader workstation right here and then right here what I can do I can do control F and I want to get Nvidia right there I hope some of you bought Nvidia when I was talking about it in December and there you go so it switched to an Nvidia chart and then I can switch time frames and so forth so second example just dynamically fetching data from different time frames and dynamically switching symbols so create the user interface for this leveraging IBM sync and this lightweight charts in Python Library the third feature I want to demonstrate that this Library provides is this ability to create panels so you want to be cool you want to have like two monitors with like 20 different charts up at once let's say you just want to create this grid of four charts what I've done here I have this static grid example and this just uses Yahoo finance to fetch free data so let's just say you want some daily time frame data over the course of a year you want to Watermark these charts and display them display four charts at once I run that and then look at that I have four different symbols that's data fetched from up to June 30th the past year just like that I have Microsoft Apple Nvidia and Google so that's the third example just dynamically fetching a price data and rendering multiple charts at once next we'll learn how to do real-time rendering using tick data and so what I'm going to do here is render this chart so I have this real-time bar section and this tick data section so we're going to do here is programmatically subscribe to these ticker events on interactive brokers and so I'm going to render the initial chart so we're going to fetch some up to the second data here from interactive brokers and render it here and then you can see this last Candlestick here as being uh rendered in real time so you can see it's moving up and down and I'm receiving these various ticker events right here and so here we're doing a real time charting and interacting with our broker and we have this stream of data coming in right there and the fifth and final example I'll show is how to subscribe to Bar data so we'll subscribe to data from interactive brokers and respond to that price data so new new bars are going to come in and we can even respond to that and actually place a trade and plot when that order is filled on this trading view chart so uh yeah we're going to get real-time data in place an actual live market trade typical disclaimer here uh trading especially on the short term is often a way to to lose money very quickly so if you're doing this I suggest doing it in a paper trading account studying it before actually trying to do something like this at home it's very risky and can result in loss of capital so yeah try this at your own risk but it's a very cool thing to be able to see in action and I'm going to actually do that now I'm going to run this real-time example right here and what we're doing is subscribing to Bar updates and when a certain condition happens let's say you want some pattern you want to detect or whatever when that happens what you can do is place an order programmatically and then you can render a marker on that chart when the order is filled so I'm going to run this on the live market now and I made it very simple condition so it's probably going to actually buy a stock here and so I'm going to open this chart and it's subscribing to Bar updates for apple and you see apple is moving up pretty rapidly and I think I just did something simple here because I want to show this actually executing on the camera so you can see it works this is not a good strategy to apply so it's going to check I think it's like five second Parts it's gonna be like if the openness if the close is greater than the open like three times in a row it's gonna actually place a buy order all right so I'm going to try to show all this side by side this is my trading view lightweight chart uh this is my uh python code that we're gonna walk through that renders this chart and it's also going to be watching this price data that comes in and so what we do here is uh on bar update so we have an onbar update event and what I'm doing is updating this chart with new bars of data and there you go you see it just happened this is the simplest condition here so this is actually buying Apple's stock right now so I'm gonna stop that and I just killed the program but I just noticed that actually close the chart so I didn't get to discuss uh what I was going to show you on the chart so I took a screenshot from the video recording here and I'll just talk about the screenshot so but what was happening here is this on bar update function is getting called and what I'm doing is creating these new bars and saying chart update and passing at the latest open high low close and volume data from my brokerage account and then I'm updating the chart and then what we can do this gives you the ability and on bar update you can look at the previous bar so this is looking at the last bar we can do is look at other bars in the series so this I'm just looking at the last bar the one before that the one before that comparing them and just creating a simple condition here and if that condition is true I can for instance place a buy order and specify a callback function whenever that order is filled and so I have an order filled event here that actually plots a marker right there and I say order filled at and I show the execution price and so you'll see here this is a screenshot of the chart that was just rendering this has an order filled marker right here and so they're getting rendered on the chart and you can see I actually spent real money on their uh I spent like 600 bucks there uh executing uh Apple's share orders just to show on this channel that's how much I care um and yeah and then you see an email here you'll see these this is what interactive brokers sends you whenever orders uh fill so I actually got three messages uh just like that and so that's the fifth project and what's cool about that I've a lot of people ask me how to integrate trading view uh with interactive brokers and use web Hooks and I did come up with a way to do this and I created this whole video on how to do this um which was fairly popular people want to see this uh but this relies on so many moving parts right you're relying on trading view to send you alert that to go to a web app that you create sing it sending it a special payload and then you're executing a trade on your desktop which is it's kind of clunky uh and it's cool to see that it works but what I like about here is I still get the benefits of the trading view visualization but all my python code is locally right here so I can just run it right here and show myself the chart without juggling data back and forth between trading View and my own personal server for instance so I feel like this is an improvement upon this whole Pine script plus web hooks approach here that I demonstrated so those are the five projects we're building and what I want to do now is walk you through how to actually build this up line by line I'm not going to type line by line I have the source code on the website here and we'll copy it but then we'll also kind of build it up and show from the simplest components I'm going to progressively add lines of code here so you can see how it builds up and how I actually integrated um this uh Yahoo finance data and interactive brokers data and all this functionality with an open source package that's a little more generic and I'm going to show you my thought process that went into combining all these pieces together so let's go ahead and get started with that all right so let's start very simple I have Visual Studio code I use that for all of the projects on this channel I'm going to do open and I'm going to start with a blank folder so I'm calling this trading view charts python Interactive Broker so I just have you can use whatever folder name name you want here so I have a folder here I'm going to create one for the static chart so we're going to start with that so I'm going to do a static example here and then at the base level I'm going to create a requirements.txt now in my visual studio code editor I have the python extension so if you click on the side here on under extensions you'll see that I have an extension called python there and so my editor is very aware of python and that's how I get all the tab completion and so forth that you see a lot of people are asking how I navigate around in code okay and so what I can do is create a new file under static here and I'm just going to call this what I'm going to call it a basic chart dot pi just like that and if I run that you'll see it fires up a command line so if you have your python configured with vs code here you run just like that some people just run everything from the command line or use other editors so this is just what I do and I typically create a virtual environment and what I do here is type python3 Dash M V and V V and V just like that and what that does is create a virtual environment right there and visual studio code will actually detect that I created a new environment and it'll use that one every time I hit the play button so it's going to be aware of this environment I create right there so there's my virtual environment and I've covered this on the channel many times and a lot of people already know this stuff but I'm trying to briefly touch on this and so I can activate this virtual environment by doing a van bin activate so running that and you'll see now I have a virtual environment activated now you can technically install all these because technically you don't have to do this you can install these packages globally but since I do so many projects on here some of them require different versions I create this isolated environment where I'm going to install my packages and so most python programmers do that and so people that watch this channel are all different levels some don't know this some will find this very uh boring so what I can do is specify all the packages required in this requirements.txt now if you're following along on the website I've included the full source code here and what we get at the end but I want to start a little bit simpler so the first things we need I'm just going to use these three libraries first so I'm going to copy lightweight charts why finance and pandas TA first is lightweight charts that's one of the main points of discussion that's how we're getting this cool visualization so that package that's on GitHub we're going to install y Finance so I've done Yahoo finance tutorials on here just for the people that want free data I'm going to go more advanced for people that want to integrate with interactive brokers in their brokerage account but I realize not everyone has that yet or wants to do that so I want to not exclude people and so I want to provide a free data source here now one downside to this it's not really an official paid for supported Yahoo thing so this this thing can be flaky at times but it will work for this tutorial and we can't do the short term uh short time frame uh stuff we can't place orders we can just fetch like daily time frame data pretty much is what you're going to do here but it's sufficient for this simple example I'm also going to install this pandas ta library and if you go on YouTube and want to learn more about pandas TI you can YouTube it and then I'll be right there I was the first one to do this but you see there's several other ones now of people uh creating their own versions of different things I've covered and it's been kind of cool to see how when I create a video about something how now there's other YouTubers in the same Niche like creating something about it a few weeks or months uh later than that so I just remember first starting this YouTube python for finance stuff there wasn't many people really doing that and now it seems like there's there's quite a few people making this type of content which is pretty cool but anyway if you want a full tutorial on pandas ta there's like a 30 minute video that I had created on this and it covers a lot of this in detail but I want to use it um and integrate it into this example so I have this basic chart.pi I run it you see it's using my environment and it's running basicchart.pi but it doesn't do anything yet it's how do I implement this basic version of a static chart with Yahoo finance integration so let's first start out with the GitHub example that he has provided here and talk about how that works and so I can copy this code here and let's see if it runs so what I'm going to do now is run this basic chart.pi run it like that it says no module name pandas it's because I created this requirements text but I didn't install the packages I'm going to clear this out I wish I would have given this a shorter name because that's taken up way too much space and I spelled it wrong so uh move training the charge to TV python I'm going to call it that and then go back into my directory and now I'm going to do a pip install Dash R requirements text or pip3 install Dash R requirements text and there you go you see it's installing some packages now so now when I go back and run this so if everything's set up correctly you can run this it's not going to say pandas is missing but it does say it's missing this file so he's rendering this using a static data so a ohlcv data and so I'm going to link to this repository but you see in his examples here on setting data he includes a basic CSV from data from 2010 through a certain period so I'm going to go to Raw there and I'm just going to copy this data and I'm going to make a file called ohlcv.csv just like that and include that and let's see if it can read it um still didn't find it I think I need to put static since it's in that static directory and I run that and you see just like that this is how you render a static chart from CSV data and you notice it's a bit it's pretty nice has a nice feel to it feels fast and Slick now uh this is just CSV data that's static that's downloaded already so what I wanted to do is the first thing I thought of was okay well how do I get a data from another source so on the website I show how to do exactly that and so I'm going to copy this example hopefully you get the picture there and then what I'm going to do here is talk about this line by line so we'd already imported pandas before in lightweight charts pandas manipulates pandas data frames a Panacea lets you apply various technical indicators to a pandas data frame so I import that as ta and Yahoo finance has the Y Finance package which is open source right here and so we do here is we instantiate this chart object that we're importing from lightweight charts with Yahoo finance you can create a new ticker objects you can specify the stock symbol of whatever stock you're getting data for you can call the history function and give it a period you could do one year you can get one month of data and what this does is return a pandas data frame that we store in a a variable called a DF here now I'm going to comment out this indicator part let's just focus on fetching the data from Yahoo finance and displaying this chart okay so one thing about this if you look at oh lcv CSV file he's provided you'll get an error if you don't do any manipulation of the data frame so you'll notice this date is its own column and then there's this index with zero one two three four so those are the rows of the data frame um that's the date and then open high low close volume when you use Yahoo finance the date is actually the index here right it's not its own column and so if you run this Library without doing this reset index let me show you what happens so I'm going to run this and just use the data directly from Yahoo finance so I'm going to comment out this bit and I'm also going to comment out the part that plots the line I'm going to run this just like that okay you'll notice what I get is an error it's like key error time so it doesn't it can't find the column with my date and time stamp right so what I want to show here is what causes this error so if I print the data frame without doing any manipulation here I'm going to run this and so if I run this it's still the error but if I scroll up I can print what the data frame looked like before the error and so you see how the date is the index here and then there's open high low close how this expects it it wants the date to be its own column and you see how it wants the column names to be lowercase and so when I do the this reset Index this date will become its own column and then I just lower case all the columns in pandas and so if I do this reset index and lowercase all the columns and then I run this what you're going to see is that dynamically fetch this data for Microsoft so this isn't the CSV file anymore it's returning a data frame from Yahoo finance and then plotting Microsoft and then I can easily change the chart here to Let's provide a different symbol so let me create a variable called um AMD for instance and then I'm going to pass it a symbol and then when I set the watermark since so I don't have to do it twice that's why I use a variable called symbol there right and so I can run this I should get the watermark with AMD and different price data and so you can see this works as expected the next thing I'm going to do here is plot some indicator values and so using pandas ta which I've imported here so what I can do here is for this Microsoft history data frame I can take that same data frame and what Panda's ta does it gives you this dot ta so this extra attribute where you can call these functions for different indicators and pass uh parameters here right and so if I go to pandas ta you can watch my video or you can look at this particular list here and so you can see here there's tons of different attributes you can call here if you're into these momentum indicators and revert mean reversion statistics Trend all those sorts of things but I'm just using SMA it's the simplest one that anyone understands and rather than the default I'm doing length equals 20 so a 20-day SMA and then so I'm saying two frame I need a pandas data frame here and so if I just print this SMA a data frame raw like this I want to show you what that looks like and so I have a date index and the SMA 20 and the first 19 of them are going to be not a number because we need 20 values to calculate that average right and so yeah that's what that looks like and so if you just pass that in that's going to bomb remember we need this date in its own column and we need all a lowercase and so that's why I did this manipulation here so what I did was SMA I'm going to reset the index I'm renaming these columns from date to time and SMA 20 to just value so the way this lightweight charge Library works right now you just give it a series of times and values and so that's why I'm doing a little bit of manipulation and also I can't pass it not a number maybe that's something that's going to change over time but when I pass it that's not a number it doesn't know what to do so I'm going to drop all these rows that don't actually have a number and then I just get this new SMA format right here and then what I can do is add a line here and so to do that with lightweight charts I do chart dot create line so I have I set it with a series of bar data and then I also create a new line and I set the data for that SMA so I'm setting a data frame of price data and a line I'm setting it with this data frame the simple moving average data frame right here and if I run that you should see I get my first example which is a full chart that has my moving average plotted so let me stop that and run it with my new code and there you go just like that AMD you see it with my moving average line that's calculated on Yahoo finance data so that's the first example of what you can do with this just render a simple chart with indicator but let's get a little more advanced here so I've created a new file callbacks chart.pi you can call it whatever you want that's what I chose and so the next thing I want to do with this library is see if I could integrate it with a broker I noticed uh he provides this callbacks example here that lets you put these little widgets on here to change time frames and also to change symbols and it shows how to implement them he adds a switcher so that's a switcher that lets you switch time frames and he adds a text box in the corner so he places his text box in the corner and if you hit Ctrl F you can change symbols and type in a different symbol you'll see types Tesla there in this animated gif and clicks between different time frames but how this actually works on here he's just pulling in different CSV files so what I want to do is see if I could do the same thing but interact with my brokerage account and so I wrote some interactive brokers code right here to actually do that and so I'm going to paste this in and talk through how this works and so to do this we need a two additional packages and so if you look on the website I started with the simplest example but I also need this IBM sync and Nest ice async IO in order to do this so I'm going to add these and I'm going to install these packages again and make sure I have IB and sync and so IBN sync is the library I used it's a python package for interacting with the interactive brokers API and I've created a full like one hour long video on how to do this and so if it seems like I'm moving kind of fast some people are complaining that this video is way too long they're like dude get to the point so if I have an hour of five minutes of like installing it setting up the port person connecting your first script and I also have a full GitHub example so I'm going to take my GitHub examples from hacking the markets here so I already had some pre-written code that I cover in that tutorial on how to use interactive brokers API it's called interactive brokers demo and so what I did was take some of that code for placing orders fetching a fundamental data scanners and so forth and I take this same code for connecting and I'm going to integrate it with this lightweight charts Library here okay so I took this second example from the website it's in callback charts right here and let me see if this works if I need to change anything there you go so it works right there so it's running and I'm going to walk you through it so here's me markets open I'm changing time frames on Apple stock right there it's updating the chart and I'm also going to hit command F and I'm going to change to um AI there and there you go there's AI stock that has add a big move there if you look on the daily time frame so all that's interacting with my Trader workstation that I have open right now so how does this work so the main things here is I'm importing the IB and sync library up here and async IO because it's required for this callback functionality you'll notice here when my program runs you'll see on my get data versus the example instead of getting data from that CSV file so in his get data he's reading a CSV file and in my case I'm connecting to interactive brokers right here I'm creating a stock contract object which I've covered in the past I'm requesting some historical data for that contract in this case I'm requesting 90 days of data and then I'm converting that to a data frame using this IBN sync function called util.df and I pass the bar data that's returned from this request historical data here and then I'm returning it and then you'll notice when we're running this program we instantiate this API object right here let me stop this and then you'll notice down here in the main function we're instantiating chart but we're passing at this API object that specifies what to do when these callbacks are fired so I'm instantiating a chart and passing it in some new parameters I'm not just using the basic chart I'm providing this API parameter a top bar which let's uh which puts that widget on the top and a search box right so I'm passing in some details about the widgets and the UI I'm building and so the first thing I'm going to do is get the initial data that I want to show on the chart I'm going to render the text box in the switcher here and I'm specifying a callback function saying this is a time frame switcher that five minute 15 minute one day whatever and I'm saying when this value changes call Api dot on time frame right and so this is the parameters for my switcher I want 15 minute one hour one day options here and whenever this changes I'm calling this on time frame function and you'll see what that does us is I get the value of the time frame and symbol and pass it to my get data function and so instead of reading that from a CSV file I can provide whatever parameters I want and then I request historical data using this dynamically created stock contract here so I get the symbol here I pass it to my stock contract object and then I also get the time frame here and pass it to interactive brokers API and use that as my bar size setting so when I switch time frames I fetch bars for that time frame when I switch symbols I call get data again pass it in a different symbol and just to show a little bit what that looks like here and on search I can log a message I can just print I'll do an S string I'm going to say symbol has changed to symbol like that and then whenever the time frame change I'm going to print the value of the time frame so here I can just do a print an F string and I'm going to say um time frame has changed to uh time frame just like that and just to see this a little bit in action I demonstrate it but I want to see in the console it reacting so I'm going to click one hour you see it says time frame has changed to one hour executes that code time frame is changed to one day command F Type Nvidia symbol is to change to Nvidia as you can see these callback functions are being executed when these widget values are changed and then here I just whenever I request that new data I just get the chart again and I just set a new data frame uh based on whatever your data was fetched from this get data function so in the get data function you see I'm fetching the data converting it to data frame returning that data frame and then setting it on the chart the third example here that I wanted to show you have to dig into the actual documentation here so if you scroll down he has linked to a documentation site which discusses the methods in detail and this isn't on the main GitHub but if you dig in a little bit you'll see that he has these panels here so this create subchart function right and so I'm using create a sub chart right here and so this has a lot of power under the hood if you study the documentation a bit it's a very new library but looks he's doing some really cool work here and so what we're doing is creating a sub chart and he has a little example of doing that here and so he's just getting the same CSV data and plugging it multiple times and so what I did here is instead take our Yahoo finance integration and I'm just going to fetch data the same way so I'm going to do a grid.pi here and I'm going to take this example on the website that I've created here and look at this so all this really is is creating a new chart object but here what we do is we can create multiple subcharts and control their positioning and we're saying each of those sub charts take up a half the height and half the space and that's how we're able to get those four charts all on the same panel we give them unique names and unique watermarks so we can tell which chart is which and then instead of just calling Yahoo finance one time I'm creating four different ticker objects fetching the history for each one so that we have four different data frames and then we do that same manipulation of uh resetting the index and lowercasing the column names you can put all this in a single function I just did it four times for Simplicity here and then we're just setting each one of those four charts with the four different data frames and I actually used the same one twice there so DF df12 3 and 4 and then we can show those so I'm going to run this and you see now I have four different charts each watermarked for Microsoft Apple Google and Nvidia so another example of the power that this library has alright so here's where we get a little fancier people like to see real-time data and so you see what he does with this updating bars from Kik data in real time here he reads a CSV of some initial open high low close values here and then he has a separate file called ticks.csv and what he's doing is iterating oh he's simulating real-time data here by iterating over a CSV file and then implementing a delay with the sleep function here and so he calls chart.update from tick so tick by tick he's looping over a CSV file to emulate real-time data and re-render it right here and so if you look at the example she's provided in example three of tick data you see ticks.csv is just a time and a price and this is very a short time frame so tick by tick each trade each price is here and it's getting he's just looping over for this and with a delay here and so what I want to do is take real real-time Market data realtic data from the market and see if I could integrate it with this chart and so I've done that right here and provided you the source code once again for doing this and so let's talk about how this works so this is static and we'll create another directory for let's call this real time and I'm going to do a tick tock pie right and let me see if this runs right now if I need to add any more packages I don't think I do there you go and so you see it's logging Pender ticker event received and you see there's lots of updates coming in for I believe I'm doing Apple stock right now so you can see there's a bunch of real-time data streaming in right now and if you look at this chart here it fetches some initial data show the initial chart and then this last Candle on the on the back here you can see how this one's actually moving up and down with the prices so you see that says 19304 19303 so short term fluctuations and you can see this is very a short time frame data right there and it renders that red bar and then you see another bars coming in and it's starting and rendering that as well so how does this actually work I'm going to let that keep running same thing we imported IBN sync is what we use to connect with interactive brokers and this isn't a callback function just when this program runs I'm going to connect to interactive brokers right off the bat I'm deciding which stock I want to follow so just Apple stock for Simplicity right and so I create a new contract object since we need to show something on the chart to start with I request historical data here I'm requesting a 3 000 seconds of data and I'm saying the bar size setting I'm saying show me some one minute bars right and so I request historical data and this is going to return me a list of bar objects and that gets returned in bars and so what I do is convert those bars to a pandas data frame calling util.df and now I have a pandas data frame just like I need and then so that'll render my chart and so let me stop that real quick and just stop this there let's leave out all this real time stuff to start so this is how you fetch data and show it on the chart so no real-time Market data let's just show I believe I just did 30 minutes of data there you go it's not moving I fetched it from my workstation and there you go there's the chart now how do I add real-time data to that we've talked about the static data well what I'm going to do is call this function request Market data this is my stock contract up here that I've instantiated so I'm gonna request Market data for that particular stock this number 233 where's that come from well if I jump into the interactive brokers documentation or use my navigation in Python Visual Studio code to jump into IBM sync you'll see should have a list of all the different tick types here so I can request all types of data with interactive brokers so that's one of the big benefits so if I do interactive brokers tick types here you can see those all listed out and then also you can see this request Market data all the different arguments and so you can do 233 here and that'll give you the last price and so that's where that number comes from so I'm requesting Market data and then what I can say is when there's a new tick call a function called on pending ticker and that's my on pending ticker function here and so I'm printing each time a new tick is received I'm printing the word pinning ticker received and so you see that's printed a lot and then what I'm doing is looping through all the ticks it gives me I can convert it to a data frame and I can process it I get the last price uh tick here and I say if I found it then call chart.update from tick with the last price and then I'm rendering it on the chart in real time right here so you see it moving up and down and the reason I call this squeeze function is because this comes back as a data frame this I believe wanted a series object so if I jump into this update from tick it wants a pandas series and so I need to convert a data frame to a series right there so some subscribing to real-time data from interactive brokers processing this tick data and then calling update from a tick on that data and re-rendering that last bar on the chart and the final project I'll walk through is real time or order dot pi and so this one carries some risk because it's subscribed to real-time data you can put in some condition if you want to detect a pattern or however you want to trade I don't want to tell people what to do with their money but I just wanted to show a proof of concept of what you could do and so what this does is subscribes to a minute bar data and what you can do is look at that data frame see if there's certain some sort of pattern or some condition you recognize and you can actually do a callback to Interactive Broker so call place order and do a callback with a fill event and I wanted to do this to show this feature of the library that lets you plot an actual marker so if you look at the lightweight charts example on the GitHub repository here he has this updating bars in real time and again he's simulating real-time Market data right here with two different CSV files with a delay here and so you see this one right here he's saying if the close is above a certain price then he's adding a marker so you see those little markers that little blue text there he's just marking when the price uh crosses above a certain value and so we can do the same thing here and so on the website once again the final example I have is called reacting to minute bars and placing an order and so what I'm going to do here in real time orders let's walk through what this is doing and I'm not going to run this quite yet because I actually have my Live account hooked up right now which is spending real money and so since this carries a lot of risk to run something like this what you can do in interactive brokers you can log in with a real your Live account or you can log in with a paper trading account and the paper trading feature is great because you can just see how this stuff actually works study it get comfortable with it before you actually do something like you can evaluate the risk with simulated money and see how that works right so what this does this version of the program it connects to interactive brokerage once again instantiates a contract object right there request historical data we're already doing that we've already done that and then we play those bars in a data frame and put it on the chart and show that and so let's start at that point again and then iterate and add lines so let's see if this bit works there you go so this is my chart you'll notice how Jagged that is and so I think I'm doing very short-term data here so you see this period only represents five minutes right and so if you look uh at this program let me kill that you'll see when I request the historical data yeah now you can see here my bar size setting when I'm requesting historical data is actually five seconds which is extremely short period of time every five seconds there's another bar uh coming in and this does not mean I think this is a good idea or recommending that it's just because if I'm recording a video a tutorial on uh real-time data and showing these plots in real time I have a short period of time when the Market's open when I can record a video like this and so if I'm demonstrating like some long-term month-long strategy the video will never get done and I'll never be able to show it but in this case every five seconds we can probably assume a certain condition is going to take place and I can actually verify that this ordering functionality works like I expected to so I plug of the historical data start and you'll see I have some callback functions here commented out so let's go to the bottom here and so at the bottom here you see what I'm doing I'm saying request real-time bars so you see here now I have this request real-time bars I give it my contract and I'm specifying a five second bars here so I'm saying each time you get a new bar call this on bar update function so I'm saying bars.update event and I'm adding this on bar update function which is currently commented out so request five second bars call this function every time you get a new one right and so up here you'll see I have the onbar update function and so let me go ahead and uncomment this let's walk through this so on bar update I'm going to print a bars just to show this and I'm going to return real quick right so I just want to show that how this works when these bars come in so I'm rendering that and look at this you'll see a bunch of bars keep coming in right and this list is going to grow because there's going to be a history of each bar that comes in so lots of five second bars are coming in you'll see another one come in you wait a few more seconds should be another one come in there you go more more data is coming in and this list is growing but I can get the last one in Python right since that's a list I can get the last one by using bars negative one so negative indexing I can get the last bar and so I want to take out the details of this bar and convert it to a panda series and so I've taken all these attributes you see how this had a dot open with an underscore I don't know why the underscore is in there but that's why there's an underscore there high low close and so forth I'm creating this series um this Panda series here and I'm updating my chart with the last bar in the series and I'll return so I don't want this code to run down here because that's my order code let's just see if this works and updates the bars with the series so if I run this now you see it has my historical data and you see it's actually updating the chart but we're not processing the data any further we're just using this to visualize the five second bars as they come in right five seconds then three four five should be another one there you go another one comes in and so forth so data comes in renders on the chart okay so now I'm going to take out my last uh return statement and what I mentioned here is that this bar list is getting longer and so let me return here but I want to do is print the length of bars so I'm going to print the length of bars as this comes in and I just want to show you that this list of bars is growing so I grab the initial set historically and then I get a new bar one bar now I have two of them five more seconds pass now I have three of them and so forth so I have all the bars that are added to this chart since it was initially rendered and so what I can do let's say I want the simplest condition saying oh there's three of these green five second bars in a row this is not a good idea but I want to demonstrate that so I'm going to say if I've received three bars already right I can say if the last bar is closed is greater than it's open and the bar before that close is greater than it's open and the bar before that the negative third one with close greater than it's opens I'm going to just say three green bars let's buy right and then I'm just going to say buy one share and so in interactive brokers I can do a market order and specify the number of the of shares to order and I place the order for the contract and there's my details of the order and then I also have the option to pass a callback function saying uh call me back whenever that order actually fills so I call my broker I'm saying hey get me a message and then tell me what price did I get it for after I place the order right and so I'm calling a function called order filled and I have that commented out up here and what I'm doing here is specifying a function called order filled and that will receive some details about the trade and the fill price and so what I'm doing is uh printing that out on the screen here so the details of the trade in the fill and I'm creating a marker on the chart when the order is filled and I'm using an F string to say oh premium marker on the chart and this is the text and write order filled app and I'm accessing the execution price so I do fill.execution dot average price and yeah that's the reason I print these out I don't memorize all of these attributes it's just I have to print them out look at the type see what's available and then I know that I can get the fill price from there and so I just love when I'm trying to figure out how these data structures work I'm just printing printing them as I go and building up this program progressively and so I'm going to run this let's run this code and let's see there's the chart rendered so yeah the Grand Finale real-time data in the actual order placed we've got five second bar data this is my Trader workstation uh it looks like it's going up one more green bar it should place an order I have no control whether this is going to happen or not but let's see wait a few more seconds ah looks like it's flat right now so it didn't hit all right we got this running it looks like we got one little green bar there let's see if we can get a little bit more movement if this will happen here looks like that second one is flat so it didn't trigger so hopefully we get this there's a second one one more come on autofilled there you go it execute the order you see you see it actually logged and if I scroll up here you'll see where that order actually executed happened real fast uh and there's some details about the order that I printed out and you see there's actually a fourth order there and we actually got filled and if you look at my chart here it says order filled at 193 33 was the last one right there and that's dynamic chemically integrated with my broker and this lightweight church library pure python code no trading view no web hooks no Pi script all beautiful python code and real orders right there so very fun exercise and there you have it that is the trading view lightweight charts library in Python you make sexy trading view visualizations of your data not only can you read static data from csvs as shown here we can integrate it with whatever data source we want and even Place uh orders subscribe to real-time data all without leaving our cozy python Visual Studio code environment right there and it's all free code that's available linked below play around with it have fun uh thanks a lot everyone for continuing to watch see you next time bye
Info
Channel: Part Time Larry
Views: 7,582
Rating: undefined out of 5
Keywords: tradingview, python, interactive brokers api, ib_insync, lightweight charts, algotrading, finance, charts, visualization, real-time data
Id: TlhDI3PforA
Channel Id: undefined
Length: 48min 5sec (2885 seconds)
Published: Sun Jul 16 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.