Sviluppo TradingBot

This commit is contained in:
2026-06-09 18:29:41 +02:00
parent 61f1e59964
commit e3c0bd51b2
133 changed files with 24903 additions and 1 deletions
@@ -0,0 +1,188 @@
# 24/5 Trading
### What is 24/5 Trading?
Overnight Trading extends market hours to provide a 24-hour, 5-day-a-week trading experience for all NMS securities. The overnight session operates from 8:00 PM ET Sunday to 4:00 AM ET Friday, bridging the gap between one day's post-market session and the next day's pre-market session.
***
### How does the overnight trading session work?
Overnight trade executions and market data are facilitated by the Blue Ocean Alternative Trading System (BOATS). As an Alternative Trading System (ATS), BOATS operates an independent overnight trading session outside of traditional stock exchanges.
***
### What are the hours for the 24/5 trading sessions?
The trading sessions are structured as follows, from Sunday evening to Friday evening:
* **Overnight Session:** 8:00 PM - 4:00 AM ET (technically occurs on the evening before the trade date)
* **Pre-Market Session:** 4:00 AM 9:30 AM ET
* **Regular Market Session:** 9:30 AM - 4:00 PM ET
* **After-Hours Session:** 4:00 PM - 8:00 PM ET
The overnight session follows the NYSE holiday calendar. For example, if there is a market holiday on a Friday, the overnight session will not run on Thursday evening. However, the overnight session runs for a full 8 hours on market half-days.
***
### How can I enable overnight trading?
Trading API accounts are enabled for 24/5 trading by default. If needed, you can disable trading in the overnight session.
***
### How can I access market data for the overnight session?
Alpacas 24/5 trading includes overnight market access, which is powered by two data sources: the Blue Ocean Alternative Trading System (BOATS) and Overnight. Which feed you use depends on your [market data plan](https://alpaca.markets/data).
Overnight market data is available between 8:00 PM and 4:00 AM ET and supports the following data types: Bars, Quotes, Trades, and Snapshots.
**Market data plans and feeds**
Algo Trader Plus Plan
* Use feed=`boats` for:
* [Latest Quotes](https://docs.alpaca.markets/reference/stocklatestquotes-1) and [Latest Trades](https://docs.alpaca.markets/reference/stocklatesttrades-1), [Snapshots](https://docs.alpaca.markets/reference/stocksnapshotsingle)
* [Historical Bars](https://docs.alpaca.markets/reference/stockbarsingle-1), [Quotes](https://docs.alpaca.markets/reference/stockquotes-1), and [Trades](https://docs.alpaca.markets/reference/stocktrades-1)
Free Plan
* Use feed=`overnight` for:
* [Latest Bars](https://docs.alpaca.markets/reference/stocklatestbars-1),
* [Latest Quotes](https://docs.alpaca.markets/reference/stocklatestquotes-1) (real-time indicative),
* [Latest Trades](https://docs.alpaca.markets/reference/stocklatesttrades-1) (15-minute delayed),
* [Snapshots](https://docs.alpaca.markets/reference/stocksnapshots-1)
* Use feed=`boats` for
* [Historical Bars](https://docs.alpaca.markets/reference/stockbarsingle-1), [Quotes](https://docs.alpaca.markets/reference/stockquotes-1), and [Trades](https://docs.alpaca.markets/reference/stocktrades-1) (all 15-minute delayed BOATS data)
You can select the feed by setting the feed parameter on the Bars, Quotes, Trades, and Snapshots endpoints.
See the [API documentation for “DataFeed”](https://alpaca.markets/sdks/python/api_reference/data/enums.html#alpaca.data.enums.DataFeed) for details.
***
### What securities are available for overnight trading?
All National Market System (NMS) securities are available for trading during the overnight session. Assets tradable in the overnight session can be identified via the `overnight_tradable` attribute in the Assets API. The list may be limited due to compliance or risk procedures, and the best way to validate the available securities is by using our Assets API as outlined above. OTC securities are not part of the NMS and are therefore not available.
***
### What order types and time-in-force (TIF) options are supported?
* **Order Type:** Only `limit` orders are supported during the overnight session.
* **Time-in-Force (TIF):** The only TIF currently supported is `day` and `gtc`.
* `day` orders placed during the overnight session will remain active through the regular and after-hours sessions of the upcoming trading day. If unfilled, the order is canceled at 8:00 PM ET.
* `gtc` (Good-Til-Canceled) orders will expire 90 days after the order is placed. In the case of corporate actions events, the `gtc` order will be cancelled prior to the corporate action event.
***
### Is fractional share trading supported?
Yes, fractional share trading is supported during the overnight session and functions the same way as it does during other extended-hours sessions.
***
### Are there restrictions on margin or buying power during the overnight session?
Yes. Day Trading Buying Power (DTBP) does not apply to the overnight session. This means 2x multiplier is the max margin buying power for overnight session trades. If an account uses DTBP for an order during the post market session, the order might be rejected (at 8 PM ET) due to insufficient buying power (if reg\_t or non-DT buying power is insufficient).
***
### How does overnight trading impact Pattern Day Trader (PDT) rules?
A day trade is defined as buying and selling the same security on the same calendar day. Trades executed during the overnight session are assigned a trade date based on when they occur:
* Trades between **8:00 PM and 11:59 PM ET** are assigned the next day's trade date (T+1).
* Trades between **12:00 AM and 4:00 AM ET** are assigned the current day's trade date (T).
Therefore, a position opened during the overnight session and closed during the regular hours of the same assigned trade date would count as a day trade.
***
### What happens to an order that is not filled during the overnight session?
If your `day` order is not filled during the overnight session, it will automatically carry over into the pre-market, regular, and after-hours sessions for that trade date. It remains an active order until it is executed or the market closes at 8:00 PM ET.
***
### How does trade settlement work for overnight trades?
The overnight session marks the beginning of a new trading day. Trades are assigned a date based on their execution time and settle on a T+1 basis from that date.
* **Example:** A trade executed at 9:00 PM ET on a Monday is assigned a trade date of Tuesday and will settle on Wednesday (T+1).
***
### How do corporate actions affect overnight trading?
A security may be halted from trading during the overnight session while a pending corporate action is being processed. Furthermore, due to the way trade dates are assigned, purchasing a stock during the overnight session on its ex-dividend date will not entitle you to that stock's dividend.
***
### What happens when a security is halted during the overnight session?
If an asset is halted overnight (e.g., due to a corporate action or pending news), the halt typically persists for the entire session. Orders submitted for a halted security will be accepted by the system with a status of `accepted` but will be held in a pending state. This ensures your order can be executed as soon as the halt is lifted and trading resumes in the next session.
***
### What API changes were made?
Two new boolean attributes have been added to the Assets API to support 24/5 trading:
When retrieving assets from the Assets API, youll see the following new attributes:
* `overnight_tradable`: Indicates whether an asset is eligible for overnight trading.
* `overnight_halted`: Indicates whether an otherwise eligible asset is temporarily halted from overnight trading, such as during a corporate action.
In addition, `boats` and `overnight` data feeds have been introduced in the Market Data API.
***
### How can I identify which assets are tradable overnight via the API?
You can identify eligible assets by calling the `v1/assets` endpoint and filtering for assets where the `overnight_tradable` attribute is `true`.
***
### When is the best time to sync the list of overnight-tradable assets?
We begin syncing our list of tradable assets at 7:05 PM ET and run updates every 10 minutes until 7:45 PM ET. For the most up-to-date list, we recommend syncing your asset list between 7:45 PM and 8:00 PM ET, with 7:55 PM ET being the ideal time.
***
### Can I access delayed historical overnight requests with an overnight subscription?
Yes, you can access delayed historical overnight requests with an overnight subscription, provided that the end parameter in your request is at least 15 minutes old.
**To access delayed historical overnight data, make sure to include the parameter `feed=boats` in your request, `feed=overnight` will give error.**
Example:
If you have an overnight subscription and want to request overnight/BOATS data ending at 10:00 PM EST , you can do so any time after 10:15 PM by specifying`feed=boats` in your request.
***
####
#### Disclosures
The content of this article is for general information only and is believed to be accurate as of the posting date, but may be subject to change. Alpaca does not provide investment, tax, or legal advice. Please consult your own independent advisor as to any investment, tax, or legal statements made herein.
Orders placed outside regular trading hours (9:30 a.m. 4:00 p.m. ET) may experience price fluctuations, partial executions, or delays due to lower liquidity and higher volatility. 
Orders not designated for extended hours execution will be queued for the next trading session.
Additionally, fractional trading may be limited during extended hours. For more details, please review [Alpaca Extended Hours & Overnight Trading Risk Disclosure](https://files.alpaca.markets/disclosures/library/ExtHrsOvernightRisk.pdf).
Fractional share trading allows a customer to buy and sell fractional share quantities and dollar amounts of certain securities. Fractional share trading presents unique risks and is subject to particular limitations that you should be aware of before engaging in such activity. See Alpaca Customer Agreement at [Alpaca - Disclosures and Agreements](https://alpaca.markets/disclosures) for more details.
Margin trading involves significant risk and is not suitable for all investors. Before considering a margin loan, it is crucial that you carefully consider how borrowing fits with your investment objectives and risk tolerance.
When trading on margin, you assume higher market risk, and potential losses can exceed the collateral value in your account. Alpaca may sell any securities in your account, without prior notice, to satisfy a margin call. Alpaca may also change its “house” maintenance margin requirements at any time without advance written notice. You are not entitled to an extension of time on a margin call. Please review the Firms [Margin Disclosure Statement](https://files.alpaca.markets/disclosures/library/MarginDiscStmt.pdf) before investing.
All investments involve risk, and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Please note that diversification does not ensure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.
Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), member [FINRA](https://www.finra.org/)/[SIPC](https://www.sipc.org/), a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.
Cryptocurrency services are made available by Alpaca Crypto LLC ("Alpaca Crypto"), a FinCEN registered money services business (NMLS # 2160858), and a wholly-owned subsidiary of AlpacaDB, Inc. Alpaca Crypto is not a member of SIPC or FINRA. Cryptocurrencies are not stocks and your cryptocurrency investments are not protected by either FDIC or SIPC. Please see the [Disclosure Library](https://alpaca.markets/disclosures) for more information.
This is not an offer, solicitation of an offer, or advice to buy or sell securities or cryptocurrencies or open a brokerage account or cryptocurrency account in any jurisdiction where Alpaca Securities or Alpaca Crypto, respectively, are not registered or licensed, as applicable.
@@ -0,0 +1,15 @@
# About FIX API
Alpaca FIX (Financial Information eXchange) API
# Introduction
Welcome to the Alpaca FIX (Financial Information eXchange) API! The purpose of this document is to show how the FIX messaging protocol can be used to place orders, receive order updates and trades, replace orders and cancel orders.
## Overview
Our API is based on FIX 4.2 specification. Please reach out to our support for FIX credentials.
## Hours of Operation
FIX connectivity is available between \<3:30a-4a> and \<8p-8:15p> New York time, Monday through Friday for equities trading. Any changes or maintenance activities will be notified via email.
@@ -0,0 +1,25 @@
# About Alpaca
# About Alpaca
## History & Founders
Alpaca is a technology company headquartered in Silicon Valley that builds a simple and modern API for stock and crypto trading. Our Brokerage services are provided by Alpaca Securities LLC, a member of [FINRA](https://www.finra.org/#/)/[SIPC](https://www.sipc.org/). We are a team of diverse background individuals with deep financial and technology expertise, backed by some of the top investors in the industry globally. We are proud to be supported by the love of enthusiastic community members on various platforms.
Alpacas globally distributed team consists of developers, traders, and brokerage business specialists, who collectively have decades of financial services and technology industry experience at organizations such as FINRA, Apple, Wealthfront, Robinhood, EMC, Cloudera, JP Morgan, and Lehman Brothers. Alpaca is co-founded and led by [Yoshi Yokokawa](https://www.linkedin.com/in/yoshiyokokawa/) (CEO) and [Hitoshi Harada](https://www.linkedin.com/in/hitoshi-harada-02b01425/) (CPO).
Our investors include a group of well-capitalized investors including Portage Ventures, Spark Capital, Tribe Capital, Social Leverage, Horizons Ventures, Elderidge, and Y Combinator as well as highly experienced industry angel investors such as Joshua S. Levine (former CTO/COO of ETRADE), Nate Rodland (former COO of Robinhood & GP of Elefund), Patrick OShaughnessy (“Invest Like the Best” podcast host & Partner of Positive Sum), Jacqueline Reses (former Executive Chairman of Square Financial Services), Asiff Hirjii (former President/COO of Coinbase), Aaron Levie (CEO of Box), and founders of leading Fintech companies including Plaid and Wealthsimple.
## Vision
> ## Allow 8+ billion people on the planet to access financial markets.
We are committed to providing a secure, reliable and compliant platform for anyone who wants to build their own trading strategies, asset management automation, trading and robo-advisor apps, new brokerage services, investment advisory services and investment products. We value having a variety of developers who create exciting and innovative projects with our API.
## What Services Does Alpaca Provide?
Alpaca provides trading and clearing services for US equities under its subsidiary Alpaca Securities LLC. We currently support stocks, ETFs listed in the US public exchanges (NMS stocks), Options trading, and cryptocurrencies. Support for other asset classes, such as futures, FX, private equities, and international equities are on our roadmap.
We work with retail traders and institutional investors directly, and also work with app developers, broker-dealers globally, investment advisors and fintech companies that offer US stock investing features to their end customers, both in and out of the United States.
To serve our customers, we provide Web API, Web dashboards, market data, paper trading simulation, API sandbox environment, and community platforms.
@@ -0,0 +1,58 @@
# About Connect API
Develop applications on Alpacas platform using OAuth2. Let 10M+ users with an Alpaca brokerage account connect to your app.
Alpacas OAuth allows you to seamlessly integrate financial markets into your application and expand your audience to millions of brokerage accounts on Alpacas platform
Read Register Your App to learn how you can register your app. In addition, you can visit OAuth Integration Guide to learn more about using OAuth to connect your applications with Alpaca.
# Broker Partners
Broker partners are able to create their own OAuth service. Allow your end users to use OAuth apps like TradingView through your Broker API application. Learn more about OAuth with Broker API in the [Broker API reference](https://docs.alpaca.markets/docs/about-broker-api)
<br />
# Non-Registered and Fintech Partners
Alpaca Connect allows non-registered firms, developers and fintech companies to build trading apps on Alpacas platform. Using OAuth, your application can connect to Alpaca brokerage accounts . Apps ranging from algorithmic trading and charting to crypto and more are published on the Alpaca Connect Marketplace once they are approved by Alpaca Compliance.
<br />
# Terms of Access and Use
* You must read the terms and register in order to connect and use Alpacas APIs
* All API clients must authenticate with OAuth 2.0
* You may not imply that the app was developed by Alpaca.
* If you are building a commercial application that makes money (including ads, in-app purchases, etc), you must disclose it in the registration form and receive written approval.
* To allow live trading for other users, the app needs to be approved by Alpaca. Please create your application via the Alpaca Dashboard under the [Alpaca Connect](https://app.alpaca.markets/connect) tab. For further details, please review [Registering Your App](https://docs.alpaca.markets/update/docs/registering-your-app)
* For any additional questions, please reach out to [Support@alpaca.markets](mailto:Support@alpaca.markets)
<br />
> ❗️ This is not an offer, solicitation of an offer, or advice to open a brokerage account.
>
> Disclosure can be found [here](https://alpaca.markets/#disclosures)
# FAQs
### Q: What can an OAuth app do?
A: OAuth allows you to manage your end-users Alpaca brokerage account on their behalf. This means you can create many types of financial services including automated investing, portfolio analytics and much more.
### Q: Should I use OAuth or Broker API?
A: OAuth allows you to expand your audience to users with Alpaca brokerage accounts. On the other hand, Broker API allows you to build an application fully within your environment. Users sign up for a brokerage account under your application. If you want to create your own brokerage, automated investment app, or any app where you want to own your users, use the Broker API. If you want to build your trading service on Alpacas platform, use OAuth.
### Q: How secure is OAuth?
A: OAuth2 itself is very secure. However you must make sure to follow good practices in how you handle tokens. Make sure to never publicly expose your client secret and access tokens.
### Q: How to get OAuth App live?
A: You will need to register your app in the OAuth apps section of the dashboard. Learn more about [Registering Your App](https://docs.alpaca.markets/update/docs/registering-your-app)
### Q: Im developing an app/service targeting non-US users. Can we integrate with Alpacas OAuth API?
A: Alpacas platform supports brokerage accounts for international users. When you build an app on OAuth, all users on Alpacas platform will be able to use your service, including international users.
<br />
@@ -0,0 +1,117 @@
# About Market Data API
Gain seamless access to a wealth of data with Alpaca Market Data API, offering real-time and historical information for equities, options, crypto and more.
# Overview
The Market Data API offers seamless access to market data through both HTTP and WebSocket protocols. With a focus on historical and real-time data, developers can efficiently integrate these APIs into their applications.
To simplify the integration process, we provide user-friendly SDKs in [Python](https://github.com/alpacahq/alpaca-py), [Go](https://github.com/alpacahq/alpaca-trade-api-go), [NodeJS](https://github.com/alpacahq/alpaca-trade-api-js), and [C#](https://github.com/alpacahq/alpaca-trade-api-csharp). These SDKs offer comprehensive functionalities, making it easier for developers to work with the Market Data APIs & Web Sockets.
To experiment with the APIs, developers can try them with [Postman](https://www.postman.com/): either through the [public workspace on Postman](https://www.postman.com/alpacamarkets) or directly from our [GitHub repository](https://github.com/alpacahq/alpaca-postman).
By leveraging Alpaca Market Data API and its associated SDKs, developers can seamlessly incorporate historical and real-time market data into their applications, enabling them to build powerful and data-driven financial products.
# Subscription Plans
Alpaca offers two distinct subscription models depending on how you access our platform:
* **Trading API:** For individual traders using Alpaca's trading platform directly
* **Broker API:** For broker partners building their own trading platforms on top of Alpaca's infrastructure
<Callout icon="️">
Which one applies to me?
If you signed up for an Alpaca account to trade or build a personal trading app, you're using the Trading API. If you're a business integrating Alpaca as your backend brokerage provider, you're using the Broker API.
</Callout>
## Trading API Subscriptions
For individual traders and developers using Alpaca's Trading API, we offer two subscription plans: **Basic** and **Algo Trader Plus**.
The **Basic** plan serves as the default option for both Paper and Live trading accounts, ensuring all users can access essential data with zero cost. However, this plan only includes limited real-time data: for equities only the IEX exchange, for options only the indicative feed. For advanced traders we recommend subscribing to **Algo Trader Plus** which includes complete market coverage for stocks and options as well.
### Equities
| | Basic | Algo Trader Plus |
| :--------------------------- | :---------------- | :--------------------- |
| Pricing | Free | $99 / month |
| Securities coverage | US Stocks & ETFs | US Stocks & ETFs |
| Real-time market coverage | IEX | All US Stock Exchanges |
| Websocket subscriptions | 30 symbols | Unlimited |
| Historical data timeframe | Since 2016 | Since 2016 |
| Historical data limitation\* | latest 15 minutes | no restriction |
| Historical API calls | 200 / min | 10,000 / min |
Our data sources are directly fed by the CTA (Consolidated Tape Association), which is administered by NYSE (New York Stock Exchange), and the UTP (Unlisted Trading Privileges) stream, which is administered by Nasdaq. The synergy of these two sources ensures comprehensive market coverage, encompassing 100% of market volume.
### Options
| | Basic | Algo Trader Plus |
| :--------------------------- | :---------------------- | :-------------------- |
| Securities coverage | US Options Securities | US Options Securities |
| Real-time market coverage | Indicative Pricing Feed | OPRA Feed |
| Websocket subscriptions | 200 quotes | 1000 quotes |
| Historical data limitation\* | latest 15 minutes | no restriction |
| Historical API calls | 200 / min | 10,000 / min |
Our options data sources are directly fed by OPRA (Options Price Reporting Authority).
## Broker API Subscriptions
For broker partners integrating Alpaca's Broker API, we offer tiered subscription plans designed for higher-volume, multi-user platforms.
For equities, the below subscription plans are available.
| Subscription Name | RPM (Request Per Minute) | Stream Connection Limit | Stream Symbol Limit | Price (per month) | Options Indicative Feed |
| :---------------- | :----------------------- | :---------------------- | :------------------ | :---------------- | :-------------------------- |
| Standard | 1,000 | 5 | unlimited | included | additional $1,000 per month |
| StandardPlus3000 | 3,000 | 5 | unlimited | $500 | additional $1,000 per month |
| StandardPlus5000 | 5,000 | 5 | unlimited | $1,000 | included |
| StandardPlus10000 | 10,000 | 10 | unlimited | $2,000 | included |
Note: Standard subscription plans will only be active when integration starts. Prior to that, the account will be on the Basic plan listed above. Additionally, similar to the free plan all the standard plans are real time IEX or 15 mins delayed SIP.
For partners on the Standard and StandardPlus3000 plans, an additional subscription fee of $1,000 / month enables access to the same equities plan for options. For StandardPlus5000 and StandardPlus10000 plans, options are included.
<Callout icon="📘" theme="info">
We offer custom pricing and tailored solutions for Broker API partners seeking to leverage our comprehensive market data. Our goal is to meet the specific needs and requirements of our valued partners, ensuring they have access to the data and tools necessary to enhance their services and provide exceptional value to their customers. If none of the subscription plans listed above are believed to be suitable, kindly reach out to our [sales team](https://alpaca.markets/contact).
</Callout>
# Authentication
With the exception of historical crypto data, all market data endpoints require authentication. Authentication differs between the Trading & Broker API. API keys can be acquired in the web UI (under the API keys on the right sidebar).
### Trading API
You should authenticate by passing the key / secret pair in the HTTP request headers named:
* `APCA-API-KEY-ID`
* `APCA-API-SECRET-KEY`
### Broker API
Broker API uses the [Client Credentials](https://docs.alpaca.markets/docs/authentication#client-credentials) authentication flow. You must first exchange your credentials for a short-lived access token, then use that token to authenticate API requests.
* Step 1: Request an access token
```curl
curl -X POST "https://authx.alpaca.markets/v1/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id={YOUR_CLIENT_ID}" \
-d "client_secret={YOUR_CLIENT_SECRET}"
```
* Step 2: Use the token to authenticate
```curl
curl -X GET "https://data.alpaca.markets/v2/..." \
-H "Authorization: Bearer {TOKEN}"
```
<Callout icon="🚧" theme="warn">
Note: Access tokens are valid for 15 minutes. Do not request a new token for each API call.
</Callout>
For the WebSocket stream authentication, kindly refer to the [WebSocket Stream documentation](https://docs.alpaca.markets/docs/streaming-market-data#authentication).
@@ -0,0 +1,117 @@
# Account Activities
The account activities API provides access to a historical record of transaction activities that have impacted your account.
# The TradeActivity Object
## Sample TradeActivity
```json
{
"activity_type": "FILL",
"cum_qty": "1",
"id": "20190524113406977::8efc7b9a-8b2b-4000-9955-d36e7db0df74",
"leaves_qty": "0",
"price": "1.63",
"qty": "1",
"side": "buy",
"symbol": "LPCN",
"transaction_time": "2019-05-24T15:34:06.977Z",
"order_id": "904837e3-3b76-47ec-b432-046db621571b",
"type": "fill"
}
```
## Properties
| Attribute | Type | Description |
| :----------------- | :----------------- | :-------------------------------------------------------------------------------------------------------------------------- |
| `activity_type` | string | For trade activities, this will always be `FILL` |
| `cum_qty` | string\<number> | The cumulative quantity of shares involved in the execution. |
| `id` | string | An ID for the activity. Always in `::` format. Can be sent as `page_token` in requests to facilitate the paging of results. |
| `leaves_qty` | string\<number> | For `partially_filled` orders, the quantity of shares that are left to be filled. |
| `price` | string\<number> | The per-share price that the trade was executed at. |
| `qty` | string\<number> | The number of shares involved in the trade execution. |
| `side` | string | `buy` or `sell` |
| `symbol` | string | The symbol of the security being traded. |
| `transaction_time` | string\<timestamp> | The time at which the execution occurred. |
| `order_id` | string\<uuid> | The id for the order that filled. |
| `type` | string | `fill` or `partial_fill` |
# The NonTradeActivity (NTA) Object
## Sample NTA
```json
{
"activity_type": "DIV",
"id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf",
"date": "2019-08-01",
"net_amount": "1.02",
"symbol": "T",
"cusip": "C00206R102",
"qty": "2",
"per_share_amount": "0.51"
}
```
## Properties
| Attribute | Type | Description |
| :----------------- | :----------------- | :-------------------------------------------------------------------------------------------------------------------------- |
| `activity_type` | string | See below for a list of possible values. |
| `id` | string | An ID for the activity. Always in `::` format. Can be sent as `page_token` in requests to facilitate the paging of results. |
| `date` | string\<timestamp> | The date on which the activity occurred or on which the transaction associated with the activity settled. |
| `net_amount` | string\<number> | The net amount of money (positive or negative) associated with the activity. |
| `symbol` | string | The symbol of the security involved with the activity. Not present for all activity types. |
| `cusip` | string | The CUSIP of the security involved with the activity. Not present for all activity types. |
| `qty` | string\<number> | For dividend activities, the number of shares that contributed to the payment. Not present for other activity types. |
| `per_share_amount` | string\<number> | For dividend activities, the average amount paid per share. Not present for other activity types. |
# Pagination of Results
Pagination is handled using the `page_token` and `page_size` parameters.
`page_token` represents the ID of the end of your current page of results. If specified with a direction of desc, for example, the results will end before the activity with the specified ID. If specified with a direction of `asc`, results will begin with the activity immediately after the one specified. `page_size` is the maximum number of entries to return in the response. If `date` is not specified, the default and maximum value is 100. If `date` is specified, the default behavior is to return all results, and there is no maximum page size.
# Activity Types
| `activity_type` | Description |
| :-------------- | :------------------------------------------------------------------------------------------ |
| `FILL` | Order fills (both partial and full fills) |
| `TRANS` | Cash transactions (both CSD and CSW) |
| `MISC` | Miscellaneous or rarely used activity types (All types except those in TRANS, DIV, or FILL) |
| `ACATC` | ACATS IN/OUT (Cash) |
| `ACATS` | ACATS IN/OUT (Securities) |
| `CFEE` | Crypto fee |
| `CGD` | Capital Gain Distribution |
| `CSD` | Cash deposit(+) |
| `CSW` | Cash withdrawal(-) |
| `DIV` | Dividends |
| `DIVCGL` | Dividend (capital gain long term) |
| `DIVCGS` | Dividend (capital gain short term) |
| `DIVFEE` | Dividend fee |
| `DIVFT` | Dividend adjusted (Foreign Tax Withheld) |
| `DIVNRA` | Dividend adjusted (NRA Withheld) |
| `DIVROC` | Dividend return of capital |
| `DIVTW` | Dividend adjusted (Tefra Withheld) |
| `DIVTXEX` | Dividend (tax exempt) |
| `FEE` | Fee denominated in USD |
| `FOPT` | Free of Payment Transfer |
| `INT` | Interest (credit/margin) |
| `INTNRA` | Interest adjusted (NRA Withheld) |
| `INTTW` | Interest adjusted (Tefra Withheld) |
| `JNL` | Journal entry |
| `JNLC` | Journal entry (cash) |
| `JNLS` | Journal entry (stock) |
| `MA` | Merger/Acquisition |
| `NC` | Name change |
| `OPASN` | Option assignment |
| `OPEXP` | Option expiration |
| `OPXRC` | Option exercise |
| `PTC` | Pass Thru Charge |
| `PTR` | Pass Thru Rebate |
| `REORG` | Reorg CA |
| `SC` | Symbol change |
| `SSO` | Stock spinoff |
| `SSP` | Stock split |
@@ -0,0 +1,545 @@
# Trading Account
# Alpaca Brokerage Account (Live Trading)
After creating an Alpaca Paper Only Account, you can enable live trading by becoming an Alpaca Brokerage Account holder. This requires you to go through an account on-boarding process with Alpaca Securities LLC, a FINRA member and SEC registered broker-dealer. We now support brokerage accounts for individuals and business entities from around the world.
With a brokerage account, you will be able to fully utilize Alpaca for your automated trading and investing needs. Using the Alpaca API, youll be able to buy and sell stocks in your brokerage account, and youll receive real-time consolidated market data. In addition, you will continue to be able to test your strategies and simulate your trades in our paper trading environment. And with the Alpaca web dashboard, its easy to monitor both your paper trading and your real money brokerage account. All accounts are opened as margin accounts. Accounts with $2,000 or more equity will have access to margin trading and short selling.
## Individuals
Alpaca Securities LLC supports individual taxable brokerage accounts. At this time, we do not support retirement accounts.
## Businesses/Incorporated Entities
You can open a business trading account to use Alpaca for trading purposes, but not for building apps/services.
<Callout icon="👀" theme="default">
### Alpaca currently accepts entities that are *Corporations*, *LLCs* and *Partnerships* in the U.S., and around the world. There is a $30,000 minimum deposit required for opening a business account at Alpaca.
</Callout>
# Markets Supported
Currently, Alpaca only supports trading of listed U.S. stocks and select cryptocurrencies.
# The Account Object
The account API serves important information related to an account, including account status, funds available for trade, funds available for withdrawal, and various flags relevant to an accounts ability to trade.
An account maybe be blocked for just for trades (`trading_blocked` flag) or for both trades and transfers (`account_blocked` flag) if Alpaca identifies the account to be engaging in any suspicious activity. Also, in accordance with FINRAs pattern day trading rule, an account may be flagged for pattern day trading (`pattern_day_trader` flag), which would inhibit an account from placing any further day-trades.
Please note that cryptocurrencies are not eligible assets to be used as collateral for margin accounts and will require the asset be traded using cash only.
## Sample Object
```json
{
"account_blocked": false,
"account_number": "010203ABCD",
"buying_power": "262113.632",
"cash": "-23140.2",
"created_at": "2019-06-12T22:47:07.99658Z",
"currency": "USD",
"crypto_status": "ACTIVE",
"non_marginable_buying_power": "7386.56",
"accrued_fees": "0",
"pending_transfer_in": "0",
"pending_transfer_out": "0",
"daytrade_count": "0",
"daytrading_buying_power": "262113.632",
"equity": "103820.56",
"id": "e6fe16f3-64a4-4921-8928-cadf02f92f98",
"initial_margin": "63480.38",
"last_equity": "103529.24",
"last_maintenance_margin": "38000.832",
"long_market_value": "126960.76",
"maintenance_margin": "38088.228",
"multiplier": "4",
"pattern_day_trader": false,
"portfolio_value": "103820.56",
"regt_buying_power": "80680.36",
"short_market_value": "0",
"shorting_enabled": true,
"sma": "0",
"status": "ACTIVE",
"trade_suspended_by_user": false,
"trading_blocked": false,
"transfers_blocked": false
}
```
## Account Properties
<Table align={["left","left","left"]}>
<thead>
<tr>
<th>
Attribute
</th>
<th>
Type
</th>
<th>
Description
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
`id`
</td>
<td>
string`<uuid>`
</td>
<td>
Account ID.
</td>
</tr>
<tr>
<td>
`account_number`
</td>
<td>
string
</td>
<td>
Account number.
</td>
</tr>
<tr>
<td>
`status`
</td>
<td>
string\<account\_status>
</td>
<td>
See detailed account statuses below
</td>
</tr>
<tr>
<td>
`crypto_status`
</td>
<td>
string\<account\_status>
</td>
<td>
The current status of the crypto enablement. See detailed crypto statuses below.
</td>
</tr>
<tr>
<td>
`currency`
</td>
<td>
string
</td>
<td>
"USD"
</td>
</tr>
<tr>
<td>
`cash`
</td>
<td>
string`<number>`
</td>
<td>
Cash balance
</td>
</tr>
<tr>
<td>
`portfolio_value`
</td>
<td>
string`<number>`
</td>
<td>
* *lpaca Broker*\* Total value of cash + holding positions (Equivalent to the equity field)
</td>
</tr>
<tr>
<td>
`non_marginable_buying_power`
</td>
<td>
string`<number>`
</td>
<td>
Current available non-margin dollar buying power
</td>
</tr>
<tr>
<td>
`accrued_fees`
</td>
<td>
string`<number>`
</td>
<td>
The fees collected.
</td>
</tr>
<tr>
<td>
`pending_transfer_in`
</td>
<td>
string`<number>`
</td>
<td>
Cash pending transfer in.
</td>
</tr>
<tr>
<td>
`pending_transfer_out`
</td>
<td>
string`<number>`
</td>
<td>
Cash pending transfer out
</td>
</tr>
<tr>
<td>
`pattern_day_trader`
</td>
<td>
boolean
</td>
<td>
Whether or not the account has been flagged as a pattern day trader
</td>
</tr>
<tr>
<td>
`trade_suspended_by_user`
</td>
<td>
boolean
</td>
<td>
User setting. If `true`, the account is not allowed to place orders.
</td>
</tr>
<tr>
<td>
`trading_blocked`
</td>
<td>
boolean
</td>
<td>
If `true`, the account is not allowed to place orders.
</td>
</tr>
<tr>
<td>
`transfers_blocked`
</td>
<td>
boolean
</td>
<td>
If `true`, the account is not allowed to request money transfers.
</td>
</tr>
<tr>
<td>
`account_blocked`
</td>
<td>
boolean
</td>
<td>
If `true`, the account activity by user is prohibited.
</td>
</tr>
<tr>
<td>
`created_at`
</td>
<td>
string`<timestamp>`
</td>
<td>
Timestamp this account was created at
</td>
</tr>
<tr>
<td>
`shorting_enabled`
</td>
<td>
boolean
</td>
<td>
Flag to denote whether or not the account is permitted to short
</td>
</tr>
<tr>
<td>
`long_market_value`
</td>
<td>
string`<number>`
</td>
<td>
Real-time MtM value of all long positions held in the account
</td>
</tr>
<tr>
<td>
`short_market_value`
</td>
<td>
string`<number>`
</td>
<td>
Real-time MtM value of all short positions held in the account
</td>
</tr>
<tr>
<td>
`equity`
</td>
<td>
string`<number>`
</td>
<td>
`cash` + `long_market_value` + `short_market_value`
</td>
</tr>
<tr>
<td>
`last_equity`
</td>
<td>
string`<number>`
</td>
<td>
Equity as of previous trading day at 16:00:00 ET
</td>
</tr>
<tr>
<td>
`multiplier`
</td>
<td>
string`<number>`
</td>
<td>
Buying power (BP) multiplier that represents account margin classification
Valid values:
* **1** (standard limited margin account with 1x BP),
* **2** (reg T margin account with 2x intraday and overnight BP; this is the default for all non-PDT accounts with $2,000 or more equity),
* **4** (PDT account with 4x intraday BP and 2x reg T overnight BP)
</td>
</tr>
<tr>
<td>
`buying_power`
</td>
<td>
string`<number>`
</td>
<td>
Current available $ buying power; If multiplier = 4, this is your daytrade buying power which is calculated as (last\_equity - (last) maintenance\_margin) *4; If multiplier = 2, buying*power = max(equity initial\_margin,0) *2; If multiplier = 1, buying*power = cash
</td>
</tr>
<tr>
<td>
`initial_margin`
</td>
<td>
string`<number>`
</td>
<td>
Reg T initial margin requirement (continuously updated value)
</td>
</tr>
<tr>
<td>
`maintenance_margin`
</td>
<td>
string`<number>`
</td>
<td>
Maintenance margin requirement (continuously updated value)
</td>
</tr>
<tr>
<td>
`sma`
</td>
<td>
string`<number>`
</td>
<td>
Value of special memorandum account (will be used at a later date to provide additional buying\_power)
</td>
</tr>
<tr>
<td>
`daytrade_count`
</td>
<td>
int
</td>
<td>
The current number of daytrades that have been made in the last 5 trading days (inclusive of today)
</td>
</tr>
<tr>
<td>
`last_maintenance_margin`
</td>
<td>
string`<number>`
</td>
<td>
Your maintenance margin requirement on the previous trading day
</td>
</tr>
<tr>
<td>
`daytrading_buying_power`
</td>
<td>
string`<number>`
</td>
<td>
Your buying power for day trades (continuously updated value)
</td>
</tr>
<tr>
<td>
`regt_buying_power`
</td>
<td>
string`<number>`
</td>
<td>
Your buying power under Regulation T (your excess equity - equity minus margin value - times your margin multiplier)
</td>
</tr>
</tbody>
</Table>
# Account Status ENUMS
The following are the possible account status values. Most likely, the account status is `ACTIVE` unless there is an issue. The account status may get to `ACCOUNT_UPDATED` when personal information is being updated from the dashboard, in which case you may not be allowed trading for a short period of time until the change is approved.
| status | description |
| :------------------ | :--------------------------------------------------------- |
| `ONBOARDING` | The account is onboarding. |
| `SUBMISSION_FAILED` | The account application submission failed for some reason. |
| `SUBMITTED` | The account application has been submitted for review. |
| `ACCOUNT_UPDATED` | The account information is being updated. |
| `APPROVAL_PENDING` | The final account approval is pending. |
| `ACTIVE` | The account is active for trading. |
| `REJECTED` | The account application has been rejected. |
@@ -0,0 +1,29 @@
# Additional Resources
# Alpaca Learn
We post regular content on our Alpaca Learn resource site where you can find the latest market updates, development tools and tips and much more to help you along your journey developing with Alpaca. For more click [here](https://alpaca.markets/learn/).
# Blog
Dont miss a beat and find the latest updates from Alpaca in our blog. For more click [here](https://alpaca.markets/blog/).
# Slack Community
We have an active community on Slack with developers and traders from all over the world. For Broker API we have a dedicated channel #broker-api for you to discuss with the rest of the community building new products using Broker API. You will be automatically added to `#announcements`, `#community`, `#feedback`, and `#q-and-a`. To join click [here](https://join.slack.com/t/alpaca-community/shared_invite/zt-1mwc1kpf8-ssNEGH6IyKgAAtFaSC_GMg).
# Forum
We have set up a community forum to discuss topics ranging from integration, programming, API questions, market data, etc. The forum is also a place to find up-to-date announcements about Alpaca and its features. The forum is the recommended place for discussion, since it has more advanced indexing and search functionality compared to our other community channels. For more click [here](https://forum.alpaca.markets/).
# Support
Have questions? Need help? Check out our support page for FAQs and to get in contact with our team. For more click [here](https://alpaca.markets/support).
# Systems Status
Stay up to date with Alpaca services status and any updates on outages. For more click [here](https://status.alpaca.markets/).
# Disclosures
To view our disclosures library click [here](https://alpaca.markets/disclosures).
@@ -0,0 +1,52 @@
# Alpaca API Platform
# Why API?
Alpacas features to access financial markets are provided primarily via API. We believe API is the means to interact with services such as ours and innovate your business. Our API is designed to fit your needs and we continue to build what you need.
# REST, SSE and Websockets
Our API is primarily built in the REST style. It is a simple and powerful way to integrate with our services.
In addition to the REST API which replies via synchronous communication, our API includes an asynchronous event API which is based on WebSocket and SSE, or [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html). As many types of events occur in the financial markets (orders fill based on the market movement, cash settles after some time, etc), this event-based API helps you get updates instantly and provide the best user experiences to your customers.
# Architecture
Alpacas platform consists of APIs, Web dashboards, trade simulator, sandbox environment, authentication services, order management system, trading routing, back office accounting and clearing system, and all of these components are built in-house from the ground up with modern architecture.
The Alpaca platform is currently hosted on the Google Cloud Platform in the us-east4 region. The site is connected with dedicated fiber lines to a data center in Secaucus, NJ, to cross-connect with various market venues.
Under the hood, Alpaca works with various third parties. As we are self clearing for equities trade clearing and settlement on DTCC, we are also self clearing for options trade clearing and settlement with the OCC. Cash transfers and custody are primarily provided by BMO Harris, We use Currency Cloud and Airwallex for funding wallets and international transfers. Citadel Securities, Virtu America, Jane Street, Ion Group, and other execution providers provide execution services for our customer orders. We integrate with multiple data service providers, with ICE Data Services being our primary vendor for various kinds of market data.
Alpaca Crypto executes customer trades on our internal central limit order book, self-clears all trades and does not custody customer cash but has banking relationships with Customers Bank, Cross River Bank, Choice Financial and FVBank. To provide live market data, Alpaca Crypto works with Coinbase, Kraken, FalconX and Stillman Digital.
# API Updates & Upgrades
In an effort to continuously provide value to our developers, Alpaca frequently performs updates and upgrades to our API.
Weve added the following sections to our docs in order to help make sure that as a developer you know what to expect, when to expect, and how to properly handle certain scenarios .
## Backwards Compatible Changes
You should expect any of the following kind of changes that we make to our API to be considered a backwards compatible change:
* Adding new or similarly named APIs
* Adding new fields to already defined models and objects such as API return objects, nested objects, etc. (Example: adding a new code field to error payloads)
* Adding new items to defined sets or enumerations such as statuses, supported assets, etc. (Example: adding new account status to a set of all )
* Enhancing ordering on how certain lists get returned
* Supporting new HTTP versions (HTTP2, QUIC)
* Adding new HTTP method(s) for an existing endpoint
* Expecting new HTTP request headers (eg. new authentication)
* Sending new HTTP headers (eg. HTTP caching headers, gzip encoding, etc.)
* Increasing HTTP limits (eg. Nginx large-client-header-buffers)
* Increasing rate limits
* Supporting additional SSL/TLS versions
Generally, as a rule of thumb, any append or addition operation is considered a backwards compatible update and does not need an upfront communication. These updates should be backwards compatible with existing interfaces and not cause any disruption to any clients calling our APIs.
## Breaking Changes
When and if Alpaca decides to perform breaking changes to our APIs the following should be expected:
* Upfront communication with sufficient time to allow developers to be able to react to new upcoming changes
* Our APIs are versioned, if breaking changes are intended we will generally bump the API version. For example, a route might go from being `/v1/accounts/{account_id}` to `/v2/accounts/{account_id}` if we had to make a breaking change to either the parameters it can take or its return structure
@@ -0,0 +1,448 @@
# DMA Gateway / Advanced Order Types
Take Control of Your Trades with Direct Market Access Gateway and Advanced Order Types
# Elite Smart Router
Elite Smart Router is designed to meet the needs of institutional clients and experienced algorithmic traders. A wide array of advanced investing and trading strategies are supported with higher API limits and cost-effective pricing.
One year after launching Alpaca Elite, we are expanding the feature set of the Elite Smart Router. The two key additions are Direct Market Access (DMA) Gatewa&#x79;*\** and Advanced Order Types. Direct Market Access Gateway\* (DMA Gateway) gives you direct control of where your orders are sent. This, along with advanced order types like Volume-Weighted Average Price (VWAP) and Time-Weighted Average Price (TWAP), enables you to efficiently manage large orders, control execution costs, help minimize market impact, and meet your specific trading objectives. DMA Gateway, VWAP, and TWAP can only be accessed if users are on the Elite Smart Router as part of the Alpaca Elite Program.
\*Direct Market Access Gateway is provided solely by DASH Financial Technologies ("DASH"), a member of the listed exchanges. Alpaca enables customers to route orders to the selected exchange through DASHs DMA capabilities.
## DMA Gateway
DMA Gateway is a tool that gives you customization over where your trades are sent.
Benefits:
* Efficiently manage large orders
* Execution customization
* Help minimize market impact
* Meet your specific trading objectives
### Implementation
DMA orders are configured using `advanced_instructions` in your order request payload:
```curl Submit
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"side": "buy",
"symbol": "AAPL",
"type": "limit",
"qty": "100",
"time_in_force": "day",
"limit_price": "212",
"order_class": "simple",
"advanced_instructions": {
"algorithm": "DMA",
"destination": "NYSE",
"display_qty": "100"
}
}' | jq -r
```
```curl Cancel
curl --request DELETE \
--url $APIDOMAIN/v2/orders/<your_order_id> \
--header 'accept: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
```
#### Parameters
| Parameter | Required | Description | Values |
| ------------- | ------------- | -------------------------------------------------------------- | -------------------------------------- |
| `algorithm` | **mandatory** | Must be set to "DMA" for Direct Market Access routing | `"DMA"` |
| `destination` | **mandatory** | Target exchange for order execution | `"NYSE"`, `"NASDAQ"`, `"ARCA"` |
| `display_qty` | optional | Maximum shares/contracts displayed on the exchange at any time | Must be in round lot increments (100s) |
Notes:
* Parameter replacement is not supported for DMA orders
#### Available Destinations
* **NYSE** - New York Stock Exchange
* **NASDAQ** - NASDAQ Stock Market
* **ARCA** - NYSE Arca
Were starting with the three destinations listed above, with plans to expand to 10+ additional destinations—including BATS, IEX, AMEX, and more—in the coming months.
### Extended Hours Trading
DMA orders support extended hours trading for the following destinations:
* **NASDAQ** - Pre-market and after-hours sessions
* **ARCA** - Pre-market and after-hours sessions
## VWAP: Volume-Weighted Average Price Orders
A VWAP order is designed to execute a trade at or near the volume-weighted average price of a security over a specified time period. It is calculated by dividing the total dollar value traded for the security (price × volume) by the total volume traded during that period.
VWAP automatically weights each trade price by its corresponding trade volume, ensuring the average reflects both price and trading activity. This makes VWAP a valuable reference for assessing execution quality and market trends.
Benefits:
* Market Impact Management: VWAP orders are designed to execute in proportion to market volume, which may help reduce the likelihood of large trades significantly influencing the market price.
* Benchmark Alignment: VWAP can be used as a benchmark strategy, aiming to achieve execution prices close to the volume-weighted average price over a specified time period. This approach may help align fills with average market pricing trends.
### Implementation
VWAP orders are configured using `advanced_instructions` in your order request payload:
```curl Submit
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"side": "buy",
"symbol": "AAPL",
"type": "limit",
"qty": "100",
"time_in_force": "day",
"limit_price": "212",
"order_class": "simple",
"advanced_instructions": {
"algorithm": "VWAP",
"start_time": "2025-07-21T09:30:00-04:00",
"end_time": "2025-07-21T15:30:00-04:00",
"max_percentage": "0.123"
}
}' | jq -r
```
```curl Replace
curl --request PATCH \
--url $APIDOMAIN/v2/orders/<your_order_id> \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"qty": "200",
"advanced_instructions": {
"algorithm": "VWAP",
"start_time": "2025-07-21T09:40:00-04:00",
"end_time": "2025-07-21T15:20:00-04:00",
"max_percentage": "0.321"
}
}' | jq -r
```
```curl Cancel
curl --request DELETE \
--url $APIDOMAIN/v2/orders/<your_order_id> \
--header 'accept: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
```
Notes:
* If `advanced_instructions` is not included in the replace payload then it will remain the same
* If `advanced_instructions` is included in the replace payload then it will replace the original one. So if the client wants to update only the `end_time` and keep the rest parameters as is, then the whole `advanced_instructions` payload needs to be sent in the replace request, including the unchanged parameters.
#### Parameters
<Table align={["left","left","left","left"]}>
<thead>
<tr>
<th>
Parameter
</th>
<th>
Required
</th>
<th>
Description
</th>
<th>
Values
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
`algorithm`
</td>
<td>
**mandatory**
</td>
<td>
Must be set to "VWAP" for Volume-Weighted Average Price Orders
</td>
<td>
`"VWAP"`
</td>
</tr>
<tr>
<td>
`start_time`
</td>
<td>
optional
</td>
<td>
When the algorithm is to start executing
</td>
<td>
`RFC3339` Timestamp, must be within current market trading hours. Defaults to start immediately or at start of the regular market hours (whichever is later). VWAP orders do NOT participate in Open Auction.
</td>
</tr>
<tr>
<td>
`end_time`
</td>
<td>
optional
</td>
<td>
When the algorithm is to be done executing
</td>
<td>
`RFC3339` Timestamp, must be within current market trading hours and after `start_time`. Defaults to end of regular market hours. VWAP orders do NOT participate in Close Auction.
</td>
</tr>
<tr>
<td>
`max_percentage`
</td>
<td>
optional
</td>
<td>
Maximum percentage of the ticker's period volume this\
order might participate in
</td>
<td>
Decimal number, must be 0 \< `max_percentage` \< 1, with up to 3 decimal points precision.
</td>
</tr>
</tbody>
</Table>
## TWAP: Time-Weighted Average Price Orders
A TWAP order is designed to execute a trade evenly over a specified time period, regardless of market volume. The order is divided into equal-sized trades that are placed at regular, pre-defined intervals until the order is complete.
Benefits:
* Reduces Market Impact: By spreading the order evenly across time, TWAP can help minimize the risk of significant price swings caused by large trades.
* Execution Predictability: Unlike VWAP, which adjusts based on market volume, TWAP may offer more consistent, evenly paced execution, which can be helpful in managing certain trading strategies.
* Effective in Low-Liquidity Environments: When volume patterns are unpredictable, TWAP can help prevent trades from disrupting the market and can help maintain price stability.
### Implementation
TWAP orders are configured using `advanced_instructions` in your order request payload:
```curl Submit
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"side": "buy",
"symbol": "AAPL",
"type": "limit",
"qty": "100",
"time_in_force": "day",
"limit_price": "212",
"order_class": "simple",
"advanced_instructions": {
"algorithm": "TWAP",
"start_time": "2025-07-21T09:30:00-04:00",
"end_time": "2025-07-21T15:30:00-04:00",
"max_percentage": "0.123"
}
}' | jq -r
```
```curl Replace
curl --request PATCH \
--url $APIDOMAIN/v2/orders/<your_order_id> \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"qty": "200",
"advanced_instructions": {
"algorithm": "TWAP",
"start_time": "2025-07-21T09:40:00-04:00",
"end_time": "2025-07-21T15:20:00-04:00",
"max_percentage": "0.321"
}
}' | jq -r
```
```curl Cancel
curl --request DELETE \
--url $APIDOMAIN/v2/orders/<your_order_id> \
--header 'accept: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
```
Notes:
* If `advanced_instructions` is not included in the replace payload then it will remain the same
* If `advanced_instructions` is included in the replace payload then it will replace the original one. So if the client wants to update only the `end_time` and keep the rest parameters as is, then the whole `advanced_instructions` payload needs to be sent in the replace request, including the unchanged parameters.
#### Parameters
<Table align={["left","left","left","left"]}>
<thead>
<tr>
<th>
Parameter
</th>
<th>
Required
</th>
<th>
Description
</th>
<th>
Values
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
`algorithm`
</td>
<td>
**mandatory**
</td>
<td>
Must be set to "TWAP" for Time-Weighted Average Price Orders
</td>
<td>
`"TWAP"`
</td>
</tr>
<tr>
<td>
`start_time`
</td>
<td>
optional
</td>
<td>
When the algorithm is to start executing
</td>
<td>
`RFC3339` Timestamp, must be within current market trading hours. Defaults to start immediately or at start of the regular market hours (whichever is later). TWAP orders do NOT participate in Open Auction.
</td>
</tr>
<tr>
<td>
`end_time`
</td>
<td>
optional
</td>
<td>
When the algorithm is to be done executing
</td>
<td>
`RFC3339` Timestamp, must be within current market trading hours and after `start_time`. Defaults to end of regular market hours. TWAP orders do NOT participate in Close Auction.
</td>
</tr>
<tr>
<td>
`max_percentage`
</td>
<td>
optional
</td>
<td>
Maximum percentage of the ticker's period volume this\
order might participate in
</td>
<td>
Decimal number, must be 0 \< `max_percentage` \< 1, with up to 3 decimal points precision.
</td>
</tr>
</tbody>
</Table>
## Key Considerations:
* `advanced_instructions` will be accepted for paper trading; however, the order will not be simulated in the paper environment.
* DMA gateway only supports market and limit orders and Time in Force (TIF) = day. If you wish to use MOO/MOC, gtc, or stop orders, you cannot specify advanced\_instructions
***
*Direct Market Access Gateway is provided solely by DASH Financial Technologies ("DASH"), a member of the listed exchanges. Alpaca enables customers to route orders to the selected exchange through DASHs DMA capabilities..*
*Please note that this is currently only available to users who are on the[Elite Smart Router](https://alpaca.markets/elite). For more information on Alpaca Elite please see the [term and conditions](https://files.alpaca.markets/disclosures/library/Alpaca+Elite+Agreement.pdf).*
*The content of this article is for general informational purposes only. All examples are for illustrative purposes only.*
*All investments involve risk, and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Please note that diversification does not ensure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.*
*Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), member[FINRA/SIPC](https://www.finra.org/), a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.*
*This is not an offer, solicitation of an offer, or advice to buy or sell securities or open a brokerage account in any jurisdiction where Alpaca Securities are not registered or licensed, as applicable.*
@@ -0,0 +1,154 @@
# Alpaca's MCP Server
Turn your words into action with Alpacas MCP Server
Alpacas MCP Server allows traders to research markets, analyze data, and place orders using natural language across AI chat applications, coding tools, and Command Line Interfaces.
Alpacas MCP Server GitHub URL: [https://github.com/alpacahq/alpaca-mcp-server](https://github.com/alpacahq/alpaca-mcp-server)
For more information, visit [Alpaca's MCP Server Homepage](https://alpaca.markets/mcp-server).
*All data and instructions are current as of November 20, 2025.*
## MCP Server Overview
An MCP server is a component of the [Model Context Protocol](https://docs.anthropic.com/en/docs/agents-and-tools/mcp) (MCP) architecture developed by Anthropic. MCP is an open standard that provides a consistent way for AI applications, code editors, or Command Line Interface to interact with external tools, data sources, and services through a structured protocol.
As AI interfaces improve, connecting them to trading workflows often requires multiple APIs, custom integrations, and authentication steps. MCP architecture streamlines this by providing a standard method for accessing data and performing actions.
An MCP server itself acts as a bridge between the MCP client (AI interfaces) and the capabilities. It presents these capabilities in a predictable and secure format so an AI model can request market data, retrieve information, or carry out defined operations without additional SDKs or complex setup.
## Alpacas MCP Server Overview
Alpacas MCP Server brings this same bridge-like concept to trading by exposing capabilities powered by Alpacas Trading API, including:
* Market data, both historical and live
* Order actions such as entry, change, and cancel
* Portfolio details like positions, buying power, and unrealized P/L
* Optional automation like alerts or risk checks
This helps users accelerate their research, streamline decision making, and support efficient trade execution, helping users capitalize on potential market opportunities more efficiently.
For more information about the available functions, please see the Available Endpoints section below.
## Main Benefits
### Reinforced Decisions, Transparent Execution
Alpacas MCP Server gives your AI model structured access to real time market data, news context, portfolio details, and order actions powered by Alpacas Trading API. Instead of acting on its own, the AI assistants help surface relevant insights, organize information, and prepare the actions you ask for.
### One Interface for Many Markets
Alpacas MCP Server brings equities, ETFs, crypto, and multi-leg options into one workflow and interface. This allows an AI agent to research, analyze, and help execute trading ideas without switching between platforms or juggling APIs.
### Code-Optional, Extensible by Design
Alpacas MCP Server lets traders begin with natural language prompts and move into vibe coding or full code whenever they want to optimize strategies.
<br />
## Supported MCP Clients and Connection Types
Alpacas MCP Server can be configured on the following MCP clients. Each client has its own setup requirements. For more details, visit [Alpacas MCP Server GitHub](https://github.com/alpacahq/alpaca-mcp-server) . The connection type indicates how you can set up Alpacas MCP Server.
Note: Remote hosting for Alpacas MCP Server is not yet available. Traders who wish to use it remotely will need to self host for now. We may consider additional options for remote MCP Server use over time, depending on feasibility and demand.
For instructions on self hosting Alpacas remote MCP Server, visit our learn article “[How to Deploy Alpacas MCP Server Remotely on Claude Mobile App](https://alpaca.markets/learn/how-to-deploy-alpaca-mcp-server-remotely-on-claude-mobile-app) ”.
| MCP client name | Connection type |
| :----------------- | :-------------- |
| Cloud Desktop | Local or Remote |
| Claude Web | Remote only |
| Claude Mobile App | Remote only |
| ChatGPT Web | Remote only |
| ChatGPT Desktop | Remote only |
| ChatGPT Mobile App | Remote only |
| VS Code | Local or Remote |
| Cursor | Local or Remote |
| PyCharm | Local or Remote |
| Claude Code (CLI) | Local or Remote |
| Gemini CLI | Local or Remote |
## Prerequisites for Connections
You will need the following prerequisites to configure and run Alpacas MCP Server. The requirements may vary depending on which MCP client you connect it with remotely or locally.
* Terminal (macOS/Linux) | Command Prompt or PowerShell (Windows)
* Python 3.10+ (Check the [official installation guide](https://www.python.org/downloads/) and confirm the version by typing the following command: `python3 --version` in Terminal)
* uv (Install using the [official installation guide](https://docs.astral.sh/uv/getting-started/installation/)) for local setup
* Tip: uv can be installed either through a package manager (like Homebrew) or directly using `curl | sh`.
* Alpaca Trading API keys (free paper trading account available)
* To find your Alpaca API keys, please check our “[How to Get Alpacas Trading API Key and Start Connect](https://alpaca.markets/learn/connect-to-alpaca-api) ” or “[How to Start Paper Trading with Alpaca](https://alpaca.markets/learn/start-paper-trading) ”
* MCP client (Claude Desktop, Cursor, VS Code, etc.)
* Some MCP clients may require a paid subscription if you use the MCP server frequently
## Available Endpoints
Alpacas MCP Server offers 43 functions (endpoints) of Trading API. We are optimizing and expanding the capabilities of our MCP server.
| Category | Function name | Description |
| :-------------------- | :------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
| Account | get\_account\_info | Retrieves current account information including balances, buying power, and account status. |
| Positions | get\_all\_positions | Retrieves all current positions in the portfolio with details like quantity, market value, and P\&L. |
| Positions | get\_open\_position | Retrieves detailed information for a specific open position. |
| Portfolio History | get\_portfolio\_history | Retrieves account portfolio history with equity and P\&L over a requested time window. |
| Assets | get\_asset | Retrieves detailed information about a specific asset including trading status and attributes. |
| Assets | get\_all\_assets | Retrieves all available assets with optional filtering by status, class, and exchange. |
| Watchlist | create\_watchlist | Creates a new watchlist with specified symbols for tracking assets. |
| Watchlist | get\_watchlists | Retrieves all watchlists for the account with their symbols. |
| Watchlist | update\_watchlist\_by\_id | Updates an existing watchlist by modifying names or symbols. |
| Watchlist | get\_watchlist\_by\_id | Get a specific watchlist by its ID. |
| Watchlist | add\_asset\_to\_watchlist\_by\_id | Add an asset by symbol to a specific watchlist by ID. |
| Watchlist | remove\_asset\_from\_watchlist\_by\_id | Remove an asset by symbol from a specific watchlist by ID. |
| Watchlist | delete\_watchlist\_by\_id | Delete a specific watchlist by its ID. |
| Corporate Actions | get\_corporate\_actions | Retrieves corporate action announcements like earnings, dividends, and stock splits. |
| Calendar | get\_calendar | Retrieves market calendar for specified date range showing trading days and holidays. |
| Clock | get\_market\_clock | Retrieves current market status and next open or close times. |
| Market Data (Stock) | get\_stock\_bars | Retrieves historical stock price bars with OHLCV data using flexible timeframes. |
| Market Data (Stock) | get\_stock\_quote | Retrieves the historical quote for a stock including bid or ask prices and volumes. |
| Market Data (Stock) | get\_stock\_trades | Retrieves historical trade data for a stock with individual trade details. |
| Market Data (Stock) | get\_stock\_latest\_bar | Retrieves the most recent minute bar for a stock. |
| Market Data (Stock) | get\_stock\_latest\_quote | Retrieves the latest quote for a stock including bid or ask prices and volumes. |
| Market Data (Stock) | get\_stock\_latest\_trade | Retrieves the latest trade information for a stock. |
| Market Data (Stock) | get\_stock\_snapshot | Retrieves comprehensive snapshot with latest quote, trade, minute bar, daily bar, and previous daily bar. |
| Market Data (Crypto) | get\_crypto\_bars | Retrieves historical cryptocurrency price bars with OHLCV data. |
| Market Data (Crypto) | get\_crypto\_quotes | Retrieves historical cryptocurrency quote data with bid or ask information. |
| Market Data (Crypto) | get\_crypto\_trades | Retrieves historical trade prints for one or more cryptocurrencies. |
| Market Data (Crypto) | get\_crypto\_latest\_quote | Returns the latest quote for one or more crypto symbols. |
| Market Data (Crypto) | get\_crypto\_latest\_bar | Returns the latest minute bar for one or more crypto symbols. |
| Market Data (Crypto) | get\_crypto\_latest\_trade | Returns the latest trade for one or more crypto symbols. |
| Market Data (Crypto) | get\_crypto\_snapshot | Returns snapshots including latest trade, quote, minute bar, daily and previous daily bars for crypto symbols. |
| Market Data (Crypto) | get\_crypto\_latest\_orderbook | Returns the latest orderbook for one or more crypto symbols. |
| Market Data (Options) | get\_option\_contracts | Searches for option contracts with flexible filtering by expiration, strike price, and type. |
| Market Data (Options) | get\_option\_latest\_quote | Retrieves the latest quote for an option contract with bid or ask prices and Greeks. |
| Market Data (Options) | get\_option\_snapshot | Retrieves comprehensive snapshots of option contracts including latest trade, quote, implied volatility, and Greeks. |
| Trading (Orders) | get\_orders | Retrieves order history with filtering options by status, date range, and limits. |
| Trading (Orders) | place\_stock\_order | Places a stock order with support for market, limit, stop, stop limit, and trailing stop orders. |
| Trading (Orders) | place\_crypto\_order | Places a cryptocurrency order with support for market, limit, and stop limit orders. |
| Trading (Orders) | place\_option\_market\_order | Places option orders including single leg and multi leg strategies like spreads and straddles. |
| Trading (Orders) | cancel\_all\_orders | Cancels all open orders and returns the status of each cancellation. |
| Trading (Orders) | cancel\_order\_by\_id | Cancels a specific order by its ID. |
| Trading (Positions) | close\_position | Closes a specific position for a single symbol, either partially or completely. |
| Trading (Positions) | close\_all\_positions | Closes all open positions in the portfolio. |
| Trading (Positions) | exercise\_options\_position | Exercises a held option contract, converting it into the underlying asset. |
## Important Considerations When Trading with Alpacas MCP Server
Using Alpacas MCP Server introduces a few important considerations:
1. Make sure your Alpaca API keys are linked to the correct account type such as live or paper.
2. Some AI tools (MCP clients) may require a paid subscription if you use the MCP Server frequently.
3. Review and confirm orders directly on your Alpaca dashboard. You can do this in real time to ensure accuracy before or after submitting trades.
## Security Considerations for Remote MCP Server Deployment
Running an MCP server remotely introduces a few important security considerations. Many early stage examples such as FastMCP are designed for local testing and may not include authentication or encrypted communication by default.
When a server is publicly accessible, it is possible for external requests to reach it. If the server handles sensitive information such as Alpaca Trading API keys, this can create a risk of unauthorized access or unintended tool execution.
To reduce these risks, a secure deployment should include HTTPS or TLS for encrypted communication and a reliable token based authentication method. Taking these steps helps protect your credentials and ensures that only trusted clients can interact with your MCP server.
<br />
## Disclosure
*Insights generated by our MCP server and connected AI agents are for educational and informational purposes only and should not be taken as investment advice. Past performance from models does not guarantee future results. Please conduct your own due diligence before making any decisions..*
@@ -0,0 +1,81 @@
# Authentication
# How to call our API
Alpaca's APIs are available under different domain names, and you first need to make sure that you are calling the right one. This page describes the machine-to-machine authentication types available in the following scenarios:
* If you have a live account, you can call:
* Trading API endpoints on `api.alpaca.markets`
* Market Data API endpoints on `data.alpaca.markets`
* If you have a paper account, you can call:
* Trading API endpoints on `paper-api.alpaca.markets`
* Market Data API endpoints on `data.alpaca.markets`
* If you are a live broker partner, you can call:
* Broker API endpoints on `broker-api.alpaca.markets`
* Market Data API endpoints on `data.alpaca.markets`
* Authentication endpoints on `authx.alpaca.markets`
* If you are a sandbox broker partner, you can call:
* Broker API endpoints on `broker-api.sandbox.alpaca.markets`
* Market Data API endpoints on `data.sandbox.alpaca.markets`
* Authentication endpoints on `authx.sandbox.alpaca.markets`
If you have more than one account (or in case of broker partners, more than one correspondent), each of those have separate credentials. As an example, you cannot use your live account's credentials with the paper API, or vice versa.
# Authentication flows
## Client credentials
<Callout icon="🚧" theme="warn">
The Client Credentials authentication flow is not yet available for Trading API.
</Callout>
When using this flow, you first need to exchange your credentials for a short-lived access token, then use that token to authenticate with our API. Do not request a new access token for each API call. Access tokens issued by our token endpoint are valid for 15 minutes.
We offer two types of credentials you can use with this flow:
* Use a client ID and a client secret (`client_secret`) - this is easier, as you can simply pass the secret that was generated when you created your credentials to our token endpoint. Note that we only support passing the client secret in the request body (`client_secret_post`), not in the `Authorization` header (`client_secret_basic`).
* Use a client ID and a signed client assertion (`private_key_jwt`) - this ensures that the private key used to sign client assertions never leaves your custody, but it requires you to construct and sign a JWT token with a private key before each call to the token endpoint. See [RFC 7523](https://www.rfc-editor.org/rfc/rfc7523.html#section-2.2) for more information on how to do so.
As an example, here is how a Broker API user would request an access token from our [token endpoint](../reference/issuetokens) using the first method:
```curl
curl -X POST "https://authx.alpaca.markets/v1/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id={YOUR_CLIENT_ID}" \
-d "client_secret={YOUR_CLIENT_SECRET}"
```
The response will contain an access token:
```json
{
"access_token": "{TOKEN}",
"expires_in": 899,
"token_type": "Bearer"
}
```
The returned token can be used to authenticate with Broker API:
```curl
curl -X GET "https://broker-api.alpaca.markets/v1/accounts" \
-H "Authorization: Bearer {TOKEN}"
```
## Legacy
Our older authentication flow lets you authenticate with your key ID and secret key directly. You have two options to authenticate your requests:
* Use HTTP Basic Authentication, send your key ID as the username, and your secret key as the password.
* Use the `APCA-API-KEY-ID` and `APCA-API-SECRET-KEY` headers to send your key ID and secret key.
As an example, here is how a Trading API user would authenticate with our API using the second method:
```curl
curl -X GET "https://api.alpaca.markets/v2/account" \
-H "APCA-API-KEY-ID: {YOUR_API_KEY_ID}" \
-H "APCA-API-SECRET-KEY: {YOUR_API_SECRET_KEY}"
```
<br />
@@ -0,0 +1,45 @@
# Crypto Spot Trading Fees
While Alpaca stock trading remains commission-free, crypto trading includes a small fee per trade dependent on your executed volume and order type. Any market or exchange consists of two parties, buyers and sellers. When you place an order to buy crypto on the Alpaca Exchange, there is someone else on the other side of the trade selling what you want to buy. The seller's posted order on the order book is providing liquidity to the exchange and allows for the trade to take place. Note, that both buyers and sellers can be makers or takers depending on the order entered and current quote of the coin. **A maker is someone who adds liquidity, and the order gets placed on the order book. A Taker on the other hand removes the liquidity by placing a market or marketable limit order which executes against posted orders.**
See the below table with volume-tiered fee pricing:
| Tier | 30D Crypto Volume (USD) | Maker | Take |
| :--- | :----------------------- | :---- | :---- |
| 1 | 0 - 100,000 | 0.15% | 0.25% |
| 2 | 100,000 - 500,000 | 0.12% | 0.22% |
| 3 | 500,000 - 1,000,000 | 0.10% | 0.20% |
| 4 | 1,000,000 - 10,000,000 | 0.08% | 0.18% |
| 5 | 10,000,000- 25,000,000 | 0.05% | 0.15% |
| 6 | 25,000,000 - 50,000,000 | 0.02% | 0.13% |
| 7 | 50,000,000 - 100,000,000 | 0.02% | 0.12% |
| 8 | 100,000,000+ | 0.00% | 0.10% |
The crypto fee will be charged on the credited crypto asset/fiat (what you receive) per trade. Some examples:
* Buy `ETH/BTC`, you receive `ETH`, the fee is denominated in `ETH`
* Sell `ETH/BTC`, you receive `BTC`, the fee is denominated in `BTC`
* Buy `ETH/USD`, you receive `ETH`, the fee is denominated in `ETH`
* Sell `ETH/USD`, you receive `USD`, the fee is denominated in `USD`
To get the fees incurred from crypto trading you can use Activities API to query `activity_type` by `CFEE` or `FEE`.
See below example of CFEE object:
```json
{
"id": "20220812000000000::53be51ba-46f9-43de-b81f-576f241dc680",
"activity_type": "CFEE",
"date": "2022-08-12",
"net_amount": "0",
"description": "Coin Pair Transaction Fee (Non USD)",
"symbol": "ETHUSD",
"qty": "-0.000195",
"price": "1884.5",
"status": "executed"
}
```
Fees are currently calculated and posted end of day. If you query on same day of trade you might not get results. We will be providing an update for fee posting to be real-time in the near future.
> 📘 Check out our Crypto Trading FAQ [here](https://alpaca.markets/support/alpaca-crypto-coin-pair-faq)
@@ -0,0 +1,25 @@
# Crypto Orders
You can submit crypto orders through the traditional orders API endpoints (`POST/orders`).
* The following order types are supported: `market`, `limit` and `stop_limit`
* The following `time_in_force` values are supported: `gtc`, and `ioc`
* We accept fractional orders as well with either `notional` or `qty` provided
You can submit crypto orders for a any supported crypto pair via API, see the below cURL POST request.
```curl
curl --request POST 'https://paper-api.alpaca.markets/v2/orders' \
--header 'Apca-Api-Key-Id: <KEY>' \
--header 'Apca-Api-Secret-Key: <SECRET>' \
--header 'Content-Type: application/json' \
--data-raw '{
"symbol": "BTC/USD",
"qty": "0.0001",
"side": "buy",
"type": "market",
"time_in_force": "gtc"
}'
```
The above request submits a market order via API to buy 0.0001 BTC with USD (BTC/USD pair) that is good till end of day.
@@ -0,0 +1,61 @@
# Crypto Pricing Data
Alpaca provides free limited crypto data and a more advanced unlimited paid plan.
To request trading pairs data via REST API, see [Crypto Pricing Data REST API](https://docs.alpaca.markets/reference/v1beta2cryptobars) Reference.
The example below requests the latest order book data (bid and asks) for the following three crypto trading pairs: BTC/USD, ETH/BTC and ETH/USD.
```curl
curl --request GET 'https://data.alpaca.markets/v1beta3/crypto/us/latest/orderbooks?symbols=BTC/USD,ETH/BTC,ETH/USD,SOL/USDT' \
--header 'Apca-Api-Key-Id: <KEY>' \
--header 'Apca-Api-Secret-Key: <SECRET>'
```
```
{
"orderbooks": {
"BTC/USD": {
"a": [
{
"p": 27539.494,
"s": 0.2632414
},
...
],
"b": [
{
"p": 27511.78083,
"s": 0.26265668
},
...
],
"t": "2023-03-18T13:31:44.932988033Z"
},
"ETH/USD": { ... },
"ETH/BTC": { ... },
"SOL/USDT": { ... }
}
}
```
# Real-Time Crypto Market Data
Additionally, you can subscribe to real-time crypto data via Websockets. Example below leverages wscat to subscribe to:
* BTC/USD trades.
* ETH/USDT and ETH/USD quotes.
* BTC/USD order books
```
$ wscat -c wss://stream.data.alpaca.markets/v1beta3/crypto/us
Connected (press CTRL+C to quit)
< [{"T":"success","msg":"connected"}]
> {"action": "auth", "key": "<KEY>", "secret": "<SECRET>"}
< [{"T":"success","msg":"authenticated"}]
> {"action":"subscribe", "trades":["BTC/USD"], "quotes":["ETH/USDT","ETH/USD"], "orderbooks":["BTC/USD"]}
< [{"T":"subscription","trades":["BTC/USD"],"quotes":["ETH/USDT","ETH/USD"],"orderbooks":["BTC/USD"],"updatedBars":[],"dailyBars":[]}]
< [{"T":"o","S":"BTC/USD","t":"2023-03-18T13:51:29.754747009Z","b":[{"p":27485.3445,"s":0.25893365},{"p":27466.92727,"s":0.52351568},...],"a":[{"p":27512.92,"s":0.26137249},{"p":27547.9425,"s":0.52011956},...],"r":true}]
< [{"T":"q","S":"ETH/USDT","bp":1815.55510989,"bs":8.24941727,"ap":1818.4,"as":4.15121428,"t":"2023-03-18T13:51:33.256826818Z"}]
< ...
```
@@ -0,0 +1,190 @@
# Crypto Spot Trading
Trade crypto through our API and the Alpaca web dashboard! Trade all day, seven days a week, as frequently as youd like.
> 🚧 As of November 18, 2022, cryptocurrency trading is open to select international jurisdictions and some U.S. jurisdictions.
>
> To view the supported US regions for crypto trading, click [here](https://alpaca.markets/support/what-regions-support-cryptocurrency-trading).
# Supported Coins
Alpaca supports over 20+ unique crypto assets across 56 trading pairs. Current trading pairs are based on BTC, USD, USDT and USDC) with more assets and trading pairs coming soon.
To query all available crypto assets and pairs you can you use the following API call:
```curl
curl --request GET 'https://api.alpaca.markets/v2/assets?asset_class=crypto' \
--header 'Apca-Api-Key-Id: <KEY>' \
--header 'Apca-Api-Secret-Key: <SECRET>'
```
Below is a sample trading pair object composed of two assets, BTC and USD.
```json JSON
{
"id": "276e2673-764b-4ab6-a611-caf665ca6340",
"class": "crypto",
"exchange": "ALPACA",
"symbol": "BTC/USD",
"name": "BTC/USD pair",
"status": "active",
"tradable": true,
"marginable": false,
"shortable": false,
"easy_to_borrow": false,
"fractionable": true,
"min_order_size": "0.0001",
"min_trade_increment": "0.0001",
"price_increment": "1"
}
```
Note that symbology for trading pairs has changed from our previous format, where `BTC/USD` was previously referred to as `BTCUSD`. Our API has made proper changes to support the legacy convention as well for backwards compatibility.
For further reference see Assets API. **add link**
# Supported Orders
When submitting crypto orders through the Orders API and the Alpaca web dashboard, Market, Limit and Stop Limit orders are supported while the supported `time_in_force` values are `gtc`, and `ioc`. We accept fractional orders as well with either `notional` or `qty` provided.
You can submit crypto orders for any supported crypto pair via API, see the below cURL POST request.
```curl
curl --request POST 'https://paper-api.alpaca.markets/v2/orders' \
--header 'Apca-Api-Key-Id: <KEY>' \
--header 'Apca-Api-Secret-Key: <SECRET>' \
--header 'Content-Type: application/json' \
--data-raw '{
"symbol": "BTC/USD",
"qty": "0.0001",
"side": "buy",
"type": "market",
"time_in_force": "gtc"
}'
```
The above request submits a market order via API to buy 0.0001 BTC with USD (BTC/USD pair) that is good till end of day.
To learn more see **orders** and **fractional trading**.
All cryptocurrency assets are fractionable but the supported decimal points vary depending on the cryptocurrency. See **Assets entity** for information on fractional precisions per asset.
Note these values could change in the future.
# Crypto Market Data
You can check out the [documentation](https://docs.alpaca.markets/docs/historical-crypto-data-1) and the [API reference](https://docs.alpaca.markets/reference/cryptobars-1) of our crypto market data.
Here we provide an example to request the latest order book data (bids and asks) for the following three coin pairs: BTC/USD, ETH/BTC, and ETH/USD.
```curl
curl 'https://data.alpaca.markets/v1beta3/crypto/us/latest/orderbooks?symbols=BTC/USD,ETH/BTC,ETH/USD'
```
```json
{
"orderbooks": {
"BTC/USD": {
"a": [
{
"p": 66051.621,
"s": 0.275033
},
...
],
"b": [
{
"p": 65986.962,
"s": 0.27813
},
...
],
"t": "2024-07-24T07:31:01.373709495Z"
},
"ETH/USD": { ... }
},
"ETH/BTC": { ... }
}
}
```
Additionally, you can subscribe to real-time crypto data via Websockets. Example below leverages wscat to subscribe to BTC/USD order book.
```json
$ wscat -c wss://stream.data.alpaca.markets/v1beta3/crypto/us
Connected (press CTRL+C to quit)
< [{"T":"success","msg":"connected"}]
> {"action":"auth","key":"<YOUR API KEY>","secret":"<YOUR API SECRET>"}
< [{"T":"success","msg":"authenticated"}]
> {"action":"subscribe","quotes":["ETH/USD"]}
< [{"T":"subscription","trades":[],"quotes":["ETH/USD"],"orderbooks":[],"bars":[],"updatedBars":[],"dailyBars":[]}]
< [{"T":"q","S":"ETH/USD","bp":3445.34,"bs":4.339,"ap":3450.2,"as":4.3803,"t":"2024-07-24T07:38:06.88490478Z"}]
< [{"T":"q","S":"ETH/USD","bp":3445.34,"bs":4.339,"ap":3451.1,"as":8.73823,"t":"2024-07-24T07:38:06.88493591Z"}]
< [{"T":"q","S":"ETH/USD","bp":3445.34,"bs":4.339,"ap":3447.03,"as":4.36424,"t":"2024-07-24T07:38:06.88511154Z"}]
< [{"T":"q","S":"ETH/USD","bp":3444.644,"bs":8.797,"ap":3447.03,"as":4.36424,"t":"2024-07-24T07:38:06.88512141Z"}]
< [{"T":"q","S":"ETH/USD","bp":3444.51,"bs":4.33,"ap":3447.03,"as":4.36424,"t":"2024-07-24T07:38:06.88516355Z"}]
```
For further reference of real-time crypto pricing data see [its documentation](https://docs.alpaca.markets/docs/real-time-crypto-pricing-data).
# Transferring Crypto
Alpaca now offers native on-chain crypto transfers with wallets! If you have crypto trading enabled and reside in an eligible US state or international jurisdiction you can access wallets on the web dashboard via the Crypto Transfers tab.
Alpaca wallets currently support transfers for Bitcoin, Ethereum, and all Ethereum (ERC20) based tokens. To learn more on transferring crypto with Alpaca, see **[Crypto Wallets FAQs](https://alpaca.markets/support/crypto-wallet-faq)**
# Crypto Spot Trading Fees
While Alpaca stock trading remains commission-free, crypto trading includes a small fee per trade dependent on your executed volume and order type. Any market or exchange consists of two parties, buyers and sellers. When you place an order to buy crypto on the Alpaca Exchange, there is someone else on the other side of the trade selling what you want to buy. The seller's posted order on the order book is providing liquidity to the exchange and allows for the trade to take place. Note, that both buyers and sellers can be makers or takers depending on the order entered and current quote of the coin. **A maker is someone who adds liquidity, and the order gets placed on the order book. A Taker on the other hand removes the liquidity by placing a market or marketable limit order which executes against posted orders.**
See the below table with volume-tiered fee pricing:
| Tier | 30D Trading Volume (USD) | Maker | Taker |
| :--- | :----------------------- | :----- | :----- |
| 1 | 0 - 100,000 | 15 bps | 25 bps |
| 2 | 100,000 - 500,000 | 12 bps | 22 bps |
| 3 | 500,000 - 1,000,000 | 10 bps | 20 bps |
| 4 | 1,000,000 - 10,000,000 | 8 bps | 18 bps |
| 5 | 10,000,000 - 25,000,000 | 5 bps | 15 bps |
| 6 | 25,000,000 - 50,000,000 | 2 bps | 13 bps |
| 7 | 50,000,000 - 100,000,000 | 2 bps | 12 bps |
| 8 | 100,000,000+ | 0 bps | 10 bps |
The crypto fee will be charged on the credited crypto asset/fiat (what you receive) per trade. Some examples,
* Buy `ETH/BTC`, you receive `ETH`, the fee is denominated in `ETH`
* Sell `ETH/BTC`, you receive `BTC`, the fee is denominated in `BTC`
* Buy `ETH/USD`, you receive `ETH`, the fee is denominated in `ETH`
* Sell `ETH/USD`, you receive `USD`, the fee is denominated in `USD`
To get the fees incurred from crypto trading you can use Activities API to query `activity_type` by `CFEE` or `FEE`. See below example of CFEE object:
```json
{
"id": "20220812000000000::53be51ba-46f9-43de-b81f-576f241dc680",
"activity_type": "CFEE",
"date": "2022-08-12",
"net_amount": "0",
"description": "Coin Pair Transaction Fee (Non USD)",
"symbol": "ETHUSD",
"qty": "-0.000195",
"price": "1884.5",
"status": "executed"
}
```
Fees are currently calculated and posted end of day. If you query on same day of trade you might not get results. We will be providing an update for fee posting to be real-time in the near future.
# Margin and Short Selling
Cryptocurrencies cannot be bought on margin. This means that you cannot use leverage to buy them and orders are evaluated against `non_marginable_buying_power`.
Cryptocurrencies can not be sold short.
# Trading Hours
Crypto trading is offered for 24 hours everyday and your orders will be executed throughout the day.
# Trading Limits
Currently, an order (buy or sell) must not exceed $200k in notional. This is per an order.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,84 @@
# Fractional Trading
Fractional shares are fractions of a whole share, meaning that you dont need to buy a whole share to own a portion of a company. You can now buy as little as $1 worth of shares for over 2,000 US equities.
By default all Alpaca accounts are allowed to trade fractional shares in both live and paper environments. Please make sure you reset your paper account if you run into any issues dealing with fractional shares.
# Supported Order Types
Alpaca currently supports fractional trading for market, limit, stop & stop limit orders with a time in force=Day, accommodating both fractional quantities and notional values. You can pass either a fractional amount (qty), or a notional value (notional) in any POST/v2/orders request. Note that entering a value for either parameters, will automatically nullify the other. If both qty and notional are entered the request will be rejected with an error status 400.
Both notional and qty fields can take up to 9 decimal point values.
Moreover, we support fractional shares trading not only during standard market hours, but extending into pre-market (4:00 a.m. - 9:30 a.m. ET), post-market (4:00 p.m. - 8:00 p.m. ET) and overnight (8:00 p.m. - 4:00 a.m.) hours, offering global investors the ability to trade during the full extended hours session.
# Eligible Securities
Only exchange-listed securities are eligible to trade in the extended hours. Additionally, the asset must be enabled as a fractional asset on Alpacas side. If there is an asset you want to trade in the extended hours and it is not eligible, please contact our [support](mailto:support@alpaca.markets) team.
# Sample Requests
## Notional Request
```json
{
"symbol": "AAPL",
"notional": 500.75,
"side": "buy",
"type": "market",
"time_in_force": "day"
}
```
## Fractional Request
```json
{
"symbol": "AAPL",
"qty": 3.654,
"side": "buy",
"type": "market",
"time_in_force": "day"
}
```
# Supported Assets
Not all assets are fractionable yet so please make sure you query assets details to check for the parameter `fractionable = true`.
Supported fractionable assets would return a response that looks like this
```json
{
"id": "b0b6dd9d-8b9b-48a9-ba46-b9d54906e415",
"class": "us_equity",
"exchange": "NASDAQ",
"symbol": "AAPL",
"name": "Apple Inc. Common Stock",
"status": "active",
"tradable": true,
"marginable": true,
"shortable": true,
"easy_to_borrow": true,
"fractionable": true
}
```
If you request a fractional share order for a stock that is not yet fractionable, the order will get rejected with an error message that reads `requested asset is not fractionable`.
# Dividends
Dividend payments occur the same way in fractional shares as with whole shares, respecting the proportional value of the share that you own.
For example if the dividend amount is $0.10 per share and you own 0.5 shares of that stock then you will receive $0.05 as dividend. As a general rule of thumb all dividends are rounded to the nearest penny.
# Notes on Fractional Trading
* We do not support short sales in fractional orders. All fractional sell orders are marked long.
* The expected price of fill is the NBBO quote at the time the order was submitted. If you submit an order for a whole and fraction, the price for the whole share fill will be used to price the fractional portion of the order.
* Day trading fractional shares counts towards your day trade count.
* You can cancel a fractional share order that is pending, the same way as whole share orders.
* Limit orders are supported for both fractional and notional orders. Extended hours are also supported with limit orders (same as whole share orders).
* Fees for fractional trading work the same way as with whole shares.
Alpaca does not make recommendations with regard to fractional share trading, whether to use fractional shares at all, or whether to invest in any specific security. A securitys eligibility on the list of fractional shares available for trading is not an endorsement of any of the securities, nor is it intended to convey that such stocks have low risk. Fractional share transactions are executed either on a principal or riskless principal basis, and can only be bought or sold with market orders during normal market hours.
@@ -0,0 +1,179 @@
# Getting Started with Market Data API
This is a quick guide on how to start consuming market data via APIs. Starting from beginning to end, this section outlines how to install Alpacas software development kit (SDK), create a free alpaca account, locate your API keys, and how to request both historical and real-time data.
# Installing Alpacas Client SDK
In this guide, well be making use of the SDKs provided by Alpaca. Alpaca maintains SDKs in four languages: Python, JavaScript, C#, and Go. Follow the steps in the installation guide below to install the SDK of your choice before proceeding to the next section.
```python
pip install alpaca-py
```
```go
go get -u github.com/alpacahq/alpaca-trade-api-go/v3/alpaca
```
```javascript
npm install --save @alpacahq/alpaca-trade-api
```
```csharp
dotnet add package Alpaca.Markets
```
# Generate API Keys
Go to the [Alpaca dashboard](https://app.alpaca.markets/brokerage/dashboard/overview) and find the **API Keys** section on the right sidebar. Click on Generate New Keys and save the generated API credentials. If you have previously generated keys there and you lost the secret, you can also regenerate them here.
# How to Request Market Data Through the SDK
With the SDK installed and our API keys ready, you can start requesting market data. Alpaca offers many options for both historical and real-time data, so to keep this guide succint, these examples are on obtaining historical and real-time bar data. Information on what other data is available can be found in the Market Data API reference.
To start using the SDK for historical data, import the SDK and instantiate the crypto historical data client. Its not required for this client to pass in API keys or a paper URL.
```python
from alpaca.data.historical import CryptoHistoricalDataClient
# No keys required for crypto data
client = CryptoHistoricalDataClient()
```
```go
package main
import "github.com/alpacahq/alpaca-trade-api-go/v3/marketdata"
func main() {
// No keys required for crypto data
client := marketdata.NewClient(marketdata.ClientOpts{})
}
```
```javascript JavaScript
import Alpaca from "@alpacahq/alpaca-trade-api";
// Alpaca() requires the API key and sectret to be set, even for crypto
const alpaca = new Alpaca({
keyId: "YOUR_API_KEY",
secretKey: "YOUR_API_SECRET",
});
```
Next well define the parameters for our request. Import the request class for crypto bars, CryptoBarsRequest and TimeFrame class to access time frame units more easily. This example queries for historical daily bar data of Bitcoin in the first week of September 2022.
```python
from alpaca.data.requests import CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame
# Creating request object
request_params = CryptoBarsRequest(
symbol_or_symbols=["BTC/USD"],
timeframe=TimeFrame.Day,
start=datetime(2022, 9, 1),
end=datetime(2022, 9, 7)
)
```
```go
request := marketdata.GetCryptoBarsRequest{
TimeFrame: marketdata.OneDay,
Start: time.Date(2022, 9, 1, 0, 0, 0, 0, time.UTC),
End: time.Date(2022, 9, 7, 0, 0, 0, 0, time.UTC),
}
```
```javascript JavaScript
let options = {
start: "2022-09-01",
end: "2022-09-07",
timeframe: alpaca.newTimeframe(1, alpaca.timeframeUnit.DAY),
};
```
Finally, send the request using the clients built-in method, get\_crypto\_bars. Additionally, well access the .df property which returns a pandas DataFrame of the response.
```python
# Retrieve daily bars for Bitcoin in a DataFrame and printing it
btc_bars = client.get_crypto_bars(request_params)
# Convert to dataframe
btc_bars.df
```
```go
bars, err := client.GetCryptoBars("BTC/USD", request)
if err != nil {
panic(err)
}
for _, bar := range bars {
fmt.Printf("%+v\n", bar)
}
```
```javascript JavaScript
(async () => {
const bars = await alpaca.getCryptoBars(["BTC/USD"], options);
console.table(bars.get("BTC/USD"));
})();
```
Returns
```text Python
open high low close volume trade_count vwap
symbol timestamp
BTC/USD 2022-09-01 05:00:00+00:00 20055.79 20292.00 19564.86 20156.76 7141.975485 110122.0 19934.167845
2022-09-02 05:00:00+00:00 20156.76 20444.00 19757.72 19919.47 7165.911879 96231.0 20075.200868
2022-09-03 05:00:00+00:00 19924.83 19968.20 19658.04 19806.11 2677.652012 51551.0 19800.185480
2022-09-04 05:00:00+00:00 19805.39 20058.00 19587.86 19888.67 4325.678790 62082.0 19834.451414
2022-09-05 05:00:00+00:00 19888.67 20180.50 19635.96 19760.56 6274.552824 84784.0 19812.095982
2022-09-06 05:00:00+00:00 19761.39 20026.91 18534.06 18724.59 11217.789784 128106.0 19266.835520
```
```go Go
{Timestamp:2022-09-01 05:00:00 +0000 UTC Open:20055.79 High:20292 Low:19564.86 Close:20156.76 Volume:7141.975485 TradeCount:110122 VWAP:19934.1678446199}
{Timestamp:2022-09-02 05:00:00 +0000 UTC Open:20156.76 High:20444 Low:19757.72 Close:19919.47 Volume:7165.911879 TradeCount:96231 VWAP:20075.2008677126}
{Timestamp:2022-09-03 05:00:00 +0000 UTC Open:19924.83 High:19968.2 Low:19658.04 Close:19806.11 Volume:2677.652012 TradeCount:51551 VWAP:19800.1854803241}
{Timestamp:2022-09-04 05:00:00 +0000 UTC Open:19805.39 High:20058 Low:19587.86 Close:19888.67 Volume:4325.67879 TradeCount:62082 VWAP:19834.4514137038}
{Timestamp:2022-09-05 05:00:00 +0000 UTC Open:19888.67 High:20180.5 Low:19635.96 Close:19760.56 Volume:6274.552824 TradeCount:84784 VWAP:19812.0959815687}
{Timestamp:2022-09-06 05:00:00 +0000 UTC Open:19761.39 High:20026.91 Low:18534.06 Close:18724.59 Volume:11217.789784 TradeCount:128106 VWAP:19266.8355201911}
```
```javascript JavaScript
┌─────────┬──────────┬──────────┬──────────┬────────────┬──────────┬────────────────────────┬──────────────┬──────────────────┐
│ (index) │ Close │ High │ Low │ TradeCount │ Open │ Timestamp │ Volume │ VWAP │
├─────────┼──────────┼──────────┼──────────┼────────────┼──────────┼────────────────────────┼──────────────┼──────────────────┤
│ 0 │ 20156.76 │ 20292 │ 19564.86 │ 110122 │ 20055.79 │ '2022-09-01T05:00:00Z' │ 7141.975485 │ 19934.1678446199 │
│ 1 │ 19919.47 │ 20444 │ 19757.72 │ 96231 │ 20156.76 │ '2022-09-02T05:00:00Z' │ 7165.911879 │ 20075.2008677126 │
│ 2 │ 19806.11 │ 19968.2 │ 19658.04 │ 51551 │ 19924.83 │ '2022-09-03T05:00:00Z' │ 2677.652012 │ 19800.1854803241 │
│ 3 │ 19888.67 │ 20058 │ 19587.86 │ 62082 │ 19805.39 │ '2022-09-04T05:00:00Z' │ 4325.67879 │ 19834.4514137038 │
│ 4 │ 19760.56 │ 20180.5 │ 19635.96 │ 84784 │ 19888.67 │ '2022-09-05T05:00:00Z' │ 6274.552824 │ 19812.0959815687 │
│ 5 │ 18724.59 │ 20026.91 │ 18534.06 │ 128106 │ 19761.39 │ '2022-09-06T05:00:00Z' │ 11217.789784 │ 19266.8355201911 │
└─────────┴──────────┴──────────┴──────────┴────────────┴──────────┴────────────────────────┴──────────────┴──────────────────┘
```
# Request ID
All market data API endpoint provides a unique identifier of the API call in the response header with `X-Request-ID` key, the Request ID helps us to identify the call chain in our system.
Make sure you provide the Request ID in all support requests that you created, it could help us to solve the issue as soon as possible. Request ID can't be queried in other endpoints, that is why we suggest to persist the recent Request IDs.
```shell
$ curl -v https://data.alpaca.markets/v2/stocks/bars
...
> GET /v2/stocks/bars HTTP/1.1
> Host: data.alpaca.markets
> User-Agent: curl/7.88.1
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Date: Fri, 25 Aug 2023 09:37:03 GMT
< Content-Type: application/json
< Content-Length: 26
< Connection: keep-alive
< X-Request-ID: 0d29ba8d9a51ee0eb4e7bbaa9acff223
<
...
```
@@ -0,0 +1,27 @@
# Getting Started with Trading API
This section outlines how to install Alpacas SDKs, create a free alpaca account, locate your API keys, and how to submit orders applicable for both stocks and crypto.
# Request ID
All trading API endpoint provides a unique identifier of the API call in the response header with `X-Request-ID` key, the Request ID helps us to identify the call chain in our system.
Make sure you provide the Request ID in all support requests that you created, it could help us to solve the issue as soon as possible. Request ID can't be queried in other endpoints, that is why we suggest to persist the recent Request IDs.
```shell
$ curl -v https://paper-api.alpaca.markets/v2/account
...
> GET /v2/account HTTP/1.1
> Host: paper-api.alpaca.markets
> User-Agent: curl/7.88.1
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Date: Fri, 25 Aug 2023 09:34:40 GMT
< Content-Type: application/json
< Content-Length: 26
< Connection: keep-alive
< X-Request-ID: 649c5a79da1ab9cb20742ffdada0a7bb
<
...
```
@@ -0,0 +1,18 @@
# Welcome
This page will help you get started with Alpaca Docs. You'll be up and running in a jiffy!
# Welcome to Alpaca 🦙
Alpaca offers simple, modern API-first solutions to enable anyone, either individuals or businesses, to connect applications and build algorithms to buy and sell stocks or crypto.
Whether you are launching an app to access the US equities market or deploy algorithmic trading-strategies with stocks and crypto, Alpaca has an API for you.
* Build trading apps and brokerage services for your end users. Tailored for businesses such as trading apps, challenger banks, etc. - **Start [here](/docs/getting-started-with-broker-api)**
* Stock trading for individuals and business accounts. Built for retail, algorithmic and proprietary traders. - **Start [here](https://docs.alpaca.markets/docs/getting-started-with-trading-api)**
* Access real-time market pricing data and up to 6+ years worth of historical data for stocks and crypto. - **Start [here](https://docs.alpaca.markets/docs/getting-started-with-alpaca-market-data)**
* Develop applications on Alpacas platform using OAuth2. Let any user with an Alpaca brokerage account connect to your app. - **Start [here](https://docs.alpaca.markets/docs/about-connect-api)**
If you are not a developer and an API is not for you, we also enable users to trade on our responsive web dashboard.
Stay tuned for our API updates as we have on roadmap plans for futures, FX, and much more!
@@ -0,0 +1,24 @@
# Historical API
This RESTful API provides historical market data through the HTTP protocol. This allows you to query historical market information, which can be used for charting, backtesting and to power your trading strategies.
Historical market data is available for the following types:
* [Stocks](https://docs.alpaca.markets/docs/historical-stock-data-1)
* [Crypto](https://docs.alpaca.markets/docs/historical-crypto-data-1)
* [Options](https://docs.alpaca.markets/docs/historical-option-data)
* [News](https://docs.alpaca.markets/docs/historical-news-data)
# Base URL
The Base URL for the historical endpoints is
```
https://data.alpaca.markets/{version}
```
Sandbox URL (for broker partners):
```
https://data.sandbox.alpaca.markets/{version}
```
@@ -0,0 +1,9 @@
# Historical Crypto Data
This API provides historical market data for crypto. Check the [API Reference](https://docs.alpaca.markets/reference/cryptobars-1) for the detailed descriptions of all the endpoints.
Since Alpaca now executes all crypto orders in its own exchange, the v1beta3 crypto market data endpoints no longer distribute data from other providers, but from Alpaca itself.
> 📘 Crypto bars contain quote mid-prices
>
> Due to the volatility of some currencies, including lack of trade volume at any given time, we include the quote midpoint prices in the bars to offer a better data experience. If in a bar no trade happens, the volume will be 0, but the prices will be determined by the quote prices.
@@ -0,0 +1,15 @@
# Historical News Data
This API provides historical news data dating back to 2015. You can expect to receive an average of 130+ news articles per day. All news data is currently provided directly by [Benzinga](https://www.benzinga.com/). With a single endpoint, you can request news for both stocks and cryptocurrency tickers. Check the [API Reference](https://docs.alpaca.markets/reference/news-3) for the detailed descriptions the endpoint.
# Use Cases
News API is a versatile tool that can be used to support a variety of use cases, such as building an app with the Broker API or Algorithmic Trading using Sentiment Analysis on News with the Trading API.
1. **News Widgets**
News API can be used to create visual news widgets for web and mobile apps. These widgets can be used to display the latest news for any stock or crypto symbol, and they include different sized images to give your app a visual appeal.
2. **News Sentiment Analysis**\
News API can be used to train models that can determine the sentiment of a given headline or news content. This can be done by using historical data from News API to train the model on a variety of different sentiment labels.
3. **Realtime Trading on News**\
[Real-time news over WebSockets](https://docs.alpaca.markets/edit/streaming-real-time-news) can be used to enable your trading algorithms to react to the latest news across any stock or cryptocurrency.
@@ -0,0 +1,16 @@
# Historical Option Data
This API provides historical market data for options. Check the [API Reference](https://docs.alpaca.markets/reference/optionbars) for the detailed descriptions of all the endpoints.
> 🚧 Data availability
>
> Currently we only offer historical option data since February 2024.
# Data sources
Similarly to stocks, Alpaca offers two different data sources for options:
| Source | Description |
| :------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Indicative** | Indicative Pricing Feed is a free derivative of the original OPRA feed: the quotes are not actual OPRA quotes, theyre just indicative derivatives. The trades are also derivatives and theyre delayed by 15 minutes. |
| **OPRA (Options Price Reporting Authority)** | OPRA is the consolidated BBO feed of OPRA. [OPRA Plan](https://www.opraplan.com/document-library) defines the BBO as the highest bid and lowest offer for a series of options available in one or more of the options markets maintained by the parties. OPRA feed is only available to subscribed users. |
@@ -0,0 +1,71 @@
# Historical Stock Data
This API provides historical market data for equities. Check the [API Reference](https://docs.alpaca.markets/reference/stockbars) for detailed descriptions of all REST endpoints.
# Data Sources
Alpaca offers market data from various data sources described below. You can use the `feed` parameter on all the stock endpoints to switch between them.
<Table align={["left","left"]}>
<thead>
<tr>
<th>
Source
</th>
<th>
Description
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
**iex**
</td>
<td>
IEX ([The Investors Exchange](https://www.iexexchange.io/)) is ideal for initial app testing and situations where precise pricing may not be the primary focus. It's a single US exchange that accounts for approximately \~2.5% of the market volume.
️ This is the only feed that can be used without a subscription.
</td>
</tr>
<tr>
<td>
**sip**
</td>
<td>
This feed covers all US exchanges, originating directly from exchanges and is consolidated by the Securities Information Processors: [UTP](https://utpplan.com/) (Nasdaq) and [CTA](https://www.nyse.com/data/cta) (NYSE). These SIPs play a crucial role in connecting various U.S. markets, processing and consolidating all bid/ask quotes and trades from multiple trading venues into a single, easily accessible data feed.
Our data delivery ensures ultra-low latency and high reliability, as the information is transmitted directly to Alpaca's bare metal servers located in New Jersey, situated alongside many market participants.
SIP data is particularly advantageous for developing your trading app, where precise and up-to-date price information is essential for traders and internal operations. It accounts for 100% of the market volume, providing comprehensive coverage for your trading needs.
</td>
</tr>
<tr>
<td>
**boats**
</td>
<td>
[Blue Ocean ATS](https://blueocean-tech.io/) is the first alternative trading system to expand market hours, filling the gap to trade equities continuously throughout US evening hours.
</td>
</tr>
<tr>
<td>
**overnight**
</td>
<td>
Our "overnight" feed is Alpaca's derived feed from the original BOATS source. It offers a cheaper, but slightly less accurate alternative for overnight US market data. The trades are 15 minutes delayed and adjusted to fit the bid-ask spread.
</td>
</tr>
</tbody>
</Table>
<br />
@@ -0,0 +1,86 @@
# Margin and Short Selling
> In order to trade on margin or sell short, you must have $2,000 or more account equity. Accounts with less than $2,000 will not have access to these features and will be restricted to 1x buying power.
>
> This is only for Equities Trading. Margin Trading for Crypto is not applicable. In addition, PDT checks do not count towards crypto orders or fills.
# How Margin Works
Trading on margin allows you to trade and hold securities with a value that exceeds your account equity. This is made possible by funds loaned to you by your broker, who uses your accounts cash and securities as collateral. For example, a Reg T Margin Account holding $10,000 cash may purchase and hold up to $20,000 in marginable securities overnight (Note: some securities may have a higher maintenance margin requirement making the full 2x overnight buying power effectively unavailable). In addition to the 2x buying power afforded to margin accounts, a Reg T Margin Account flagged as a Pattern Day Trader(PDT) with $25,000 or greater equity will further be allowed to use up to 4x intraday buying power. As an example, a PDT account holding $50,000 cash may purchase and hold up to $200,000 in securities intraday; however, to avoid receiving a margin call the next morning, the securities held would need to be reduced to $100,000 or less depending on the maintenance margin requirement by the end of the day.
## Initial Margin
Initial margin denotes the percentage of the trade price of a security or basket of securities that an account holder must pay for with available cash in the margin account, additions to cash in the margin account or other marginable securities.
Alpaca applies a minimum initial margin requirement of 50% for marginable securities and 100% for non-marginable securities per Regulation T of the Federal Reserve Board.
## Maintenance Margin
Maintenance margin is the amount of cash or marginable securities required to continue holding an open position. FINRA has set the minimum maintenance requirement to at least 25% of the total market value of the securities, but brokers are free to set higher requirements as part of their risk management.
Alpaca uses the following table to calculate the overnight maintenance margin applied to each security held in an account:
| Position Side | Condition | Margin Requirement |
| :------------ | :-------------------------------- | :----------------------------- |
| LONG | share price \< $2.50 | 100% of EOD market value |
| LONG | share price between $2.50 & $6.00 | 50% of EOD market value |
| LONG | share price > $6.00 | 30% of EOD market value |
| LONG | 2x Leveraged ETF | 50% of EOD market value |
| LONG | 3x Leveraged ETF | 75% of EOD market value |
| SHORT | share price \< $5.00 | Greater of $2.50/share or 100% |
| SHORT | share price >= $5.00 | Greater of $5.00/share or 30% |
## Margin Calls
If your account does not satisfy its initial and maintenance margin requirements at the end of the day, you will receive a margin call the following morning. We will contact you and advise you of the call amount that you will need to satisfy either by depositing new funds or liquidating some or all of your positions to reduce your margin requirement sufficiently.
We may contact you prior to the end of the day and ask you to liquidate your positions immediately in the event that your account equity is materially below your maintenance requirement. Furthermore, although we will make every effort to contact you so that you can determine how to best resolve your margin call, we reserve the right to liquidate your holdings in the event we cannot get ahold of you and your account equity is in danger of turning negative.
Calculating and tracking your margin requirement at all times is helpful to avoid receiving a margin call. We strongly recommend doing so if you plan to aggressively use overnight leverage. Please use a 50% initial requirement and refer to the maintenance margin table above. In the future, we will provide real-time estimated initial and maintenance margin values as part of the Account API to help users better manage their risk.
# Margin Interest Rate
We are pleased to offer a competitive and low annual margin interest rate of 4.75% for elite users and 6.25% for non-elite users (check “Alpaca Securities Brokerage Fee Schedule” on **Important Disclosures** for the latest rate).
The rate is charged only on your accounts end of day (overnight) debit balance using the following calculation:
`daily_margin_interest_charge = (settlement_date_debit_balance * rate[non-elite: 0.0625 | elite: 0.0475])) / 360`
Interest will accrue daily and post to your account at the end of each month. Note that if you have a settlement date debit balance as of the end of day Friday, you will incur interest charges for 3 days (Fri, Sat, Sun).
As an example, if you are a regular trader and deposited $10,000 into your account and bought $15,000 worth of securities that you held at the end of the day, you would be borrowing $5,000 overnight and would incur a daily interest expense of ($5000 \* 0.0625) / 360 = $0.87.
On the other hand, if you deposited $10,000 and bought $15,000 worth of stock that you liquidated the same day, you would not incur any interest expense. In other words, this allows you to make use of the additional buying power for intraday trading without any cost.
# Stock Borrow Rates
Alpaca currently only supports opening short positions in easy to borrow (“ETB”) securities. Any open short order in a stock that changes from ETB to hard to borrow (“HTB”) overnight will be automatically cancelled prior to market open.
**Note: Support for HTB securities is not yet available, but we are actively working towards supporting HTB in the future.**
**In addition, Alpaca has introduced $0 borrow fees on all ETB (easy-to-borrow) shares for Trading API users.**
Please note that stock borrow availability changes daily, and we update our assets table each morning, so please use our API to check each stocks borrow status daily. It is infrequent but names can go from ETB → HTB and vice versa.
While we do not currently support opening short positions in HTB securities, we will not force you to close out a position in a stock that has gone from ETB to HTB unless the lender has called the stock. If a stock you hold short has gone from ETB to HTB, you will incur a daily stock borrow fee for that stock. We do not currently provide HTB rates via our API, so please contact us in these cases.
If you hold an HTB short at any time during the day, you will incur a daily stock borrow fee:
`Daily stock borrow fee = Daily HTB stock borrow fee`
Where,
`Daily HTB stock borrow fee = Σ((each stocks HTB short $ market value _ that stocks HTB rate) / 360)`
Please note that if you hold HTB short positions as of a Friday settlement date, you will incur stock borrow fees for 3 days (Fri, Sat, Sun). HTB stock borrow fees are charged in the nearest round lot (100 shares), regardless of the actual number of shares shorted. This is because stocks are borrowed in round lots.
# Concentrated Margin Requirements
Accounts concentrated into a single position will see an increased maintenance margin rate on the symbol in which the account is concentrated.
1. Concentration is defined as a single security accounting for 70% of the market value of equities and the account is carrying a margin balance of $100,000 or more.
2. The Maintenance Margin Rate on the concentrated position will increase to 50%.
***
**Margin trading involves significant risk and is not suitable for all investors.** Before considering a margin loan, it is crucial that you carefully consider how borrowing fits with your investment objectives and risk tolerance.
When trading on margin, you assume higher market risk, and potential losses can exceed the collateral value in your account. Alpaca may sell any securities in your account, without prior notice, to satisfy a margin call. Alpaca may also change its “house” maintenance margin requirements at any time without advance written notice. You are not entitled to an extension of time on a margin call. Please review the Firms <Anchor label="Margin Disclosure Statement" target="_blank" href="https://files.alpaca.markets/disclosures/library/MarginDiscStmt.pdf">Margin Disclosure Statement</Anchor> before investing.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,86 @@
# Non-Trade Activities for Option Events
This page provides an overview of new NTAs for options-specific events
# Option Exercise
```
[
{
"id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf",
"activity_type": "OPEXC",
"date": "2023-07-21",
"net_amount": "0",
"description": "Option Exercise",
"symbol": "AAPL230721C00150000",
"qty": "-2",
"status": "executed"
},
{
"id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf",
"activity_type": "OPTRD",
"date": "2023-07-21",
"net_amount": "-30000",
"description": "Option Trade",
"symbol": "AAPL",
"qty": "200",
"price": "90",
"status": "executed"
}
]
```
The exercise event (OPEXC) is applicable to 2 contracts, and the corresponding trade (OPTRD) represents 200 of the underlying shares being purchased at a per-share amount of $150 (strike price).
# Option Assignment
```
[
{
"id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf",
"activity_type": "OPASN",
"date": "2023-07-01",
"net_amount": "0",
"description": "Option Assignment",
"symbol": "AAPL230721C00150000",
"qty": "2",
"status": "executed"
},
{
"activity_type": "OPTRD",
"id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf",
"date": "2023-07-01",
"net_amount": "30000",
"description": "Option Trade",
"symbol": "AAPL",
"qty": "-200",
"price": "150",
"status": "executed"
}
]
```
The assignment event (OPASN) is applicable to 2 contracts, and the corresponding trade (OPTRD) represents 200 of the underlying shares being sold at a per-share amount of $150 (strike price).
# ITM Option Expiry
In the event of an in-the-money (ITM) option reaching expiration without being designated as "Do Not Exercise" (DNE), the Alpaca system will automatically initiate the exercise process on behalf of the user. This process mirrors the Exercise event described earlier. In cases where there is insufficient buying power or underlying positions to facilitate the exercise, the system will generate an automated order for the liquidation of the position.
# OTM Option Expiry
```
[
{
"id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf",
"activity_type": "OPEXP",
"date": "2023-07-21",
"net_amount": "0",
"description": "Option Expiry",
"symbol": "AAPL230721C00150000",
"qty": "-2",
"status": "executed"
}
]
```
When a contract expires OTM, the Alpaca system will flatten the position and no further action is taken.
@@ -0,0 +1,432 @@
# Options Level 3 Trading
We're excited to support Multi-leg options trading! Use this section to read up on Alpaca's Multi-leg options trading capabilities.
<Callout icon="🎉" theme="default">
### Multi-leg options trading is now available for live trading!
</Callout>
## What are Multi-leg Orders?
A multi-leg (MLeg) order is a single, combined order that includes multiple option contracts calls, puts, or even shares—on the same underlying security. By bundling all legs together, the trade is executed as a single unit and each leg is associated with its own strike price, expiration date, or position type (long or short). MLeg orders are often used when traders need to set up complex strategies with several moving parts. A common example is the call spread, where the trader buys a call option at one strike price while simultaneously selling another call option at a higher strike, both for the same underlying asset.
## Why are Multi-leg Orders useful?
MLeg orders are particularly useful because they allow traders to execute complex options or stock combinations in one streamlined process, avoiding the delay or slippage risk of placing each transaction separately. By handling multiple legs at once, traders gain better control over their target price, reduce the chance of partial fills that could distort the intended strategy, and simplify trade management. The potential to minimize transaction costs—whether through tighter spreads, combined commissions, or efficient margin usage, also adds to their appeal.
A trader anticipates a stock will remain in a narrow price range.\
They set up an iron condor, which involves four legs:
* Buying one out-of-the-money (OTM) call.
* Selling a call at a closer strike.
* Buying an OTM put.
* Selling another put.
Placing these four legs as a single MLeg order ensures they fill together or not at all.\
This reduces the risk of partial fills, which could otherwise leave the trader with unwanted market exposure or unbalanced positions.
## How to submit a Multi-leg Order?
To submit a multi-leg (MLeg) order, set your “order\_class” to “mleg” and list each component of the strategy in a “legs” array, specifying details like the symbol, side (buy or sell), ratio quantity, and position intent (e.g., buy\_to\_open). Include any additional parameters (limit price, time in force, etc.) as part of the orders settings. Below is a cURL example showing how to place a POST request to the Alpaca API, passing in the necessary headers and JSON payload:
```curl
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"order_class": "mleg",
"qty": "1",
"type": "limit",
"limit_price": "0.6",
"time_in_force": "day",
"legs": [
{"symbol": "AAPL250117P00200000", "ratio_qty": "1", "side": "buy", "position_intent": "buy_to_open"},
{"symbol": "AAPL250117C00250000", "ratio_qty": "1", "side": "buy", "position_intent": "buy_to_open"}
]
}' | jq -r
```
## Some examples
### Long Call Spread
<Image align="center" className="border" border={true} src="https://files.readme.io/444efc02ec4fecfc528035df0c4dabacf34a9082a46b08af4de56859ef498e02-long_call_spread.png" />
Buy a lower-strike (190) call and sell a higher-strike (210) call on the same underlying:
```curl
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"order_class": "mleg",
"qty": "1",
"type": "limit",
"limit_price": "1.00",
"time_in_force": "day",
"legs": [
{
"symbol": "AAPL250117C00190000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_open"
},
{
"symbol": "AAPL250117C00210000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_open"
}
]
}' | jq -r
```
### Long Put Spread
<Image align="center" className="border" border={true} src="https://files.readme.io/a807ae88d756237e9fc54b29b2c0bcfa4d24c0013becbfbda70244f2144082f8-long_put_spread.png" />
Buy a higher-strike (210) put and sell a lower-strike (190) put on the same underlying:
```curl
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"order_class": "mleg",
"qty": "1",
"type": "limit",
"limit_price": "1.25",
"time_in_force": "day",
"legs": [
{
"symbol": "AAPL250117P00210000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_open"
},
{
"symbol": "AAPL250117P00190000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_open"
}
]
}' | jq -r
```
### Iron Condor
<Image align="center" src="https://files.readme.io/f86f771f0b68ce6af0706ba6e7a6d308af0678bbf3d71c23027722c600d67854-iron_condor.png" />
Combine two spreads (a put spread and a call spread) to bet on limited movement:
```curl
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"order_class": "mleg",
"qty": "1",
"type": "limit",
"limit_price": "1.80",
"time_in_force": "day",
"legs": [
{
"symbol": "AAPL250117P00190000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_open"
},
{
"symbol": "AAPL250117P00195000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_open"
},
{
"symbol": "AAPL250117C00205000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_open"
},
{
"symbol": "AAPL250117C00210000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_open"
}
]
}' | jq -r
```
Learn about the [differences between an iron condor and iron butterfly](https://alpaca.markets/learn/iron-condor-vs-iron-butterfly).
### Roll a Call Spread (strike price)
Close an existing short call spread and open a new one at different strikes in a single transaction:
```curl
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"order_class": "mleg",
"qty": "1",
"type": "limit",
"limit_price": "2.05",
"time_in_force": "day",
"legs": [
{
"symbol": "AAPL250117C00200000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_close"
},
{
"symbol": "AAPL250117C00205000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_close"
},
{
"symbol": "AAPL250117C00210000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_open"
},
{
"symbol": "AAPL250117C00215000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_open"
}
]
}' | jq -r
```
### Roll a Call Spread (expiration date)
Below is an example of rolling a short call spread from one expiration date to another in a single multi-leg (MLeg) order. The first two legs (with symbols ending in `250117`) are closed (`buy_to_close` and `sell_to_close`), and the new positions are opened at later-dated strikes (`250224`):
```curl
curl --request POST \
--url $APIDOMAIN/v2/orders \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Apca-Api-Key-Id: $APIKEY" \
--header "Apca-Api-Secret-Key: $SECRET" \
--data '
{
"order_class": "mleg",
"qty": "1",
"type": "limit",
"limit_price": "2.05",
"time_in_force": "day",
"legs": [
{
"symbol": "AAPL250117C00200000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_close"
},
{
"symbol": "AAPL250117C00205000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_close"
},
{
"symbol": "AAPL250124C00200000",
"ratio_qty": "1",
"side": "sell",
"position_intent": "sell_to_open"
},
{
"symbol": "AAPL250124C00205000",
"ratio_qty": "1",
"side": "buy",
"position_intent": "buy_to_open"
}
]
}' | jq -r
```
## Some deeper explanations
### How do we calculate maintenance margin requirements?
1. **Ignore Premiums**\
When calculating maintenance margin, do not factor in the premiums paid or received. Instead, focus on the intrinsic (exercise) payoffs.
2. **Model Each Options Payoff**\
Each option is represented by a piecewise linear payoff function (PnL) based on the underlying price (p).
<Image align="center" src="https://files.readme.io/32286a51ed97659a53b176cec7edbe0df282c76a42831ac7f81dc7bf80c4d26d-Screenshot_2025-01-20_at_19.01.45.png" />
3. **Combine Positions**\
To determine total payoff, sum the piecewise functions for all open positions:
<Image align="center" width="400px" src="https://files.readme.io/995133508c4fd0176faf1c370ba26aa1444b74719ecbb3e3d6ec4cb2d3b8f77a-Screenshot_2025-01-20_at_19.05.08.png" />
4. **Find Theoretical Maximum Loss**\
Maintenance margin is based on the worst-case scenario for the portfolio:
<Image align="center" width="450px" src="https://files.readme.io/66772ec029ae5859d8c97d2e063ea2893faa9c0c794c8593ee2af5f7fe514111-Screenshot_2025-01-20_at_19.04.45.png" />
In other words, you determine the underlying price p that yields the lowest (most negative) net payoff. The absolute value of this lowest point is the margin requirement.
5. **Different Expirations**\
For option positions with multiple expiration dates, calculate this theoretical maximum-loss approach separately for each expiration date, then use the largest resulting requirement across all expirations.
Lets see an example in order to understand why this way of calculating the maintenance margin is benefiting the customers.
Lets assume that a customer has the following positions
* Long Call for AAPL with Strike Price = 100
* Short Call for AAPL with Strike Price = 110
* Long Call for AAPL with Strike Price = 200
* Short Call for AAPL with Strike Price = 190
Using the traditional way of calculating maintenance margin we would form 2 spreads
Spread 1 (Call Credit Spread):
* Long Call for AAPL with Strike Price = 200
* Short Call for AAPL with Strike Price = 190
<Image align="center" src="https://files.readme.io/12a13471e5bdfaeb7669cac5d145b9f5ed1c7545b93c82999a38c447bde6f158-call_spread_1.png" />
With maintenance margin = 1000 since the difference between strike prices is 10 and the options multiplier is 100 so the `maintenance_margin = strike_price_diff * multiplier`
Spread 2 (Call Debit Spread):
* Long Call for AAPL with Strike Price = 100
* Short Call for AAPL with Strike Price = 110
<Image align="center" src="https://files.readme.io/ec7e1a5000f960cb984d595becc471067bafb8b8fa597cc08f15ac986c64aa88-call_spread_2.png" />
With maintenance margin = 0 since the difference between strike prices is 10 but the long is higher than the short.
So the **Total Maintenance Margin (Traditional) = 1000 + 0 = $1000**
**Universal Spread Rule Calculation**
When combining all four positions and evaluating the theoretical maximum combined loss, the payoff analysis shows that losses from one spread offset gains or losses in the other, resulting in a net theoretical maximum loss of zero. Hence:
* **Total Maintenance Margin (Universal Spread) = $0**
<Image align="center" src="https://files.readme.io/e30a3e59350972901aed6ff30df3409cba7f8115e4b88df66a9c33dfa8337bec-2_call_spreads.png" />
This “universal spread rule” or piecewise-payoff approach better reflects the true risk when these positions are considered together. By recognizing how the different calls offset one anothers exposures, the required margin is lower—benefiting the customer by aligning margin requirements with the actual worst-case scenario of the entire portfolio rather than assigning sums of individual spreads.
***
References:\
[https://cdn.cboe.com/resources/membership/Margin\_Manual.pdf](https://cdn.cboe.com/resources/membership/Margin_Manual.pdf)
*First, compute the intrinsic value of the options at price points for the underlying security or instrument that are set to correspond to every exercise price present in the spread. Then, net the intrinsic values at each price point. The maximum potential loss is the greatest loss, if any, from among the results.*
[https://cdn.cboe.com/resources/regulation/rule\_filings/margin\_requirements/SR-CBOE-2012-043.pdf](https://cdn.cboe.com/resources/regulation/rule_filings/margin_requirements/SR-CBOE-2012-043.pdf)
*(A) For spreads as defined in subparagraph (a)(5) of this Rule, the long options\
must be paid for in full. In addition, margin is required equal to the lesser of the\
amount required for the short option(s) by subparagraph (c)(5)(A) or (B),\
whichever is applicable, or the spreads maximum potential loss, if any. To\
determine the spreads maximum potential loss, first compute the intrinsic value\
of the options at price points for the underlying security or instrument that are set\
to correspond to every exercise price present in the spread. Then, net the intrinsic\
values at each price point. The maximum potential loss is the greatest loss, if any,\
from among the results. The proceeds for establishing the short options may be\
applied toward the cost of the long options and/or any margin requirement.*
***
### How do we calculate order cost basis?
**Definition:**
The **cost basis** of a multi-leg (MLeg) order is the **sum of**:
1. The **maintenance margin** required for the combined positions (as determined by the universal spread rule), and
2. The **net price** (debit/credit) from buying or selling the option contracts.
**Example:**
Consider a call credit spread on AAPL:
* Long Call (buy) for AAPL with Strike Price = 200
* Short Call (sell) for AAPL with Strike Price = 190
**Maintenance Margin:** Universal spread rule requires a margin of $1,000 for this spread.
**Net Option Price:**
* The **long call** premium to be paid is $10 (cost to the buyer).
* The **short call** premium to be received is $15 (credit to the seller).
* **Net Price** = (1510)=(15 - 10) =$5 credit
* Because each option contract covers 100 shares, multiply by 100:\
Net Price (per contract) x 100 = 5 x 100 = $500
* However, for cost-basis purposes, a credit (positive $5) effectively reduces the overall cost, so it becomes **-$5** in the orders net debit/credit calculation.
So, Total Cost Basis:\
Cost Basis = (Maintenance Margin) + (Net Price×Option Multiplier) = 1000 + (-5 x 100) = 1000 - 500 = $500
Hence, the cost basis—and the amount charged to the customer—for this multi-leg order is $500.
### Some Edge Scenarios
#### GCD `ratio_qty` requirement
When submitting an MLeg order, each legs `leg_ratio` must be in its simplest form. In other words, the greatest common divisor (GCD) among the `leg_ratio` values for the legs must be 1.
**Example** (wrong)
* Leg 1: `leg_ratio = 4`
* Leg 2: `leg_ratio = 2`
Because both ratios share a common divisor of 2, the system will reject this order. If a ratio must be 2:4, for instance, the user should enter it as 1:2 instead (dividing both sides by the GCD of 2).
**Reason for Enforcing Simplified Ratios**
By requiring that leg ratios be in their simplest form (prime to each other), the system can:
**Avoid Redundant Parent Quantities**: The ratio is intended to show the relative proportions of each leg; if the ratio isnt simplified, youre effectively duplicating the same information already available through the parent order quantity.
This approach ensures clarity in trade definitions and prevents potential confusion or errors in calculating fill quantities and margin requirements.
#### Restrictions on Combo Order(equity leg + contract leg)
MLeg orders that include an equity leg are not supported at this time. This means that combining an equity position with an options contract in a single order is not currently available for any trading strategy.
#### MLeg restrictions regarding uncovered legs
Starting on day zero of Options Level 3 trading, an MLeg order is accepted only if all its legs are covered within the same MLeg order. For example, an MLeg order containing two short call legs would be rejected, though submitting those short calls separately as single-leg orders is allowed. This restriction also impacts certain strategies, including rolling a short contract or rolling a calendar spread, since they would involve uncovered short legs within the same multi-leg order.
***
*The content of this article is for general informational purposes only. All examples are for illustrative purposes only.*
*Options trading is not suitable for all investors due to its inherent high risk, which can potentially result in significant losses. Please read[Characteristics and Risks of Standardized Options](https://www.theocc.com/company-information/documents-and-archives/options-disclosure-document) before investing in options.*
*All investments involve risk, and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Please note that diversification does not ensure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.*
*Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), member[FINRA/SIPC](https://www.finra.org/), a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.*
*This is not an offer, solicitation of an offer, or advice to buy or sell securities or open a brokerage account in any jurisdiction where Alpaca Securities are not registered or licensed, as applicable.*
@@ -0,0 +1,64 @@
# Options Orders
This page provides examples of valid order payloads
# Tier 1 Orders
## Sell a Covered Call
```
{
"symbol": "AAPL231201C00195000",
"qty": "2",
"side": "sell",
"type": "limit",
"limit_price": "1.05",
"time_in_force": "day"
}
```
Note, the account must have an existing position of 200 shares of AAPL as the order is for 2 contracts, and each option contract is for 100 shares of underlying.
## Sell a Cash-Secured Put
```
{
"symbol": "AAPL231201P00175000",
"qty": "1",
"side": "sell",
"type": "market",
"time_in_force": "day"
}
```
Note, the account must have sufficient buying power. The account must have ($175 strike) x (100 shares) x (1 contract) = $17,500 USD buying power available.
# Tier 2 Orders
## Buy a Call
```
{
"symbol": "AAPL240119C00190000",
"qty": "1",
"side": "buy",
"type": "market",
"time_in_force": "day"
}
```
The account must have sufficient buying power to afford the call option. If the market order is executed at $5.10, the account must have ($5.10 execution price) x (100 shares) x (1 contract) = $510.00 USD buying power.
## Buy a Put
```
{
"symbol": "AAPL240119P00170000",
"qty": "1",
"side": "buy",
"type": "market",
"time_in_force": "day"
}
```
The account must have sufficient buying power to afford purchasing put option. If the market order is executed at $1.04, the account must have ($1.04 execution price) x (100 shares) x (1 contract) = $104.00 USD buying power.
@@ -0,0 +1,227 @@
# Options Trading
We're excited to support options trading! Use this section to read up on Alpaca's options trading capabilities.
<Callout icon="🎉" theme="default">
### Options trading is now available on Live!
Share your feedback on [Options API for Trading API here](https://docs.google.com/forms/d/e/1FAIpQLScIYvKDJnKjXWESs6qxzpgk7pbvkt0IF1_nhv46t4o31-YOng/viewform)
</Callout>
# OpenAPI Spec
You can find our Open API docs here: [\<https://docs.alpaca.markets/reference>](https://docs.alpaca.markets/reference).
# Enablement
In the Paper environment, options trading capability will be enabled by default - there's nothing you need to do!
*Note, in production there will be a more robust experience to request options trading.*
For those who do not wish to have options trading enabled, you can disable options trading by navigating to your Trading Dashboard; Account > Configure.
The [Trading Account](https://docs.alpaca.markets/reference/getaccount-1) model was updated to reflect the account's options approved and trading levels.
The [Account Configuration](https://docs.alpaca.markets/reference/getaccountconfig-1) model was updated to show the maximum options trading level, and allow a user to downgrade to a lower level. Note, a different API will be provided for requesting a level upgrade for live account.
## Trading Levels
Alpaca supports the below options trading levels.
<Table align={["left","left","left"]}>
<thead>
<tr>
<th>
Level
</th>
<th>
Supported Trades
</th>
<th>
Validation
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
0
</td>
<td>
* Options trading is disabled
</td>
<td>
* NA
</td>
</tr>
<tr>
<td>
1
</td>
<td>
* Sell a covered call
* Sell cash-secured put
</td>
<td>
* User must own sufficient underlying shares
* User must have sufficient options buying power
</td>
</tr>
<tr>
<td>
2
</td>
<td>
* Level 1
* Buy a call
* Buy a put
</td>
<td>
* User must have sufficient options buying power
</td>
</tr>
<tr>
<td>
3
</td>
<td>
* Level 1,2
* Buy a call spread
* Buy a put spread
</td>
<td>
* User must have sufficient options buying power
</td>
</tr>
</tbody>
</Table>
# Option Contracts
## Assets API Update
The [Assets](https://docs.alpaca.markets/reference/get-v2-assets-1) endpoint has an existing `attributes` query parameter. Symbols which have option contracts will have an attribute called `options_enabled`.
Querying for symbols with the `options_enabled` attribute allows users to identify the universe of symbols with corresponding option contracts.
## Fetch Contracts
To obtain contract details, a new endpoint was introduced: `/v2/options/contracts?underlying_symbols=`. The endpoint supports fetching a single contract such as `/v2/options/contracts/{symbol_or_id}`
The default params are:
* expiration\_date\_lte: Next weekend
* limit: 100
Example: if `/v2/options/contracts` is called on Thursday, the response will include Thursday and Friday data. If called on a Saturday, the response will include Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, and Friday.
Here is an example of a response object:
```json
{
"option_contracts": [
{
"id": "6e58f870-fe73-4583-81e4-b9a37892c36f",
"symbol": "AAPL240119C00100000",
"name": "AAPL Jan 19 2024 100 Call",
"status": "active",
"tradable": true,
"expiration_date": "2024-01-19",
"root_symbol": "AAPL",
"underlying_symbol": "AAPL",
"underlying_asset_id": "b0b6dd9d-8b9b-48a9-ba46-b9d54906e415",
"type": "call",
"style": "american",
"strike_price": "100",
"size": "100",
"open_interest": "6168",
"open_interest_date": "2024-01-12",
"close_price": "85.81",
"close_price_date": "2024-01-12"
},
...
],
"page_token": "MTAw",
"limit": 100
}
```
More detailed information regarding this endpoint can be found on the OpenAPI spec [here](https://docs.alpaca.markets/reference/get-options-contracts).
# Market Data
Alpaca offers both [real-time](https://docs.alpaca.markets/docs/real-time-option-data) and [historical](https://docs.alpaca.markets/docs/historical-option-data) option data.
# Placing an Order
Placing an order for an option contract uses the same [Orders API](https://docs.alpaca.markets/reference/postorder) that is used for equities and crypto asset classes.
Given the same Orders API endpoint is being used, Alpaca has implemented a series of validations to ensure the options order does not include attributes relevant to other asset classes. Some of these validations include:
* Ensuring `qty` is a whole number
* `Notional` must not be populated
* `time_in_force` must be `day` or `gtc`
* `extended_hours` must be `false` or not populated
* `type` must be `market`,`limit`,`stop` or ,`stop_limit` (`stop` and `stop_limit` are only available for single-leg orders)
Examples of valid order payloads can be found as a child page [here](https://docs.alpaca.markets/docs/options-orders).
# Options Positions
Good news - the existing [Positions API](https://docs.alpaca.markets/reference/getallopenpositions) model will work with options contracts. There is not expected to be a change to this model.
As an additive feature, we aim to support fetching positions of a certain asset class; whether that be options, equities, or crypto.
# Account Activities
The existing schema for trade activities (TAs) are applicable for the options asset class. For example, the `FILL` activity is applicable to options and maintains it's current shape for options.
There are new non-trade activities (NTAs) entry types for options, however the schema stays the same. These NTAs reflect exercise, assignment, and expiry. More details can be found on a child page [here](https://docs.alpaca.markets/docs/non-trade-activities-for-option-events) and on the OpenAPI spec [here](https://docs.alpaca.markets/reference/getaccountactivities-2).
> 🚧 On PAPER NTAs are synced at the start of the following day. While your balance and positions are updated instantly, NTAs on PAPER will be visible in the Activities endpoint only the next day
# Exercise and DNE Instructions
## Exercise
Contract holders may submit exercise instructions to Alpaca. Alpaca will process instructions and work with our clearing partner accordingly.
All available held shares of this option contract will be exercised. By default, Alpaca will automatically exercise in-the-money (ITM) contracts at expiry.
Exercise requests will be processed immediately once received. Exercise requests submitted between market close and midnight will be rejected to avoid any confusion about when the exercise will settle.
Endpoint: `POST /v2/positions/{symbol_or_contract_id}/exercise`(no body)
More details in our OpenAPI Spec [here](https://docs.alpaca.markets/reference/optionexercise).
## Do Not Exercise
To submit a Do-not-exercise (DNE) instruction, please contact our support team.
# Expiration
* In the event no instruction is provided on an ITM contract, the Alpaca system will exercise the contract as long as it is ITM by at least $0.01 USD.
* Alpaca Operations has tooling and processes in place to identify accounts which pose a buying power risk with ITM contracts.
* In the event the account does not have sufficient buying power to exercise an ITM position, Alpaca will sell-out the position within 1 hour before expiry.
# Assignment
Options assignments are not delivered through websocket events. To check for assignment activity (non-trade activity, or NTA events), youll need to poll the REST API endpoints. Websocket support for NTAs is not currently available.
# FAQ
Please see our full FAQs here: [https://alpaca.markets/support/tag/options](https://alpaca.markets/support/tag/options)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,78 @@
# Paper Trading
Test your algos in our paper environment. Free and available to all Alpaca users.
Paper trading is a real-time simulation environment where you can test your code. You can reset and test your algorithm as much as you want using free, real-time market data. Paper trading simulates crypto trading as well. Paper trading works the same way as live trading end to end - except the order is not routed a live exchange. Instead, the system simulates the order filling based on the real-time quotes.
When you run your algorithm with the live market, there are many things that can happen that you may not see in backtesting. Orders may not be filled, prices may spike, or your network may get disconnected and retry may be needed. During the software development process, it is important to test your algorithm to catch these things in advance.
<Callout icon="🌍" theme="default">
### Anyone globally can create an Alpaca **Paper Only Account**! All you need to do is sign up with your email address.
</Callout>
An Alpaca **Paper Only Account** is for paper trading only. It allows you to fully utilize the Alpaca API and run your algorithm in our paper trading environment only. You wont be trading real money, but you will be able to track your simulated activity and balance in the Alpaca web dashboard. As an Alpaca Paper Only Account holder, you are only entitled to receive and make use of IEX market data. For more information about our paper trading environment, please refer to Paper Trading Specification.
# Paper vs Live
We are thrilled that many users have found paper trading useful, and we continue to work on improving our paper trading assumptions so that users may have a superior experience. However, please note that paper trading is only a simulation. It provides a good approximation for what one might expect in real trading, but it is not a substitute for real trading and performance may differ. Specifically, paper trading does not account for:
* Market impact of your orders
* Information leakage of your orders
* Price slippage due to latency
* Order queue position (for non-marketable limit orders)
* Price improvement received
* Regulatory fees
* Dividends
If you are interested to incorporate these issues into your testing, you may do so by trading a live brokerage account. Even small amounts of real money can often provide insight into issues not seen in a simulation environment.
## Paper vs Live
| Feature | Paper | Live |
| :---------------------------- | :---------------- | :--- |
| Eligibility | ✅ | ✅ |
| API Access | ✅ | ✅ |
| Free IEX Real Time Data | ✅ | ✅ |
| MFA | ✅ | ✅ |
| Margin Trading | ✅ | ✅ |
| Short Selling | ✅ | ✅ |
| Premarket/After Hours Trading | ✅ | ✅ |
| Borrow Fees | ⛔️ (Coming Soon!) | ✅ |
# Comparing Other Simulators
Users may be interested to compare their paper trading results on Alpaca with their paper trading results on other platforms such as Quantopian or Interactive Brokers. Please note there are several factors that may lead to performance differences. Paper trading platforms may have different:
* Fill prices
* Fill assumptions
* Liquidity assumptions
* Return calculation methodologies
* Market data sources
# Getting Started with Paper Trading
Your initial paper trading account is created with $100k balance as a default setting. You can reset the paper trading account at any time later with arbitrary amount as you configure.
Your paper trading account will have a different API key from your live account, and all you need to do to start using your paper trading account is to replace your API key and API endpoint with ones for the paper trading. The API spec is the same between the paper trading and live accounts. The API endpoint (base URL) is displayed in your paper trading dashboard, and please follow the instruction about how to set it depending on the library you are using. In most cases, you need to set an environment variable `APCA_API_BASE_URL = https://paper-api.alpaca.markets`
# Reset Your Paper Trading Account
We've updated the dashboard to allow you to create and delete paper accounts, rather than resetting them.
To create a new paper account, click the paper account number in the upper left corner of the dashboard and select "Open New Paper Account."
To delete an existing paper account, click the paper account number in the upper left corner, then go to "Account Settings." Locate the paper account you'd like to remove and click the "Delete Account" button next to it.
Don't forget to generate new API keys for any newly created account.
# Rules and Assumptions
* Paper trading account simulates our Pattern Day Trader checks. Orders that would generate a 4th Day Trade within 5 business days will be rejected if the real-time net worth is below $25,000. Please read the [Pattern DayTrader Protection](/docs/user-protection#pattern-day-trader-pdt-protection-at-alpaca) page for more details.
* Paper trading account **does NOT** simulate dividends.
* Paper trading account **does NOT** send order fill emails.
* Market Data API works identically.
* You cannot change the account balance after it is created, unless you reset it.
* Orders are filled only when they become marketable. This means that a non-marketable buy limit order will not be filled until its limit price is equal to or greater than the best ask price, and a non-marketable sell limit order will not be filled until its limit price is equal to or less than the best bid.
* Your order quantity is not checked against the NBBO quantities. In other words, you can submit and receive a fill for an order that is much larger than the actual available liquidity.\
When orders are eligible to be filled, they will receive partial fills for a random size 10% of the time. If the order price is still marketable, the remaining quantity would be re-evaluated for a subsequent fill.
* Regardless of whether you have a Paper Trading Only account or a real money brokerage account, all orders submitted in paper trading will be matched against the best available current market price (NBBO).
@@ -0,0 +1,139 @@
# Position Average Entry Price Calculation
How is the average entry price of a position is calculated?
# Description
The average entry price and the cost basis of a position are returned in the `avg_entry_price` and `cost_basis` fields in the [positions endpoints](https://docs.alpaca.markets/reference/positions).
```json
{
"asset_id": "904837e3-3b76-47ec-b432-046db621571b",
"symbol": "AAPL ",
"exchange": "NASDAQ",
"asset_class": "us_equity",
"avg_entry_price": "100.0",
"qty": "5",
"qty_available": "4",
"side": "long",
"market_value": "600.0",
"cost_basis": "500.0",
"unrealized_pl": "100.0",
"unrealized_plpc": "0.20",
"unrealized_intraday_pl": "5.0",
"unrealized_intraday_plpc": "0.0084",
"current_price": "120.0",
"lastday_price": "119.0",
"change_today": "0.0084"
}
```
There are different methods that can be used to calculate the cost basis and the average entry price of a position such as `Strict FIFO`, `Compressed FIFO`, `Weighted Average`, and others. Each method has its own rules for calculating the cost basis and average entry price after a sell transaction. This page aims to clarify which method is Alpaca using.
# Which Method is Alpaca Using?
* [Weighted Average](https://docs.alpaca.markets/us/docs/position-average-entry-price-calculation#weighted-average) is used for intraday positions (positions from intraday trades)
* [Compressed FIFO](https://docs.alpaca.markets/us/docs/position-average-entry-price-calculation#compressed-fifo-first-in-first-out) is used for the end-of-day positions (positions from previous trading days)
## Strict FIFO (First-In, First-Out)
Under the Strict FIFO method, the first position bought is the first position sold. Let's understand how it works:
The cost basis after the sell is calculated by deducting from the previous cost basis the price of the first open position multiplied by the sell quantity. In Strict FIFO, the sell quantity is covered using the first open position, however, if the first open position's quantity is not enough to cover the sell quantity, subsequent open positions are used.
### Example:
Suppose we have the following transactions:
Day 1:
1. Buy 100 shares at $10 per share (Cost basis = $1,000)
2. Buy 50 shares at $12 per share (Cost basis = $600)
Day 2:
1. Buy 30 shares at $15 per share (Cost basis = $450)
Day 3:
1. Sell 120 shares
After the sell transaction:
* Cost basis: `2050 - 100*10 - 20*12` = `$810`
* Average Entry Price: `cost_basis/qty_left` = `810/60` = `$13.5`
## Compressed FIFO (First-In, First-Out)
The Compressed FIFO method follows similar rules to Strict FIFO, with one key difference. It compresses intraday positions using a weighted average. Let's see how it differs:
### Example 1:
Using the same example from before:\
Day 1:
1. Buy 100 shares at $10 per share (Cost basis = $1,000)
2. Buy 50 shares at $12 per share (Cost basis = $600)
Day 2:
1. Buy 30 shares at $15 per share (Cost basis = $450)
Day 3:
1. Sell 120 shares
After the sell transaction:
* Cost Basis: `2050 - 120*(100*10 + 50*12)/150` = `$770`
* Average entry price: `cost_basis/qty_left` = `770/60` = `$12.83`
As you can see the positions in Day 1 were compressed into a total of 150 shares with an average price of `(100*10 + 50*12)/150`.
### Example 2
Day 1:
1. Buy 100 shares at $10 per share (Cost basis = $1,000)
2. Buy 50 shares at $9 per share (Cost basis = $450)
3. Sell 50 shares
4. Buy 50 shares at $11 per share (Cost basis = $550)
At the end of Day 1:
* Cost Basis: `2000 - 50*(100*10 + 50*9 + 50*11)/200` = `$1,500`
* Average Entry Price: `1500/150` = `$10`
## Weighted Average
The Weighted Average method calculates the cost basis based on the weighted average price per share. Here's how it works:
On Sell: The cost basis for the sold quantity is calculated by deducting the sell quantity multiplied by the average entry price of all the opened positions that the account holds.
### Example:
Using the same example from before:
Day 1:
1. Buy 100 shares at $10 per share (Cost basis = $1,000)
2. Buy 50 shares at $12 per share (Cost basis = $600)
Day 2:
1. Buy 30 shares at $15 per share (Cost basis = $450)
Day 3:
1. Sell 120 shares
After the sell the calculations based on the Weighted average method would be:
* Cost Basis: `2050 - 120*(100*10 + 50*12 + 30*15)/180` = `$683.33`
* Average Entry Price: `cost_basis/qty_left` = `683.33/60` = `$11.39`
# FAQ
## Why did the `avg_entry_price` and `cost_basis` of a position change the next day?
As described in the [Which method is Alpaca using?](https://docs.alpaca.markets/us/docs/position-average-entry-price-calculation#which-method-is-alpaca-using) the calculation method for determining the `avg_entry_price` and `cost_basis` differs between the `intraday positions` and the `end-of-day positions`. Consequently, it is possible for the `avg_entry_price` and `cost_basis` fields of a position to change the day after the last trade has occurred. This change occurs when our beginning-of-day (BOD) job executes and synchronizes positions from our ledger. For details regarding the timing of the beginning-of-day (BOD) job, please refer to the [Daily Processes and Reconciliations](https://docs.alpaca.markets/us/docs/daily-processes-and-reconcilations).
@@ -0,0 +1,279 @@
# Real-time Crypto Data
Crypto Data API provides websocket streaming for trades, quotes, orderbooks, minute bars and daily bars. This helps receive the most up to date market information that could help your trading strategy to act upon certain market movements.
Alpaca executes your crypto orders in its own exchange, and also supports Kraken, which is another crypto exchange. Therefore, `v1beta3` crypto market data endpoint distributes data from Alpaca and Kraken.
You can find the general description of the real-time WebSocket Stream [here](https://docs.alpaca.markets/docs/streaming-market-data). This page focuses on the crypto stream.
> 👍 Advanced Websockets Tutorial
>
> Check out our tutorial [Advanced Live Websocket Crypto Data Streams in Python](https://alpaca.markets/learn/advanced-live-websocket-crypto-data-streams-in-python/) for some tips on handling live crypto data stream in Python.
# URL
The URL for the crypto stream is
```
wss://stream.data.alpaca.markets/v1beta3/crypto/{loc}
```
Sandbox URL:
```
wss://stream.data.sandbox.alpaca.markets/v1beta3/crypto/{loc}
```
Possible values `{loc}` can have are:
* us - Alpaca US
* us-1 - Kraken US
* eu-1 - Kraken EU
The location us-1 represents the states listed below:
1. AL (Alabama)
2. AK (Alaska)
3. AR (Arkansas)
4. CO (Colorado)
5. DC (District of Columbia)
6. DE (Delaware)
7. FL (Florida)
8. HI (Hawaii)
9. LA (Louisiana)
10. MN (Minnesota)
11. NV (Nevada)
12. NH (New Hampshire)
13. NJ (New Jersey)
14. NM (New Mexico)
15. OK (Oklahoma)
16. OR (Oregon)
17. PA (Pennsylvania)
18. PR (Puerto Rico)
19. TN (Tennessee)
20. TX (Texas)
21. VA (Virginia)
22. WI (Wisconsin)
23. WY (Wyoming)
Please note that, at the moment `us-1` and `eu-1` stream Kraken market data (which is another crypto exchange), but the providers may change over time.
Multiple data points may arrive in each message received from the server. These data points have the following formats, depending on their type.
# Channels
## Trades
### Schema
| Attribute | Type | Notes |
| :-------- | :----- | :------------------------------------------------------------------------------------------------------ |
| `T` | string | message type, always “t” |
| `S` | string | symbol |
| `p` | number | trade price |
| `s` | number | trade size |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
| `i` | int | trade ID |
| `tks` | string | taker side: B for buyer, S for seller |
### Example
```json
{
"T": "t",
"S": "AVAX/USD",
"p": 47.299,
"s": 29.205707815,
"t": "2024-03-12T10:27:48.858228144Z",
"i": 3447222699101865076,
"tks": "S"
}
```
## Quotes
### Schema
| Attribute | Type | Notes |
| :-------- | :----- | :------------------------------------------------------------------------------------------------------ |
| `T` | string | message type, always “q” |
| `S` | string | symbol |
| `bp` | number | bid price |
| `bs` | number | bid size |
| `ap` | number | ask price |
| `as` | number | ask size |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
### Example
```json
{
"T": "q",
"S": "BAT/USD",
"bp": 0.35718,
"bs": 13445.46,
"ap": 0.3581,
"as": 13561.902,
"t": "2024-03-12T10:29:43.111588173Z"
}
```
## Bars
> 📘 Crypto bars contain quote mid-prices
>
> Due to the volatility of some currencies, including lack of trade volume at any given time, we include the quote midpoint prices in the bars to offer a better data experience. If in a bar no trade happens, the volume will be 0, but the prices will be determined by the quote prices.
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 and quote midpoints from the previous minute.
#### Daily Bars (`dailyBars`)
Daily bars are emitted right after each minute mark after the market opens. The daily bars contain all trades and quote midprices 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 bars closing price and volume.
### Schema
| Attribute | Type | Description |
| :-------- | :----- | :---------------------------------------------------------------------------- |
| `T` | string | message type: “b”, “d” or “u” |
| `S` | string | symbol |
| `o` | number | open price |
| `h` | number | high price |
| `l` | number | low price |
| `c` | number | close price |
| `v` | int | volume |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp |
### Example
```json
{
"T": "b",
"S": "BTC/USD",
"o": 71856.1435,
"h": 71856.1435,
"l": 71856.1435,
"c": 71856.1435,
"v": 0,
"t": "2024-03-12T10:37:00Z",
"n": 0,
"vw": 0
}
```
## Orderbooks
### Schema
| Attribute | Type | Notes |
| :-------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `T` | string | message type, always “o” |
| `S` | string | symbol |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
| `b` | array | bids: array of `p` (price) and `s` pairs. If `s` is zero, it means that that bid entry was removed from the orderbook. Otherwise it was added or updated. |
| `a` | array | asks: array of `p` (price) and `s` pairs. If `s` is zero, it means that that ask entry was removed from the orderbook. Otherwise it was added or updated. |
| `r` | boolean | reset: if true, the orderbook message contains the whole server side orderbook. This indicates to the client that they should reset their orderbook. Typically sent as the first message after subscription. |
### Example
#### Initial full orderbook
```json
{
"T": "o",
"S": "BTC/USD",
"t": "2024-03-12T10:38:50.79613221Z",
"b": [
{
"p": 71859.53,
"s": 0.27994
},
{
"p": 71849.4,
"s": 0.553986
},
{
"p": 71820.469,
"s": 0.83495
},
...
],
"a": [
{
"p": 71939.7,
"s": 0.83953
},
{
"p": 71940.4,
"s": 0.28025
},
{
"p": 71950.715,
"s": 0.555928
},
...
],
"r": true
}
```
`r` is true, meaning that this message contains the whole BTC/USD orderbook. It's truncated here for readability, the actual book has a lot more bids & asks.
#### Update message
```json json
{
"T": "o",
"S": "MKR/USD",
"t": "2024-03-12T10:39:39.445492807Z",
"b": [],
"a": [
{
"p": 2614.587,
"s": 12.5308
}
]
}
```
This means that the ask price level 2614.587 was changed to 12.5308. If there were previously no 2614.587 ask entry in the orderbook, then it should be added, if there were, its size should be updated.
#### Remove message
```json
{
"T": "o",
"S": "CRV/USD",
"t": "2024-03-12T10:39:40.501160019Z",
"b": [
{
"p": 0.7904,
"s": 0
}
],
"a": []
}
```
This means that the 0.7904 bid price level should be removed from the orderbook.
# Example
```
$ wscat -c wss://stream.data.alpaca.markets/v1beta3/crypto/us
connected (press CTRL+C to quit)
< [{"T":"success","msg":"connected"}]
> {"action": "auth", "key": "**\***", "secret": "**\***"}
< [{"T":"success","msg":"authenticated"}]
> {"action": "subscribe", "bars": ["BTC/USD"]}
< [{"T":"subscription","trades":[],"quotes":[],"orderbooks":[],"bars":["BTC/USD"],"updatedBars":[],"dailyBars":[]}]
< [{"T":"b","S":"BTC/USD","o":26675.04,"h":26695.36,"l":26668.79,"c":26688.7,"v":3.227759152,"t":"2023-03-17T12:28:00Z","n":93,"vw":26679.5912436798}]
< [{"T":"b","S":"BTC/USD","o":26687.9,"h":26692.91,"l":26628.55,"c":26651.39,"v":11.568622108,"t":"2023-03-17T12:29:00Z","n":197,"vw":26651.7679765663}]
```
@@ -0,0 +1,102 @@
# Real-time Option Data
This API provides option 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.
You can find the general description of the real-time WebSocket Stream [here](https://docs.alpaca.markets/docs/streaming-market-data). This page focuses on the option stream.
# URL
The URL for the option stream is
```
wss://stream.data.alpaca.markets/v1beta1/{feed}
```
Sandbox URL:
```
wss://stream.data.sandbox.alpaca.markets/v1beta1/{feed}
```
Substitute `indicative` or `opra` for `{feed}` depending on your subscription. The capabilities and differences for the `indicative` and `opra` subscriptions can be found \[[here](https://docs.alpaca.markets/docs/about-market-data-api#options)].
Any attempt to access a data feed not available for your subscription will result in an error during authentication.
# Message format
> 🚧 Msgpack
>
> Unlike the stock and crypto stream, the option stream is only available in [msgpack](https://msgpack.org/index.html) format. The SDKs are using this format automatically. For readability, the examples in the rest of this documentation will still be in json format (because msgpack is binary encoded).
# Channels
## Trades
### Schema
| Attribute | Type | Notes |
| :-------- | :----- | :------------------------------------------------------------------------------------------------------ |
| `T` | string | message type, always “t” |
| `S` | string | symbol |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
| `p` | number | trade price |
| `s` | int | trade size |
| `x` | string | exchange code where the trade occurred |
| `c` | string | trade condition |
### Example
```json
{
"T": "t",
"S": "AAPL240315C00172500",
"t": "2024-03-11T13:35:35.13312256Z",
"p": 2.84,
"s": 1,
"x": "N",
"c": "S"
}
```
## Quotes
### Schema
| Attribute | Type | Notes |
| :-------- | :----- | :------------------------------------------------------------------------------------------------------ |
| `T` | string | message type, always “q” |
| `S` | string | symbol |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
| `bx` | string | bid exchange code |
| `bp` | number | bid price |
| `bs` | int | bid size |
| `ax` | string | ask exchange code |
| `ap` | number | ask price |
| `as` | int | ask size |
| `c` | string | quote condition |
### Example
```json
{
"T": "q",
"S": "SPXW240327P04925000",
"t": "2024-03-12T11:59:38.897261568Z",
"bx": "C",
"bp": 9.46,
"bs": 53,
"ax": "C",
"ap": 9.66,
"as": 38,
"c": "A"
}
```
# Errors
Other than the [general stream errors](https://docs.alpaca.markets/docs/streaming-market-data#errors), you may receive these option-specific errors during your session:
| Error Message | Description |
| :---------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- |
| `[{"T":"error","code":412,"msg":"option messages are only available in MsgPack format"}]` | Use the `Content-Type: application/msgpack` header. |
| `[{"T":"error","code":413,"msg":"star subscription is not allowed for option quotes"}]` | You cannot subscribe to `*` for option quotes (there are simply too many of them). |
@@ -0,0 +1,453 @@
# Real-time Stock Data
This API provides stock 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.
You can find the general description of the real-time WebSocket Stream [here](https://docs.alpaca.markets/docs/streaming-market-data). This page focuses on the stock stream.
# URL
The URL for the stock stream is
```
wss://stream.data.alpaca.markets/{version}/{feed}
```
Sandbox URL:
```
wss://stream.data.sandbox.alpaca.markets/{version}/{feed}
```
Substitute `{version}/{feed}` to one of the followings:
* `v2/sip` is the SIP (Securities Information Processor) feed
* `v2/iex` is the IEX (Investors Exchange) feed
* `v2/delayed_sip` is a 15-minute delayed SIP feed
* `v1beta1/boats` is the BOATS (Blue Ocean ATS) feed
* `v1beta1/overnight` is the derived Alpaca overnight feed
These feeds are described [here](https://docs.alpaca.markets/docs/historical-stock-data-1#feed-parameter).
Any attempt to access a data feed not available for your subscription will result in an error during authentication.
# Channels
You can [subscribe](https://docs.alpaca.markets/docs/streaming-market-data#subscription) to the channels described in this section. For example
```json
{"action":"subscribe","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"]}
```
## Trades
### Schema
| Attribute | Type | Notes |
| :-------- | :-------------- | :------------------------------------------------------------------------------------------------------ |
| `T` | string | message type, always “t” |
| `S` | string | symbol |
| `i` | int | trade ID |
| `x` | string | exchange code where the trade occurred |
| `p` | number | trade price |
| `s` | int | trade size |
| `c` | array`<string>` | trade condition |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
| `z` | string | tape |
### Example
```json
{
"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
| Attribute | Type | Notes |
| :-------- | :-------------- | :------------------------------------------------------------------------------------------------------ |
| `T` | string | message type, always “q” |
| `S` | string | symbol |
| `ax` | string | ask exchange code |
| `ap` | number | ask price |
| `as` | int | ask size in round lots |
| `bx` | string | bid exchange code |
| `bp` | number | bid price |
| `bs` | int | bid size in round lots |
| `c` | array`<string>` | quote condition |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
| `z` | string | tape |
### Example
```json
{
"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.
Note: Understanding which trades are excluded from minute bars is crucial for accurate data analysis. For more detailed information on how minute bars are calculated and excluded trades, please refer to this article [Stock Minute Bars](https://alpaca.markets/learn/stock-minute-bars/).
#### 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 bars closing price and volume.
### Schema
| Attribute | Type | Description |
| :-------- | :----- | :---------------------------------------------------------------------------- |
| `T` | string | message type: “b”, “d” or “u” |
| `S` | string | symbol |
| `o` | number | open price |
| `h` | number | high price |
| `l` | number | low price |
| `c` | number | close price |
| `v` | int | volume |
| `vw` | number | volume-weighted average price |
| `n` | int | number of trades |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp |
### Example
```json
{
"T": "b",
"S": "SPY",
"o": 388.985,
"h": 389.13,
"l": 388.975,
"c": 389.12,
"v": 49378,
"n": 461,
"vw": 389.062639,
"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
| Attribute | Type | Description |
| :-------- | :-------------- | :---------------------------------------------------------------------------- |
| `T` | string | message type, always “c” |
| `S` | string | symbol |
| `x` | string | exchange code |
| `oi` | int | original trade id |
| `op` | number | original trade price |
| `os` | int | original trade size |
| `oc` | array`<string>` | original trade conditions |
| `ci` | int | corrected trade id |
| `cp` | number | corrected trade price |
| `cs` | int | corrected trade size |
| `cc` | array`<string>` | corrected trade conditions |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp |
| `z` | string | tape |
### Example
```json
{
"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
| Attribute | Type | Description |
| :-------- | :----- | :---------------------------------------------------------------------------- |
| `T` | string | message type, always “x” |
| `S` | string | symbol |
| `i` | int | trade id |
| `x` | string | trade exchange |
| `p` | number | trade price |
| `s` | int | trade size |
| `a` | string | action (“C” for cancel, “E” for error) |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp |
| `z` | string | tape |
### Example
```json
{
"T": "x",
"S": "GOOGL",
"i": 465,
"x": "D",
"p": 105.31,
"s": 300,
"a": "C",
"z": "C",
"t": "2023-04-06T13:15:42.83540958Z"
}
```
## LULDs
Limit Up - Limit Down messages provide upper and lower limit price bands to securities.
### Schema
| Attribute | Type | Description |
| :-------- | :----- | :---------------------------------------------------------------------------- |
| `T` | string | message type, always “l” |
| `S` | string | symbol |
| `u` | number | limit up price |
| `d` | number | limit down price |
| `i` | string | indicator |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp |
| `z` | string | tape |
### Example
```json
{
"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
| Attribute | Type | Description |
| :-------- | :----- | :---------------------------------------------------------------------------- |
| `T` | string | message type, always “s” |
| `S` | string | symbol |
| `sc` | string | status code |
| `sm` | string | status message |
| `rc` | string | reason code |
| `rm` | string | reason message |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp |
| `z` | string | tape |
### Example
```json
{
"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)
| Code | Value |
| :--- | :----------------------------- |
| 2 | Trading Halt |
| 3 | Resume |
| 5 | Price Indication |
| 6 | Trading Range Indication |
| 7 | Market Imbalance Buy |
| 8 | Market Imbalance Sell |
| 9 | Market On Close Imbalance Buy |
| A | Market On Close Imbalance Sell |
| C | No Market Imbalance |
| D | No Market On Close Imbalance |
| E | Short Sale Restriction |
| F | Limit Up-Limit Down |
#### Tape C & O (UTP)
| Codes | Resume |
| :---- | :----------------------- |
| H | Trading Halt |
| Q | Quotation Resumption |
| T | Trading Resumption |
| P | Volatility Trading Pause |
### Reason Codes
#### Tape A & B (CTA)
| Code | Value |
| :--- | :--------------------------------------------- |
| A | Additional Information Requested |
| C | Regulatory Concern |
| D | News Released (formerly News Dissemination) |
| E | Merger Effective |
| F | ETF Component Prices Not Available |
| I | Order Imbalance |
| M | Limit Up-Limit Down (LULD) Trading Pause |
| N | Corporate Action |
| O | New Security Offering |
| P | News Pending |
| V | Intraday Indicative Value Not Available |
| X | Operational |
| Y | Sub-Penny Trading |
| 1 | Market-Wide Circuit Breaker Level 1 Breached |
| 2 | Market-Wide Circuit Breaker Level 2 Breached |
| 3 | Market-Wide Circuit Breaker Level 3 Breached |
#### Tape C & O (UTP)
| Code | Value |
| :--- | :-------------------------------------------------------------------- |
| T1 | Halt News Pending |
| T2 | Halt News Dissemination |
| T5 | Single Stock Trading Pause In Affect |
| T6 | Regulatory Halt Extraordinary Market Activity |
| T8 | Halt ETF |
| T12 | Trading Halted; For information requested by NASDAQ |
| H4 | Halt Non Compliance |
| H9 | Halt Filings Not Current |
| H10 | Halt SEC Trading Suspension |
| H11 | Halt Regulatory Concern |
| 01 | Operations Halt, Contact Market Operations |
| IPO1 | IPO Issue not yet Trading |
| M1 | Corporate Action |
| M2 | Quotation Not Available |
| LUDP | Volatility Trading Pause |
| LUDS | Volatility Trading Pause Straddle Condition |
| MWC1 | Market Wide Circuit Breaker Halt Level 1 |
| MWC2 | Market Wide Circuit Breaker Halt Level 2 |
| MWC3 | Market Wide Circuit Breaker Halt Level 3 |
| MWC0 | Market Wide Circuit Breaker Halt Carry over from previous day |
| T3 | News and Resumption Times |
| T7 | Single Stock Trading Pause/Quotation-Only Period |
| R4 | Qualifications Issues Reviewed/Resolved; Quotations/Trading to Resume |
| R9 | Filing Requirements Satisfied/Resolved; Quotations/Trading To Resume |
| C3 | Issuer News Not Forthcoming; Quotations/Trading To Resume |
| C4 | Qualifications Halt ended; maint. Req. met; Resume |
| C9 | Qualifications Halt Concluded; Filings Met; Quotes/Trades To Resume |
| C11 | Trade Halt Concluded By Other Regulatory Auth,; Quotes/Trades Resume |
| R1 | New Issue Available |
| R | Issue Available |
| IPOQ | IPO security released for quotation |
| IPOE | IPO security positioning window extension |
| MWCQ | Market Wide Circuit Breaker Resumption |
## Order imbalances
Order imbalance is a situation resulting from an excess of buy or sell orders for a specific security on a trading exchange, making it impossible to match the orders of buyers and sellers. Order imbalance messages are typically sent during limit-up and limit-down trading halts. You have to subscribe to these messages using the `imbalances` JSON key:
```json
{"action":"subscribe","imbalances":["INAQU"]}
```
### Schema
| Attribute | Type | Notes |
| :-------- | :----- | :------------------------------------------------------------------------------------------------------ |
| `T` | string | message type, always “i” |
| `S` | string | symbol |
| `p` | number | price |
| `z` | string | tape |
| `t` | string | [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) formatted timestamp with nanosecond precision |
### Example
```json
{
"T": "i",
"S": "INAQU",
"p": 9.12,
"z": "C",
"t": "2024-12-13T19:58:09.242138635Z"
}
```
# Example
```json Shell
$ 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"}]
```
@@ -0,0 +1,37 @@
# Registering Your App
<br />
Before integrating with Alpaca, youll need to create a new OAuth application from your Alpaca Connect Apps page.
You can access the [Alpaca Connect](https://app.alpaca.markets/connect) page through your dashboard after logging into your Alpaca brokerage account
### 1. Visit [Alpaca Connect](https://app.alpaca.markets/connect) on the Dashboard
![Alpaca Connect](https://files.readme.io/224a3dc-20230627_connect.png)
### 2. Navigate to My Developed Apps Tab
<br />
### 3. Click on Submit Your App and Fill in the Details
Please complete the Alpaca Connect Application for our team to review.
![](https://files.readme.io/01492f3c44bd644cb3d1eb075f17a4228a5d44abc0573c8ab808763c8d8f5d21-image.png)
<br />
### 3. Obtain Your Credentials
Once you add your relevant information and create the app, you will receive your Client ID and Client Secret. Please be sure to safely store this.
![](https://files.readme.io/7db8c14-Screenshot_2023-05-09_at_13.45.51.png)
<br />
### 4. Application Review
Once your application has been submitted, our team will follow up with you shortly via email to complete the remaining process.
<br />
@@ -0,0 +1,35 @@
# Regulatory Fees
## FEE types and effective rates
The following FEEs are applied to options trades.
| Type | When | Charged By |
| :----------------------------- | :---------------------------------- | :---------------- |
| Trading Activity Fee (TAF) | Sells only | FINRA |
| Options Regulatory Fee (ORF) | Buys and sells | Options Exchanges |
| Options Clearing Corporation | Buys and sells up to 2750 contracts | OCC |
| Consolidated Audit Trail (CAT) | Buys and sells | FINRA-CAT |
The following FEEs are applied to equities.
| Type | When | Charged By |
| :----------------------------- | :------------- | :--------- |
| Trading Activity Fee (TAF) | Sells only | FINRA |
| Consolidated Audit Trail (CAT) | Buys and sells | FINRA-CAT |
For our current effective rates, please refer to our brokerage fee schedule available here:
<Anchor label="https://alpaca.markets/disclosures" target="_blank" href="https://alpaca.markets/disclosures">[https://alpaca.markets/disclosures](https://alpaca.markets/disclosures)</Anchor>
## How Fees are charged and reflected in account balances
1. Alpaca's trading system keeps track of the accrued FEE amounts intraday and deducts the pending amounts from account balances.
2. At EOD, we charge each account the fees for that trading day
3. We round up total fees based on the currencys precision to the nearest decimal place.
For example, USD has a precision of 0.01. If the total fee is calculated as 0.00083, it will be rounded up to 0.01 (i.e., 1 penny).
## Additional resources
* [https://www.finra.org/rules-guidance/rulebooks/industry/trading-activity-fee](https://www.finra.org/rules-guidance/rulebooks/industry/trading-activity-fee)
* [https://www.catnmsplan.com/](https://www.catnmsplan.com/)
* [https://www.sec.gov/newsroom/press-releases/2024-47](https://www.sec.gov/newsroom/press-releases/2024-47)
@@ -0,0 +1,34 @@
# SDKs and Tools
# Official Client SDKs
Alpaca provides and supports the following open-source SDKs in a number of languages. You can leverage these libraries to easily access our API in your own application code or your trading scripts.
* **Python**: [alpaca-py](https://alpaca.markets/sdks/python/) / [PyPI](https://pypi.org/project/alpaca-py/)
* **.NET/C#**: [alpaca-trade-api-csharp](https://github.com/alpacahq/alpaca-trade-api-csharp/) / [NuGet](https://www.nuget.org/packages/Alpaca.Markets/)
* **Node**: [alpaca-trade-api-js](https://github.com/alpacahq/alpaca-trade-api-js/) / [npm](https://www.npmjs.com/package/@alpacahq/alpaca-trade-api)
* **Go**: [alpaca-trade-api-go](https://github.com/alpacahq/alpaca-trade-api-go/)
* **Python (legacy)**: [alpaca-trade-api-python](https://github.com/alpacahq/alpaca-trade-api-python/) / [PyPI](https://pypi.org/project/alpaca-trade-api/)
# Alpaca-py (Python SDK)
[**Alpaca-py**](https://alpaca.markets/sdks/python/getting_started.html) provides an interface for interacting with the API products Alpaca offers. These API products are provided as various REST, WebSocket and SSE endpoints that allow you to do everything from streaming market data to creating your own trading apps. Here are some things you can do with Alpaca-py:
* [**Market Data API**](https://alpaca.markets/sdks/python/api_reference/data_api.html): Access live and historical market data for 5000+ stocks and 20+ crypto.
* [**Trading API**](https://alpaca.markets/sdks/python/api_reference/trading_api.html): Trade stock and crypto with lightning fast execution speeds.
* [**Broker API & Connect**](https://alpaca.markets/sdks/python/api_reference/broker_api.html): Build investment apps - from robo-advisors to brokerages.
# Community-Made SDKs
In addition to the SDKs directly supported by Alpaca, individual members of our community have created and contributed their own wrappers for these other languages. We are providing these links as a courtesy to the community and to our users who are looking for the API wrapper in other languages or variants. Please be sure to carefully review any code you use to access our financial trading API and/or trust your account credentials to.
Made your own wrapper for a language not listed? Join our community Slack and let us know about it!
* **C++**: [alpaca-trade-api-cpp](https://github.com/marpaia/alpaca-trade-api-cpp)
* **Java**: [alpaca-java](https://github.com/Petersoj/alpaca-java)
* **Node.js** (TypeScript): [alpaca-ts](https://github.com/alpacahq/alpaca-ts)
* **R**: [alpaca-for-r](https://github.com/yogat3ch/AlpacaforR)
* **Rust**: [apca](https://github.com/d-e-s-o/apca) (SDK) & [apcacli](https://github.com/d-e-s-o/apcacli) (CLI)
* **Scala**: [Alpaca Scala](https://github.com/cynance/alpaca-scala)
* **Ruby**: [alpaca-trade-api](https://github.com/ccjr/alpaca-trade-api)
* **Elixir**: [alpaca\_elixir](https://github.com/jrusso1020/alpaca_elixir)
@@ -0,0 +1,378 @@
# WebSocket Stream
This API provides a [WebSocket](https://en.wikipedia.org/wiki/WebSocket) stream for real-time market data. This allows you to receive the most up-to-date market information, which can be used to power your trading strategies.
The WebSocket stream provides real-time updates of the following market data:
* [Stocks](https://docs.alpaca.markets/docs/real-time-stock-pricing-data)
* [Crypto](https://docs.alpaca.markets/docs/real-time-crypto-pricing-data)
* [Options](https://docs.alpaca.markets/docs/real-time-option-data)
* [News](https://docs.alpaca.markets/docs/streaming-real-time-news)
# Steps to use the stream
To use the WebSocket stream follow these steps:
## Connection
To establish a connection use the stream URL depending on the data you'd like to consume. The general schema of the URL is
```
wss://stream.data.alpaca.markets/{version}/{feed}
```
Sandbox URL:
```
wss://stream.data.sandbox.alpaca.markets/{version}/{feed}
```
Any attempt to access a data feed not available for your subscription will result in an error during authentication.
> 📘 Test stream
>
> We provide a test stream that is available all the time, even outside market hours, on this URL:
>
> ```
> wss://stream.data.alpaca.markets/v2/test
> ```
>
> Use the symbol "FAKEPACA" when trying out this test stream.
Upon successfully connecting, you will receive the welcome message:
```json
[{"T":"success","msg":"connected"}]
```
> 🚧 Connection limit
>
> The number of connections to a single endpoint from a user is limited based on the user's subscription, but in most subscriptions (including Algo Trader Plus) this limit is 1. If you try to open a second connection, you'll get this error:
>
> ```json
> [{"T":"error","code":406,"msg":"connection limit exceeded"}]
> ```
## Authentication
You need to authenticate yourself using your credentials. This can be done multiple ways
### For the Trading API, Authenticate with HTTP headers
You can set the same headers used for the historical market data and trading endpoints:
* `APCA-API-KEY-ID`
* `APCA-API-SECRET-KEY`
Here's an example using a WebSocket client called [websocat](https://github.com/vi/websocat):
```
$ websocat wss://stream.data.alpaca.markets/v2/test \
-H="APCA-API-KEY-ID: {KEY_ID}" -H="APCA-API-SECRET-KEY: {SECRET}"
```
### For the Broker API, Authenticate with Basic Authentication
You can use the same Basic Authentication header used for the historical market data and trading endpoints:
* `Authorization` = `base64encode({KEY}:{SECRET})`
**Note:** `base64encode({KEY_ID}:{SECRET})` is the base64 encoding of the `{KEY}:{SECRET}` string.
### For both Trading & Broker API, Authenticate with a message
Alternatively, for both the trading & broker API, you can authenticate with a message after connection:
```json
{"action": "auth", "key": "{KEY_ID}", "secret": "{SECRET}"}
```
Keep in mind though, that you only have 10 seconds to do so after connecting.
If you provided correct credentials you will receive another success message:
```json
[{"T":"success","msg":"authenticated"}]
```
### For OAuth applications, Authenticate with a message
For an OAuth integration, authenticate with a message and use “oauth” as your key, and user token as the “secret”. (do NOT use your Client Secret)
```json json
{"action": "auth", "key": "oauth", "secret": "{TOKEN}"}
```
Keep in mind that most users can have only 1 active stream connection. If that connection is used by another 3rd party application, you will receive an error: 406 and “connection limit exceeded” message. Similarly, if the user wants to access their stream from an API or another 3rd party application, they will also receive the same error message.
## Subscription
Congratulations, you are ready to receive real-time market data!
You can send one or more subscription messages. The general format of the subscribe message is this:
```json
{
"action": "subscribe",
"<channel1>": ["<SYMBOL1>"],
"<channel2>": ["<SYMBOL2>","<SYMBOL3>"],
"<channel3>": ["*"]
}
```
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 dont have to send what youre already subscribed to.
For example in the test stream, you can send this message:
```json
{"action":"subscribe","trades":["FAKEPACA"]}
```
The available channels are described for each streaming endpoints separately.
Much like subscribe you can also send an unsubscribe message that subtracts the list of subscriptions specified from your current set of subscriptions.
```json
{"action":"unsubscribe","quotes":["FAKEPACA"]}
```
After subscribing or unsubscribing you will receive a message that describes your current list of subscriptions.
```json
[{"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:
```json
> {"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"]}]
```
# Messages
## Format
Every message you receive from the server will be in the format:
```json json
[{"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.
## Content type
You can use the `Content-Type` header to switch between text and binary message [data frame](https://datatracker.ietf.org/doc/html/rfc6455#section-5.6):
* `Content-Type: application/json`
* `Content-Type: application/msgpack`
## 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](https://datatracker.ietf.org/doc/html/rfc7692). [Our SDKs](https://docs.alpaca.markets/us/docs/sdks-and-tools) handle this for you so in most cases you wont have to implement anything yourself.
## Errors
You may receive an error during your session. Below are the general errors you may run into.
<Table align={["left","left","left"]}>
<thead>
<tr>
<th>
Code
</th>
<th>
Message
</th>
<th>
Description
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
400
</td>
<td>
invalid syntax
</td>
<td>
The message you sent to the server did not follow the specification.\
:warning: This can also be sent if the symbol in your subscription message is in invalid format.
</td>
</tr>
<tr>
<td>
401
</td>
<td>
not authenticated
</td>
<td>
You have attempted to subscribe or unsubscribe before [authentication](https://docs.alpaca.markets/docs/streaming-market-data#authentication).
</td>
</tr>
<tr>
<td>
402
</td>
<td>
auth failed
</td>
<td>
You have provided invalid authentication credentials.
</td>
</tr>
<tr>
<td>
403
</td>
<td>
already authenticated
</td>
<td>
You have already successfully authenticated during your current session.
</td>
</tr>
<tr>
<td>
404
</td>
<td>
auth timeout
</td>
<td>
You failed to successfully authenticate after connecting. You only have a few seconds to authenticate after connecting.
</td>
</tr>
<tr>
<td>
405
</td>
<td>
symbol limit exceeded
</td>
<td>
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.
</td>
</tr>
<tr>
<td>
406
</td>
<td>
connection limit exceeded
</td>
<td>
You already have the number of sessions allowed by your subscription.
</td>
</tr>
<tr>
<td>
407
</td>
<td>
slow client
</td>
<td>
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.
</td>
</tr>
<tr>
<td>
409
</td>
<td>
insufficient subscription
</td>
<td>
You have attempted to access a data source not available in your subscription package.
</td>
</tr>
<tr>
<td>
410
</td>
<td>
invalid subscribe action for this feed
</td>
<td>
You tried to subscribe to channels not available in the stream, for example to `bars` in the [option stream](https://docs.alpaca.markets/docs/real-time-option-data) or to `trades` in the [news stream](https://docs.alpaca.markets/docs/streaming-real-time-news).
</td>
</tr>
<tr>
<td>
500
</td>
<td>
internal error
</td>
<td>
An unexpected error occurred on our end. Please let us know if this happens.
</td>
</tr>
</tbody>
</Table>
Beside these there can be some endpoint specific errors, for example in the [option stream](https://docs.alpaca.markets/docs/real-time-option-data#errors).
# Example
Here's a complete example of the test stream using the [wscat](https://github.com/websockets/wscat) cli tool:
```json
$ wscat -c wss://stream.data.alpaca.markets/v2/test
Connected (press CTRL+C to quit)
< [{"T":"success","msg":"connected"}]
> {"action":"auth","key":"<YOUR API KEY>","secret":"<YOUR API SECRET>"}
< [{"T":"success","msg":"authenticated"}]
> {"action":"subscribe","bars":["FAKEPACA"],"quotes":["FAKEPACA"]}
< [{"T":"subscription","trades":[],"quotes":["FAKEPACA"],"bars":["FAKEPACA"]}]
< [{"T":"q","S":"FAKEPACA","bx":"O","bp":133.85,"bs":4,"ax":"R","ap":135.77,"as":5,"c":["R"],"z":"A","t":"2024-07-24T07:56:53.639713735Z"}]
< [{"T":"q","S":"FAKEPACA","bx":"O","bp":133.85,"bs":4,"ax":"R","ap":135.77,"as":5,"c":["R"],"z":"A","t":"2024-07-24T07:56:58.641207127Z"}]
< [{"T":"b","S":"FAKEPACA","o":132.65,"h":136,"l":132.12,"c":134.65,"v":205,"t":"2024-07-24T07:56:00Z","n":16,"vw":133.7}]
```
@@ -0,0 +1,67 @@
# Real-time News
This API provides stock market news on a websocket stream. You can find the general description of the real-time WebSocket Stream [here](https://docs.alpaca.markets/docs/streaming-market-data). This page focuses on the news stream.
# URL
The URL for the news stream is
```
wss://stream.data.alpaca.markets/v1beta1/news
```
Sandbox URL:
```
wss://stream.data.sandbox.alpaca.markets/v1beta1/news
```
# Channels
## News
### Schema
| Attribute | Type | Notes |
| :---------- | :-------------- | :------------------------------------------------------------------------------------------- |
| T | string | Type of message (“n” for news) |
| id | int | News article ID |
| headline | string | Headline or title of the article |
| summary | string | Summary text for article (may be first sentence of content) |
| author | string | Original author of news article |
| created\_at | string | Date article was created in [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) format |
| updated\_at | string | Date article was updated in [RFC-3339](https://datatracker.ietf.org/doc/html/rfc3339) format |
| content | string | Content of news article (might contain HTML) |
| url | string | URL of article (if applicable) |
| symbols | array`<string>` | List of related or mentioned symbols |
| source | string | Source where the news originated from (e.g. Benzinga) |
### Example
```json
{
"T": "n",
"id": 24918784,
"headline": "Corsair Reports Purchase Of Majority Ownership In iDisplay, No Terms Disclosed",
"summary": "Corsair Gaming, Inc. (NASDAQ:CRSR) (“Corsair”), a leading global provider and innovator of high-performance gear for gamers and content creators, today announced that it acquired a 51% stake in iDisplay",
"author": "Benzinga Newsdesk",
"created_at": "2022-01-05T22:00:37Z",
"updated_at": "2022-01-05T22:00:38Z",
"url": "https://www.benzinga.com/m-a/22/01/24918784/corsair-reports-purchase-of-majority-ownership-in-idisplay-no-terms-disclosed",
"content": "\u003cp\u003eCorsair Gaming, Inc. (NASDAQ:\u003ca class=\"ticker\" href=\"https://www.benzinga.com/stock/CRSR#NASDAQ\"\u003eCRSR\u003c/a\u003e) (\u0026ldquo;Corsair\u0026rdquo;), a leading global ...",
"symbols": ["CRSR"],
"source": "benzinga"
}
```
# Example
```json
$ websocat -H="APCA-API-KEY-ID: ${APCA_API_KEY_ID}" -H="APCA-API-SECRET-KEY: ${APCA_API_SECRET_KEY}" \
"${APCA_API_STREAM_URL}/v1beta1/news"
[{"T":"success","msg":"connected"}]
[{"T":"success","msg":"authenticated"}]
{"action":"subscribe","news":["*"]}
[{"T":"subscription","news":["*"]}]
[{"T":"n","id":40892639,"headline":"VinFast Officially Launches VF 3 Electric Vehicle In The Philippines","summary":"VinFast Auto has officially opened pre-orders for the VF 3 in the Philippines. From September 19 to 30, early customers who reserve the VF 3 will enjoy several attractive incentives and privileges, including a","author":"Benzinga Newsdesk","created_at":"2024-09-17T09:02:44Z","updated_at":"2024-09-17T09:02:45Z","url":"https://www.benzinga.com/news/24/09/40892639/vinfast-officially-launches-vf-3-electric-vehicle-in-the-philippines","content":"\u003cp\u003eVinFast Auto has officially opened pre-orders for the VF 3 in the Philippines.\u003c/p\u003e\u003cp\u003e\u0026nbsp;\u003c/p\u003e\u003cp\u003eFrom September 19 to 30, early customers who reserve the VF 3 will enjoy several attractive incentives and privileges, including a special price of 605,000 pesos (battery subscription) or 705,000 pesos (battery included). After this period, the prices will revert to the MSRP of 645,000 pesos (battery subscription) and 745,000 pesos (battery included).\u003cbr\u003e\u003cbr\u003eAdditionally, early VF 3 customers will have the privilege of choosing from nine striking exterior paint colors, including four base colors and five premium options, free of charge. Premium paint colors will cost an additional 20,000 pesos after this period.\u003cbr\u003e\u003cbr\u003eMoreover, from September 19 to 30, for only 40,000 pesos, early customers can customize their car's paint beyond the nine available colors. This will be the only time VinFast offers this exclusive privilege for the VF 3.\u003cbr\u003e\u003cbr\u003eVinFast is accepting deposits of 5,000 pesos through its official website or at authorized dealerships (refundable under VinFast's terms).\u003cbr\u003e\u0026nbsp;\u003c/p\u003e","symbols":["VFS"],"source":"benzinga"}]
```
@@ -0,0 +1,63 @@
# The Intraday Margin Rule
<br />
### **Q: What is the Intraday Margin Rule?**
The Intraday Margin Rule is a FINRA-mandated framework that replaces the legacy Pattern Day Trader (PDT) system. The rule shifts the regulatory focus from **trade frequency** (counting transactions) to **real-time risk exposure** (measuring actual financial risk during the trading day).
### **Q: Has the Pattern Day Trader (PDT) designation been removed?**
Yes. The definition of a "pattern day trader" has been eliminated. Brokers are no longer required to track "round-trip" counts or restrict accounts that execute more than three day trades in a five-day period.
### **Q: Is the $25,000 minimum equity requirement still in effect?**
No. The specific $25,000 equity minimum required to day trade has been removed. Standard Regulation T requirements still apply; for example, margin-enabled accounts typically require a minimum of $2,000 in equity to maintain intraday debits or short positions.
## **Rule Comparison**
***
| Feature | Legacy PDT Rule | New Intraday Margin Rule |
| :--------------------- | :--------------------------------------- | :-------------------------------------------------- |
| **Trade Limits** | Max 3 day trades per 5 days (under $25k) | **Unlimited day trades** |
| **Buying Power** | Fixed (based on previous day's close) | **Dynamic** (updates in real-time) |
| **Equity Calculation** | Limited to brokerage assets | Includes **FDIC bank sweeps** & same-day deposits |
| **Profit Treatment** | Intraday gains ignored for buying power | **Intraday P\&L** factored into margin availability |
## **Risk Measurement & Definitions**
### ---
**Q: How is intraday risk calculated under the new rule?**
Risk is monitored via three primary metrics:
* **Intraday Margin Level (IML):** A running balance of your accounts maintenance margin excess or deficit, updated continuously based on transaction activity.
* **IML-Reducing Transaction:** Any action that lowers your IML, such as purchasing securities, shorting options, or withdrawing funds.
* **Intraday Margin Deficit (IMD):** The peak negative margin deficiency recorded immediately following an IML-reducing transaction at any point during the trading day.
## **Deficits and Restrictions**
### ---
**Q: What happens if an account incurs an Intraday Margin Deficit (IMD)?**
If an IMD occurs, a margin call will be issued. This call must be satisfied within **two business days**. If an IMD remains unmet by the close of the fifth business day, the account will be subject to a **90-day freeze**, restricting the account from increasing short positions or creating new debit balances.
### **Q: Are there "De Minimis" exceptions to the new rule?**
Yes. An intraday margin call is generally not triggered if the unmet deficit is less than **$1,000 or 5% of account equity** (whichever is lower)
## **Key Benefits for Traders**
- ***
**Real-Time Capital Access:** Unlike the old rule, which ignored intraday gains, the new rule allows you to use realized and unrealized intraday profits to increase your margin availability immediately.
- **Collateral Flexibility:** You can now count FDIC-insured bank sweeps and net deposits made on the same day toward your equity, providing a more accurate and favorable picture of your account's health.
- **Reduced Administrative Friction:** The removal of "counting" eliminates the risk of accidental account flags and the 90-day "PDT lock" that previously frustrated active traders.
- **Capital Efficiency:** Traders with less than $25,000 are no longer sidelined; capital can be reallocated as many times as necessary, provided the risk (IML) remains within manageable bounds.
**Margin trading involves significant risk and is not suitable for all investors.** Before considering a margin loan, it is crucial that you carefully consider how borrowing fits with your investment objectives and risk tolerance.
*When trading on margin, you assume higher market risk, and potential losses can exceed the collateral value in your account. Alpaca may sell any securities in your account, without prior notice, to satisfy a margin call. Alpaca may also change its “house” maintenance margin requirements at any time without advance written notice. You are not entitled to an extension of time on a margin call. Please review the Firms [Margin Disclosure Statement](https://files.alpaca.markets/disclosures/library/MarginDiscStmt.pdf) before investing.*
@@ -0,0 +1,29 @@
# About Trading API
Trade stocks & crypto with Alpacas easy to use Trading API. Up to 4X intraday & 2X overnight buying power. Short selling. Advanced order types. All packaged and delivered through our API.
# Paper Trading
Paper trading is free and available to all Alpaca users. Paper trading is a real-time simulation environment where you can test your code. You can reset and test your algorithm as much as you want using free, real-time market data. For more click [here](/docs/paper-trading).
# Account Plans
Anyone globally can create an paper only account. All you need to do is sign up with your email address. Alpaca also offers live brokerage accounts (with real money) for individuals and businesses plus crypto accounts. For more click [here](/docs/account-plans).
# Crypto Trading
Alpaca offers crypto trading through our API and the Alpaca web dashboard! Trade all day, seven days a week, as frequently as youd like. For more click [here](/docs/crypto-trading).
# Understand Orders
Our Trading API supports different order types such as market, limit and stop orders plus more complex ones. For more click [here](/docs/orders-at-alpaca).
# Fractional Trading
Fractional shares are fractions of a whole share, meaning that you dont need to buy a whole share to own a portion of a company. You can now buy as little as $1 worth of shares for over 2,000 US equities. For more click [here](/docs/fractional-trading).
We only allow market orders for fractional trading at the moment.
# User Protections
We have enabled several types of protections to enhance your trading experience. For more click [here](/docs/user-protection).
@@ -0,0 +1,82 @@
# Understanding FINRAs New Intraday Margin Rule and the End of PDT
<br />
### **1. Introduction to the Regulatory Shift**
The Financial Industry Regulatory Authority (FINRA) has approved a comprehensive overhaul of Rule 4210, marking a fundamental pivot in the governance of active retail trading. As part of the "FINRA Forward" initiative to modernize oversight and adapt to technological advancements, the legacy Pattern Day Trading (PDT) framework is being replaced with a modern "intraday margin" system.
The primary objective of this transition is to move away from arbitrary trade-counting metrics toward a risk-sensitive system that accurately reflects intraday market exposure. By eliminating the $25,000 equity threshold and the "four trades in five days" rule, FINRA aims to reduce unnecessary financial burdens on smaller investors while maintaining robust risk oversight.
### **2. Rationale for Reform: The Technical Underpinnings**
The shift to an intraday margin framework is necessitated by structural changes in the financial landscape and academic evidence regarding intraday volatility:
* **Obsolescence of the $25,000 Threshold:** Originally designed to protect investors from high commission costs, the $25,000 requirement is viewed by industry participants—including firms like Charles Schwab and Morgan Stanley—as anachronistic. In the era of zero-commission trading, this barrier often forces retail investors to hold positions overnight to avoid PDT status, inadvertently increasing their risk.
* **Volatility and High-Frequency Risk:** Academic research (Cotter & Longin) demonstrates that daily closing prices often neglect the dynamics investors face during the trading day. High-frequency data suggests that risk levels during intraday volatility can be 50% higher than what daily data implies. The new rule addresses this by focusing on real-time maintenance margin excess.
* **Dynamic Price Discovery:** As noted by David Russell (TradeStation), active trading provides essential liquidity and enables "dynamic price discovery in lesser-known or emerging securities." The new rule acknowledges that "one mans speculation is another mans liquidity."
* **Capturing Modern Risks (0DTE Options):** The legacy PDT rule failed to effectively capture the risks of "Zero Day to Expiration" (0DTE) options. Under the new framework, the expiration of a long option is explicitly classified as an IML-reducing transaction, ensuring these instruments are properly margined. PM
### **3. Key Definitions: Foundations of Intraday Margin**
The new regulatory framework relies on three technical definitions to determine compliance:
* **Intraday Margin Level (IML):** The running balance of an accounts maintenance margin excess or deficit during the day, defined by a dual-pronged approach:
* (A) The amount of cash a customer could withdraw while maintaining the required margin; or
* (B) The amount of additional cash (expressed as a negative number) the customer would need to deposit to satisfy maintenance margin requirements.
* **IML-Reducing Transaction:** Any transaction that decreases the accounts IML. This includes security purchases, short sales of options, the expiration of long options, and the withdrawal of cash or securities.
* **Intraday Margin Deficit (IMD):** The largest negative IML recorded during the trading day following an IML-reducing transaction. Crucially, an IMD is **not** triggered by mark-to-market (market-related) losses; if a negative IML results solely from market movement rather than customer-initiated activity, it does not necessitate an IMD satisfaction.
### **4. Comparison Table: Legacy PDT Rule vs. New Intraday Margin Rule**
| *Feature* | *Legacy PDT Rule* | *New Intraday Margin Rule* |
| :----------------------------- | :------------------------------------------------- | :----------------------------------------------------------- |
| **Minimum Equity Requirement** | $25,000 for Pattern Day Traders | Eliminated (Standard $2,000 Reg T/Rule 4210 Minimum applies) |
| **Trade Counting** | 4 trades in 5 days (unless \le 6% of total trades) | Eliminated; focus shifted to real-time risk exposure |
| **Buying Power Calculation** | Based on previous days close (DTBP) | Real-time or retrospective IML calculation |
| **Trading into a Margin Call** | No (for PDTs) | Yes |
| **Hold on Deposited Funds** | 2-day hold required | None |
| **Intraday P\&L Inclusion** | Excluded | Included (by recalculating the account) |
| **Guaranteed Accounts** | Prohibited for PDT requirements | Allowed |
| **0DTE Option Margin** | No specific intraday requirement | Required; treated as IML-reducing activity |
| **Account Restrictions** | 90-day "cash only" freeze for unmet calls | 90-day freeze on *new margin debits* and *short positions* |
| **Treatment of Bank Sweeps** | Excluded from buying power | Included (requires written firm policy) |
### **5. Mechanics of Satisfaction and Compliance**
Firms are empowered to use real-time monitoring to block trades that would create IMDs, though retrospective end-of-day calculation is permitted.
**Satisfaction of Deficits** A customer satisfies an IMD through net deposits of cash/securities or activities that increase the accounts IML (e.g., liquidating positions to release maintenance margin).
**Timeline and Capital Charge Mitigation**
* **Prompt Satisfaction:** IMDs must be satisfied "as promptly as possible."
* **5-Day Rule:** If an IMD is not satisfied within five business days, the firm must take a capital charge starting on the 6th business day.
* **Expiration:** The capital charge is capped at 10 days because the deficit itself expires for capital purposes after 15 business days.
**The "Freeze" Protocol** If a customer fails to meet an IMD within five days and demonstrates a practice of such failures, a 90-day restriction is triggered:
* **Scope:** The customer is prohibited from creating **new debits** or **short positions** (closing existing short positions is permitted).
* **De Minimis Exceptions:** Restrictions are waived if the IMD is less than $1,000 or less than 5% of account equity.
### **6. Portfolio Margin (PM) and Special Cases**
The intraday margin requirements are modified for Portfolio Margin accounts to reflect their unique risk profiles:
* **Equity Thresholds:** The intraday margin requirement does **not** apply to PM accounts with **$5 million or more in equity**, provided the firm has the technological capability to monitor intraday risk.
* **Standard PM Accounts:** PM accounts with less than $5 million in equity must maintain margin for intraday risk that is substantially similar to the margin required for end-of-day positions.
* **Bank Sweep Integration:** To mitigate unnecessary deficiencies, firms may include FDIC-insured bank sweep balances as credit balances, provided they maintain a **written policy** for this treatment.
* **"As of" Transactions:** Firms may allocate "as of" trades to the time of processing or the actual occurrence time, provided this procedure is designed for accuracy and not for the sole purpose of reducing margin requirements.
### **7. Implementation Timeline**
FINRA recognizes the need for firms to update technological infrastructure and internal risk oversight programs.
* **Effective Date & Interim Period:** Following SEC approval, a 12-month interim transition period will commence.
* **Transition Strategy:** During this 12-month window, member firms may apply either the legacy PDT rules or the new intraday margin rules (by account or across the firm) as they transition their systems.
**Margin trading involves significant risk and is not suitable for all investors.** Before considering a margin loan, it is crucial that you carefully consider how borrowing fits with your investment objectives and risk tolerance.
*When trading on margin, you assume higher market risk, and potential losses can exceed the collateral value in your account. Alpaca may sell any securities in your account, without prior notice, to satisfy a margin call. Alpaca may also change its “house” maintenance margin requirements at any time without advance written notice. You are not entitled to an extension of time on a margin call. Please review the Firms [Margin Disclosure Statement](https://files.alpaca.markets/disclosures/library/MarginDiscStmt.pdf) before investing.*
<br />
@@ -0,0 +1,31 @@
# Intraday Margin Rule for Non-Leverage Margin Accounts
### **Q: What is the Intraday Margin Rule?**
The Intraday Margin Rule is a regulatory update from FINRA designed to replace the legacy Pattern Day Trader (PDT) framework. While the old rules focused on the **frequency** of trades, the new rule focuses on **real-time risk exposure**. It measures the financial risk of positions held during the day that are closed before the market settles.
### **Q: Is the Pattern Day Trader (PDT) rule still in effect?**
No. The "pattern day trader" designation has been abolished. Brokers are no longer required to monitor or flag accounts that execute four or more day trades within a five-business-day window.
### **Q: Does the new rule limit the number of trades I can make?**
No. The previous "4-trade limit" has been eliminated. You may enter and exit positions as frequently as you choose, provided your account has sufficient equity to cover the intraday risk requirements set by your broker.
### **Q: Is the $25,000 minimum equity requirement still required?**
No. The specific $25,000 minimum previously required to maintain "Pattern Day Trader" status has been removed. However, individual firms may still maintain their own "house" requirements for risk management.
### **Q: I only trade with my own cash. Why does this matter to me?**
Even without using leverage, accounts enabled for margin trading are often utilized to avoid the delays associated with T+1 settlement. The new rule allows you to benefit from the speed of a margin account without being constrained by the intricate calculation rules or trading limitations that characterized the former Pattern Day Trader (PDT) system. Consequently, PDT restrictions are no longer necessary, and clients will no longer encounter trade rejections stemming from PDT protection and restrictions.
### **Key Advantages**
* **Capital Efficiency:** Traders can pivot strategies or re-enter positions instantly without worrying about "locking" their account for the week due to trade frequency.
* **Elimination of "Day Trading Calls":** Since the PDT status is gone, traders are no longer at risk of account freezes or "equity maintenance calls" triggered simply by the number of trades made.
* **Focus on Strategy, Not Math:** You can focus entirely on market movement rather than keeping a manual tally of "round-trip" trades to avoid a 90-day account restriction.
**Margin trading involves significant risk and is not suitable for all investors.** Before considering a margin loan, it is crucial that you carefully consider how borrowing fits with your investment objectives and risk tolerance.
*When trading on margin, you assume higher market risk, and potential losses can exceed the collateral value in your account. Alpaca may sell any securities in your account, without prior notice, to satisfy a margin call. Alpaca may also change its “house” maintenance margin requirements at any time without advance written notice. You are not entitled to an extension of time on a margin call. Please review the Firms [Margin Disclosure Statement](https://files.alpaca.markets/disclosures/library/MarginDiscStmt.pdf) before investing.*
@@ -0,0 +1,220 @@
# User Protection
We have enabled several types of protections to enhance your trading experience.
1. Pattern Day Trader (PDT) Protection
2. Day Trade Margin Call (DTMC) Protection
3. Preventing Wash Trades
4. Limit order price away sanity check
Please note that these do not apply to crypto trading as cryptocurrencies are not marginable. Pattern Day Trading rule does not apply to crypto trading either. Preventing Wash Trades does apply to crypto trading.
# Pattern Day Trader (PDT) Protection at Alpaca
In order to prevent Alpaca Brokerage Account customers from unintentionally being designated as a Pattern Day Trader (PDT), the Alpaca Trading platform checks the PDT rule condition every time an order is submitted from a customer. If the order could potentially result in the account being flagged as a PDT, the order is rejected, and API returns error with HTTP status code 403 (Forbidden).
## The Rule
A day trade is defined as a round-trip pair of trades within the same day (including extended hours). This is best described as an initial or opening transaction that is subsequently closed later in the same calendar day. For long positions, this would consist of a buy and then sell. For short positions, selling a security short and buying it back to cover the short position on the same day would also be considered a day trade.
An account is designated as a Pattern Day Trader if it makes four (4) or more day trades within five (5) business days, and the number of day trades represents more than six percent (6%) of the total trades within the same five (5) business days window. Day trades less than this criteria will not flag the account for PDT.
Cryptocurrency trading is not subject to the PDT rule. As a result, crypto orders are not evaluated by PDT protection logic and round-trip crypto trades on the same day do not contribute to the day trade count.
Day trades are counted regardless of share quantity or frequency throughout the day. Here are some FINRA-provided examples:
Example A:
09:30 Buy 250 ABC\
09:31 Buy 250 ABC\
13:00 Sell 500 ABC\
The customer has executed one day trade.
Example B:\
09:30 Buy 100 ABC\
09:31 Sell 100 ABC\
09:32 Buy 100 ABC\
13:00 Sell 100 ABC\
The customer has executed two day trades.
Example C:\
09:30 Buy 500 ABC\
13:00 Sell 100 ABC\
13:01 Sell 100 ABC\
13:03 Sell 300 ABC\
The customer has executed one day trade.
Example D:\
09:30 Buy 250 ABC\
09:31 Buy 300 ABC\
13:01 Buy 100 ABC\
13:02 Sell 150 ABC\
13:03 Sell 175 ABC\
The customer has executed one day trade.
Example E:\
09:30 Buy 199 ABC\
09:31 Buy 142 ABC\
13:00 Sell 1 ABC\
13:01 Buy 45 ABC\
13:02 Sell 100 ABC\
13:03 Sell 200 ABC\
The customer has executed two day trades.
Example F:\
09:30 Buy 200 ABC\
09:30 Buy 100 XYZ\
13:00 Sell 100 ABC\
13:00 Sell 100 XYZ
The customer has executed two day trades.
For further information, please visit [Regulatory Notice 21-13 | FINRA.org ](https://www.finra.org/rules-guidance/notices/21-13)
## Alpacas Order Rejection
Alpaca Trading platform monitors the number of day trades for the account for the past 5 business days and rejects a newly submitted orders on exit of a position if it could potentially result in the account being flagged for PDT. This protection triggers only when the previous days closing account equity is less than $25,000 at the time of order submission.
In addition to the filled orders, the system also takes into consideration pending orders in the account. In this case, regardless of the order of pending orders, a pair of buy and sell orders is counted as a potential day trade. This is because orders that are active (pending) in the marketplace may fill in random orders. Therefore, even if your sell limit order is submitted first (without being filled yet) and another buy order on the same security is submitted later, this buy order will be blocked if your account already has 3 day trades in the last 5 business days.
<br />
## Pattern Day Trader (PDT) Restriction at Alpaca
If an account falls below the required **$25,000 securities equity** at the end of the trading day, it will be flagged for not meeting the **Pattern Day Trader (PDT)** requirements. When this happens, the account will be restricted from placing any new day trades on the following business day. Day trading will remain blocked until either:
**A PDT Restriction lift is granted, or**
**A One-Time PDT Removal is granted, or**
**The account equity once again meets the $25,000 minimum requirement by the end of the trading day.**
To request a **PDT Restriction lift or One-Time PDT Removal**\* in order to place a day trade, please contact our support team at [support@alpaca.markets](mailto:support@alpaca.markets).
\***Note:** The **One-Time PDT Removal** applies for the life of all accounts at Alpaca. By requesting this, you are removing the PDT flag from your account and agree not to engage in future pattern day trading.
Please also note that once the restriction is lifted and you place a day trade, your account will be limited to **liquidation-only activity for 90 days**, or until the **$25,000 equity requirement** is met.
<br />
## Paper Trading
The same protection triggers in your paper trading account. It is advised to test your algorithm with the realistic balance amount you would manage when going live, to make sure your assumption works under this PDT protection as well.
> For more details of Pattern Day Trader rule, please visit the [FINRA website](https://www.finra.org/investors/investing/investment-products/stocks/day-trading).
# Day Trade Margin Call (DTMC) Protection at Alpaca
In order to prevent Alpaca Brokerage Account customers from unintentionally receiving day trading margin calls, Alpaca implements two forms of DTMC protection.
## The Rule
Day traders are required to have a minimum of $25,000 OR 25% of the total market value of securities (whichever is higher) maintained in their account.
The buying power of a pattern day trader is 4x the excess of the maintenance margin from the closing of the previous day. If you exceed this amount, you will receive a day trading margin call.
## How Alpacas DTMC Protection Settings Work
Users only receive day trading buying power when marked as a pattern day trader. If the user is designated a pattern day trader, the account.multiplier is equal to 4.
Daytrading buying power cannot increase beyond its start of day value. In other words, closing an overnight position will not add to your daytrading buying power.
The following scenarios and protections are applicable only for accounts that are designated as pattern day traders. Please check your Account API result for the multiplier field.
Every trading day, you start with the new `daytrading_buying_power`. This beginning value is calculated as `4 * (last_equity - last_maintenance_margin)`. The last\_equity and last\_maintenance\_margin values can be accessed through Account API. These values are stored from the end of the previous trading day.
Throughout the day, each time you enter a new position, your `daytrading_buying_power` is reduced by that amount. When you exit that position within the same day, that same amount is credited back, regardless of positions P/L.
At the end of the trading day, on close, the maximum exposure of your day trading position is checked. A Day Trade Margin Call (DTMC) is issued the next day if the maximum exposure of day trades exceeded your day trading buying power from the beginning of that day.
The buying\_power value is the larger of `regt_buying_power` and `daytrading_buying_power`. Since the basic buying power check runs on this buying\_power value, you could be exceeding your `daytrading_buying_power` when you enter the position if `regt_buying_power` is larger than your `daytrading_buying_power` at one point in the day.
The following is an example scenario:
1. Your equity is $50k
2. You hold overnight positions up to $100k
3. Your maintenance margin is $30k (\~30%), therefore your day trading buying power at the beginning of day is $80k using the calculation of 4 \* ($50k - $30k)
4. You sell all of the overnight positions ($100k value) in the morning, which brings your `regt_buying_power` up to $100k
5. You now buy and sell the same security up to $100k
6. At the end of the day, you have a $20k Day Trade Margin Call ($100k - $80k)
By default, Alpaca users have DTMC protections on entry of a position. This means that if your entering order would exceed `daytrading_buying_power` at the moment, it will be blocked, even if `regt_buying_power` still has room for it. This is based on the assumption that any entering position could be day trades later in the day. This option is the more conservative of the two DTMC protections that our users have.
The second DTMC protection option is protection on exit of a position. This means that Alpaca will block the exit of positions that would cause a Day Trading Margin Call. This may cause users to be unable to liquidate a position until the next day.
Neither of the DTMC protection options evaluate crypto orders since crypto cannot be purchased using margin.
One of the two protections will be enabled for all users (you cannot have both protections disabled). If you would like to switch your protection option, please contact our support.
We are working towards features to allow users to change their DTMC protection setting on their own without support help.
## Equity/Order Ratio Validation Check
In order to help Alpaca Brokerage Account customers from placing orders larger than the calculated buying power, Alpaca has instituted a control on the account independent of the buying power for the account. Alpaca will restrict the account to closing transactions when an account has a position that is 600% larger than the equity in the account. The account will remain restricted for closing transactions until a member of Alpacas trading team reviews the account. The trading team will either clear the alert by allowing opening transactions or will notify the client of the restriction and take corrective actions as necessary.
## Paper Trading
he same protection triggers in your paper trading account. It is advised to test your algorithm with the realistic balance amount you would manage when going live, to make sure your assumption works under this DTMC protection as well.
For more details of Pattern Day Trader rule, please read [FINRAs margin requirements](https://www.finra.org/investors/learn-to-invest/advanced-investing/day-trading-margin-requirements-know-rules-rot). For more details on day trade margins, please read [FINRAs Mind Your Margin](https://www.finra.org/investors/day-trading) article.
# Preventing Wash Trades at Alpaca
At Alpaca, we want to help our customers avoid making unintentional wash trades. A wash trade happens when a customer buys and sells the same security at the same time, which can be seen as a form of market manipulation. To prevent this, the Alpaca Trading platform checks for potential wash trades every time a customer places an order. If we detect a possible wash trade, we reject the order and send back an error message with the HTTP status code 403 (Forbidden).
## The Rule
A wash trade occurs when a customer's two orders could potentially interact with each other. Here are a couple of examples:
* A customer places an order to buy 1 share at $10 (a limit order). Then, the same customer places an order to sell 100 shares at $10 (another limit order). These orders could potentially interact, which would be a wash trade.
* A customer places an order to sell 100 shares at the market open (a market order). Then, the same customer places an order to buy 100 shares at $10 (a limit order). Again, these orders could potentially interact, which would be a wash trade.
## How Alpaca Handles Potential Wash Trades
The Alpaca Trading platform is always on the lookout for potential wash trades. If we determine that an order could result in a wash trade, we trigger our protection measures, reject the order, and send back an error message with the HTTP status code 403 (Forbidden).
If a customer wants to set up a 'take profit' and a 'stop loss' situation, we recommend using a bracket or OCO (One Cancels the Other) order. These complex orders and trailing stop orders are exceptions to our wash trade protection.
Here's a table that shows when we would reject an order to prevent a potential wash trade:
| Existing Order | New Order | Reject Condition |
| ---------------- | ---------------- | ----------------------------------------------- |
| market buy | market sell | always rejected |
| market buy | limit sell | always rejected |
| market buy | stop sell | always rejected |
| market buy | stop\_limit sell | always rejected |
| market sell | market buy | always rejected |
| market sell | limit buy | always rejected |
| market sell | stop buy | always rejected |
| market sell | stop\_limit buy | always rejected |
| stop buy | market sell | always rejected |
| stop buy | limit sell | always rejected |
| stop buy | stop sell | always rejected |
| stop buy | stop\_limit sell | always rejected |
| stop sell | market buy | always rejected |
| stop sell | limit buy | always rejected |
| stop sell | stop buy | always rejected |
| stop sell | stop\_limit buy | always rejected |
| limit buy | market sell | always rejected |
| limit buy | limit sell | rejected if buy limit price >= sell limit price |
| limit buy | stop sell | always rejected |
| limit buy | stop\_limit sell | rejected if buy limit price >= sell limit price |
| limit sell | market buy | always rejected |
| limit sell | limit buy | rejected if buy limit price >= sell limit price |
| limit sell | stop buy | always rejected |
| limit sell | stop\_limit buy | rejected if buy limit price >= sell limit price |
| stop\_limit buy | market sell | always rejected |
| stop\_limit buy | limit sell | rejected if buy limit price >= sell limit price |
| stop\_limit buy | stop sell | always rejected |
| stop\_limit buy | stop\_limit sell | rejected if buy limit price >= sell limit price |
| stop\_limit sell | market buy | always rejected |
| stop\_limit sell | limit buy | rejected if buy limit price >= sell limit price |
| stop\_limit sell | stop buy | always rejected |
| stop\_limit sell | stop\_limit buy | rejected if buy limit price >= sell limit price |
## Paper Trading
Our wash trade protection also applies to your paper trading account. We recommend testing your trading algorithm with a realistic balance amount. This way, you can make sure your strategy works under our wash trade protection rules before you start live trading.
For more details of wash trade rule, please read\
[FINRA's self-trades requirements](https://www.finra.org/rules-guidance/rulebooks/finra-rules/5210).
@@ -0,0 +1,155 @@
# Using OAuth2 and Trading API
Alpaca implements OAuth 2.0 to allow third party applications to access Alpaca Trading API on behalf of the end-users. This document describes how you can integrate with Alpaca through OAuth.
By default once you have a valid client\_id and client\_secret, any paper account and the live account associated with the OAuth Client will be available to connect to your app. We welcome developers to build applications and products that are powered by Alpaca while also protecting the privacy and security of our users. To build using Alpacas APIs, please follow the guide below.
> ️ Note
>
> An single Alpaca OAuth token may authorize access to either:
>
> * One live account
> * One paper account
> * One live account and one paper account
>
> For users with multiple paper accounts, the user must go through the authorization flow separately for each account they want to connect.
# Getting the Access Token
At a high level the flow looks like this, we will go into detail about each step
1. User requests a connection between your application and Alpaca
2. User is redirected to Alpaca to login and authorize the application from inside the dashboard
3. Alpaca grants an authorization token to your application through user-agent
4. You application then makes an access token request
5. Alpaca returns an access token grant
## 1. Request for Connection on Behalf of User
When redirecting a user to Alpaca to authorize access to your application, youll need to construct the authorization URL with the correct parameters and scopes.
```
GET https://app.alpaca.markets/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URL&state=SOMETHING_RANDOM&scope=account:write%20trading&env=live
```
Heres a list of parameters you should always specify:
| Parameter | Required? | Description |
| :-------------- | :-------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
| `response_type` | Required | Must be `code` to request an authorization code. |
| `client_id` | Required | The `client_id` you were provided with when registering your app |
| `redirect_uri` | Required | The redirect URL where the user will be sent after authorization. It must match one of the whitelisted redirect URIs for your application. |
| `state` | Optional | An unguessable random string, used to protect against request forgery attacks. |
| `scope` | Optional | A space-delimited list of scopes your application requests access to. Read-only endpoint access is assumed by default. |
| `env` | Optional | If provided, must be one of `live` or `paper`. If not specified, the user will be prompted to authorized both a live and a paper account. |
**Allowed Scopes**
| Scope | Description |
| :-------------- | :------------------------------------------------------ |
| `account:write` | Write access for account configurations and watchlists. |
| `trading` | Place, cancel or modify orders. |
| `data` | Access to the Data API. |
## 2. Users Authorizing App to Access Alpaca Account
After you redirect a user to Alpaca, we will display the following OAuth consent screen and ask the user to authorize your app to connect to their Alpaca account.
<Image align="center" width="50% " src="https://files.readme.io/06f62610cde297ce4ce76d38c3570190006ea4a6e4612eade17a658d03025b6b-Screenshot_2025-02-14_at_12.00.23_PM.png" />
If you specify a value for the `env` parameter when redirecting to us, we will ask the user to authorize only a live or a paper account, depending on whether you specified `live` or `paper` respectivley.
For example, if specifying `env=paper` as a query parameter, we will show the following consent screen.
<Image align="center" width="51% " src="https://files.readme.io/9b92fd7ba5d76739d84d77054f4c37f453eb5f86a9fcfa66a57342d1bdef8dfb-Screenshot_2025-02-14_at_11.57.09_AM.png" />
## 3. Alpaca Redirect Back to App
If the user approves access, Alpaca will redirect them back to your `redirect_uri` with a temporary `code` parameter. If you specified a state parameter in step 1, it will be returned as well. The parameter will always match the value specified in step 1. If the values dont match, the request should not be trusted.
Example
```
GET https://example.com/oauth/callback?code=67f74f5a-a2cc-4ebd-88b4-22453fe07994&state=8e02c9c6a3484fadaaf841fb1df290e1
```
## 4. App Receives Authorization Code
You can then use this code to exchange for an access token.
## 5. App Exchanges Auth Code with Access Token
After you have received the temporary `code`, you can exchange it for an access token. This can be done by making a `POST` call to `https://api.alpaca.markets/oauth/token`
### Parameters (All Required)
| Parameter | Description |
| :-------------- | :------------------------------------------------------------------ |
| `grant_type` | Must be set to authorization\_code for an access token request. |
| `code` | The authorization code received in step 4 |
| `client_id` | The Client ID you received when you registered the application. |
| `client_secret` | The Client Secret you received when you registered the application. |
| `redirect_uri` | The redirect URI you used for the authorization code request. |
> 🚧 Note
>
> This request should take place behind-the-scenes from your backend server and shouldnt be visible to the end users for security purposes.
The content type must be application/x-www-form-urlencoded as defined in RFC.
Example request:
```curl
curl -X POST https://api.alpaca.markets/oauth/token \
-d 'grant_type=authorization_code&code=67f74f5a-a2cc-4ebd-88b4-22453fe07994&client_id=fc9c55efa3924f369d6c1148e668bbe8&client_secret=5b8027074d8ab434882c0806833e76508861c366&redirect_uri=https://example.com/oauth/callback'
```
After a successful request, a valid access token will be returned in the response:
```json
{
"access_token": "79500537-5796-4230-9661-7f7108877c60",
"token_type": "bearer",
"scope": "account:write trading"
}
```
# API Calls
Once you have integrated and have a valid access token you can start make calls to Alpaca Trading API v2 on behalf of the end-user.
## Example Requests
A
```curl
curl https://api.alpaca.markets/v2/account /
-H 'Authorization: Bearer 79500537-5796-4230-9661-7f7108877c60'
```
```curl
curl https://paper-api.alpaca.markets/v2/orders /
-H 'Authorization: Bearer 79500537-5796-4230-9661-7f7108877c60'
```
The OAuth token can also be used for the trade update websockets stream.
```
{
"action": "authenticate",
"data": {
"oauth_token": "79500537-5796-4230-9661-7f7108877c60"
}
}
```
The OAuth Token can be used to authenticate for Market Data Stream. Please note that most users can have only 1 active stream connection. If that connection is used by another 3rd party application, you will receive an error: 406 and “connection limit exceeded” message.
```
{
"action": "auth",
"key": "oauth",
"secret": "79500537-5796-4230-9661-7f7108877c60"
}
```
@@ -0,0 +1,369 @@
# Websocket Streaming
Learn how to stream market data using Websockets.
Alpacas API offers WebSocket streaming for trade, account, and order updates which follows the [RFC6455 WebSocket protocol](https://datatracker.ietf.org/doc/html/rfc6455).
To connect to the WebSocket follow the standard opening handshake as defined by the RFC specification to `wss://paper-api.alpaca.markets/stream` or `wss://api.alpaca.markets/stream`. Alpacas streaming service supports both JSON and MessagePack codecs.
Once the connection is authorized, the client can listen to the `trade_updates` stream to get updates on trade, account, and order changes.
> 📘 Note:
>
> The `trade_updates` stream coming from `wss://paper-api.alpaca.markets/stream` uses binary frames, which differs from the text frames that comes from the `wss://data.alpaca.markets/stream` stream.
In order to listen to streams, the client sends a `listen` message to the server as follows:
```json
{
"action": "listen",
"data": {
"streams": ["trade_updates"]
}
}
```
The server acknowledges by replying a message in the listening stream.
```json
{
"stream": "listening",
"data": {
"streams": ["trade_updates"]
}
}
```
If any of the requested streams are not available, they will not appear in the streams list in the acknowledgement. Note that the streams field in the listen message is to tell the set of streams to listen, so if you want to stop receiving updates from the stream, you must send an empty list of streams values as a listen message. Similarly, if you want to add more streams to get updates in addition to the ones you are already doing so, you must send all the stream names, not only the new ones.
Subscribing to real-time trade updates ensures that a user always has the most up-to-date picture of their account actvivity.
> 📘 Note
>
> To request with MessagePack, add the header: Content-Type: `application/msgpack`.
# Authentication
The WebSocket client can be authenticated using the same API key when making HTTP requests. Upon connecting to the WebSocket, client must send an authentication message over the WebSocket connection with the API key and secret key as its payload.
```json
{
"action": "auth",
"key": "{YOUR_API_KEY_ID}",
"secret": "{YOUR_API_SECRET_KEY}"
}
```
The server will then authorize the connection and respond with either an authorized (successful) response
```json
{
"stream": "authorization",
"data": {
"status": "authorized",
"action": "authenticate"
}
}
```
or an unauthorized (unsuccessful) response:
```json
{
"stream": "authorization",
"data": {
"status": "unauthorized",
"action": "authenticate"
}
}
```
In the case that the socket connection is not authorized yet, a new message under the authorization stream is issued in response to the listen request.
```json
{
"stream": "authorization",
"data": {
"status": "unauthorized",
"action": "listen"
}
}
```
# Trade Updates
With regards to the account associated with the authorized API keys, updates for orders placed at Alpaca are dispatched over the WebSocket connection under the event trade\_updates. These messages include any data pertaining to orders that are executed with Alpaca. This includes order fills, partial fills, cancellations and rejections of orders. Clients may listen to this stream by sending a listen message:
```json
{
"action": "listen",
"data": {
"streams": ["trade_updates"]
}
}
```
Any listen messages received by the server will be acknowledged via a message on the listening stream. The messages data payload will include the list of streams the client is currently listening to:
```json
{
"stream": "listening",
"data": {
"streams": ["trade_updates"]
}
}
```
The fields present in a message sent over the `trade_updates` stream depend on the type of event they are communicating. All messages contain an `event` type and an `order` field, which is the same as the order object that is returned from the REST API. Potential event types and additional fields that will be in their messages are listed below.
## Common Events
These are the events that are the expected results of actions you may have taken by sending API requests.
* `new`: Sent when an order has been routed to exchanges for execution.
* `fill`: Sent when an order has been completely filled.
* `timestamp`: The time at which the order was filled.
* `price`: The price per share for the fill event. This may be different from the average fill price for the order if there were partial fills.
* `qty`: The number of shares for the fill event. This will be different from the filled quantity for the order if there were partial fills.
* `position_qty`: The total size of your position after this event, in shares. Positive for long positions, negative for short positions.
* `partial_fill`: Sent when a number of shares less than the total remaining quantity on your order has been filled.
* `timestamp`: The time at which the order was partially filled.
* `price`: The price per share for the partial fill event.
* `qty`: The number of shares for the partial fill event.
* `position_qty`: The total size of your position after this event, in shares. Positive for long positions, negative for short positions.
* `canceled`: Sent when your requested cancelation of an order is processed.
* `timestamp`: The time at which the order was canceled.
* `expired`: Sent when an order has reached the end of its lifespan, as determined by the orders time in force value.
* `timestamp`: The time at which the order was expired.
* `done_for_day`: Sent when the order is done executing for the day, and will not receive further updates until the next trading day.
* `replaced`: Sent when your requested replacement of an order is processed.
* `timestamp`: The time at which the order was replaced.
## Less Common Events
These are events that may rarely be sent due to uncommon circumstances on the exchanges. It is unlikely you will need to design your code around them, but you may still wish to account for the possibility that they can occur.
* `accepted`: Sent when your order has been received by Alpaca, but hasnt yet been routed to the execution venue.
* `rejected`: Sent when your order has been rejected.
* `timestamp`: The time at which the order was rejected.
* `pending_new`: Sent when the order has been received by Alpaca and routed to the exchanges, but has not yet been accepted for execution.
* `stopped`: Sent when your order has been stopped, and a trade is guaranteed for the order, usually at a stated price or better, but has not yet occurred.
* `pending_cancel`: Sent when the order is awaiting cancelation. Most cancelations will occur without the order entering this state.
* `pending_replace`: Sent when the order is awaiting replacement.
* `calculated`: Sent when the order has been completed for the day - it is either “filled” or “done\_for\_day” - but remaining settlement calculations are still pending.
* `suspended`: Sent when the order has been suspended and is not eligible for trading.
* `order_replace_rejected`: Sent when the order replace has been rejected.
* `order_cancel_rejected`: Sent when the order cancel has been rejected.
# Example
An example of a message sent over the `trade_updates` stream looks like:
```json
{
"stream": "trade_updates",
"data": {
"event": "fill",
"execution_id": "2f63ea93-423d-4169-b3f6-3fdafc10c418",
"order": {
"asset_class": "crypto",
"asset_id": "1cf35270-99ee-44e2-a77f-6fab902c7f80",
"cancel_requested_at": null,
"canceled_at": null,
"client_order_id": "4642fd68-d59a-47d7-a9ac-e22f536828d1",
"created_at": "2022-04-19T13:45:04.981350886-04:00",
"expired_at": null,
"extended_hours": false,
"failed_at": null,
"filled_at": "2022-04-19T17:45:05.024916716Z",
"filled_avg_price": "105.8988475",
"filled_qty": "1790.86",
"hwm": null,
"id": "a5be8f5e-fdfa-41f5-a644-7a74fe947a8f",
"legs": null,
"limit_price": null,
"notional": null,
"order_class": "",
"order_type": "market",
"qty": "1790.86",
"replaced_at": null,
"replaced_by": null,
"replaces": null,
"side": "sell",
"status": "filled",
"stop_price": null,
"submitted_at": "2022-04-19T13:45:04.980944666-04:00",
"symbol": "SOLUSD",
"time_in_force": "gtc",
"trail_percent": null,
"trail_price": null,
"type": "market",
"updated_at": "2022-04-19T13:45:05.027690731-04:00"
},
"position_qty": "0",
"price": "105.8988475",
"qty": "1790.86",
"timestamp": "2022-04-19T17:45:05.024916716Z"
}
}
```
An example message for MultilegOptionsOrder fill event:
```json
{
"stream": "trade_updates",
"data": {
"at": "2025-01-21T07:32:40.70095Z",
"event_id": "01JJ3WE73W5PG672TC4XACXH5R",
"event": "fill",
"timestamp": "2025-01-21T07:32:40.695569506Z",
"order": {
"id": "31cd620f-3bd5-41b7-8bb2-6834524679d0",
"client_order_id": "fe999618-6435-497b-9fdd-a63d3da3615f",
"created_at": "2025-01-21T07:32:40.678963102Z",
"updated_at": "2025-01-21T07:32:40.699359002Z",
"submitted_at": "2025-01-21T07:32:40.691562346Z",
"filled_at": "2025-01-21T07:32:40.695569506Z",
"expired_at": null,
"cancel_requested_at": null,
"canceled_at": null,
"failed_at": null,
"replaced_at": null,
"replaced_by": null,
"replaces": null,
"asset_id": "00000000-0000-0000-0000-000000000000",
"symbol": "",
"asset_class": "",
"notional": null,
"qty": "1",
"filled_qty": "1",
"filled_avg_price": "1.62",
"order_class": "mleg",
"order_type": "limit",
"type": "limit",
"side": "buy",
"time_in_force": "day",
"limit_price": "2",
"stop_price": null,
"status": "filled",
"extended_hours": false,
"legs": [
{
"id": "3cbe69ef-241c-43ba-9d8c-09361930a1af",
"client_order_id": "e868fb88-ce92-442b-91be-4b16defbc883",
"created_at": "2025-01-21T07:32:40.678963102Z",
"updated_at": "2025-01-21T07:32:40.697474882Z",
"submitted_at": "2025-01-21T07:32:40.687356797Z",
"filled_at": "2025-01-21T07:32:40.695564076Z",
"expired_at": null,
"cancel_requested_at": null,
"canceled_at": null,
"failed_at": null,
"replaced_at": null,
"replaced_by": null,
"replaces": null,
"asset_id": "925af3ed-5c00-4ef1-b89b-e4bd05f04486",
"symbol": "AAPL250321P00200000",
"asset_class": "us_option",
"notional": null,
"qty": "1",
"filled_qty": "1",
"filled_avg_price": "1.6",
"order_class": "mleg",
"order_type": "",
"type": "",
"side": "buy",
"time_in_force": "day",
"limit_price": null,
"stop_price": null,
"status": "filled",
"extended_hours": false,
"legs": null,
"trail_percent": null,
"trail_price": null,
"hwm": null,
"ratio_qty": "1"
},
{
"id": "ec694de5-5028-4347-8f89-d8ea00c9341f",
"client_order_id": "0a1bf1e1-6992-4c23-85a6-9469bbe05f1a",
"created_at": "2025-01-21T07:32:40.678963102Z",
"updated_at": "2025-01-21T07:32:40.699294952Z",
"submitted_at": "2025-01-21T07:32:40.691562346Z",
"filled_at": "2025-01-21T07:32:40.695569506Z",
"expired_at": null,
"cancel_requested_at": null,
"canceled_at": null,
"failed_at": null,
"replaced_at": null,
"replaced_by": null,
"replaces": null,
"asset_id": "9f8c3d65-f5f7-42cd-acbc-9636cc32d3b5",
"symbol": "AAPL250321C00380000",
"asset_class": "us_option",
"notional": null,
"qty": "1",
"filled_qty": "1",
"filled_avg_price": "0.02",
"order_class": "mleg",
"order_type": "",
"type": "",
"side": "buy",
"time_in_force": "day",
"limit_price": null,
"stop_price": null,
"status": "filled",
"extended_hours": false,
"legs": null,
"trail_percent": null,
"trail_price": null,
"hwm": null,
"ratio_qty": "1"
}
],
"trail_percent": null,
"trail_price": null,
"hwm": null
},
"price": "1.62",
"qty": "1",
"position_qtys": {
"AAPL250321P00200000": "1",
"AAPL250321C00380000": "1"
},
"legs": [
{
"execution_id": "69a70e98-f370-427d-bcd3-834dc4800aed",
"qty": "1",
"price": "1.6",
"order_id": "3cbe69ef-241c-43ba-9d8c-09361930a1af",
"symbol": "AAPL250321P00200000",
"timestamp": "2025-01-21T07:32:40.695564076Z"
},
{
"execution_id": "fb878d87-569e-49f3-b42e-a09ad06e3d3a",
"qty": "1",
"price": "0.02",
"order_id": "ec694de5-5028-4347-8f89-d8ea00c9341f",
"symbol": "AAPL250321C00380000",
"timestamp": "2025-01-21T07:32:40.695569506Z"
}
]
}
}
```
## Error messages
In the case of in-stream errors, the server sends an `error` action before closing the connection.
```json
{
"action": "error",
"data": {
"error_message": "internal server error"
}
}
```
@@ -0,0 +1,199 @@
# Working with /account
Learn how to use the /account endpoint to learn about the state of your account
# View Account Information
By sending a `GET` request to our `/v2/account` endpoint, you can see various information about your account, such as the amount of buying power available or whether or not it has a PDT flag.
```Text Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
trading_client = TradingClient('api-key', 'secret-key')
# Get our account information.
account = trading_client.get_account()
# Check if our account is restricted from trading.
if account.trading_blocked:
print('Account is currently restricted from trading.')
# Check how much money we can use to open new positions.
print('${} is available as buying power.'.format(account.buying_power))
```
```Text JavaScript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Get our account information.
alpaca.getAccount().then((account) => {
// Check if our account is restricted from trading.
if (account.trading_blocked) {
console.log("Account is currently restricted from trading.");
}
// Check how much money we can use to open new positions.
console.log(`$${account.buying_power} is available as buying power.`);
});
```
```Text C#
using Alpaca.Markets;
using System;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Get our account information.
var account = await client.GetAccountAsync();
// Check if our account is restricted from trading.
if (account.IsTradingBlocked)
{
Console.WriteLine("Account is currently restricted from trading.");
}
Console.WriteLine(account.BuyingPower + " is available as buying power.");
Console.Read();
}
}
}
```
```Text Go
package main
import (
"fmt"
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
// Get our account information.
account, err := alpaca.GetAccount()
if err != nil {
panic(err)
}
// Check if our account is restricted from trading.
if account.TradingBlocked {
fmt.Println("Account is currently restricted from trading.")
}
// Check how much money we can use to open new positions.
fmt.Printf("%v is available as buying power.\n", account.BuyingPower)
}
```
# View Gain/Loss of Portfolio
You can use the information from the account endpoint to do things like calculating the daily profit or loss of your account.
```Text Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
trading_client = TradingClient('api-key', 'secret-key')
# Get our account information.
account = trading_client.get_account()
# Check our current balance vs. our balance at the last market close
balance_change = float(account.equity) - float(account.last_equity)
print(f'Today\'s portfolio balance change: ${balance_change}')
```
```Text JavaScript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Get account information.
alpaca.getAccount().then((account) => {
// Calculate the difference between current balance and balance at the last market close.
const balanceChange = account.equity - account.last_equity;
console.log("Today's portfolio balance change:", balanceChange);
});
```
```Text C#
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
// With the Alpaca API, you can check on your daily profit or loss by
// comparing your current balance to yesterday's balance.
namespace GetPnLExample
{
internal class GetPnL
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Get account info
var account = await client.GetAccountAsync();
// Check our current balance vs. our balance at the last market close
var balance_change = account.Equity - account.LastEquity;
Console.WriteLine($"Today's portfolio balance change: ${balance_change}");
}
}
}
```
```Text Go
package main
import (
"fmt"
"log"
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
)
func main() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
// Get account information.
account, err := alpaca.GetAccount()
if err != nil {
log.Fatalln(err)
}
// Calculate the difference between current balance and balance at the last market close.
balanceChange := account.Equity.Sub(account.LastEquity)
fmt.Println("Today's portfolio balance change:", balanceChange)
}
```
@@ -0,0 +1,191 @@
# Working with /assets
Learn how to use the `/assets` endpoint to learn more about assets available on Alpaca. Both Securities and Crypto can be retrieved from the `/assets` endpoint.
# Get a List of Assets
If you send a `GET` request to our `/v2/assets` endpoint, youll receive a list of US equities.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
from alpaca.trading.enums import AssetClass
trading_client = TradingClient('api-key', 'secret-key')
# search for US equities
search_params = GetAssetsRequest(asset_class=AssetClass.US_EQUITY)
assets = trading_client.get_all_assets(search_params)
```
```javascript JavaScript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Get a list of all active assets.
const activeAssets = alpaca
.getAssets({
status: "active",
})
.then((activeAssets) => {
// Filter the assets down to just those on NASDAQ.
const nasdaqAssets = activeAssets.filter(
(asset) => asset.exchange == "NASDAQ"
);
console.log(nasdaqAssets);
});
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Get a list of all active assets.
var assets = await client.ListAssetsAsync(
new AssetsRequest { AssetStatus = AssetStatus.Active });
// Filter the assets down to just those on NASDAQ.
var nasdaqAssets = assets.Where(asset => asset.Exchange == Exchange.NyseMkt);
Console.Read();
}
}
}
```
```go Go
package main
import (
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
// Get a list of all active assets.
status := "active"
assets, err := alpaca.ListAssets(&status)
if err != nil {
panic(err)
}
// Filter the assets down to just those on NASDAQ.
nasdaq_assets := []alpaca.Asset{}
for _, asset := range assets {
if asset.Exchange == "NASDAQ" {
nasdaq_assets = append(nasdaq_assets, asset)
}
}
}
```
# See If a Particular Asset is Tradable on Alpaca
By sending a symbol along with our request, we can get the information about just one asset. This is useful if we just want to make sure that a particular asset is tradable before we attempt to buy it.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
trading_client = TradingClient('api-key', 'secret-key')
# search for AAPL
aapl_asset = trading_client.get_asset('AAPL')
if aapl_asset.tradable:
print('We can trade AAPL.')
```
```javascript JavaScript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Check if AAPL is tradable on the Alpaca platform.
alpaca.getAsset("AAPL").then((aaplAsset) => {
if (aaplAsset.tradable) {
console.log("We can trade AAPL.");
}
});
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Check if AAPL is tradable on the Alpaca platform.
try
{
var asset = await client.GetAssetAsync("AAPL");
if (asset.IsTradable)
{
Console.WriteLine("We can trade AAPL");
}
}
catch (Exception)
{
Console.WriteLine("Asset not found for AAPL.");
}
Console.Read();
}
}
}
```
```go Go
package main
import (
"fmt"
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
// Check if AAPL is tradable on the Alpaca platform.
asset, err := alpaca.GetAsset("AAPL")
if err != nil {
fmt.Println("Asset not found for AAPL.")
} else if asset.Tradable {
fmt.Println("We can trade AAPL.")
}
}
```
@@ -0,0 +1,998 @@
# Working with /orders
Learn how to submit orders to Alpaca.
This page contains examples of some of the things you can do with order objects through our API. For additional help understanding different types of orders and how they behave once theyre placed, please check out the Orders on Alpaca page.
# Place New Orders
Orders can be placed with a `POST` request to our `/v2/orders` endpoint.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
trading_client = TradingClient('api-key', 'secret-key', paper=True)
# preparing market order
market_order_data = MarketOrderRequest(
symbol="SPY",
qty=0.023,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
# Market order
market_order = trading_client.submit_order(
order_data=market_order_data
)
# preparing limit order
limit_order_data = LimitOrderRequest(
symbol="BTC/USD",
limit_price=17000,
notional=4000,
side=OrderSide.SELL,
time_in_force=TimeInForce.FOK
)
# Limit order
limit_order = trading_client.submit_order(
order_data=limit_order_data
)
```
```javascript JavaScript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Submit a market order to buy 1 share of Apple at market price
alpaca.createOrder({
symbol: "AAPL",
qty: 1,
side: "buy",
type: "market",
time_in_force: "day",
});
// Submit a limit order to attempt to sell 1 share of AMD at a
// particular price ($20.50) when the market opens
alpaca.createOrder({
symbol: "AMD",
qty: 1,
side: "sell",
type: "limit",
time_in_force: "opg",
limit_price: 20.5,
});
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Submit a market order to buy 1 share of Apple at market price
var order = await client.PostOrderAsync(MarketOrder.Buy("AAPL", 1));
// Submit a limit order to attempt to sell 1 share of AMD at a
// particular price ($20.50) when the market opens
order = await client.PostOrderAsync(
LimitOrder.Sell("AMD", 1, 20.50M).WithDuration(TimeInForce.Opg));
Console.Read();
}
}
}
```
```go Go
package main
import (
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
"github.com/shopspring/decimal"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
// Submit a market order to buy 1 share of Apple at market price
symbol := "AAPL"
alpaca.PlaceOrder(alpaca.PlaceOrderRequest{
AssetKey: &symbol,
Qty: decimal.NewFromFloat(1),
Side: alpaca.Buy,
Type: alpaca.Market,
TimeInForce: alpaca.Day,
})
// Submit a limit order to attempt to sell 1 share of AMD at a
// particular price ($20.50) when the market opens
symbol = "AMD"
alpaca.PlaceOrder(alpaca.PlaceOrderRequest{
AssetKey: &symbol,
Qty: decimal.NewFromFloat(1),
Side: alpaca.Sell,
Type: alpaca.Limit,
TimeInForce: alpaca.OPG,
LimitPrice: decimal.NewFromFloat(20.50),
})
}
```
# Submit Shorts
Short orders can also be placed for securities which you do not hold an open long position in.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
trading_client = TradingClient('api-key', 'secret-key', paper=True)
# preparing orders
market_order_data = MarketOrderRequest(
symbol="SPY",
qty=1,
side=OrderSide.SELL,
time_in_force=TimeInForce.GTC
)
# Market order
market_order = trading_client.submit_order(
order_data=market_order_data
)
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
// With the Alpaca API, you can open a short position by submitting a sell
// order for a security that you have no open long position with.
namespace ShortingExample
{
internal class ShortProgram
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
// The security we'll be shorting
private static string symbol = "TSLA";
public static async Task Main(string[] args)
{
// First, open the API connection
var tradingClient = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
var dataClient = Alpaca.Markets.Environments.Paper
.GetAlpacaDataClient(new SecretKey(API_KEY, API_SECRET));
// Submit a market order to open a short position of one share
var order = await tradingClient.PostOrderAsync(MarketOrder.Sell(symbol, 1));
Console.WriteLine("Market order submitted.");
// Submit a limit order to attempt to grow our short position
// First, get an up-to-date price for our security
var snapshot = await dataClient.GetSnapshotAsync(symbol);
var price = snapshot.MinuteBar.Close;
// Submit another order for one share at that price
order = await tradingClient.PostOrderAsync(LimitOrder.Sell(symbol, 1, price));
Console.WriteLine($"Limit order submitted. Limit price = {order.LimitPrice}");
// Wait a few seconds for our orders to fill...
Thread.Sleep(2000);
// Check on our position
var position = await tradingClient.GetPositionAsync(symbol);
if (position.Quantity < 0)
{
Console.WriteLine($"Short position open for {symbol}");
}
}
}
}
```
# Using Client Order IDs
`client_order_id` can be used to organize and track specific orders in your client program. Unique `client_order_ids` for different strategies is a good way of running parallel algos across the same account.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
trading_client = TradingClient('api-key', 'secret-key', paper=True)
# preparing orders
market_order_data = MarketOrderRequest(
symbol="SPY",
qty=0.023,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY,
client_order_id='my_first_order',
)
# Market order
market_order = trading_client.submit_order(
order_data=market_order_data
)
# Get our order using its Client Order ID.
my_order = trading_client.get_order_by_client_id('my_first_order')
print('Got order #{}'.format(my_order.id))
```
```javascript
const Alpaca = require('@alpacahq/alpaca-trade-api')
const alpaca = new Alpaca()
// Submit a market order and assign it a Client Order ID.
alpaca.createOrder({
symbol: 'AAPL',
qty: 1,
side: 'buy',
type: 'market',
time_in_force: 'day',
client_order_id='my_first_order'
})
// Get our order using its Client Order ID.
alpaca.getOrderByClientOrderId('my_first_order')
.then((myOrder) => {
console.log(`Got order #${myOrder.id}.`)
})
```
```csharp C#
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
private static string CLIENT_ORDER_ID = "my_first_order";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Submit a market order and assign it a Client Order ID
await client.PostOrderAsync(
MarketOrder.Buy("AAPL", 1)
.WithClientOrderId(CLIENT_ORDER_ID));
// Get our order using its Client Order ID
var order = await client.GetOrderAsync(CLIENT_ORDER_ID);
Console.WriteLine($"Got order #{order.ClientOrderId}");
Console.Read();
}
}
}
```
# Submitting Bracket Orders
Bracket orders allow you to create a chain of orders that react to execution and stock price. For more details, go to Bracket Order Overview.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest, TakeProfitRequest, StopLossRequest
from alpaca.trading.enums import OrderSide, TimeInForce, OrderClass
trading_client = TradingClient('api-key', 'secret-key', paper=True)
# preparing bracket order with both stop loss and take profit
bracket__order_data = MarketOrderRequest(
symbol="SPY",
qty=5,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY,
order_class=OrderClass.BRACKET,
take_profit=TakeProfitRequest(limit_price=400),
stop_loss=StopLossRequest(stop_price=300)
)
bracket_order = trading_client.submit_order(
order_data=bracket__order_data
)
# preparing oto order with stop loss
oto_order_data = LimitOrderRequest(
symbol="SPY",
qty=5,
limit_price=350,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY,
order_class=OrderClass.OTO,
stop_loss=StopLossRequest(stop_price=300)
)
# Market order
oto_order = trading_client.submit_order(
order_data=oto_order_data
)
```
```javascript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
const symbol = "AAPL";
alpaca
.getBars("minute", symbol, {
limit: 5,
})
.then((barset) => {
const currentPrice = barset[symbol].slice(-1)[0].closePrice;
// We could buy a position and add a stop-loss and a take-profit of 5 %
alpaca.createOrder({
symbol: symbol,
qty: 1,
side: "buy",
type: "limit",
time_in_force: "gtc",
limit_price: currentPrice,
order_class: "bracket",
stop_loss: {
stop_price: currentPrice * 0.95,
limit_price: currentPrice * 0.94,
},
take_profit: {
limit_price: currentPrice * 1.05,
},
});
// We could buy a position and just add a stop loss of 5 % (OTO Orders)
alpaca.createOrder({
symbol: symbol,
qty: 1,
side: "buy",
type: "limit",
time_in_force: "gtc",
limit_price: currentPrice,
order_class: "oto",
stop_loss: {
stop_price: currentPrice * 0.95,
},
});
// We could split it to 2 orders. first buy a stock,
// and then add the stop/profit prices (OCO Orders)
alpaca.createOrder({
symbol: symbol,
qty: 1,
side: "buy",
type: "limit",
time_in_force: "gtc",
limit_price: currentPrice,
});
// wait for it to buy position and then
alpaca.createOrder({
symbol: symbol,
qty: 1,
side: "sell",
type: "limit",
time_in_force: "gtc",
limit_price: currentPrice,
order_class: "oco",
stop_loss: {
stop_price: currentPrice * 0.95,
},
take_profit: {
limit_price: currentPrice * 1.05,
},
});
});
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ShortingExample
{
internal class ShortProgram
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
private static string symbol = "APPL";
public static async Task Main(string[] args)
{
// First, open the API connection
var tradingClient = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
var dataClient = Alpaca.Markets.Environments.Paper
.GetAlpacaDataClient(new SecretKey(API_KEY, API_SECRET));
var snapshot = await dataClient.GetSnapshotAsync(symbol);
var price = snapshot.MinuteBar.Close;
// We could buy a position and add a stop-loss and a take-profit of 5 %
await tradingClient.PostOrderAsync(
MarketOrder.Buy(symbol, 1)
.WithDuration(TimeInForce.Gtc)
.Bracket(
stopLossStopPrice: price * 0.95M,
takeProfitLimitPrice: price * 0.94M,
stopLossLimitPrice: price * 1.05M));
// We could buy a position and just add a stop loss of 5 % (OTO Orders)
await tradingClient.PostOrderAsync(
MarketOrder.Buy(symbol, 1)
.WithDuration(TimeInForce.Gtc)
.StopLoss(
stopLossStopPrice: price * 0.95M));
// We could split it to 2 orders. first buy a stock,
// and then add the stop/profit prices (OCO Orders)
await tradingClient.PostOrderAsync(
LimitOrder.Buy(symbol, 1, price));
await tradingClient.PostOrderAsync(
LimitOrder.Sell(symbol, 1, price)
.WithDuration(TimeInForce.Gtc)
.OneCancelsOther(
stopLossStopPrice: price * 0.95M,
stopLossLimitPrice: price * 1.05M));
}
}
}
```
```go
package main
import (
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
"github.com/alpacahq/alpaca-trade-api-go/common"
"github.com/shopspring/decimal"
)
func init() {
API_KEY := "YOUR_API_KEY_HERE"
API_SECRET := "YOUR_API_SECRET_HERE"
BASE_URL := "https://paper-api.alpaca.markets"
// Check for environment variables
if common.Credentials().ID == "" {
os.Setenv(common.EnvApiKeyID, API_KEY)
}
if common.Credentials().Secret == "" {
os.Setenv(common.EnvApiSecretKey, API_SECRET)
}
alpaca.SetBaseUrl(BASE_URL)
}
func main() {
// Submit a limit order to buy 1 share of Apple and add
// StopLoss and TakeProfit orders.
client := alpaca.NewClient(common.Credentials())
symbol := "AAPL"
tpp := decimal.NewFromFloat(320.)
spp := decimal.NewFromFloat(317.)
limit := decimal.NewFromFloat(318.)
tp := &alpaca.TakeProfit{LimitPrice: &tpp}
sl := &alpaca.StopLoss{
LimitPrice: nil,
StopPrice: &spp,
}
req := alpaca.PlaceOrderRequest{
AccountID: common.Credentials().ID,
AssetKey: &symbol,
Qty: decimal.New(1, 0),
Side: alpaca.Buy,
LimitPrice: &limit,
TimeInForce: alpaca.GTC,
Type: alpaca.Limit,
OrderClass: alpaca.Bracket,
TakeProfit: tp,
StopLoss: sl,
}
order, err := client.PlaceOrder(req)
fmt.Println(order)
fmt.Println(err)
// We could buy a position and just add a stop loss (OTO Orders)
spp := decimal.NewFromFloat(317.)
limit := decimal.NewFromFloat(318.)
sl := &alpaca.StopLoss{
StopPrice: &spp,
}
req := alpaca.PlaceOrderRequest{
AccountID: common.Credentials().ID,
AssetKey: &symbol,
Qty: decimal.New(1, 0),
Side: alpaca.Buy,
LimitPrice: &limit,
TimeInForce: alpaca.GTC,
Type: alpaca.Limit,
OrderClass: alpaca.Oto,
StopLoss: sl,
}
order, err := client.PlaceOrder(req)
fmt.Println(order)
fmt.Println(err)
// We could split it to 2 orders. first buy a stock,
// and then add the stop/profit prices (OCO Orders)
limit := decimal.NewFromFloat(318.)
req := alpaca.PlaceOrderRequest{
AccountID: common.Credentials().ID,
AssetKey: &symbol,
Qty: decimal.New(1, 0),
Side: alpaca.Buy,
LimitPrice: &limit,
TimeInForce: alpaca.GTC,
Type: alpaca.Limit,
OrderClass: alpaca.Simple,
}
order, err := client.PlaceOrder(req)
fmt.Println(order)
fmt.Println(err)
// wait for it to complete and then
tpp := decimal.NewFromFloat(320.)
spp := decimal.NewFromFloat(317.)
tp := &alpaca.TakeProfit{LimitPrice: &tpp}
sl := &alpaca.StopLoss{
LimitPrice: nil,
StopPrice: &spp,
}
req := alpaca.PlaceOrderRequest{
AccountID: common.Credentials().ID,
AssetKey: &symbol,
Qty: decimal.New(1, 0),
Side: alpaca.Sell,
TimeInForce: alpaca.GTC,
Type: alpaca.Limit,
OrderClass: alpaca.Oco,
TakeProfit: tp,
StopLoss: sl,
}
order, err := client.PlaceOrder(req)
fmt.Println(order)
fmt.Println(err)
}
```
# Submitting Trailing Stop Orders
Trailing stop orders allow you to create a stop order that automatically changes the stop price allowing you to maximize your profits while still protecting your position with a stop price. For more details, go to Trailing Stop Order Overview.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import TrailingStopOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
trading_client = TradingClient('api-key', 'secret-key', paper=True)
trailing_percent_data = TrailingStopOrderRequest(
symbol="SPY",
qty=1,
side=OrderSide.SELL,
time_in_force=TimeInForce.GTC,
trail_percent=1.00 # hwm * 0.99
)
trailing_percent_order = trading_client.submit_order(
order_data=trailing_percent_data
)
trailing_price_data = TrailingStopOrderRequest(
symbol="SPY",
qty=1,
side=OrderSide.SELL,
time_in_force=TimeInForce.GTC,
trail_price=1.00 # hwm - $1.00
)
trailing_price_order = trading_client.submit_order(
order_data=trailing_price_data
)
```
```javascript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Submit a market order to buy 1 share of Apple at market price
alpaca.createOrder({
symbol: "AAPL",
qty: 1,
side: "buy",
type: "market",
time_in_force: "day",
});
// Submit a trailing stop order to sell 1 share of Apple at a
// trailing stop of
alpaca.createOrder({
symbol: "AAPL",
qty: 1,
side: "sell",
type: "trailing_stop",
trail_price: 1.0, // stop price will be hwm - 1.00$
time_in_force: "day",
});
// Alternatively, you could use trail_percent:
alpaca.createOrder({
symbol: "AAPL",
qty: 1,
side: "sell",
type: "trailing_stop",
trail_percent: 1.0, // stop price will be hwm*0.99
time_in_force: "day",
});
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Submit a market order to buy 1 share of Apple at market price
var order = await client.PostOrderAsync(
new NewOrderRequest("AAPL", 1, OrderSide.Buy, OrderType.Market, TimeInForce.Day));
// Submit a trailing stop order to sell 1 share of Apple at a
// trailing stop of
order = await client.PostOrderAsync(
TrailingStopOrder.Sell("AAPL", 1, TrailOffset.InDollars(1.00M))); // stop price will be hwm - 1.00$
/**
// Alternatively, you could use trail_percent:
order = await client.PostOrderAsync(
TrailingStopOrder.Sell("AAPL", 1, TrailOffset.InPercent(0.99M))); // stop price will be hwm * 0.99
*/
Console.Read();
}
}
}
```
```go
package main
import (
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
"github.com/shopspring/decimal"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
// Submit a market order to buy 1 share of Apple at market price
symbol := "AAPL"
alpaca.PlaceOrder(alpaca.PlaceOrderRequest{
AssetKey: &symbol,
Qty: decimal.NewFromFloat(1),
Side: alpaca.Buy,
Type: alpaca.Market,
TimeInForce: alpaca.Day,
})
// Submit a trailing stop order to sell 1 share of Apple at a
// trailing stop of
symbol = "AAPL"
alpaca.PlaceOrder(alpaca.PlaceOrderRequest{
AssetKey: &symbol,
Qty: decimal.NewFromFloat(1),
Side: alpaca.Sell,
Type: alpaca.TrailingStop,
StopPrice: decimal.NewFromFloat(1.00), // stop price will be hwm - 1.00$
TimeInForce: alpaca.Day,
})
// Alternatively, you could use trail_percent:
symbol = "AAPL"
alpaca.PlaceOrder(alpaca.PlaceOrderRequest{
AssetKey: &symbol,
Qty: decimal.NewFromFloat(1),
Side: alpaca.Sell,
Type: alpaca.TrailingStop,
TrailPercent: decimal.NewFromFloat(1.0), // stop price will be hwm*0.99
TimeInForce: alpaca.Day,
})
}
```
# Retrieve All Orders
If youd like to see a list of your existing orders, you can send a `GET` request to our `/v2/orders` endpoint.
```python Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetOrdersRequest
from alpaca.trading.enums import QueryOrderStatus
trading_client = TradingClient('api-key', 'secret-key', paper=True)
# Get the last 100 closed orders
get_orders_data = GetOrdersRequest(
status=QueryOrderStatus.CLOSED,
limit=100,
nested=True # show nested multi-leg orders
)
trading_client.get_orders(filter=get_orders_data)
```
```javascript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Get the last 100 of our closed orders
const closedOrders = alpaca
.getOrders({
status: "closed",
limit: 100,
nested: true, // show nested multi-leg orders
})
.then((closedOrders) => {
// Get only the closed orders for a particular stock
const closedAaplOrders = closedOrders.filter(
(order) => order.symbol == "AAPL"
);
console.log(closedAaplOrders);
});
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Get the last 100 of our closed orders
var closedOrders = await client.ListOrdersAsync(
new ListOrdersRequest
{
LimitOrderNumber = 100,
OrderStatusFilter = OrderStatusFilter.Closed
});
// Get only the closed orders for a particular stock
var aaplOrders = closedOrders.Where(order => order.Symbol.Equals("AAPL"));
Console.Read();
}
}
}
```
```go
package main
import (
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
// Get the last 100 of our closed orders
status := "closed"
limit := 100
nested := true // show nested multi-leg orders
closed_orders, err := alpaca.ListOrders(&status, nil, &limit, &nested)
if err != nil {
panic(err)
}
// Get only the closed orders for a particular stock
var aaplOrders []alpaca.Order
for _, order := range closed_orders {
if order.Symbol == "AAPL" {
aaplOrders = append(aaplOrders, order)
}
}
}
```
# Listen for Updates to Orders
You can use Websockets to receive real-time updates about the status of your orders as they change. You can see the full documentation here.
```python Python
from alpaca.trading.stream import TradingStream
stream = TradingStream('api-key', 'secret-key', paper=True)
@conn.on(client_order_id)
async def on_msg(data):
# Print the update to the console.
print("Update for {}. Event: {}.".format(data.event))
stream.subscribe_trade_updates(on_msg)
# Start listening for updates.
stream.run()
```
```javascript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Prepare the websocket connection and subscribe to trade_updates.
alpaca.websocket.onConnect(function () {
console.log("Connected");
client.subscribe(["trade_updates"]);
setTimeout(() => {
client.disconnect();
}, 30 * 1000);
});
alpaca.websocket.onDisconnect(() => {
console.log("Disconnected");
});
alpaca.websocket.onStateChange((newState) => {
console.log(`State changed to ${newState}`);
});
// Handle updates on an order you've given a Client Order ID.
const client_order_id = "my_client_order_id";
alpaca.websocket.onOrderUpdate((orderData) => {
const event = orderData["event"];
if (orderData["order"]["client_order_id"] == client_order_id) {
console.log(`Update for ${client_order_id}. Event: ${event}.`);
}
});
// Start listening for updates.
alpaca.websocket.connect();
```
```csharp C#
using Alpaca.Markets;
using System;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
// Print a message to the console when the account's status changes.
public static async Task Main(string[] args)
{
// Prepare the websocket connection and subscribe to trade_updates.
var alpacaStreamingClient = Environments.Paper
.GetAlpacaStreamingClient(new SecretKey(API_KEY, API_SECRET));
await alpacaStreamingClient.ConnectAndAuthenticateAsync();
alpacaStreamingClient.OnTradeUpdate += HandleTradeUpdate;
Console.Read();
}
// Handle incoming trade updates.
private static void HandleTradeUpdate(ITradeUpdate update)
{
if (update.Order.ClientOrderId.Equals("my_client_order_id"))
{
Console.WriteLine($"Update for {update.Order.ClientOrderId}. Event: {update.Event}");
}
}
}
}
```
```go
package main
import (
"fmt"
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
"github.com/alpacahq/alpaca-trade-api-go/stream"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
if err := stream.Register(alpaca.TradeUpdates, tradeHandler); err != nil {
panic(err)
}
}
func tradeHandler(msg interface{}) {
tradeupdate := msg.(alpaca.TradeUpdate)
if tradeupdate.Order.ClientOrderID == "my_client_order_id" {
fmt.Printf("Update for {}. Event: {}.\n", tradeupdate.Order.ClientOrderID, tradeupdate.Event)
}
}
```
# FAQ
**What should I do if I receive a timeout message from Alpaca when submitting an order?**
The order may have been sent to the market for execution. You should not attempt to resend the order or mark the timed-out order as canceled until confirmed by Alpaca Support or the trading team. Before taking any action on the timed-out order you should check the broker dashboard and contact Alpaca support.\
Please contact our Support Team at [support@alpaca.markets](mailto:support@alpaca.markets) to verify if the order was successfully submitted and routed to the market.
@@ -0,0 +1,117 @@
# Working with /positions
You can view the positions in your portfolio by making a `GET` request to the `/v2/positions` endpoint. If you specify a symbol, youll see only your position for the associated stock.
```python
from alpaca.trading.client import TradingClient
trading_client = TradingClient('api-key', 'secret-key')
# Get our position in AAPL.
aapl_position = trading_client.get_open_position('AAPL')
# Get a list of all of our positions.
portfolio = trading_client.get_all_positions()
# Print the quantity of shares for each position.
for position in portfolio:
print("{} shares of {}".format(position.qty, position.symbol))
```
```javascript
const Alpaca = require("@alpacahq/alpaca-trade-api");
const alpaca = new Alpaca();
// Get our position in AAPL.
aaplPosition = alpaca.getPosition("AAPL");
// Get a list of all of our positions.
alpaca.getPositions().then((portfolio) => {
// Print the quantity of shares for each position.
portfolio.forEach(function (position) {
console.log(`${position.qty} shares of ${position.symbol}`);
});
});
```
```csharp
using Alpaca.Markets;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CodeExamples
{
internal static class Example
{
private static string API_KEY = "your_api_key";
private static string API_SECRET = "your_secret_key";
public static async Task Main(string[] args)
{
// First, open the API connection
var client = Alpaca.Markets.Environments.Paper
.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));
// Get our position in AAPL.
var aaplPosition = await client.GetPositionAsync("AAPL");
// Get a list of all of our positions.
var positions = await client.ListPositionsAsync();
// Print the quantity of shares for each position.
foreach (var position in positions)
{
Console.WriteLine($"{position.Quantity} shares of {position.Symbol}.");
}
Console.Read();
}
}
}
```
```go
package main
import (
"fmt"
"github.com/alpacahq/alpaca-trade-api-go/alpaca"
)
func init() {
alpaca.SetBaseUrl("https://paper-api.alpaca.markets")
}
func main() {
// Get our position in AAPL.
aapl_position, err := alpaca.GetPosition("AAPL")
if err != nil {
fmt.Println("No AAPL position.")
} else {
fmt.Printf("AAPL position: %v shares.\n", aapl_position.Qty)
}
// Get a list of all of our positions.
positions, err := alpaca.ListPositions()
if err != nil {
fmt.Println("No positions found.")
} else {
// Print the quantity of shares for each position.
for _, position := range positions {
fmt.Printf("%v shares in %s", position.Qty, position.Symbol)
}
}
}
```
The current price reflected will be based on the following:
**4:00 am ET - 9:30 am ET** - Last trade based on the premarket
**9:30 am ET - 4pm ET** - Last trade
**4:00 pm ET - 10:00 pm ET** - Last trade based on after-hours trading
**10 pm ET - 4:00 am ET next trading day** - Official closing price from the primary exchange at 4 pm ET.