### Install Go SDK Source: https://docs.alpaca.markets/us/docs/getting-started-with-alpaca-market-data Install the Alpaca Go SDK using go get. ```go go get -u github.com/alpacahq/alpaca-trade-api-go/v3/alpaca ``` -------------------------------- ### Get All Assets Example Source: https://docs.alpaca.markets/us/docs/getting-started-with-broker-api This snippet shows how to make a GET request to the /v1/assets endpoint to retrieve all available assets. This call does not require a request body. ```json { "id": "7595a8d2-68a6-46d7-910c-6b1958491f5c", "class": "us_equity", "exchange": "NYSE", "symbol": "A", "name": "Agilent Technologies Inc.", "status": "active", "tradable": true, "marginable": true, "shortable": true, "easy_to_borrow": true, "fractionable": true } ``` -------------------------------- ### Install C# SDK Source: https://docs.alpaca.markets/us/docs/getting-started-with-alpaca-market-data Install the Alpaca C# SDK using dotnet add package. ```csharp dotnet add package Alpaca.Markets ``` -------------------------------- ### Install Shell Completions for Alpaca CLI Source: https://docs.alpaca.markets/us/docs/alpacas-cli Install shell completions for Bash, Zsh, Fish, and PowerShell. Follow the output instructions to complete the installation for your specific shell. ```bash alpaca completion bash ``` ```bash alpaca completion zsh ``` ```bash alpaca completion fish ``` ```bash alpaca completion powershell ``` -------------------------------- ### Install JavaScript SDK Source: https://docs.alpaca.markets/us/docs/getting-started-with-alpaca-market-data Install the Alpaca JavaScript SDK using npm. ```javascript npm install --save @alpacahq/alpaca-trade-api ``` -------------------------------- ### Install Alpaca CLI using Go Source: https://docs.alpaca.markets/us/docs/alpacas-cli Install the Alpaca CLI using the Go programming language. Ensure your $GOPATH/bin is on your PATH. ```bash go install github.com/alpacahq/cli/cmd/alpaca@latest ``` -------------------------------- ### Install Python SDK Source: https://docs.alpaca.markets/us/docs/getting-started-with-alpaca-market-data Install the Alpaca Python SDK using pip. ```python pip install alpaca-py ``` -------------------------------- ### Get Account Information (C#) Source: https://docs.alpaca.markets/us/docs/working-with-account Fetch account details using the Alpaca.Markets SDK for C#. This example demonstrates checking trading blocks and buying power. ```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(); } } } ``` -------------------------------- ### Options Position Example Source: https://docs.alpaca.markets/us/docs/options-trading-overview This JSON represents an example of an options position as it would appear in the positions endpoint. ```json { "asset_id": "fe4f43e5-60a4-4269-ba4c-3d304444d58b", "symbol": "PTON240126C00000500", "exchange": "", "asset_class": "us_option", "asset_marginable": true, "qty": "2", "avg_entry_price": "6.05", "side": "long", "market_value": "1068", "cost_basis": "1210", "unrealized_pl": "-142", "unrealized_plpc": "-0.1173553719008264", "unrealized_intraday_pl": "-142", "unrealized_intraday_plpc": "-0.1173553719008264", "current_price": "5.34", "lastday_price": "5.34", "change_today": "0", "qty_available": "2" } ``` -------------------------------- ### Worked Example: POST Request Headers Source: https://docs.alpaca.markets/us/docs/tokenization-guide-for-issuer An example of Alpaca-generated headers for a POST /tokenization/mint request, including specific values for created, keyid, nonce, and Content-Digest. ```http POST /tokenization/mint HTTP/1.1 Host: issuer.example.com Content-Type: application/json Content-Digest: sha-256=:X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=: Signature-Input: sig=("@method" "@target-uri" "content-type" "content-digest");created=1700000000;keyid="alpaca-issuer-2026-01";alg="ed25519";nonce="deadbeefdeadbeefdeadbeefdeadbeef" Signature: sig=:lD6c6jHb6kQTzZ5pK6m7Bt2u8m1bF1mE4qLh3i2cIuv6xv1uYwK1Kx4G2k8nC0z3pE5p9c4r4cZ8aFwq9XnZAg==: {"tokenization_request_id":"12345-678-90AB", ...} ``` -------------------------------- ### Verify Alpaca CLI Installation Source: https://docs.alpaca.markets/us/docs/alpacas-cli Verify the installation of the Alpaca CLI by checking its version and running a diagnostic check. ```bash alpaca version alpaca doctor ``` -------------------------------- ### Install Alpaca CLI using Homebrew Source: https://docs.alpaca.markets/us/docs/alpacas-cli Install the Alpaca CLI on macOS or Linux using the Homebrew package manager. ```bash brew install alpacahq/tap/cli ``` -------------------------------- ### Example API Call with Request ID Source: https://docs.alpaca.markets/us/docs/getting-started-with-broker-api This example demonstrates a curl request to the /v1/accounts endpoint and highlights the X-Request-ID in the response headers. This ID is essential for support inquiries. ```shell $ curl -v https://broker-api.sandbox.alpaca.markets/v1/accounts ... > GET /v1/accounts HTTP/1.1 > Host: broker-api.sandbox.alpaca.markets > User-Agent: curl/7.88.1 > Accept: */* > < HTTP/1.1 403 Forbidden < Date: Fri, 25 Aug 2023 09:10:03 GMT < Content-Type: application/json < Content-Length: 26 < Connection: keep-alive < X-Request-ID: 65ddd35ed1b3433dbf29d11f6d932c88 < ... ``` -------------------------------- ### Mint Request Response Body Example Source: https://docs.alpaca.markets/us/docs/tokenization-guide-for-authorized-participant Example JSON response body after a successful mint request, including request ID, creation timestamp, status, and token details. ```json { "tokenization_request_id": "14d484e3-46f9-4e11-99ac-6fee0d4455c7", "created_at":"2025-09-12T17:28:48.642437-04:00", "status": "pending", "underlying_symbol": "AAPL", "token_symbol": "AAPLx", "qty": "3", "issuer": "xstocks", "network": "solana" } ``` -------------------------------- ### Get Account Information Source: https://docs.alpaca.markets/us/docs/using-oauth2-and-trading-api Example of making a GET request to the v2/account endpoint using the obtained access token for authorization. ```curl curl https://api.alpaca.markets/v2/account / -H 'Authorization: Bearer 79500537-5796-4230-9661-7f7108877c60' ``` -------------------------------- ### Create Bracket, OTO, and OCO Orders (C#) Source: https://docs.alpaca.markets/us/docs/working-with-orders Demonstrates creating bracket, OTO, and OCO orders with stop-loss and take-profit using the Alpaca.Markets library. Ensure API keys are correctly configured. ```csharp 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)); } } } ``` -------------------------------- ### Connect and Authenticate with wscat Source: https://docs.alpaca.markets/us/docs/streaming-market-data This example demonstrates how to connect to the Alpaca streaming API using the wscat CLI tool, authenticate with your API keys, and subscribe to market data. It shows the initial connection, authentication request, and subscription confirmation. ```bash $ wscat -c wss://stream.data.alpaca.markets/v2/test Connected (press CTRL+C to quit) < [{"T":"success","msg":"connected"}] > {"action":"auth","key":"","secret":""} < [{"T":"success","msg":"authenticated"}] ``` -------------------------------- ### Get Orders Source: https://docs.alpaca.markets/us/docs/using-oauth2-and-trading-api Example of making a GET request to the v2/orders endpoint using the paper trading API and the obtained access token for authorization. ```curl curl https://paper-api.alpaca.markets/v2/orders / -H 'Authorization: Bearer 79500537-5796-4230-9661-7f7108877c60' ``` -------------------------------- ### Alpaca Redirect Back to App Example Source: https://docs.alpaca.markets/us/docs/using-oauth2-and-trading-api This is an example of the GET request Alpaca makes to your redirect URI after user approval, including the authorization code and state parameter. ```HTTP GET https://example.com/oauth/callback?code=67f74f5a-a2cc-4ebd-88b4-22453fe07994&state=8e02c9c6a3484fadaaf841fb1df290e1 ``` -------------------------------- ### Shorting Example in C# Source: https://docs.alpaca.markets/us/docs/working-with-orders Demonstrates how to open a short position by submitting a sell order for a security without an existing long position. Includes submitting market and limit orders. ```csharp 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}"); } } } } ``` -------------------------------- ### Login with API Keys (Paper or Live) Source: https://docs.alpaca.markets/us/docs/alpacas-cli Authenticate using API keys for either paper or live trading. Ensure your API keys are correctly set up. ```bash # Paper trading with API keys alpaca profile login --api-key # Live trading with API keys alpaca profile login --api-key --live ``` -------------------------------- ### Get Stock Quotes Data Source: https://docs.alpaca.markets/us/docs/alpacas-cli Retrieve historical quote data (bid/ask prices) for a stock symbol starting from a specified date. Useful for analyzing price movements. ```bash alpaca data quotes --symbol AAPL --start 2025-06-01 ``` -------------------------------- ### Example Subscription and Unsubscription Sequence Source: https://docs.alpaca.markets/us/docs/streaming-market-data Illustrates a typical sequence of sending a subscription request, followed by a confirmation, then an unsubscription request, and its subsequent confirmation. ```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"]}] ``` ```json > {"action": "unsubscribe", "bars": ["*"]} < [{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":[],"updatedBars":[],"dailyBars":[],"statuses":[],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}] ``` -------------------------------- ### Get a List of All Active Assets (C#) Source: https://docs.alpaca.markets/us/docs/working-with-assets Retrieve a list of all active assets and filter them by exchange using the Alpaca.Markets library. Requires API keys and environment setup. ```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 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(); } } } ``` -------------------------------- ### Instantiate MarketData Client (Go) Source: https://docs.alpaca.markets/us/docs/getting-started-with-alpaca-market-data Instantiate the marketdata client in Go. API keys are not required for crypto data. ```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{}) } ``` -------------------------------- ### Get Stock Trades Data Source: https://docs.alpaca.markets/us/docs/alpacas-cli Retrieve historical trade data (executed trades) for a stock symbol starting from a specified date. Provides details on transaction prices and volumes. ```bash alpaca data trades --symbol AAPL --start 2025-06-01 ``` -------------------------------- ### Connect and Subscribe to Crypto Data Stream Source: https://docs.alpaca.markets/us/docs/real-time-crypto-pricing-data Example using wscat to connect to the Alpaca crypto data stream, authenticate, and subscribe to bar data for BTC/USD. ```bash $ 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}] ``` -------------------------------- ### Get Trading Account Details Source: https://docs.alpaca.markets/us/docs/instant-funding Fetch a user's trading account details, including their current buying power, after an instant funding transfer has been executed. This is useful for guiding users to trade with immediate funds. ```json { "id": "{ACCOUNT_ID}", "admin_configurations": { "allow_instant_ach": true, "disable_shorting": true, "max_margin_multiplier": "1" }, "user_configurations": null, "account_number": "{ACCOUNT_NO}", "status": "ACTIVE", "crypto_status": "INACTIVE", "currency": "USD", "buying_power": "100", "regt_buying_power": "100", "daytrading_buying_power": "0", "effective_buying_power": "100", "non_marginable_buying_power": "0", "bod_dtbp": "0", "cash": "100", "cash_withdrawable": "0", "cash_transferable": "0", "accrued_fees": "0", "pending_transfer_out": "0", "pending_transfer_in": "0", "portfolio_value": "0", "pattern_day_trader": false, "trading_blocked": false, "transfers_blocked": false, "account_blocked": false, "created_at": "2024-07-10T17:23:51.655324Z", "trade_suspended_by_user": false, "multiplier": "1", "shorting_enabled": false, "equity": "0", "last_equity": "0", "long_market_value": "0", "short_market_value": "0", "position_market_value": "0", "initial_margin": "0", "maintenance_margin": "0", "last_maintenance_margin": "0", "sma": "0", "daytrade_count": 0, "balance_asof": "2024-07-09", "previous_close": "2024-07-09T20:00:00-04:00", "last_long_market_value": "0", "last_short_market_value": "0", "last_cash": "0", "last_initial_margin": "0", "last_regt_buying_power": "0", "last_daytrading_buying_power": "0", "last_buying_power": "0", "last_daytrade_count": 0, "clearing_broker": "ALPACA_APCA", "memoposts": "100", "intraday_adjustments": "0", "pending_reg_taf_fees": "0" } ``` -------------------------------- ### Get IPO by ID Response (200) Source: https://docs.alpaca.markets/us/docs/us-ipos-initial-public-offerings-1 This is an example of a successful response when retrieving a single IPO offering by its ID. It provides comprehensive details about the IPO, including its status, pricing, and important dates. Note the presence of `no_new_orders` and `sixty_minute_expiration_time` for offerings within the withdrawal window. ```json { "data": { "name": "Example Corp", "description": "Example business description", "ticker_symbol": "EXMP", "ipo_reference": "EXMP260615", "cusip_id": "123456789", "prospectus_url": "https://example.com/prospectus.pdf", "offering_type": "IPO", "availability": "available", "anticipated_shares": 1000000, "max_price": "25", "min_price": "20", "trade_date": "2026-06-15", "settlement_date": "2026-06-16", "no_new_orders": true, "sixty_minute_expiration_time": "2026-06-15T13:00:00Z", "underwriters": ["Bank A", "Bank B"], "unit_step_size": "1", "min_ticket_size": "100", "max_ticket_size": "10000" } } ``` -------------------------------- ### Get Account Information via GET Request Source: https://docs.alpaca.markets/us/docs/portfolio-rebalancing Retrieve account details, including withdrawable cash, using this GET request. This is used to verify funds before withdrawal. ```HTTP GET https://broker-api.sandbox.alpaca.markets/v1/trading/accounts/\{account_id}/account ``` -------------------------------- ### Receive Quote Data with wscat Source: https://docs.alpaca.markets/us/docs/streaming-market-data This example demonstrates receiving real-time quote data for a subscribed symbol using the wscat CLI tool. It shows the structure of a quote message, including bid and ask prices and sizes. ```bash < [{"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"}] ``` -------------------------------- ### Submit Short Orders in Python Source: https://docs.alpaca.markets/us/docs/working-with-orders Place a short sell order using the TradingClient. This example demonstrates a Good 'Til Cancelled (GTC) order. ```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 ) ``` -------------------------------- ### Example Subscription Message Source: https://docs.alpaca.markets/us/docs/streaming-market-data An example of a subscription message for the 'trades' channel with a specific symbol 'FAKEPACA'. ```json {"action":"subscribe","trades":["FAKEPACA"]} ``` -------------------------------- ### Create Watchlist Source: https://docs.alpaca.markets/us/docs/alpacas-cli Create a new watchlist with a specified name and initial set of symbols. Watchlists help organize assets for monitoring. ```bash alpaca watchlist create --name "Tech Stocks" --symbols AAPL,MSFT,NVDA ``` -------------------------------- ### Subscribe to Market Data with wscat Source: https://docs.alpaca.markets/us/docs/streaming-market-data Following authentication, this snippet shows how to subscribe to specific market data streams, such as bars and quotes for a given symbol, using the wscat CLI tool. It also illustrates the server's confirmation of the subscription. ```bash > {"action":"subscribe","bars":["FAKEPACA"],"quotes":["FAKEPACA"]} < [{"T":"subscription","trades":[],"quotes":["FAKEPACA"],"bars":["FAKEPACA"]}] ``` -------------------------------- ### Multileg Options Order Fill Event Example Source: https://docs.alpaca.markets/us/docs/websocket-streaming Example of a fill event message for a MultilegOptionsOrder from the trade_updates stream. ```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": null, "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": null, "filled_avg_price": null, "order_class": "mleg", "order_type": "", "type": "", "side": "sell", "time_in_force": "day", "limit_price": null, "stop_price": null, "status": "new", "extended_hours": false, "legs": null, "trail_percent": null, "trail_price": null, "hwm": null, "ratio_qty": "1" } ] } } } ``` -------------------------------- ### Using Client Order IDs in Python Source: https://docs.alpaca.markets/us/docs/working-with-orders Demonstrates how to use client_order_id to organize and track specific orders. Includes submitting a market order and retrieving it by its client order ID. ```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)) ``` -------------------------------- ### Create Bracket, OTO, and OCO Orders (JavaScript) Source: https://docs.alpaca.markets/us/docs/working-with-orders Demonstrates creating bracket, OTO (One-Triggers-Other), and OCO (One-Cancels-Other) orders with stop-loss and take-profit. Requires the Alpaca trade API library. ```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, }, }); }); ``` -------------------------------- ### Trade Update Fill Event Example Source: https://docs.alpaca.markets/us/docs/websocket-streaming Example of a fill event message from the trade_updates stream for a crypto order. ```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" } } ``` -------------------------------- ### List Positions with Different Output Formats Source: https://docs.alpaca.markets/us/docs/alpacas-cli Demonstrates how to list your current positions using different output formats: default JSON, CSV, and filtered JSON using the built-in jq. ```bash # JSON (default) alpaca position list # CSV alpaca position list --csv # Filtered JSON with built-in jq (no external jq needed) alpaca position list --jq '[.[] | {symbol, qty, unrealized_pl}]' ``` -------------------------------- ### Trade Cancel/Error Example Source: https://docs.alpaca.markets/us/docs/real-time-stock-pricing-data An example of a trade cancel or error message, indicating a previously sent trade was canceled. ```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" } ``` -------------------------------- ### Manage Account Configuration Source: https://docs.alpaca.markets/us/docs/alpacas-cli View and update account configuration settings. Use 'get' to see current settings and 'set' to modify them. ```bash alpaca account config get # Account configuration ``` ```bash alpaca account config set # Update account configuration ``` -------------------------------- ### News Message Schema Example Source: https://docs.alpaca.markets/us/docs/streaming-real-time-news An example of a news message received from the WebSocket stream, illustrating the structure and fields. ```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\"\]CRSR\u003c/a\u003e) (\u0026ldquo;Corsair\u0026rdquo;), a leading global ...", "symbols": ["CRSR"], "source": "benzinga" } ``` -------------------------------- ### Compressed FIFO Example 1 Calculation Source: https://docs.alpaca.markets/us/docs/position-average-entry-price-calculation Illustrates the Compressed FIFO method for calculating cost basis and average entry price, showing how intraday positions are compressed using a weighted average before a sell transaction. ```plaintext 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`. ```