algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
algotradelib::alpaca::AlpacaBlockingClient Class Reference

A blocking client for Alpaca's Trading API and Market Data API: exchange-listed US equities, whole shares, limit and market day orders in the regular session. More...

#include <algotradelib/src/brokers/alpaca/client.hpp>

Public Member Functions

 AlpacaBlockingClient (ssl::context &context, AlpacaConfig config, network::HttpClientOptions options={}, std::shared_ptr< network::TokenStore > store=nullptr)
 Constructs a client; it connects on the first request.
const AlpacaConfig & config () const noexcept
 Returns the configuration.
const network::RateLimitStats * rate_limit_stats () const
 Returns the trading connection's rate-limit statistics; read them between calls.
Result< std::vector< AlpacaAccountInfo > > accounts ()
 Returns the one account the keys drive (/v2/account).
Result< QuoteSnapshot > quote (InstrumentId instrument)
 Returns the last trade on the IEX feed, in dollars.
Result< BarSeries > bars (BarQuery query)
 Returns closed bars, oldest first: the newest count_ (1 to 9,999) at or before before_ (or now), on the IEX feed, in one request.
Result< HoldingsSnapshot > holdings (AlpacaAccount account={})
 Returns the US equity positions (/v2/positions), in dollars.
Result< Instrument > instrument (InstrumentId instrument)
 Returns one instrument's reference data (/v2/assets/{symbol}), with lot 1, dollars and us::equity_price_rule().
Result< TradingCalendar > calendar (Country country, std::optional< Date > from=std::nullopt)
 Returns the New York Stock Exchange's trading calendar with each open day's session hours, as instants (/v3/calendar/XNYS).
Result< AlpacaOrderAck > place_order (AlpacaAccount account, OrderRequest order)
 Places an order (POST /v2/orders). The outcome can be unknown after an error.
Result< AlpacaOrderAck > cancel_order (AlpacaAccount account, AlpacaAmendment amendment)
 Cancels a whole order (DELETE /v2/orders/{id}; 204, also for an order already cancelled). The outcome can be unknown after an error.
Result< AlpacaOpenOrders > working_orders (AlpacaAccount account={})
 Returns the open US equity orders (/v2/orders?status=open, up to 499).
Result< OrderSnapshot > order_by_id (AlpacaAccount account, const std::string &id)
 Returns one order by its id (/v2/orders/{id}); an order that is not a US equity is a PROTOCOL error.
Result< OrderPage > order_history (AlpacaAccount account, OrderHistoryQuery query)
 Returns US equity orders submitted from from_ to to_ (New York dates), newest first, up to limit_ (500 by default) rows.

Static Public Member Functions

static network::RateLimitBudget default_rate_limit () noexcept
 The pacing each connection gets when the caller sets none.

Friends

struct AlpacaClientTestAccess

Detailed Description

A blocking client for Alpaca's Trading API and Market Data API: exchange-listed US equities, whole shares, limit and market day orders in the regular session.

Paper trading unless AlpacaConfig::is_demo_ is false; live is the same code path on another host. Each call runs its requests on a private event loop over two network::AsyncHttpClient connections (trading, market data) and returns the result. Not thread-safe: one session uses it.

When HttpClientOptions::rate_limit_ is empty, each connection is paced at one request a second with a burst of two, one of them reserved for orders (RateLimitBudget{2, 1, 1}), under Alpaca's 200 a minute even if both hosts share one allowance; a budget you set is used as given, on each connection.

Every placement is checked by detail::validate_order, then reads the asset (refusing OTC and anything not active and tradable), for a sell the position (refusing a sell above it), and Alpaca's clock (refusing unless the regular session is on), before the order is sent. A refusal for the clock is CANCELLED with reached_broker_ false, which a runner keeps and offers again; the others are not sent either.

Definition at line 566 of file client.hpp.

Constructor & Destructor Documentation

◆ AlpacaBlockingClient()

algotradelib::alpaca::AlpacaBlockingClient::AlpacaBlockingClient ( ssl::context & context,
AlpacaConfig config,
network::HttpClientOptions options = {},
std::shared_ptr< network::TokenStore > store = nullptr )
inline

