Introduction
Let’s face it, navigating the dynamic world of financial markets demands a well-defined approach, and it’s here where an asset’s last trading price plays a vital role. Whether you are developing a trading bot for options trading or futures trading, adding the asset’s last price is essential as the bot must consider the price movement each second and work dynamically on the strategy it is built upon. Unlike the closing price, which is the final price at the end of the trading session, the asset’s last price fluctuates as trades occur. It shows the current price of a lump sum transaction where a buyer and seller agree to some terms while trading any security or asset. It offers investors a method to gauge the most recent trading value of a security, offering an alternative for those aiming to make quick gains without engaging in continuous trading.
By adding the asset’s last price to your trading bot, you can not only fetch it in real-time till required but can also automate the code execution and use the refreshed value in your strategy. Built using Python, Lumibot allows you to get the asset’s last price in your trading strategies t. Whether it is to fetch an asset’s last price or a set of asset’s last prices, Lumibot lets users fetch through a few simple lines of code in Python.
Let’s find out how you can get an asset’s last price using Lumibot’s last price method.
But before getting into the nitty-gritty, let’s find out why you need an asset’s last price in your trading bot.
Why You Need Asset’s Last Price in Your Trading Bot
Whether you want to implement real-time decision-making functionality in your trading bot or calculate the profit target, adding the Asset’s last price to your trading bot is essential. By adding the asset’s last price to your trading bot, you can not only do a proper risk assessment, but you can also create more profitable strategies.
Read on to find out why you need to add Asset’s Last Price to your trading bot.
- Real-time Decision-making
It goes without saying that real-time data can be essential for traders who have to make informed decisions every hour, especially for traders who want to implement a real-time decision-making feature in their bot. While implementing different strategies in a trading bot, the first and foremost requirement is the asset’s last price. The value also requires updating each second. Many Python trading bot frameworks like Lumibot come with the asset_last_price() method, which, on implementation, updates the asset’s last price variable each hour with the most recent value.
- Market Sentiment
In addition to helping you make real-time decisions, adding the asset’s last price to your trading bot can also help you determine the shifts in market sentiment. Furthermore, sudden increases or decreases convey investor perceptions, which impact buying or selling decisions. On this basis, traders can program trading bots to make buying or selling decisions on their own.
- Analyzing Price Movements
No matter what trading strategy the traders are looking to make, observing the LTP over a period in the trading bot from an investor perspective is essential as it helps analyze price movements and identify trends in the stock’s performance. Knowing an asset’s last price is a must for technical analysis, where traders study historical price data to predict future price movements.
- Execution of Market Orders
The trading bots can be triggered to execute the market order using the asset’s last price. While the market order conveys a clear-cut message to buy or sell the asset immediately at the best available price, the asset’s last price helps the traders figure out the market condition. The market order is generally filled at a price different from the last traded price, but the asset’s last price ideally helps in deciding when to execute the market order.
Steps to Use the get_last_price() Method in Lumibot
Prerequisites
Before adding the main code, you need to ensure the following prerequisites:
Must have Python installed in the system(version 3.10 or above)
Setting Up Lumibot
- Ensure you have Python installed on your PC.
Note 1: Users can download the most recent stable version of Python from here.
Note 2: For the screenshots below, we used Pycharm as an IDE.
Check the Python version using the command: python –version
python -version
2. Once you have downloaded and installed Python, install Lumibot using pip: pip install Lumibot from the terminal.
pip install lumibot
3. After you have installed the Lumibot, import the classes below to run the Python file.
import lumibot
from lumibot.strategies import Strategy
from lumibot.entities import Asset
from lumibot.traders import Trader
from datetime import datetime
4. Finally, create ALPACA_CONFIG with API KEY and API SECRET by logging in or signing up at https://alpaca.markets/.
Steps for Using get_last_price()
Step 1: Add ALPACA_CONFIG Details
To get an asset’s last price using Lumibot, you need to configure a broker.
Note: For this blog, ALPACA has been used as a broker.
To use ALPACA broker API, add the API Key and API secret key as below:
ALPACA_CONFIG = {
"API_KEY": "YOUR_API_KEY_HERE", # Get your API Key from
https://alpaca.markets/
"API_SECRET": "YOUR_SECRET_HERE", # Get your secret from
https://alpaca.markets/
"PAPER":True # Set to False for real money
}
Step 2: Create a GetLastPrice Class
Once you have added ALPACA_CONFIG details, you need to create a GetLastPrice class, which will inherit the Strategy class below.
class GetLastPrice(Strategy):
Step 3: Add Class Parameters
After you have created the GetLastPrice() class, add the class parameters like last_price_symbol and expiry.
parameters = {
"last_price_symbol": "AAPL", # The symbol of the asset to get the last Price
"expiry": datetime(2024, 11, 20), # The expiry date
}
Step 4: Add Initialize Method
Add an initializing method and set the sleep time as per your preference
def initialize(self):
self.sleeptime = "1m"
Step 5: Add on_trading_iteration() Method
Once you have initialized the initialize() method, create the on_trading_iteration() method as below:
- Create the last_price_symbol variable and assign it the value of last_price_symbol, which is the parameter of the GetLastPrice class in self.parameters.
- Create an object of Asset class and set its symbol as last_price_symbol and asset type as stock.
- The GetLastPrice is the Strategy class, which contains the get_last_price(symbol) method. Call the method using self and pass last_price_symbol as a method parameter.
- Finally, using log_message, print the fetched last price for the stock used.
def on_trading_iteration(self):
"""get the last price for an asset"""
last_price_symbol = self.parameters['last_price_symbol']
if self.first_iteration:
asset = Asset(
symbol=last_price_symbol,
asset_type='stock',
)
last_price = self.get_last_price(last_price_symbol)
self.log_message(f'Last Price {last_price} for {last_price_symbol}')
Note 1: Running the Code in the Same File
In Python, if name == “main“: is a conditional statement with which you can control the execution of code based on whether the script should be run directly or you require importing as a module. We can run the code from the same file with the help of the code mentioned below.
if __name__ == "__main__":
Step 6: Import Alpaca and Trader
Once you have created the class and methods as above, import Alpaca and Trader classes into the main method, as below
from lumibot.brokers import Alpaca
from lumibot.traders import Trader
Step 7: Create Trader Class Object
After you have imported Alpaca and trader, create an object of the Trader Class.
trader = Trader()
Step 8: Create an Object of Alpaca Class
Created the object of the Alpaca class by passing the Alpaca_Config list created previously.
broker = Alpaca(ALPACA_CONFIG)
Step 9: Create an Object of GetLastPrice Class
Once you have created the object for the Alpaca class, you need to create an object of the GetLastPrice class by passing the alpaca object (broker) as a parameter to the GetLastPrice class.
strategy = GetLastPrice(broker = broker)
Step 10: Pass the Strategy to Trader Class Object
Using the add_strategy method (), pass the strategy as a parameter, and add the strategy to the object of the Trader() class.
trader.add_strategy(strategy)
Step 11: Execute Strategy for Getting the Last Price of the Asset
Finally, to execute the get_last_prices() method, run the run_all method of the trader class using the trader object
trader.run_all()
Complete Program Code
import lumibot
from lumibot.strategies import Strategy
from lumibot.entities import Asset
from lumibot.traders import Trader
from datetime import datetime
ALPACA_CONFIG = {
"API_KEY": "",
"API_SECRET": "",
"PAPER":True
}
class GetLastPrice(Strategy):
parameters = {
"last_price_symbol":"AAPL", # The symbol of the asset to get the last Price
"expiry": datetime(2024, 11, 20), # The expiry date
}
def initialize(self):
self.sleeptime = "1m"
def on_trading_iteration(self):
"""get the last price for an asset"""
last_price_symbol = self.parameters['last_price_symbol']
if self.first_iteration:
asset = Asset(
symbol=last_price_symbol,
asset_type='stock',
)
last_price = self.get_last_price(last_price_symbol)
self.log_message(f'Last Price {last_price} for {last_price_symbol}')
if __name__ == "__main__":
from lumibot.brokers import Alpaca
from lumibot.traders import Trader
trader = Trader()
broker = Alpaca(ALPACA_CONFIG)
strategy = GetLastPrice(broker = broker)
trader.add_strategy(strategy)
trader.run_all()
Output
Conclusion
With the rapid evolution in technology and the improving accessibility of the financial markets, it has become more important than ever to have an in-depth understanding of the last traded price and its impact on trading decisions. Whether you are building a trading bot for options trading or futures, adding the asset’s last price is important as the bot must look into the price movement each second and operate dynamically on the strategy it is built upon. Are you looking to add an asset’s last price to your trading bot using Lumibot? Developed by expert developers and financial experts at Lumiwealth Lumibot is a trading framework that can help you easily add asset’s last price in even the most complex trading strategies effortlessly. Visit our site now to register for a training course where our expert programmers with ample knowledge in trading will teach you the nitty-gritty of algorithmic trading programming in Python using Lumibot.