How to Build a Momentum Algorithm Trading Bot in Python w/ Lumibot & Alpaca

Matt Macarty · Beginner ·📅 Project Management ·1y ago

About this lesson

@MattMacarty #lumibot #algotrading #python #momentum #tradingbots **Build a real-time Momentum Trading Algorithm in Python using LumiBot and Alpaca.** In Part 2 of our algorithmic trading series, we move beyond simple "Buy and Hold" strategies to build a dynamic Momentum Bot. Using Nvidia (NVDA) as our target asset, we code an algorithm that monitors price action every 5 seconds to identify and capture intraday momentum. This tutorial covers everything from overriding LumiBot’s life cycle methods to executing live paper trades and backtesting with Polygon data. ### ⏱️ Technical Milestones 0:00 - Introduction & Alpaca Paper Trading Setup 0:02:00 - **LumiBot Life Cycle:** Understanding Initialize vs. On Trading Iteration 0:03:00 - Setting High-Frequency Execution (5-Second Intervals) 0:04:04 - Managing State: Using the `self.vs` Object to Avoid Namespace Pollution 0:05:35 - **The Logic:** Identifying Momentum via Three-Price Comparison 0:07:32 - Risk Management: Cash Checks & Position Limits 0:08:33 - **Execution:** Submitting Market Orders in Python 0:09:32 - Exit Strategies: Implementing Stop-Loss and Take-Profit Thresholds 0:10:53 - Day Trading Logic: Ensuring "Sell All" Before Market Close 0:11:34 - **Backtesting:** Connecting to the Polygon.io Data API 0:12:44 - Real-Time Demo: Watching the Bot Place Trades on Alpaca 0:14:20 - Analyzing Performance: Strategy vs. Benchmark (NVDA) --- ### 🏛️ Implementation Highlights This video bridges the gap between static code and live execution: **1. High-Frequency State Management:** * We implement a list-based data tracker to monitor the last three price points. This allows the bot to "see" momentum in real-time and trigger trades only when a consistent upward trend is established. **2. The `self.vs` Dictionary:** * Learn the professional way to manage strategy-specific variables without shadowing the core `Strategy` class attributes. **3. Integrated Performance Reporting:** * See how LumiBot automatically generates

Full Transcript