Constructs a client; it connects on the first request.

Parameters
contextThe TLS context; borrowed, and must outlive the client.
configThe keys and environment.
optionsHTTP options; an empty rate_limit_ gets the default pacing above.
storeIgnored: Alpaca has no token to share. Accepted so network::make_client can build the client.

Definition at line 575 of file client.hpp.

Member Function Documentation

◆ accounts()

Result< std::vector< AlpacaAccountInfo > > algotradelib::alpaca::AlpacaBlockingClient::accounts ( )
inline

Returns the one account the keys drive (/v2/account).

Returns
The account, or an error; an account not in USD is a PROTOCOL error.

Definition at line 621 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::accounts().

◆ bars()

Result< BarSeries > algotradelib::alpaca::AlpacaBlockingClient::bars ( BarQuery query)
inline

Returns closed bars, oldest first: the newest count_ (1 to 9,999) at or before before_ (or now), on the IEX feed, in one request.

Minute and hour bars are stamped at their start and daily bars at New York's midnight (BarStamp::OPEN); a bar whose period has not ended is dropped. IEX carries a small part of the consolidated volume, and its intraday bars include pre- and post-market trades.

Parameters
queryThe query.
Returns
The bars, or an error.

Definition at line 675 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::bars().

◆ calendar()

Result< TradingCalendar > algotradelib::alpaca::AlpacaBlockingClient::calendar ( Country country,
std::optional< Date > from = std::nullopt )
inline

Returns the New York Stock Exchange's trading calendar with each open day's session hours, as instants (/v3/calendar/XNYS).

Without from, it covers 41 days from the UTC date ten days before now, so the last trading day before now and the next ones after it are both listed; with from, 41 days from it. A listed date is open, with regular_ from its core session and extended_ from its pre-market start to its post-market end when both are stated; an unlisted date is closed. A date listed twice or outside the range fails the read.

Parameters
countryCountry::US; any other is refused before sending.
fromThe first date, or empty for the default range.
Returns
The calendar, or an error.

Definition at line 852 of file client.hpp.

Referenced by calendar(), and algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::calendar().

◆ cancel_order()

Result< AlpacaOrderAck > algotradelib::alpaca::AlpacaBlockingClient::cancel_order ( AlpacaAccount account,
AlpacaAmendment amendment )
inline

Cancels a whole order (DELETE /v2/orders/{id}; 204, also for an order already cancelled). The outcome can be unknown after an error.

Parameters
accountThe account (empty).
amendmentThe order.
Returns
The acknowledgement (the same id), or an error.

Definition at line 965 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::cancel_order().

◆ config()

const AlpacaConfig & algotradelib::alpaca::AlpacaBlockingClient::config ( ) const
inlinenoexcept

Returns the configuration.

Returns
The configuration.

Definition at line 604 of file client.hpp.

Referenced by AlpacaBlockingClient().

◆ default_rate_limit()

network::RateLimitBudget algotradelib::alpaca::AlpacaBlockingClient::default_rate_limit ( )
inlinestaticnoexcept

The pacing each connection gets when the caller sets none.

Returns
RateLimitBudget{2, 1, 1}.

Definition at line 596 of file client.hpp.

◆ holdings()

Result< HoldingsSnapshot > algotradelib::alpaca::AlpacaBlockingClient::holdings ( AlpacaAccount account = {})
inline

Returns the US equity positions (/v2/positions), in dollars.

The sellable figure is qty_available, with the basis {WHOLE_HOLDING, DEDUCT, verified_ = false}. The read fails (PROTOCOL, invalid_holdings_response) when a symbol appears twice among all rows, when a row names no symbol or class, and when a us_equity row is short or has no readable qty: a short equity position anywhere in the account stops the read. Rows of other classes (crypto, options) are skipped.

Parameters
accountThe account (empty).
Returns
The holdings, or an error.

Definition at line 749 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::holdings().

◆ instrument()

Result< Instrument > algotradelib::alpaca::AlpacaBlockingClient::instrument ( InstrumentId instrument)
inline

