Trading Stocks with Google Cloud Functions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey welcome back today i'm going to be talking about google cloud functions so this is a service provided by google that lets me write a function in my language of choice whether that language is node.js python rubyjava.net and it lets me write that function and put it up in google cloud not only that it is serverless which means i don't need to ssh into a server like i did in my last linux video i just have this code that runs in the cloud and i don't really have to do a lot of management it just i can trust it to execute whenever i run it and one nice thing about google cloud functions as you can see here on the pricing page is it's really cheap you can actually invoke this it looks like you can invoke it millions of times for absolutely free so you don't need to even pay five dollars a month so if you just have a simple use case where you need to write a function that runs over and over again whether it's for uh like a discord bot or a slack bot or um a trading view web hook for instance this seems like a pretty good solution and it's very similar to aws lambda functions which i talked about in my trading view web hook video where i used a framework called aws chalice so uh today i'm going to talk about how to write one of these google cloud functions i'm going to make a very basic google cloud function that buys and sells stock and i'm just going to use alpaca since it's an easy api we can use to buy and sell stock and it's free to sign up and but i'll also write some other functions in the next videos uh to trade uh using other exchanges and brokers so i'll probably write a function for binance maybe coinbase ftx and uh trade year some of the other brokerage brokerages that i like to use so um yeah let's go ahead and get started with uh exploring google cloud functions and seeing how to write them and so with google cloud functions uh you click and you can go to the console here so i'm at cloud.google.com and i have a google cloud account and i have a couple projects in it i use this for my newsletter trading bot that i wrote in the last video and so i'm going to create a new project here and so the first thing you need to do is create a new project so i'm going to call it uh trading functions and that'll just be the name of my project and i can click create okay and that will go ahead and start initializing a project and the next thing i'm going to do is google cloud functions allows you to actually write some functions in the browser but what i'm going to do is use this functions framework so google cloud platform has something called the functions framework and this lets me test my google cloud functions locally on my desktop so we can develop it there similar to how we we would develop a flask or basic python web application we can run it locally test it out locally and then we can deploy it to the cloud so i'm going to click this functions framework here i'm going to scroll down and since i'm interested in python notice that it supports several languages we do python typically on this channel and i'm going to go to the functions framework for python and we're just going to go ahead and set this up so you can see all you need to do is write a simple python function and it will get a parameter or an input called the request and that request can have a message so like a json message that you post to this function that way you can send it different data and then you just need to return a response so you just need to do whatever you want inside the function and then return a response to the client that invoked the function and so let's figure out how to use this real quick so this says just we need to install the functions framework so i'm going to go to a new visual studio code editor so i'm going to open a new window here and we're going to start a fresh project and write a google cloud function to buy and sell stock and then i'm going to deploy it to google cloud so i'm going to create a new folder and i'm going to call it google cloud cloud functions alpaca and we'll create several iterations of this using other brokers okay so i have a new folder here and then it says all i need to do is create a file called main.pi so it says create a file called main.pi and i'll do that and then it says just put a basic python function inside so i'm going to put a function called hello world just like that and i'm going to try to run this okay so that doesn't do anything just running it but what i need to do is set up this function framework so i use pip to install that so the python package manager and so i have my environment here and so in this terminal in whatever terminal you use i'm going to install functions framework using pip and that'll install the functions framework once i have that framework set up what i can do is run the function so if you look here you see you just need to run the functions framework command and you give it a target of the function that you're executing okay so i'm going to take this and run functions framework dash dash target equals and since my function is named hello i'm going to type hello okay and what that's going to do is run this function locally on a server and so you can't see what's happening here so i'm going to stop that real quick and i'm going to do dash desk debug so if you look here it it has dash dash debug and that'll let you actually see what's happening so it'll write a log to your screen so you'll see what's actually happening and it'll also reload the program every time you make a change so i'm going to do target hello so i'm going to do target hello and i'm going to do dash dash debug okay so let's run it like that so you'll notice in the console now i'm running a local server at my local host and it's at port 8080 and so if i go to my browser and go to localhost 8080 you'll see i get hello world right there so i'll get hello world because that's what's returned from that function and so now let's go ahead and just return we can return a dictionary and it'll automatically convert it to json so i'll do a code success okay so we'll just return a success code if i run that you see i get a little response it says code success so very handy so now instead of calling this hello let's call it something else so i'm going to call it a trade stock and we're just going to modify this function until it actually trades stock and then we're going to deploy that to the cloud okay so you see that stock because i changed the name of the function and now i'm going to call the target trade stock and run it like that and you see that it still works so now let's put some code inside to actually trade stock so i'm going to go to alpaca so i have alpaca here sign up for an account if you don't have one already if you want to follow along and i'm going to create an api key real quick so i'm going to create a new one for my paper trading account i'm going to get this url here so we're going to use paper trading and i'm going to get my alpaca api key and secret key so let's review how to make a trade using the alpaca api if i search for alpaca trade api python you get this little library here and all we need to do is pip install alpaca trade api so i'm going to get that right there so i'll do a pip install i'll pack a trade api and i'll get the trade api package right there and then once that's done i just need to make a new instance of the trade api rest client so you see they import alpaca trade api as trade api so i'll do that so at the top here i'll import uh alpaca trade api as trade api so now that i've imported the trade api here i can just create a new instance of it so i'm going to do api equals a trade api.rest so there's this object i can instantiate and i need to pass it my api key my secret key and the base url and so i have these already so i will just i'm going to assign assign these to variables real quick so i'll call that base url i'll call this api key and i'll call this a secret key okay and then i will pass those in as three parameters that api key secret key and base url and once that's done i have an instance of the alpaca trade api and i can do api dot and then i have a function called submit order okay and this accepts a number of parameters so i need a symbol a quantity aside so i'm going to do a symbol let's just do apple quantity of 8 shares aside we can do buy and then we can do we need a type and a time in force so the type can be market or limit so i'll just do market and then the time and force i'll do gtc for good till cancelled and i know i'm going through this kind of fast because i've used alpaca so many times uh on this channel and so i'm going to store the result of this call to submit order in a variable called order and let's just see what happens so i'll print order to the screen here and let's see let's rerun our functions framework so i'm going to do functions framework target is trade stock since that's the name of the function and i'll keep debugging okay so let's see what happens if i submit the url does this work so i'm going to hit my localhost url and it didn't throw an error so maybe it did work so i'm going to look in here i printed the order object and you see i indeed submitted an order and if i go to the alpaca console here you should be able to see let's see if i ordered some stock so i'm going to check it down here and you see i have a market buy for apple stock for eight shares that was accepted which is great so uh we successfully submitted an order from a google cloud function albeit it's one that i'm running locally on my machine i haven't deployed it to the cloud yet okay um so um not quite happy with this function yet what's the limitation of it right uh you can see i've hard-coded apple in there i've hard-coded eight shares and that it's a buy at market and so forth right and so um how do i actually send it a different parameters so let's say if i want to buy microsoft stock i still want to use the same function here so what i'll do here is this this request input allows me to control the input that comes into that function and then i can use those inputs as inputs to the submit order function okay so let's look at the google google cloud function uh documentation real quick and so if i look at google cloud functions and how they look in python and let's just see the quick example that they show us here so you see in their quick start example they show request json equals request dot get json so so i can actually submit a json message or a json payload to this function and then parse out those values into a python dictionary and then we can process that request and so what i'm going to do is take this request.getjson right and so for our request we can say i'm going to call this data data equals request.getjson and so i'm going to post some type of request and get that data here okay and i'll print that data just to show what it looks like and so to test this locally i'm going to use insomnia which is a rest client or an api client that i've used previously on this channel and i used it in a very recent video so if you look up insomnia rest client there's this free easy to use graphical client where you can test api requests okay so i've downloaded that and used it and it's free and so i'm running this locally on my machine and it looks like this when you start it up and what i can do is do create and then create a request collection and i'm going to call this test google cloud functions okay and i'm going to test out this google cloud function by creating a new request i'm going to hit that plus i'm going to go to new request and then a trade stock function okay so i'm going to do a trade stock function test and i'm going to do a post request because i'm posting data to the function and i'm going to pick a type of json so i'm posting a json body to this url and so the url that i'm posting to is localhost 8080 okay so i'm going to post a localhost 8080 and now let's let's format some json so i'm going to put some data it's the key and then some value is the value and if i send this i still get my success response on the right side and then if i look in my console here at my function you can see it submitted another order and you can see where i printed some data and some value right so that worked pretty well so i'm able to get data from an http request that i submitted and so now let's go ahead and make our own data format that lets us adjust these parameters so instead of apple right here i'm going to do data and i'll call it symbol and then i'll call it a data quantity and i'll do a data side and i'll do data order type and then i'll do data what is that time in force okay and so for my data here i'm going to format this in such a way that i use all those keys so symbol quantity side order type quantity and then i'll put like three there side is by and then the order type and let's just do market so quotes market and then the time in force i'm going to do good till cancelled right and then my symbol i'll do let's do nvidia okay so i'm gonna do three shares of nvidia and let's see if i can dynamically send in a request and have it make the order so i'm going to click that it still says success which is good and if i check my alpaca console and look at my order history let me see if i can refresh you see that i have this market buy order for nvidia stock and then i could also modify this again and do netflix right and let's do a cell so i'll do sell 10 shares from netflix which i don't have template shares of netflix so i'm going to click that and now i triggered an error and you see it says api error invalid side and so i need to do it with lowercase okay so i'm going to click that and it says success so i submitted an order for netflix and it looks like i did have 10 shares of netflix so that didn't cause an error and so i'm going to submit to sell 100 shares of netflix and then that gave me an error uh insufficient quantity available for the order and you see how it dumped this really ugly debugging error um usually i'm going to be requesting this endpoint from a mobile app or a web application right and so i need this data this error message returned in a useful format that's easy to parse and so instead of just dumping this stack trace on the screen we need to handle this error and so i'm going to do a try catch so i'm going to catch this exception so i'm going to try and then i'm going to do accept exception as e and then let's go ahead and return some type of error so instead of returning code success if there's any exceptions we're going to turn return a code of error and then we can return some type of message of what that error is so i'm going to do uh i'm going to convert that exception to a string and let's see what that does so i'm going to run that and i'm going to submit this again and now you see we have this nice json response that says error insufficient quantity available for order and then now we know what the message it we know what the error message is and then whatever client we use to call our api we can format this this error message in a nice way for the end user right so we'll display it in red or something and display it in a clean way where it's easy for the user to understand uh what they did wrong and then likewise we're just returning a generic success message here but what i want to do since i have this order object returned what i want to do is maybe we want to store the order id so since it returns an id here i will return an order id and that's order.id and i'll also return the status so i'll do order we have this order.status okay and so maybe if we're making some bot or trading system we want to return the order id and the status so that we can check it later later and so maybe we want to store this order id in a database or maybe we want to check on the uh filled price for the order and so a lot of this information is useful um so right now i'm just going to return this basic information and let me see if i can do another buy so i'm going to buy some some uh att stock so i'll submit that you see i have an order id and that was accepted and then you see i have my market by order of att so that's great we have this nice function working already and we're sending it json data and getting a nice json response so how do i make this even better what else do i want to do to this so one thing i want to do here is i don't like my api key and a secret key living in the main program here so i'm going to create a file i usually create a config.pi file or store these keys somewhere else and so what i'll do is take these out i'm going to copy those into config.pi okay and then i'm going to import config and then now instead of just api key i'll do config.api key config.secretkey and config.baseurl and that just makes my program a little bit cleaner okay and then uh the last thing i'll do i don't want people just uh invoking this function with no there's no protection here right anyone that has this url that has access can execute this url and post this and order make orders and so i'm just going to put a simple way of authenticating this now and maybe we'll add a more complex authentication layer uh we'll look up what google provides for this so if they provide some type of uh api key or other way of authenticating these requests for now i'll just use like some secret string i come up with so i'm going to make a a passphrase and we'll call that secret phrase one two three and then inside of my main function what we can do is require uh the user to pass in some type of passphrase in the request here and if they don't have that then they don't have permission so we'll have the secret passphrase that's required so you see where we get the request json here what i'll do is see if the key passphrase is in the data and no i'll say if a passphrase is not in data so if they didn't provide a passphrase or the data's passphrase does not equal myconfig.passphrase right so if they didn't pass the passphrase or they did pass the passphrase and it's not the one in my config file then i'm going to return an error and so i'll return a dictionary that says code error and then i'll say a message you are unauthorized right and technically technically we could return a forbidden like an http http response of 403 which means http forbidden uh status code i'm just going to return a json message like this for now and so i'm going to submit that now and you see now since i didn't pass a passphrase i'm unauthorized so i can add a passphrase into my json here and so i'll do abc123 i submit it i'm still unauthorized but if i know the secret passphrase secret phrase one two three so i'll do secret phrase one two three then it actually executes the order so now i've created this nice function here we have a config file with our our keys and our passphrase and we're able to make different orders depending on how the request is submitted so pretty happy with that so let's see if we can deploy this to the cloud now so i'm going to go back to my google cloud here and so you'll remember earlier i created that a project called trading functions and so the first thing i need to do here there's one step is i need to look for build api in the search box and there's this cloud build api and so in order to deploy these functions to google cloud i need to enable this cloud build api and once that's done i'll actually be able to go to google cloud functions and deploy them so now i can go down here i'm going to scroll down to cloud functions just like this and it says google cloud functions is getting ready and so um note i believe this functions framework lets you deploy from the command line so i should be able to type some special command like uh gcloud deploy or something like that to uh deploy this google cloud function right but that requires installing extra stuff i'll do that in a follow-up video so what i'm going to do is just use the user interface now that i've tested this locally and so i'm going to go to my cloud functions i'm going to click create function there and i'll call this uh alpaca trades so i'll call it alpaca trade as my function name i'm i'm deploying this to the u.s central region i can click and select other regions i'm going to trigger it with an http request so a web request and i'm going to say allow unauthenticated invocations i'm just going to use my passphrase authentication for now technically i can use google cloud's identity access management service but i haven't studied that yet i'll talk about that when i when i learn more about it and i'm going to say require https so i'm going to require a secure connection in order to make this post request i'm going to click save here and i'm going to go to next and then this gives me a little editor for my google cloud function so technically i didn't have to edit that function locally i i could have just written it right in here but it's kind of hard to write your code inside of a web form so i wrote it locally first and then i can just put the code in here so by default it shows this node.js version so if you're interested in writing in javascript you could use this one but i'm going to do python and you can select any version these are all fine i'll just do 3.8 and i have a main dot pi here and then locally we developed a main dot pi already so i'm just going to copy this right in and see if it works so i have that and then i can click plus and i'll just create my config pi right here okay and let's see if we can take that and we'll throw this into google cloud so just like that and then my requirements.txt this is where i put any dependencies so locally i installed alpaca trade api but google cloud doesn't have a copy of that so we need to put our list of dependencies in right and so since i installed google alpaca trade api i need to put that here as a in my list and so if i installed you know pandas ta or any of these other libraries i just put all those listed in this requirements text file but we only have one dependency for this particular program so i put alpaca trade api in requirements text i put my keys in my config.pi and then i have my main code in my main.pi and yeah let's go ahead and click deploy and actually i've already noticed one thing i did wrong it has entry point by default is hello world but my function is called trade stock so i expect this deployment is probably going to fail and so that's fine though because that gives us a chance to talk about the log files and how to check if things go wrong so you see it's trying to deploy it right now and if i click on the name of the function there um you can see there's this tab called logs uh you can see a lot of metrics here on the function so you can see as soon as we get this deployed if you want to monitor this function right let's so let's say we're using this as a trading view web hook or you we have a web app web application or mobile application that's using this cloud function we want to see and be able to monitor the users that are using this function and see if anything's going wrong we want to see if you know maybe it's using a lot of memory or this is being accessed too frequently maybe we want to make some adjustments to the runtime environment okay i can also click around and see some details so maybe we want to allocate more memory based on some of these metrics right we can see the source code obviously and it looks like you can create some environment variables here so now i'm thinking it's probably the best practice to create some environment variables here for those api keys so that's something i'll try later as well so uh i'm just learning this as i go and just showing you what i learn as i go so um i'm just doing this very iteratively and then i'll keep following up with videos to as i find out better and better practices here so we can probably define some environment variables for these uh config values that i put in such as the passphrase and the api key so that's something i'll look into as well and this is the web address where i can invoke the function so since i'm no longer using localhost in insomnia it looks like i can just use this web address right here and then in my insomnia when i want to test it i'm going to go to https and this is the address to my cloud function and hopefully whenever i hit this endpoint it's going to make trades exactly the same way when it's running in the cloud looks like there are some permissions that i can control here so i'll see if i can figure out more information about that and then here are my logs and so now i'm in my logs and you can see it failed to deploy and i look at my logs and i can see uh main.pi is expected to contain a function named hello world so i didn't call the function hello world so i'm going to go back here to my entry point so let's see in my source let's see if i can edit this entry point real quick i'm going to click edit and i'm going to go to next and instead of hello world i'm going to do trade stock as my entry point and then i'll try to redeploy this and see if it works so i'm going to go back to my logs here so i'm going to click on the function name i'll go to logs and let's see if this thing will actually deploy and so while that's running i'm going to have a drink here by the way i'm having been trying these cocktails in a can lately so that's one called salt point can you see that yeah so you can get like a high ball you can get like anything you can get a margarita a margarita in a can you can get like a rum and coke in a can now so it's kind of crazy the the food and drink technology these days that you can just get that this in a can bring it to the park and have a drink so uh been enjoying trying out these different uh hard selters and they've also been a great investment uh lately like there's a sam adams stock right so if you check out sam adams stock uh you know this thing really ran right from 300 to like 1200 a share and that's because i think they own a hard seltzer what do they own they don't own white claw they own a truly hard seltzer and so yeah this has been kind of a hot thing everyone's into these heart seltzers these days but anyway i've been trying some of them and they've been pretty good i try this one called cut water that's pretty good as well and so look at that i have a green check mark now and it says version 2 is deployed so i think this thing might be in the cloud now so let's check it out i copied the url i copied the trigger url already right so that's it and then i put this in my post here and let's try something so i'm going to order some tesla here and i'm going to do 50 shares and click buy and let's see if this goes and it says it accepted and if i go to alpaca here you see let's see what went down let's see if i can refresh it and go to my orders and there's a tesla market buy for 50 shares and we have deployed a google cloud function that buys and sells stocks which is great and now we can really build upon this and use google cloud functions more it seems pretty easy to use and let me see if i can update my trading view strategy alert web hooks videos so maybe i'll make one of those that executes this cloud function and i'll also see in the next video if i can run a google cloud function on a schedule so maybe we'll have a google cloud function that grabs data on a schedule and then applies an indicator and makes buys and sells and so maybe we can have our entire trading system living in these google cloud functions so excited to explore this a little bit more and see what else is possible but for now i just wanted to show a simple example of how to create a google cloud function locally test it and deploy it to the cloud so hope you like this video and i'll see you in the next one
Info
Channel: Part Time Larry
Views: 6,080
Rating: 4.9732442 out of 5
Keywords: google cloud functions, tutorial, python, trading api, alpaca, stock trading
Id: j1_lqxsdJ8E
Channel Id: undefined
Length: 31min 5sec (1865 seconds)
Published: Wed May 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.