Alpaca Market Data API (Part 1) - Streaming with Python and Websockets

Поделиться
HTML-код
  • Опубликовано: 21 май 2024
  • In this video, I show you how to use the new Alpaca Market Data API to stream price data for a list of stocks in real-time over websockets. We first use wscat to demonstrate how to use websockets, then write a Python websocket app to stream data for multiple symbols.
    Source code: github.com/hackingthemarkets/...
    For more tutorials, subscribe to this channel and follow me:
    Buy Me a Coffee: buymeacoffee.com/parttimelarry
    Twitter: / parttimelarry
    Website: hackingthemarkets.com
    Source Code: github.com/hackingthemarkets

Комментарии • 103

  • @parttimelarry
    @parttimelarry  3 года назад +1

    Buy Me a Coffee: buymeacoffee.com/parttimelarry
    Twitter: twitter.com/PartTimeLarry
    Website: hackingthemarkets.com
    Source Code: github.com/hackingthemarkets

    • @kyleyoung4974
      @kyleyoung4974 3 года назад +1

      How have you not introduced your dog on any of your videos! haha

    • @lineage13
      @lineage13 2 года назад

      I can't seem to extract data from this json message. simple things like print(message['data']['p']) just dont work...

    • @lineage13
      @lineage13 2 года назад

      nvm message2 = json.loads(message) this worked!

  • @mschuer100
    @mschuer100 4 года назад +2

    Awesome video. Thanks for sharing. Just started using the new data api with Alpaca. Will hopefully build something this week using it.

  • @kfletcher2005
    @kfletcher2005 3 года назад +1

    This is pretty cool. I got my account, installed python, wscat, etc. and got authenticated pretty quickly. Now just need to make a few bucks.

  • @MrRSBlack13
    @MrRSBlack13 3 года назад +1

    U Da Man Larry! Simple yet AWESOME. I am on my way.

  • @willreisfernandes
    @willreisfernandes 4 года назад

    Amazing work!

  • @smjure
    @smjure 3 года назад +3

    Hey Larry, thanks for another great video, you truly understand the topic and convey it to ppl in simple n awesome way. Would it be possible to do similar for Interactive Broker Python API?

  • @JeJe-gx2pb
    @JeJe-gx2pb 3 года назад +4

    Hi and tx, Ar e you gonna do a tutorial for React Stock-Charts? it seemed promising

  • @arthakalpasan4205
    @arthakalpasan4205 3 года назад +1

    Hey Larry, awesome tutorial. Thanks a ton. Everything works as shown in the video and I am really happy about that. However, how much ever I have tried and searched online, I am unable to figure out how to subscribe to ['trade_updates', 'account_updates']. My intuition tells me that it's available at a different endpoint (something specific to trades). But, that endpoint eludes me how much ever I google or search Alpaca's documentation. Could you please shed some light on how to track order_updates for the orders that are placed with Alpaca? - Thanks

  • @sychikdenis4779
    @sychikdenis4779 3 года назад +1

    you're the best. thx

  • @tonychen4841
    @tonychen4841 3 года назад

    Hi Larry, I am new to websockets. May I ask for websocket stream data, does it include historical data ? For example, if we start the streaming from today, 1hr resolution, and need a TA indicator SMA20 to trigger the buy signal, is the SMA20 calculation is from today or from previous days ? Thanks.

  • @buuusyleung
    @buuusyleung 2 года назад +1

    Thanks very much!

  • @brayseville8468
    @brayseville8468 3 года назад +1

    thank you dude!

  • @VigzMotion
    @VigzMotion 4 года назад +3

    Having an issue in my terminal where the Websocket won't stream or even 'open the connection' until after I terminate the python file execution...

  • @waynefilkins8394
    @waynefilkins8394 4 года назад +2

    I'm looking forward to the next video. One thing i'm wondering about though...how are you going to get the old data to make the charts? The way it is right now it grabs realtime data and so the chart would start when you run the program, so you'll have to have a way of populating the chart with old data, then update it with the new data stream.

    • @sofievw2315
      @sofievw2315 3 месяца назад +1

      You could run a script to store data into a csv and let it run for a few months maybe.

    • @waynefilkins8394
      @waynefilkins8394 3 месяца назад

      Feels like another lifetime that I was using Alpaca and doing algo trading lol. I don't remember much of this, but I'm guessing I probably had to get historical data somewhere else. I think one of the big problems I ran into was when I grabbed historical data from multiple sources, it was inconsistent. This really turned me away from algo trading. Accurate data is probably the most important thing when working with machine learning.. without that you have nothing. @@sofievw2315

  • @jenaman0001
    @jenaman0001 2 года назад

    Hi Larry, simply the best videos for algotrading and lot of information. Do you have the video to show the react stock chart integration for data visualization? If not, request you, to please create one as this will allow to visualize , the Alpaca trades in real time ..
    Thanks ,
    MJ

  • @kyp0717
    @kyp0717 3 года назад +3

    Thanks Larry. This was incredible. It finally helped me understand Alpaca Websocket Stream. Would you be able to do a tutorial using the Asynio package with Alpaca Websocket?

    • @sherifabdelrazek7460
      @sherifabdelrazek7460 3 года назад

      I second Phat's comment!! I've been trying to figure out how to integrate between my standing trading bot that used to use aggregated minute bars to trade with Alpaca Websocket Stream!! Spent the past two days trying to find a good video to explain how the websocket can be running and the rest of the code can run as well! If you could explain that Larry, that would be AWESOME!!

    • @kyp0717
      @kyp0717 3 года назад

      @@sherifabdelrazek7460 There are some sample code that help me get further with asyncio with the alpaca stream. Here is the link github.com/alpacahq/example-scalping.

    • @kyp0717
      @kyp0717 3 года назад

      @@sherifabdelrazek7460 I would love to have a collaboration where we can figure out how to best integrate alpaca stream with asyncio.

  • @ashleykubin8574
    @ashleykubin8574 4 года назад +1

    Love the hat! 😄

  • @cetilly
    @cetilly 3 года назад

    @Part Time Larry Soooo... How is the connection actually closed? Is it implicitly closed when the script is stopped by virtue of passing the "on_close" event handler to the websocket?

  • @licheng4714
    @licheng4714 3 года назад

    Hi Larry, appreciate the work and effort you put in to make these videos. I suck at python and I'm really trying to get better and to code my own trading bot to improve my competitiveness on the job market.
    Quick question: I'm new to VScode and I am not sure if I'm doing things correctly, I copied the alpaca-market-data-streaming-api into my VScode file and I get the error, (ModuleNotFoundError: No module named 'websocket'), do you know how I can solve this problem? I've successfully pip installed websocket-client

  • @sxilent._.crypto8025
    @sxilent._.crypto8025 4 года назад +1

    Thanks bro

  • @NEVBB24
    @NEVBB24 4 года назад +1

    Nice shirt!

  • @mmmar7317
    @mmmar7317 Год назад

    Good tech, thanks

  • @waynefilkins8394
    @waynefilkins8394 4 года назад +2

    oh shit there's no limit if you are just grabbing the minute bars...man this is so perfect

    • @rafaelgomez2519
      @rafaelgomez2519 4 года назад

      how did you set yours up? I copied the code from github, opened a connection, authenticated, received a conformation signal for listening to "T.SPY", but no "stream" was received

  • @jamesjewitt8683
    @jamesjewitt8683 2 года назад

    Is it possible to trade in smaller time intervals such as 1 sec, 5 sec bars using Alpaca's API? I might be wrong, but as far as I can tell the smallest time interval they support is 1 minute bars? Perhaps by connecting TradingView to an Alpaca account, and then paying for TradingView's Premium subscription (which offers 1, 5 sec bars) this can be done?

  • @MajidKC
    @MajidKC 3 года назад

    Does it get most actives? if yes, please show. Thank you

  • @estenyen3492
    @estenyen3492 2 года назад +1

    Hi Larry, great tutorial. To be able to trade based on live stock price you need to extract price as an variable. (If price == xxx -----> execute order)
    How do you recommend doing this?

    • @zikangjiang388
      @zikangjiang388 2 года назад

      im having the same problem, does anyone know how to only get the closing price form the websocket stream?

  • @omarbaruch5328
    @omarbaruch5328 2 года назад

    And how would you do the code if the objective is only to extract the bid and ask price of the moment and storage in a variable?

  • @antoniodejesuscamposrodrig5250
    @antoniodejesuscamposrodrig5250 3 года назад +7

    Works nice! just trying to figure out how to save the streaming into a Pandas DataFrame :D

    • @kyleyoung4974
      @kyleyoung4974 3 года назад +1

      I think in general you need to say.... message2 = json.loads(message) then message2 is in proper (non-json) dictionary format so then you can write each message2's data that you are looking for into a df.

    • @kyleyoung4974
      @kyleyoung4974 3 года назад

      oh you already said this below to someone else.. my bad. enjoy buddy

  • @vimalseshadriraguraman2794
    @vimalseshadriraguraman2794 3 года назад

    @Part Time Larry,
    Hi,
    I am Vimal
    I tried doing the steps u showed in the video.
    I just didn't do the part where u suggested to check the connection on node.js using wscat cuz I dont use node.js, I am trying to run this on anaconda.
    I am getting issues while authenticating on_open function.
    It says:
    [{"ev":"status","status":"auth_timeout","message":"No authentication request received."}]
    Please let me know what to do.

  • @lambolin600
    @lambolin600 2 года назад

    is it possible to scan/filter the whole market data for winners and losers > + 12 % and < - 12 %?

  • @waynefilkins8394
    @waynefilkins8394 4 года назад

    oh shit I didn't know they had that...that'll help with my indicator based bot i'm trying to make :D

  • @T019_hodlz
    @T019_hodlz Год назад

    Hi Larry, do you know if you stream ETHBTC

  • @saltyspades7493
    @saltyspades7493 4 года назад

    Hey Larry, first and foremost, thank you for the videos! They are incredibly helpful and inspiring! Secondly, I am receiving an error when authenticating after connecting to Alpaca. I can't figure out why. Could you give some insight as to how to authenticate it? I followed every step and downloaded all the programs and got wscat running. Thank you!

    • @parttimelarry
      @parttimelarry  4 года назад +1

      Did you get any particular error? Do you have the json headers correct with your API and secret key?

    • @haoxuanxu2709
      @haoxuanxu2709 4 года назад

      @@parttimelarry Hi, Larry. Great video. I think I received a similar error. It says that "your connection is rejected while another connection is open under the same account". I don't know if there is a way to close the connection with this script because when I run it the second time, the problem usually occurs.

  • @Lightnd
    @Lightnd 3 года назад

    Question: does on_message interrupt previous on_message call? If I am doing something computationally expensive in my on_message function, should I start that on a separate thread or will it BLOCK the next incomming message from being processed until it is finished (that is ok with me).

    • @Lightnd
      @Lightnd 3 года назад

      Answer: no it doesn't interrupt the previous on_message call. If there is a blocking computation in on_message, the new call will wait for it to finish.

  • @breadandcheese1880
    @breadandcheese1880 3 года назад +4

    Hey There Larry! First, Thank you so much for the video. Great Info! I am having an issue after i connect to wscat. I did get the connected message and inputted the authentication, however after a 10 to 14 seconds, the connection drops off and i get this message "Disconnected (code: 1006, reason: "")".
    Can you help advise where i the issue most likely stems from? Thank you.

    • @CyborgGaming99
      @CyborgGaming99 3 года назад +2

      Same issue here. Have you managed to fix it?

    • @abhiraj3384
      @abhiraj3384 3 года назад

      Did you guys figure it out? I'm doing this during the weekend, maybe it won't connect unless you are doing this during market hours. I'm not sure tho.

    • @Raviexact
      @Raviexact 2 года назад

      I had same issue, and figured out that, my both keys were in single quotes ' ' , i changed to " ", it worked!!

  • @mrsafarif
    @mrsafarif 2 года назад +1

    Hi Larry, this code doesn’t work anymore. I tried to run it on my Windows machine with Spyder but it always say that the websocket connection is closed.

  • @johnwright6728
    @johnwright6728 3 года назад

    Why are you using Alpaca's socket instead of Polygon's?

  • @Steven-yd8wy
    @Steven-yd8wy 4 года назад

    Ok I fixed it!

  • @shivendrarajawat9517
    @shivendrarajawat9517 3 года назад +1

    Your videos are awesome, keep doing all the good work. Please also provide api to create candle or ohlc from stock stream and save to SQL as some broker api does not provide candle data readily...pls help.

    • @parttimelarry
      @parttimelarry  3 года назад +2

      Planning to do more videos on databases soon, stay tuned.

    • @AlexJaeger716
      @AlexJaeger716 3 года назад

      @@parttimelarry hurry!!!!

  • @hongzhengjin5899
    @hongzhengjin5899 4 года назад +1

    Is there an easy way to incorporate websocket streaming within PyQt? The difficult part is that PyQt already has its own loop events.

    • @parttimelarry
      @parttimelarry  4 года назад +1

      Don't know much about PyQT. Ive been using JavaScript and web UIs. That said, I don't see any reason you couldn't add items to a QT data grid or something when a websocket message is received.

  • @kellygraeve8291
    @kellygraeve8291 4 года назад +1

    how do you store the message in a list or df and compile them instead of just printing each message

    • @antoniodejesuscamposrodrig5250
      @antoniodejesuscamposrodrig5250 3 года назад +1

      apparently you have to convert the variable message into a dictionary, you do that by running json.loads(message)["data"] which is a dictionary containing the data

  • @AngelRivera-mc8zc
    @AngelRivera-mc8zc 3 года назад

    can you create a stock screener with this setup? for example, stocks that rose 3% in the last minute?

    • @jsr7599
      @jsr7599 3 года назад

      look at polygon for data and then look at the snapshot (all tickers) api -- or you can do a websocket with a lot of stocks, I guess.

  • @frederickkiaie8527
    @frederickkiaie8527 2 года назад +1

    Hi Larry! My "streams" is empty whenever I run my code. Alpaca returns this to me: '{"stream":"listening","data":{"streams":[]}}' even though I included the ticker correctly. I also reviewed my code multiple times and it is identical to yours. Any idea why this is happening?

    • @ALumpyA
      @ALumpyA 2 года назад

      I'v got same problem.

  • @frederickkiaie8527
    @frederickkiaie8527 2 года назад

    It looks like none of the streams are available. I keep trying to stream different stocks and none of them are being acknowledged by Alpaca. Is there anything I can do?

  • @waynefilkins8394
    @waynefilkins8394 4 года назад

    I wonder if you can get historical data too? Like vwap of the last 1000 candles? I'm only 11 minutes into video so sorry if that comes later i'll delete this if i remember. I have been looking at backtrader (I think it's called that) for the backtest part...may need to integrate that into this to run indicators on both back-data and live data (like TradingView). I created this huge 1500 line strategy on TradingView and i'm trying to move it over to Python and it's proving to be pretty difficult because I basically have to recreate TradingView's system in python, then translate my pine script strat as well.

    • @waynefilkins8394
      @waynefilkins8394 4 года назад

      before anyone mentions TradingView webhooks, I did that and it works but my strategy needs to run on pretty much ALL stocks (of a few select parameters like specific price range, exchanges,etc. but it amounts to at least several hundred) and so I would have to open every single chart on TV and set an alert and if I ever changed the script i'd have to go in and redo it ALL not to mention even the premium TV package has a pretty small alert limit, like 200 or something IDR. So I must do it all in python unfortunately

    • @waynefilkins8394
      @waynefilkins8394 4 года назад

      Oh shit I think he's getting into that now, fucking love this channel he's doing videos on all the shit I need to do :D

  • @anthonybailous3670
    @anthonybailous3670 4 года назад

    I have a question for you, how would one look at a specific piece of data in the "message"? For example if I only wanted to see the low ("l"), how would I go about doing that? I have tried message["data"]["l"] and that wasn't working for me. Sorry, I am pretty new to Python.

    • @anthonybailous3670
      @anthonybailous3670 4 года назад

      Also love the channel by the way. Your content is very helpful.

    • @anthonybailous3670
      @anthonybailous3670 4 года назад +2

      Nevermind, I figured out that "message" is a string and because of that had to use json.loads to convert into a dictionary.

    • @antoniodejesuscamposrodrig5250
      @antoniodejesuscamposrodrig5250 3 года назад

      @@anthonybailous3670 can you explain where exactly to use json.loads? Do you mean json.loads(message)["data"] or something like that?

    • @anthonybailous3670
      @anthonybailous3670 3 года назад

      Antonio de Jesús Campos Rodríguez Yes! So json.loads converts a string into a dictionary (or in this case a dictionary of dictionaries) so you would json.loads(message) or whatever your variable name is!

    • @antoniodejesuscamposrodrig5250
      @antoniodejesuscamposrodrig5250 3 года назад

      @@anthonybailous3670 Cool! Thank you! Market's already closed so I will try your answer on Monday 😁👍

  • @jwithy
    @jwithy 3 года назад +1

    Doesn't look like anything comes across on the stream during the weekends....what are us weekend warriors supposed to do? ;(

  • @hanialadmaai5596
    @hanialadmaai5596 3 года назад

    Hello, larry how we can get the price of close in less than a minute? like in seconds?

    • @outlaw4016
      @outlaw4016 3 года назад +1

      Hi Hani, pause at 2:00 and read that documenation. Or, see my comment.

  • @AlexeyZubkov
    @AlexeyZubkov 2 года назад

    how to get historical futures data?

  • @prosis-fse4566
    @prosis-fse4566 Год назад

    Hi Larry, I am looking to suspend the alpaca api once my account reaches 2% on the day. Would this series of videos lead me to that functionality? If not which video would lead me down the right path. I am using tradingview to trigger my buy/sell. Thanks in advance.

  • @Lightnd
    @Lightnd 3 года назад

    Do I need wscat for the python bits to run?

    • @parttimelarry
      @parttimelarry  3 года назад

      No wscat was just to show websockets from command line quickly before writing code

  • @akhilsharma2712
    @akhilsharma2712 3 года назад +1

    Anyone else unable to have the on_open or on_message functions ran when you run the program? It only says "closed connection"

    • @jsr7599
      @jsr7599 3 года назад +1

      Figured it out!
      Some sort of SSL certification error. Try this:
      cd /Applications/Python\ 3.7/
      ./Install\ Certificates.command
      And make sure you change 3.7 to whatever python version you have there.

    • @aureliomollo1495
      @aureliomollo1495 3 года назад

      @@jsr7599 🙏

    • @joshmckee8022
      @joshmckee8022 2 года назад

      @@jsr7599 solution for windows? I know that works for mac

  • @antoninodanselmo7212
    @antoninodanselmo7212 2 года назад

    why m I getting a bloody ssl certificate error....from local on windows and python 3.7 ?!? anyway thanks Larry you are doing a great thing

  • @Steven-yd8wy
    @Steven-yd8wy 4 года назад

    I tried this process for trade_updates, but it didn't work... hmm weird :/. Any ideas?

    • @Steven-yd8wy
      @Steven-yd8wy 4 года назад

      < {"stream":"listening","data":{"error":"you have provided an invalid symbol polyfeed/account_updates"}} got this error. > {"action": "listen", "data": { "streams": ["trade_updates"] }} this is what i sent after authenticating successfully

  • @outlaw4016
    @outlaw4016 3 года назад

    If anyone is wondering how to second by second data, pause at 2:00. You must decipher between T, Q, and AM in your listen message. You will only be able to get the price at which that stock is trading second by second, since the smallest time frame for a candle is one minute.

    • @kyleyoung4974
      @kyleyoung4974 3 года назад

      That is not a very good explanation. Can you elaborate? You mean if you want to get second by second data you should be using Trades or Quotes?? or are you saying there is a way to calibrate the AM (I assume this stands for aggregated Minutes) and instead of getting minute data instead get second by second data?

    • @outlaw4016
      @outlaw4016 3 года назад

      @@kyleyoung4974 there is no way to get candle data second by second I am assuming from alapca/polygon. As there is no real 'close' price until that minute marker is up.
      You can get bid/ask prices second by second which are found under the Q endpoint. Pause at 2:00 any on go to that url, it should further explain

    • @kyleyoung4974
      @kyleyoung4974 3 года назад

      ​@@outlaw4016 Yes i've read that whole url and that's exactly what my takeaway was as well. Thanks for confirming!!

  • @andrewswenson5105
    @andrewswenson5105 2 года назад

    How do you stop listening to the alpaca feed?

  • @kytefamily6
    @kytefamily6 Год назад

    Right?!