Returns one instrument's reference data (/v2/assets/{symbol}), with lot 1, dollars and us::equity_price_rule().

Alpaca names no security type (an ETF and a stock are both us_equity), so it is UNKNOWN. An asset that is not an active, tradable equity on a US national exchange (OTC included) is refused.

Parameters
instrumentThe instrument.
Returns
The instrument, or an error.

Definition at line 815 of file client.hpp.

Referenced by instrument(), algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::instrument(), and quote().

◆ order_by_id()

Result< OrderSnapshot > algotradelib::alpaca::AlpacaBlockingClient::order_by_id ( AlpacaAccount account,
const std::string & id )
inline

Returns one order by its id (/v2/orders/{id}); an order that is not a US equity is a PROTOCOL error.

Parameters
accountThe account (empty).
idThe order id.
Returns
The order, or an error.

Definition at line 1012 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::order_by_id().

◆ order_history()

Result< OrderPage > algotradelib::alpaca::AlpacaBlockingClient::order_history ( AlpacaAccount account,
OrderHistoryQuery query )
inline

Returns US equity orders submitted from from_ to to_ (New York dates), newest first, up to limit_ (500 by default) rows.

A full page carries a cursor, the last row's submitted_at, sent back as Alpaca's exclusive until. The page fails as working_orders does; skipped rows still count toward the page.

Parameters
accountThe account (empty).
queryThe query.
Returns
The page, or an error.

Definition at line 1041 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::order_history().

◆ place_order()

Result< AlpacaOrderAck > algotradelib::alpaca::AlpacaBlockingClient::place_order ( AlpacaAccount account,
OrderRequest order )
inline

Places an order (POST /v2/orders). The outcome can be unknown after an error.

Before anything is sent, it refuses what detail::validate_order refuses; then it reads the asset (instrument_not_listed for OTC or an exchange not known to be national, instrument_not_tradable), for a sell the position (no_position, sell_exceeds_position above qty_available or qty), and last Alpaca's clock for the New York Stock Exchange: unless its phase is core, the order is not sent (market_closed, CANCELLED, reached_broker_ false), since Alpaca would queue a day order for the next session. A failed read refuses the order with the read's own category, not sent. The clock covers market-wide state (an unscheduled closure), not a single stock's halt, and a fill between a read and the order is not seen.

Alpaca's refusals seen on the paper host (422 42210000, 403 40310000) are INVALID_ARGUMENT; any other failure leaves the outcome unknown (PROTOCOL, or HTTP for 5xx, or the transport's), to be read back.

Parameters
accountThe account (empty).
orderThe order.
Returns
The acknowledgement, or an error.

Definition at line 935 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::place_order().

◆ quote()

Result< QuoteSnapshot > algotradelib::alpaca::AlpacaBlockingClient::quote ( InstrumentId instrument)
inline

Returns the last trade on the IEX feed, in dollars.

Parameters
instrumentThe instrument.
Returns
The quote, or an error.

Definition at line 641 of file client.hpp.

Referenced by quote(), and algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::quote().

◆ rate_limit_stats()

const network::RateLimitStats * algotradelib::alpaca::AlpacaBlockingClient::rate_limit_stats ( ) const
inline

Returns the trading connection's rate-limit statistics; read them between calls.

Returns
The statistics, or null if the connection has no budget.

Definition at line 612 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::rate_limit_stats().

◆ working_orders()

Result< AlpacaOpenOrders > algotradelib::alpaca::AlpacaBlockingClient::working_orders ( AlpacaAccount account = {})
inline

Returns the open US equity orders (/v2/orders?status=open, up to 499).

The listing fails when an order id appears twice among all rows, when 500 rows come back (it may be cut), and when a us_equity row's side or quantity cannot be read; rows of other classes are skipped.

Parameters
accountThe account (empty).
Returns
The orders, or an error.

Definition at line 985 of file client.hpp.

Referenced by algotradelib::BrokerTraits< alpaca::AlpacaBlockingClient >::working_orders().

◆ AlpacaClientTestAccess

friend struct AlpacaClientTestAccess
friend

Definition at line 1080 of file client.hpp.


The documentation for this class was generated from the following file: