Real-time Stock Data

This API provides market data on a websocket stream. This helps receive the most up to date market information that could help your trading strategy to act upon certain market movements. If you wish to access the latest pricing data, using the stream provides much better accuracy and performance than polling the latest historical endpoints.

Once a connection is established and you have successfully authenticated yourself you can subscribe to a number of channels including trades, quotes and minute bars for a particular symbol or multiple symbols.

Connection

URL

To access real-time data use the URL below, substituting **iex** or **sip** to {source} depending on your subscription.

wss://stream.data.alpaca.markets/v2/{source}

Sandbox URL:

wss://stream.data.sandbox.alpaca.markets/v2/{source}

Any attempt to access a data source not available for your subscription will result in an error during authentication.

Message format

Every message you receive from the server will be in the format:

[{"T": "{message_type}", {contents}},...]

Control messages (i.e. where T is error, success or subscription) always arrive in arrays of size one to make their processing easier.

Data points however may arrive in arrays that have a length that is greater than one. This is to facilitate clients whose connection is not fast enough to handle data points sent one by one. Our server buffers the outgoing messages but slow clients may get disconnected if their buffer becomes full.

Encoding and Compression

Messages over the websocket are in encoded as clear text.

To reduce bandwidth requirements we have implemented compression as per RFC-7692. Our SDKs handle this for you so in most cases you won’t have to implement anything yourself.

Communication Flow

The communication can be thought of as two separate phases: establishment and receiving data.

Establishment

To establish the connection first you will need to connect to our server using the URL above.

Upon successfully connecting, you will receive the welcome message:

[{"T":"success","msg":"connected"}]

Now you will need to authenticate yourself using your credentials by sending the following message:

{"action": "auth", "key": "{KEY_ID}", "secret": "{SECRET}"}

Alternatively, you can use the same headers as when accessing the historical endpoints:

websocat wss://stream.data.alpaca.markets/v2/sip  
  -H="APCA-API-KEY-ID: {KEY_ID}" -H="APCA-API-SECRET-KEY: {SECRET}"

Please note that each account can have up to one concurrent websocket connection. Subsequent attempts to connect are rejected.

If you provided correct credentials you will receive another success message:

[{"T":"success","msg":"authenticated"}]

Receiving data

Congratulations, you are ready to receive real-time market data!

You can send one or more subscription messages (described below) and after confirmation you will receive the corresponding market data.

At any time you can subscribe to or unsubscribe from symbols. Please note that due to the internal buffering mentioned above for a short while you may receive data points for symbols you have recently unsubscribed from.

Client-to-Server

Authentication

After connecting you will have to authenticate as described above (unless you provided authentication headers):

{"action":"auth","key":"CK********\*\*********","secret":"****************\*\*\*****************"}

Subscribe

You can subscribe to the following channels:

  • trades (includes corrections and cancelErrors)
  • quotes
  • bars
  • dailyBars
  • updatedBars
  • statuses
  • lulds

You can subscribe to a particular symbol or to every symbol using the * wildcard. A subscribe message should contain what subscription you want to add to your current subscriptions in your session so you don’t have to send what you’re already subscribed to.

{"action":"subscribe","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"]}

Unsubscribe

Much like subscribe you can also send an unsubscribe message that subtracts the list of subscriptions specified from your current set of subscriptions.

{"action":"unsubscribe","trades":["VOO"],"quotes":["IBM"]}

Server to Client

Control Messages

You may receive the following control messages during your session.

MessageDescription
[{"T":"success","msg":"connected"}]This means you have successfully connected to our server.
[{"T":"success","msg":"authenticated"}]You means you have successfully authenticated.

Errors

You may receive an error during your session. Below are all the errors you may run into.