this is going to be the second video in my series on using lumot to create an algorithmic trading bot and I'm going to be demonstrating this using a paper trading account from alpaca markets so if you haven't seen my first video already you're probably going to want to take a look at that because in there I talk about setting up this environment and setting up your account with alpaca and some other important things that I'm not going to cover in this video so here we're just going to sort of focus on what's the trading Logic for creating this algorithmic trading bot all right and I should start out by saying that this video was for educational purposes only uh you should not use it for uh trading advice so in this video I just want to focus on the trading logic so I've gone ahead and set up the environment where we're going to have to do some imports right so I'm going to get date time and I'm using that to uh conduct back testing of eventually uh I'm getting a back testing agent from lumot uh I'm getting some parameters from lumot to see whether or not we're going live with this or we're testing it and uh then the the main algorithm is going to be uh inheriting from this strategy class and then to actually Place orders uh we're going to use the trader class okay so down here at the bottom once I write all the logic uh we're going to go through we're going to see if we're back testing and if we are we'll actually do the back test and uh you can see that I'm going to be using Nvidia so I'm going to be trying to capture some momentum in Nvidia and I'm going to do it multiple times throughout a day and uh we're going to see how that compares to just buying Nvidia and holding it all right so then if we're not back testing uh I'm going to set up the parameters to actually start placing trades on uh alpaca and and hopefully we'll be able to actually see this algorithm place a few trades all right so with that we'll go ahead and get started on the code that we're going to write and the first thing I'm going to do is uh create a class and I'm just going to name the class what I would call the algorithm so I'll just call it swing High here and it has to inherit from strategy and then when I inherit from strategy I actually have access to what they call at Lumi wealth the life cycle methods of a trading bot so uh why don't we just take a quick look there at the documentation okay so these are the life cycle methods of that strategy class all right so uh we have defaults for all of these except for on trading iteration so this is basically the meat of your trading algorithm anything that you want to do is going to be contained in there these other methods have defaults and then we can override them or overload them by defining our own code that goes inside these methods all right so I'm going to use a few of them I'm going to use initialize I'm going to use on trading iteration and then I'm going to use before market closes all right so the first thing I'm going to do is set some parameters for our bot and parameters can contain whatever you like generally it's going to contain you know the symbols of things you want to buy maybe some weights for things you want to buy that kind of stuff I'm just going to put a symbol in here and uh the quantity that I'm going to be buying when I go ahead and buy all right next I am going to start working on that initialize method here I'm going to set things like oh the frequency how often do I want the algorithm to run so maybe every day maybe every minute maybe every hour something like that the default is for it to run every day all right so uh I'm going to override that and I want to see this actually in action so I'm going to set the frequency quite High all right so so it's going to run every 5 Seconds all right and then I'm going to Define some variables that I want my algorithm to have access to all right but I don't want to run the potential of polluting the name space with uh variables that o strategy is already using all right so I don't want to Shadow any of the variables and so I am going to Define these with this self. vs object all right it's basically a dictionary inside uh lumot uh for this purpose all right all right and so I'm going to have to keep track of some data and I'm going to be doing that in a list all right so we'll start with an empty list and then I'm going to need to keep track of uh what order number am I on all right and I'll start at zero okay so that's what I'm doing for initialize uh next right we're just going to start writing the logic of the actual algorithm all right and that is going inside of on trading iteration all right so the first thing I'm going to do then is set a symbol to use on each iteration and I'm going to go ahead and get that from that parameters dictionary all right I want to get the last price and I'm going to call it entry price all right I'll pass in the symbol and then I'm going to do some sort of Diagnostics in the terminal so when the thing actually runs live we'll get a few messages printing in the in the terminal and uh we can use this for debugging or sort of confirm what we think is happening is actually happening so the first thing I'm going to do is log a message that shows me any positions I have okay and then I'm going to start adding prices into that data variable that I set up above uh to keep track of okay what is the status am I ready to place a trade or not all right so the basic logic here is going to be that oh I'm going to be trying to catch some momentum so we're going to look at the last three three prices and when the last price there is higher than the previous two uh we're going to place a trade okay so that's the preliminaries and then I'm just going to go into the logic all right and like I said uh we're going to need three prices before we can start to place a trade so I'm going to look at the length of that variable all right and I I want to wait until there's at least four prices in there before I can actually place a trade and then I'm going to create a temporary holding place for just the last three okay once that's done I'm going to start evaluating whether or not a trading condition is is been met so we'll look at the last price in Temp and when that is greater than the second price and then that one is greater than the first price all right so that's the first condition uh and then I want to make sure I still have some money in the account otherwise I'm going to keep trading and go on margin and I want to make sure I don't do that all right so I'm going to go and get my cash and uh I want to make sure that I have enough to buy the 100 Shar so I'm just going to make sure it's at least 20,000 and I'm going to print another log message here just to make sure that once we place a trade that it should have placed a trade so essentially a diagnostic here okay and so now we've met a condition to place an order so I'm going to create an order and I'm going to use that symbol and I'm going to use my quantity and I'm going to have to tell it what side I want buy or sell so I'm just going to go long and then I'm just going to submit that order okay and I will uh increment my order number okay so now now we're in and then we have to start thinking about okay when do we exit so I'm going to I'm going to set some conditions for exiting I'm going to set them pretty tight just so uh when I go ahead and back test we can see this thing working placing buys placing sells all right I don't expect this is going to make any money all right but it'll just give you an idea of oh if I want to do something like this and I want to set my own parameters how will I do that all right and yeah I'm going to be making the code available on GitHub if you don't want to sort of type along as as I'm going all right so what I'm going to do next is since we could go through all right in the next 5 Seconds Place Another buy order and then 5 seconds later Place Another buy order if Nvidia continues to move up uh I'm going to set this first entry when the order number is one I'm going to set that as the entry price for the entire position all right so we're just assuming that we're going to enter on uh whatever that last price what it should be within a few pennies of that all right and okay yes I could place an order that was a limit order and make sure that I'm not buying it higher than that but I'm not going to do that because I want to see this actually Place some trades when I go live all right but yeah it's probably a good idea to set some kind of limit order rather than just a market order like I've done so this is everything we need to do to keep track of uh the orders uh that are long and now we have to start thinking about okay when do we cut our losses and when do we take profit all right so like I said I am going to set these parameters pretty tight so that we can actually see some activity uh when I go to back test this so we'll assume that we have a position right and I'm just going to test it first right so I'm going to use get position all right and this is going to be the cell condition all right so I want a second condition here all right so that condition is going to be the last price all right is uh less than the entry price all right and and we'll we'll allow it to lose say a quarter of a percent and uh this is pretty straightforward we're just going to self. sell all all right so if I had other positions in here besides Nvidia uh this would sell those positions as well all right but since I know I don't then this is fine uh if you're implementing this on multiple symbols you would have to add additional logic to uh to control for that the other thing I need to do there is reset my order number all right and then we can set the profit taking condition we'll get out when uh We've made a 1% all right and this is essentially the entire algorithm and then uh I don't want to be holding positions overnight so I'm going to override one more of those life cycle methods and it's going to be uh before market closes all right and if I want a different default I can set that up in the initialize method here all right but the default is 5 minutes so 355 every day we're just going to go ahead and self sell all all right so this first time through I'm going to try to run it live and we're going to see if I can do all this without making any mistakes uh we'll see if it places an order and then I'll come back and back test it and then the only difference here from the uh first video where I just sort of buy something and hold it for an extended period of time is I'm using a different back testing agent all right so I'm using polygon all right and polygon's a data API I'm using a free account and then there are some limitations to the free account so since I'm doing it very frequently I'm only going to maybe back test for about a week or so anyway that will make the back test run more quickly all right but you know if if you were doing this for a live algorithm I think you would want to probably back test it longer and then you might have to consider a paid account on polygon for that so let me go ahead and set that and let's see it is okay about the middle of well at the end of uh November here for this video and so we'll go back about a week when I go ahead and back test it all right but let's try it live and see what happens all right it is going to have to go ahead and you know wait about 15 seconds before it's possible to start trading all right so we're going to see it running every 5 Seconds hopefully this won't take too long but if it does I'll just fast forward let see if we can get a an order placed all right so you can see that it did actually place an order there and uh I'm going to leave it running here for a minute it bought another one here it looks like maybe we should have uh 3 or 400 shares of Nvidia so I'm going to switch out to alpaca and and see what's going on there all right so there is my position right there as I said it was going to be 300 or 400 and okay looks like we have uh 300 and and so far we've made oh $7 just updated I liked it a second ago before it updated all right so if I sit here long enough it will probably show me another trade placed all right and if I I sort of scroll down here I can see those trades all right and I can get more information about the each order if I need to all right so it looks like the algorithm pretty much does what it's expected to do and okay yes it's actually placing at least paper trades here and let's go and try back testing it to see what happens if I do this for about a week all right so I'm going to kill that and uh I'm going to go into my environment file here and I'm going to change the back testing to true all right and then we'll run it again with a back testing okay so we can see it's getting the data from polygon and uh you can kind of see what's going on here with my balance over this last week all right so it looks like I made a little bit of money here and then once this back test is done we're going to see the a couple of reports right one of them is going to be uh generated by lumot which essentially shows our equity line over this period in the back test and uh the other one is an extensive report from Quant stats which lumot wraps around and and they've customized that somewhat all right so let me get back to the O that's not so good let me get back to the uh lumot report here and so you can see right the green line is my cash and okay so I bought and it looks like I bought a whole bunch there in Rapid succession all right and then uh it looks like you know I sold them at the end of the day so I never met that Clos condition uh throughout the day all right so the the blue line is my strategy's performance and then the red line is Oh what would happen if I bought Nvidia at the beginning of the day sold it at the end of the day for those you know five trading days that are that are seeing here all right so we can see that they're okay yeah they're pretty much uh about the same all right so let's go quickly look at that Quant stats all right and then if I scroll down here far enough I can see oh what what would have happened if I had bought the Nvidia straight up or if I had just used my strategy and and it looks like yeah they perform about the same but if I annualize that right so there's some rounding in there if I annualize this okay this strategy is going to do uh worse than than buying and holding and and yeah keep in mind I only I only tried it for a week it's possible that it would do something different if we uh tested a a longer period of time all right but yeah as I said at the beginning I I don't expect that this strategy would actually work but I wanted to show you the ins and outs of of doing something a little bit more complicated than in the first video where we just bought something and held it all right so I hope that helps and I will follow this up with more algorithmic trading videos

