Getting Market Open Price

Hi, I am only a few days into Alpaca and I am trying to get the price of a stock at Market Open with Python. I currently have this strategy which technically does work but it isn’t very lightweight and needs to be run prior to 9:30 to actually get the market open value. I streams the data and just saves the first value it gets:

from alpaca.data.live import StockDataStream

stream = StockDataStream(‘API’, ‘SECRET’)
first_ask_price = None

async def handle_quote(data):
global first_ask_price
if first_ask_price is None:
first_ask_price = data.ask_price
print(f"First received ask price: ${first_ask_price}“)
print(f"Symbol: {data.symbol}, Data: {data}”)

stream.subscribe_quotes(handle_quote, ‘AAPL’)
stream.run()

I am currently using the free version so I know I can’t use historical data as it is too soon. I am also having a hard time finding working Python code in the documentation but I may be looking in the wrong place. There has to be a simpler solution than this right? I would preferably want to be able to run it at any time of the day and get the market open value for that day. Thanks you!

NOTE:
I also see solutions like this but they don’t make sense and I cannot get them to work:
Best way to source open price right after open - #2 by maxks90

I am just coding in a Python file but some people seem to have projects open and I’m confused.

@Russell_Hertel There are several ways to get open prices. However, what is your use case? How long after open do you need the data? Are you wanting to place an order to execute at the ‘open price’?

Part of the reason I put ‘open price’ in quotes is there are several definitions of ‘open’. The prices one typically sees as the day’s open here and on sites like Yahoo are the first non-excluded trade. What is a non-excluded trade? Not all trades are created equal. The biggest reasons trades are excluded from OHLC prices is they are odd lot trades under 100 shares (trade condition I) and/or they are extended hour trades before or after markets are open (trade condition T). There is a description how bars, and open and close values are calculated in this article. However, if one places a Market On Open order (ie a time in force of OPG) then that is executed at the opening auction price on the primary exchange where the stock is listed. Here too, there can be multiple opening auctions on several exchanges so there can be several open prices using this method too. So, within the first several seconds after markets open there can be several ‘open’ prices depending upon your definition. This then goes back to what the use case is and why you need the ‘open’ price.

Now, one has the choice of streaming data or fetching data via a REST API call. Both deliver the exact same data. Streamed data can arrive a bit quicker (perhaps 100ms or so mostly due to network overhead) but the API data has more functionality (eg one can fetch the last trade which already filters for excluded trades and one can get the auction prices). The APIs are also much simpler to get set up and code.

Again, depending upon your use case, one may not always need the open price. Simply submitting a market order before markets open (with extended_hours = False) will generally result in the order filling at the open price. To ensure an order fills at the primary auction open then specify time_in_force = opg.

Unless you subscribe to the paid Algo Trader Plus data plan, you will not be able to fetch any data more current than 15 minutes. You won’t be able to fetch the open price until 15 minutes after the open.

I can provide some code samples, but need a bit more detail what you are doing. And, I would highly suggest not streaming data at least initially.

Thank you for your response. The reason I need the open price is actually quite simple. The strategy I have developed works with percentages and not prices. This has been analyzed for many penny stocks and penny stocks are what I plan on trading. For the sake of automation, the bot will execute trades at prices that will be calculated based on the percentage of that stock from the market open. I plan on getting the market open value and then determining what 50% above that price would be for example and then execute a trade that will buy at the price if it is reached.

Ex:
A stock starts at market open at 0.10 cents. I want to buy into this stock when it is up 50% if it reaches that price but I want to submit the trade earlier in the morning autonomously via a bot say between 9:30 and 9:50. So I run the bot at sometime in the morning, it gets the market open price from that morning, it calculated what price is 50% greater than the market open price and then it would place a Buy Stop Order using that price.

You won’t be able to get open prices before open because they don’t exist yet.

Haha I know that. I may run the bot before open then and it will grab the open price at open. I may run the bot after open and still need to to get the open price. That’s what I meant.

Does anyone know how to get the open price?

@Russell_Hertel Maybe something like this. You will need to wait until at least a few seconds after 9:31 ET (after the first bar is complete and calculated), but it sounded like you may want to wait a bit longer anyway? If you can wait until 9:16 this data can be fetched using the free Basic data plan. Any sooner than 15 minutes and you will need to subscribe to the paid Algo Trader Plus data plan.

!pip install -q alpaca-py

from alpaca.data import StockHistoricalDataClient, TimeFrame
from alpaca.data.requests import StockBarsRequest

import pandas as pd

ALPACA_API_KEY_ID = 'xxxxx'
ALPACA_API_SECRET_KEY = 'xxxxx'

client = StockHistoricalDataClient(api_key=ALPACA_API_KEY_ID, secret_key=ALPACA_API_SECRET_KEY,)

today = pd.Timestamp.utcnow().tz_convert('America/New_York').normalize()
todays_open = today + pd.Timedelta('9:30:00')

symbols = ['SPY', 'IBM']

opening_bar = client.get_stock_bars(StockBarsRequest(
                                  symbol_or_symbols=symbols,
                                  timeframe=TimeFrame.Minute,
                                  start=todays_open,
                                  end=todays_open,
                                  )).df.reset_index('timestamp')

open_prices = opening_bar.open

# you can fetch individual prices like this
ibm_open = open_prices['IBM']
spy_open = open_prices['SPY']

That’s excellent. I really wish Alpaca had a simple one line to get the data but this is a cleaner version of what I had. Just want to clarify one thing. The historical data cannot be read until 15 minutes after it has happened right? So if I want to price at market open I would have to wait until 9:46? I would probably need it faster than that so in this case it would just be better to stream the data and get the ask price from the first trade at 9:30 right?

@Russell_Hertel Historical data is available at the same time as streamed data. There is effectively little difference between streaming data and using the APIs. The decision to stream should generally be based upon how your algo is set up. An event driven algo may work best with streamed data while a process or time driven algo may be more suited to fetching data with the APIs.

The 15 minute delay is a licensing restriction and is imposed on both the historical and streamed data. If one does not have a paid Algo Trader Plus subscription the streamed data is real time (ie not delayed) BUT it is only a subset of trades. Specifically only trades executed on the IEX exchange. That data can be considerably different than full market data. You could stream and get the first trade, but if only using the free Basic data subscription, you would only get the first trade on the IEX exchange and not the full market.

Okay thank you for the response that makes sense