Error MessageDescription
[{"T":"error","code":400,"msg":"invalid syntax"}]The message you sent to the server did not follow the specification
[{"T":"error","code":401,"msg":"not authenticated" }]You have attempted to subscribe or unsubscribe before authentication.
[{"T":"error","code":402,"msg":"auth failed"}]You have provided invalid authentication credentials.
[{"T":"error","code":403,"msg":"already authenticated"}]You have already successfully authenticated during your current session.
[{"T":"error","code":404,"msg":"auth timeout"}]You failed to successfully authenticate after connecting. You have a few seconds to authenticate after connecting.
[{"T":"error","code":405,"msg":"symbol limit exceeded"}]The symbol subscription request you sent would put you over the limit set by your subscription package. If this happens your symbol subscriptions are the same as they were before you sent the request that failed.
[{"T":"error","code":406,"msg":"connection limit exceeded"}]You already have an ongoing authenticated session.
[{"T":"error","code":407,"msg":"slow client"}]You may receive this if you are too slow to process the messages sent by the server. Please note that this is not guaranteed to arrive before you are disconnected to avoid keeping slow connections active forever.
[{"T":"error","code":408,"msg":"v2 not enabled"}]The account does not have access to Data v2.
[{"T":"error","code":409,"msg":"insufficient subscription"}]You have attempted to access a data source not available in your subscription package.
[{"T":"error","code":500,"msg":"internal error"}]An unexpected error occurred on our end. Please let us know if this happens.

Subscription Confirmation

After subscribing or unsubscribing you will receive a message that describes your current list of subscriptions.