Original Description

@MattMacarty #lumibot #algotrading #python #momentum #tradingbots **Build a real-time Momentum Trading Algorithm in Python using LumiBot and Alpaca.** In Part 2 of our algorithmic trading series, we move beyond simple "Buy and Hold" strategies to build a dynamic Momentum Bot. Using Nvidia (NVDA) as our target asset, we code an algorithm that monitors price action every 5 seconds to identify and capture intraday momentum. This tutorial covers everything from overriding LumiBot’s life cycle methods to executing live paper trades and backtesting with Polygon data. ### ⏱️ Technical Milestones 0:00 - Introduction & Alpaca Paper Trading Setup 0:02:00 - **LumiBot Life Cycle:** Understanding Initialize vs. On Trading Iteration 0:03:00 - Setting High-Frequency Execution (5-Second Intervals) 0:04:04 - Managing State: Using the `self.vs` Object to Avoid Namespace Pollution 0:05:35 - **The Logic:** Identifying Momentum via Three-Price Comparison 0:07:32 - Risk Management: Cash Checks & Position Limits 0:08:33 - **Execution:** Submitting Market Orders in Python 0:09:32 - Exit Strategies: Implementing Stop-Loss and Take-Profit Thresholds 0:10:53 - Day Trading Logic: Ensuring "Sell All" Before Market Close 0:11:34 - **Backtesting:** Connecting to the Polygon.io Data API 0:12:44 - Real-Time Demo: Watching the Bot Place Trades on Alpaca 0:14:20 - Analyzing Performance: Strategy vs. Benchmark (NVDA) --- ### 🏛️ Implementation Highlights This video bridges the gap between static code and live execution: **1. High-Frequency State Management:** * We implement a list-based data tracker to monitor the last three price points. This allows the bot to "see" momentum in real-time and trigger trades only when a consistent upward trend is established. **2. The `self.vs` Dictionary:** * Learn the professional way to manage strategy-specific variables without shadowing the core `Strategy` class attributes. **3. Integrated Performance Reporting:** * See how LumiBot automatically generates
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Related Reads

📰
The Person Who Fixed the Bugs Just Vanished
Learn how to handle a critical situation when a key team member suddenly leaves, taking crucial knowledge with them, and why it matters for project continuity
Dev.to · xulingfeng
📰
Apa Saja yang Dinilai Skema Sertifikasi Project Management BNSP?
Learn about the certification scheme for project management by BNSP and its evaluation criteria
Medium · Data Science
📰
Why Your Team Loses Track of Work (And It's Not a Discipline Problem)
Learn how to identify and address the root causes of lost track of work in your team, beyond discipline problems
Dev.to · SarasG
📰
Wrike Review 2026: Project Management Features, Pricing and Alternatives
Learn about Wrike's project management features, pricing, and alternatives to decide if it's the right tool for your team
Dev.to · Jon

Chapters (12)

Introduction & Alpaca Paper Trading Setup
2:00 **LumiBot Life Cycle:** Understanding Initialize vs. On Trading Iteration
3:00 Setting High-Frequency Execution (5-Second Intervals)
4:04 Managing State: Using the `self.vs` Object to Avoid Namespace Pollution
5:35 **The Logic:** Identifying Momentum via Three-Price Comparison
7:32 Risk Management: Cash Checks & Position Limits
8:33 **Execution:** Submitting Market Orders in Python
9:32 Exit Strategies: Implementing Stop-Loss and Take-Profit Thresholds
10:53 Day Trading Logic: Ensuring "Sell All" Before Market Close
11:34 **Backtesting:** Connecting to the Polygon.io Data API
12:44 Real-Time Demo: Watching the Bot Place Trades on Alpaca
14:20 Analyzing Performance: Strategy vs. Benchmark (NVDA)
Up next
Agile Coach as Mentor
Agile Digest
Watch →