[{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"],"updatedBars":[],"dailyBars":["VOO"],"statuses":["*"],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}]

You will always receive your entire list of subscriptions, as illustrated by the sample communication excerpt below:

> {"action": "subscribe", "trades": ["AAPL"], "quotes": ["AMD", "CLDR"], "bars": ["*"]}
< [{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"],"updatedBars":[],"dailyBars":[],"statuses":[],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}]
> {"action": "unsubscribe", "bars": ["*"]}
< [{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":[],"updatedBars":[],"dailyBars":[],"statuses":[],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}]

Data Point Schemas

Multiple data points may arrive in each message received from the server. These data points have the following formats, depending on their type.

Trades

Schema

AttributeTypeNotes
Tstringmessage type, always “t”
Sstringsymbol
iinttrade ID
xstringexchange code where the trade occurred
pnumbertrade price
sinttrade size
carraytrade condition
tstringRFC-3339 formatted timestamp with nanosecond precision
zstringtape

Example

{
  "T": "t",
  "i": 96921,
  "S": "AAPL",
  "x": "D",
  "p": 126.55,
  "s": 1,
  "t": "2021-02-22T15:51:44.208Z",
  "c": ["@", "I"],
  "z": "C"
}

Quotes

Schema

AttributeTypeNotes
Tstringmessage type, always “q”
Sstringsymbol
axstringask exchange code
apnumberask price
asintask size
bxstringbid exchange code
bpnumberbid price
bsintbid size
sinttrade size
carrayquote condition
tstringRFC-3339 formatted timestamp with nanosecond precision
zstringtape

Example

{
  "T": "q",
  "S": "AMD",
  "bx": "U",
  "bp": 87.66,
  "bs": 1,
  "ax": "Q",
  "ap": 87.68,
  "as": 4,
  "t": "2021-02-22T15:51:45.335689322Z",
  "c": ["R"],
  "z": "C"
}

Bars

There are three separate channels where you can stream trade aggregates (bars).

Minute Bars (bars)

Minute bars are emitted right after each minute mark. They contain the trades from the previous minute. Trades from pre-market and aftermarket are also aggregated and sent out on the bars channel.

Daily Bars (dailyBars)

Daily bars are emitted right after each minute mark after the market opens. The daily bars contain all trades until the time they were emitted.

Updated Bars (updatedBars)

Updated bars are emitted after each half-minute mark if a “late” trade arrived after the previous minute mark. For example if a trade with a timestamp of 16:49:59.998 arrived right after 16:50:00, just after 16:50:30 an updated bar with t set to 16:49:00 will be sent containing that trade, possibly updating the previous bar’s closing price and volume.

Schema

AttributeTypeDescription
Tstringmessage type: “b”, “d” or “u”
Sstringsymbol
onumberopen price
hnumberhigh price
lnumberlow price
cnumberclose price
vintvolume
tstringRFC-3339 formatted timestamp

Example

{
  "T": "b",
  "S": "SPY",
  "o": 388.985,
  "h": 389.13,
  "l": 388.975,
  "c": 389.12,
  "v": 49378,
  "t": "2021-02-22T19:15:00Z"
}

Trade Corrections

These messages indicate that a previously sent trade was incorrect and they contain the corrected trade.

Subscription to trade corrections and cancel/errors is automatic when you subscribe to the trade channel.

{"action":"subscribe","trades":["AAPL"]}
[{"T":"subscription","trades":["AAPL"],"quotes":[],"bars":[],"updatedBars":[],"dailyBars":[],"statuses":[],"lulds":[],
"corrections":["AAPL"],"cancelErrors":["AAPL"]}]

Schema

AttributeTypeDescription
Tstringmessage type, always “c”
Sstringsymbol
xstringexchange code
oiintoriginal trade id
opnumberoriginal trade price
osstringoriginal trade size
ocarrayoriginal trade conditions
ciintcorrected trade id
cpnumbercorrected trade price
csintcorrected trade size
ccarraycorrected trade conditions
tstringRFC-3339 formatted timestamp
zstringtape

Example

{
  "T": "c",
  "S": "EEM",
  "x": "M",
  "oi": 52983525033527,
  "op": 39.1582,
  "os": 440000,
  "oc": [
    " ",
    "7"
  ],
  "ci": 52983525034326,
  "cp": 39.1809,
  "cs": 440000,
  "cc": [
    " ",
    "7"
  ],
  "z": "B",
  "t": "2023-04-06T14:25:06.542305024Z"
}

Trade Cancels/Errors

These messages indicate that a previously sent trade was canceled.

Subscription to trade corrections and cancel/errors is automatic when you subscribe to the trade channel.

{"action":"subscribe","trades":["AAPL"]}
[{"T":"subscription","trades":["AAPL"],"quotes":[],"bars":[],"updatedBars":[],"dailyBars":[],"statuses":[],"lulds":[],
"corrections":["AAPL"],"cancelErrors":["AAPL"]}]

Schema

AttributeTypeDescription
Tstringmessage type, always “x”
Sstringsymbol
iinttrade id
xstringtrade exchange
pnumbertrade price
sinttrade size
astringaction (“C” for cancel, “E” for error)
tstringRFC-3339 formatted timestamp
zstringtape

Example

{
  "T": "x",
  "S": "GOOGL",
  "i": 465,
  "x": "D",
  "p": 105.31,
  "s": 300,
  "a": "C",
  "z": "C",
  "t": "2023-04-06T13:15:42.83540958Z"
}

LULD

Limit Up - Limit Down messages provide upper and lower limit price bands to securities.

Schema

AttributeTypeDescription
Tstringmessage type, always “l”
Sstringsymbol
unumberlimit up price
dnumberlimit down price
istringindicator
tstringRFC-3339 formatted timestamp
zstringtape

Example

{
  "T": "l",
  "S": "IONM",
  "u": 3.24,
  "d": 2.65,
  "i": "B",
  "t": "2023-04-06T13:34:45.565004401Z",
  "z": "C"
}

Trading Status

Identifies the trading status applicable to the security and reason for the trading halt if any. The status messages can be accessed from any {source} depending on your subscription.

To enable market data on a production environment please reach out to our sales team.

Schema

AttributeTypeDescription
Tstringmessage type, always “s”
Sstringsymbol
scstringstatus code
smstringstatus message
rcstringreason code
rmstringreason message
tstringRFC-3339 formatted timestamp
zstringtape

Example

{
  "T": "s",
  "S": "AAPL",
  "sc": "H",
  "sm": "Trading Halt",
  "rc": "T12",
  "rm": "Trading Halted; For information requested by NASDAQ",
  "t": "2021-02-22T19:15:00Z",
  "z": "C"
}

Status Codes

Tape A & B (CTA)

CodeValue
2Trading Halt
3Resume
5Price Indication
6Trading Range Indication
7Market Imbalance Buy
8Market Imbalance Sell
9Market On Close Imbalance Buy
AMarket On Close Imbalance Sell
CNo Market Imbalance
DNo Market On Close Imbalance
EShort Sale Restriction
FLimit Up-Limit Down

Tape C & O (UTP)

CodesResume
HTrading Halt
QQuotation Resumption
TTrading Resumption
PVolatility Trading Pause

Readon Codes

Tape A & B (CTA)

CodeValue
DNews Released (formerly News Dissemination)
IOrder Imbalance
MLimit Up-Limit Down (LULD) Trading Pause
PNews Pending
XOperational
YSub-Penny Trading
1Market-Wide Circuit Breaker Level 1 – Breached
2Market-Wide Circuit Breaker Level 2 – Breached
3Market-Wide Circuit Breaker Level 3 – Breached

Tape C & O (UTP)

CodeValue
T1Halt News Pending
T2Halt News Dissemination
T5Single Stock Trading Pause In Affect
T6Regulatory Halt Extraordinary Market Activity
T8Halt ETF
T12Trading Halted; For information requested by NASDAQ
H4Halt Non Compliance
H9Halt Filings Not Current
H10Halt SEC Trading Suspension
H11Halt Regulatory Concern
01Operations Halt, Contact Market Operations
IPO1IPO Issue not yet Trading
M1Corporate Action
M2Quotation Not Available
LUDPVolatility Trading Pause
LUDSVolatility Trading Pause – Straddle Condition
MWC1Market Wide Circuit Breaker Halt – Level 1
MWC2Market Wide Circuit Breaker Halt – Level 2
MWC3Market Wide Circuit Breaker Halt – Level 3
MWC0Market Wide Circuit Breaker Halt – Carry over from previous day
T3News and Resumption Times
T7Single Stock Trading Pause/Quotation-Only Period
R4Qualifications Issues Reviewed/Resolved; Quotations/Trading to Resume
R9Filing Requirements Satisfied/Resolved; Quotations/Trading To Resume
C3Issuer News Not Forthcoming; Quotations/Trading To Resume
C4Qualifications Halt ended; maint. Req. met; Resume
C9Qualifications Halt Concluded; Filings Met; Quotes/Trades To Resume
C11Trade Halt Concluded By Other Regulatory Auth,; Quotes/Trades Resume
R1New Issue Available
RIssue Available
IPOQIPO security released for quotation
IPOEIPO security – positioning window extension
MWCQMarket Wide Circuit Breaker Resumption

Example

$ wscat -c wss://stream.data.alpaca.markets/v2/sip
connected (press CTRL+C to quit)
< [{"T":"success","msg":"connected"}]
> {"action": "auth", "key": "*****", "secret": "*****"}
< [{"T":"success","msg":"authenticated"}]
> {"action": "subscribe", "trades": ["AAPL"], "quotes": ["AMD", "CLDR"], "bars": ["*"],"dailyBars":["VOO"],"statuses":["*"]}
< [{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"],"updatedBars":[],"dailyBars":["VOO"],"statuses":["*"],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}]
< [{"T":"q","S":"AMD","bx":"K","bp":91.95,"bs":2,"ax":"Q","ap":91.98,"as":1,"c":["R"],"z":"C","t":"2023-04-06T11:54:21.670905508Z"}]
< [{"T":"t","S":"AAPL","i":628,"x":"K","p":162.92,"s":3,"c":["@","F","T","I"],"z":"C","t":"2023-04-06T11:54:26.838232225Z"},{"T":"t","S":"AAPL","i":75,"x":"Z","p":162.92,"s":3,"c":["@","F","T","I"],"z":"C","t":"2023-04-06T11:54:26.838562809Z"},{"T":"t","S":"AAPL","i":1465,"x":"P","p":162.91,"s":71,"c":["@","F","T","I"],"z":"C","t":"2023-04-06T11:54:26.83915973Z"}]
< [{"T":"q","S":"AMD","bx":"P","bp":91.9,"bs":1,"ax":"Q","ap":91.98,"as":1,"c":["R"],"z":"C","t":"2023-04-06T11:54:27.924933876Z"}]