algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
client.hpp
1#pragma once
2
3#include "./config.hpp"
4
5#include "../../core/calendar.hpp"
6#include "../../core/instrument.hpp"
7#include "../../core/market_data.hpp"
8#include "../../core/types.hpp"
9#include "../../network/http_client.hpp"
10#include "../../network/token_store.hpp"
11#include "../common/adapter.hpp"
12#include "../common/us.hpp"
13
14#include <boost/asio/io_context.hpp>
15#include <boost/json.hpp>
16
17#include <algorithm>
18#include <charconv>
19#include <chrono>
20#include <cmath>
21#include <cstdint>
22#include <cstdio>
23#include <functional>
24#include <memory>
25#include <optional>
26#include <set>
27#include <stdexcept>
28#include <string>
29#include <string_view>
30#include <utility>
31#include <vector>
32
34
35// What Alpaca's paper host showed on 2026-11-20 is recorded in labs/atl-thirdparty/README.md; the stored docs are
36// docs/api/alpaca at the workspace root.
37
42struct Broker {
44 static constexpr std::string_view name = "alpaca";
45};
46
53 friend bool operator==(const AlpacaAccount&, const AlpacaAccount&) {
54 return true;
55 }
56};
57
61 std::string account_number_;
62};
63
67 std::string order_id_;
69 std::optional<std::string> client_order_id_;
71 std::chrono::system_clock::time_point received_at_;
72};
73
77 std::string order_id_;
78};
79
83 std::vector<OrderSnapshot> orders_;
85 std::chrono::system_clock::time_point received_at_;
86};
87
88namespace detail {
89
91inline constexpr std::size_t client_order_id_limit = 128;
92
94inline constexpr int bar_count_limit = 9999;
95
97inline constexpr int calendar_days_back = 10;
98
100inline constexpr int calendar_span_days = 40;
101
107inline std::int64_t days_from_civil(const Date& date) {
108 std::int64_t year = date.year_;
109 const unsigned month = date.month_;
110 year -= month <= 2 ? 1 : 0;
111 const std::int64_t era = (year >= 0 ? year : year - 399) / 400;
112 const auto year_of_era = static_cast<unsigned>(year - era * 400);
113 const unsigned day_of_year = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + date.day_ - 1;
114 const unsigned day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
115 return era * 146097 + static_cast<std::int64_t>(day_of_era) - 719468;
116}
117
123inline Date utc_date(std::chrono::system_clock::time_point instant) {
124 const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(instant.time_since_epoch()).count();
125 return date_from_epoch_days(seconds >= 0 ? seconds / 86400 : (seconds - 86399) / 86400);
126}
127
138inline std::chrono::hours eastern_offset(std::chrono::system_clock::time_point instant) {
139 const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(instant.time_since_epoch()).count();
140 const auto year = utc_date(instant - std::chrono::hours(5)).year_;
141 // The n-th Sunday of a month: 1970-01-01 was a Thursday (day 4 counting Sunday as 0).
142 const auto nth_sunday = [year](unsigned month, int nth) {
143 const auto first = days_from_civil(Date{year, month, 1});
144 const auto weekday = ((first % 7) + 7 + 4) % 7;
145 return first + (7 - weekday) % 7 + 7 * (nth - 1);
146 };
147 const auto starts = nth_sunday(3, 2) * 86400 + 2 * 3600 + 5 * 3600;
148 const auto ends = nth_sunday(11, 1) * 86400 + 2 * 3600 + 4 * 3600;
149 return seconds >= starts && seconds < ends ? std::chrono::hours(-4) : std::chrono::hours(-5);
150}
151
157inline std::chrono::system_clock::time_point eastern_midnight(const Date& date) {
158 const auto utc_midnight =
159 std::chrono::system_clock::time_point{} + std::chrono::seconds(days_from_civil(date) * 86400);
160 // Local midnight is 04:00Z or 05:00Z, before either change (07:00Z in March, 06:00Z in November), so the offset at
161 // 04:00Z of the date is the one at midnight, change days included.
162 return utc_midnight - eastern_offset(utc_midnight + std::chrono::hours(4));
163}
164
170inline std::string iso_date(const Date& date) {
171 char buffer[16];
172 std::snprintf(buffer, sizeof(buffer), "%04d-%02u-%02u", date.year_, date.month_, date.day_);
173 return buffer;
174}
175
181inline std::optional<Date> parse_date(std::string_view text) {
182 if (text.size() != 10 || text[4] != '-' || text[7] != '-') {
183 return std::nullopt;
184 }
185 const auto field = [text](std::size_t from, std::size_t count, int& out) {
186 const auto parsed = std::from_chars(text.data() + from, text.data() + from + count, out);
187 return parsed.ec == std::errc{} && parsed.ptr == text.data() + from + count;
188 };
189 int year = 0;
190 int month = 0;
191 int day = 0;
192 if (!field(0, 4, year) || !field(5, 2, month) || !field(8, 2, day) || month < 1 || day < 1) {
193 return std::nullopt;
194 }
195 const Date date{year, static_cast<unsigned>(month), static_cast<unsigned>(day)};
196 if (!is_valid_date(date)) {
197 return std::nullopt;
198 }
199 return date;
200}
201
213inline std::optional<Decimal64> number(const json::object& object, const char* key) {
214 const auto* value = object.if_contains(key);
215 if (value == nullptr || value->is_null()) {
216 return std::nullopt;
217 }
218 try {
219 if (value->is_string()) {
220 return Decimal64::parse(std::string_view(value->as_string()));
221 }
222 if (value->is_int64()) {
223 return Decimal64::parse(std::to_string(value->as_int64()));
224 }
225 if (value->is_uint64()) {
226 return Decimal64::parse(std::to_string(value->as_uint64()));
227 }
228 if (value->is_double()) {
229 // The fewest decimal places that give the same double back, found by exact division: no locale, and no
230 // floating-point `std::to_chars`, which older standard libraries and macOS targets lack.
231 const double number = value->as_double();
232 double power = 1;
233 for (std::uint8_t scale = 0; std::isfinite(number) && scale <= 15; ++scale, power *= 10) {
234 const double scaled = std::round(number * power);
235 if (std::fabs(scaled) < 9007199254740992.0) {
236 const auto coefficient = static_cast<std::int64_t>(scaled);
237 if (static_cast<double>(coefficient) / power == number) {
238 return Decimal64(coefficient, scale);
239 }
240 }
241 }
242 }
243 } catch (const std::exception&) {
244 }
245 throw std::runtime_error(std::string("a field is not a number: ") + key);
246}
247
255inline Decimal64 required(const json::object& object, const char* key) {
256 auto value = number(object, key);
257 if (!value) {
258 throw std::runtime_error(std::string("a field is missing: ") + key);
259 }
260 return *value;
261}
262
269inline std::string text(const json::object& object, const char* key) {
270 const auto* value = object.if_contains(key);
271 return value != nullptr && value->is_string() ? std::string(value->as_string()) : std::string();
272}
273
281inline std::optional<std::chrono::system_clock::time_point> instant(const json::object& object, const char* key) {
282 const auto value = text(object, key);
283 if (value.empty()) {
284 return std::nullopt;
285 }
286 auto parsed = parse_iso8601_timestamp(value);
287 if (!parsed) {
288 throw std::runtime_error(std::string("a time cannot be read: ") + key);
289 }
290 return parsed;
291}
292
302inline OrderStatus order_status(std::string_view status) {
303 if (status == "new" || status == "accepted" || status == "pending_new" || status == "accepted_for_bidding") {
304 return OrderStatus::PENDING;
305 }
306 if (status == "partially_filled") {
307 return OrderStatus::PARTIAL_FILLED;
308 }
309 if (status == "filled") {
310 return OrderStatus::FILLED;
311 }
312 if (status == "canceled" || status == "expired") {
313 return OrderStatus::CANCELED;
314 }
315 if (status == "rejected") {
316 return OrderStatus::REJECTED;
317 }
318 if (status == "pending_cancel") {
319 return OrderStatus::PENDING_CANCEL;
320 }
321 if (status == "pending_replace") {
322 return OrderStatus::PENDING_REPLACE;
323 }
324 if (status == "replaced") {
325 return OrderStatus::REPLACED;
326 }
327 return OrderStatus::UNKNOWN;
328}
329
336inline BrokerError refusal(std::string code, std::string message) {
337 BrokerError error;
338 error.category_ = ErrorCategory::INVALID_ARGUMENT;
339 error.reached_broker_ = false;
340 error.broker_code_ = std::move(code);
341 error.message_ = std::move(message);
342 return error;
343}
344
350inline InstrumentId instrument_of(std::string symbol) {
351 return InstrumentId{Country::US, Venue::UNSPECIFIED, std::move(symbol)};
352}
353
360inline std::optional<BrokerError> unsupported_instrument(const InstrumentId& instrument) {
361 if (
362 instrument.country_ != Country::US || instrument.venue_ != Venue::UNSPECIFIED || instrument.symbol_.empty() ||
363 instrument.symbol_.size() > 16 ||
364 instrument.symbol_.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.") != std::string::npos
365 ) {
366 return refusal(
367 "instrument_unsupported",
368 "the Alpaca adapter takes US listings: Country::US, Venue::UNSPECIFIED and a symbol such as BRK.B"
369 );
370 }
371 return std::nullopt;
372}
373
384inline bool valid_order_id(std::string_view id) {
385 return !id.empty() && id.size() <= client_order_id_limit &&
386 id.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") == std::string_view::npos;
387}
388
393inline BrokerError invalid_order_id() {
394 return refusal("invalid_reference", "an Alpaca order id is 1 to 128 characters of letters, digits, - and _");
395}
396
403inline std::optional<BrokerError> validate_bar_query(const BarQuery& query) {
404 const auto interval = query.interval_;
405 if (
406 interval != BarInterval::ONE_MINUTE && interval != BarInterval::FIVE_MINUTES &&
408 interval != BarInterval::ONE_HOUR && interval != BarInterval::ONE_DAY
409 ) {
410 return refusal("unsupported_interval", "the Alpaca adapter serves 1m, 5m, 15m, 30m, 1h and 1d bars");
411 }
412 if (query.count_ <= 0 || query.count_ > bar_count_limit) {
413 return refusal("invalid_count", "ask Alpaca for 1 to 9999 bars per call");
414 }
415 return unsupported_instrument(query.instrument_);
416}
417
423inline bool positive(const Decimal64& value) {
424 return decimal_normalized(value).coefficient() > 0;
425}
426
439inline std::optional<BrokerError> validate_order(const OrderRequest& order) {
440 if (auto refused = unsupported_instrument(order.instrument_)) {
441 return refused;
442 }
443 if (order.venue_ != Venue::UNSPECIFIED) {
444 return refusal("venue_unsupported", "Alpaca routes orders itself; leave the venue unspecified");
445 }
446 if (
447 order.client_order_id_ &&
448 (order.client_order_id_->empty() || order.client_order_id_->size() > client_order_id_limit)
449 ) {
450 return refusal("invalid_client_order_id", "Alpaca takes a client_order_id of 1 to 128 characters");
451 }
452 if (order.time_in_force_ != TimeInForce::DAY) {
453 return refusal("time_in_force_unsupported", "the Alpaca adapter sends day orders only");
454 }
455 if (order.session_ != OrderSession::REGULAR) {
456 return refusal("session_unsupported", "the Alpaca adapter sends regular-session orders only, no extended hours");
457 }
458 if (order.trigger_price_) {
459 return refusal("order_type_unsupported", "the Alpaca adapter sends no stop orders, so no trigger price");
460 }
461 switch (order.type_) {
462 case OrderType::LIMIT: {
463 if (!order.price_ || !positive(*order.price_)) {
464 return refusal("invalid_price", "a limit order needs a positive price");
465 }
466 const auto on_grid = us::equity_price_rule().on_tick(*order.price_);
467 if (!on_grid || !*on_grid) {
468 return refusal("off_tick", "a US limit price has at most 2 decimals from $1 and 4 below (Rule 612)");
469 }
470 break;
471 }
473 if (order.price_) {
474 return refusal("invalid_price", "a market order carries no price");
475 }
476 break;
477 case OrderType::UNKNOWN:
484 return refusal("order_type_unsupported", "the Alpaca adapter sends limit and market orders only");
485 }
486 const auto quantity = decimal_normalized(order.quantity_);
487 if (quantity.coefficient() <= 0 || quantity.scale() != 0) {
488 return refusal("invalid_quantity", "the Alpaca adapter sends whole, positive share quantities only");
489 }
490 return std::nullopt;
491}
492
501inline bool listed_exchange(std::string_view exchange) {
502 return exchange == "AMEX" || exchange == "ARCA" || exchange == "BATS" || exchange == "NYSE" || exchange == "NASDAQ" ||
503 exchange == "NYSEARCA" || exchange == "TXSE";
504}
505
518inline std::optional<BrokerError> unlisted_asset(const json::object& asset, const std::string& symbol) {
519 const auto* tradable = asset.if_contains("tradable");
520 const auto asset_class = text(asset, "class");
521 const auto status = text(asset, "status");
522 const auto exchange = text(asset, "exchange");
523 if (text(asset, "symbol") != symbol) {
524 auto error = refusal("instrument_mismatch", "Alpaca's asset reply names another symbol than " + symbol);
525 error.category_ = ErrorCategory::PROTOCOL;
526 return error;
527 }
528 if (tradable == nullptr || !tradable->is_bool() || asset_class.empty() || status.empty() || exchange.empty()) {
529 auto error =
530 refusal("instrument_unreadable", "Alpaca's asset reply for " + symbol + " leaves out a field it needs");
531 error.category_ = ErrorCategory::PROTOCOL;
532 return error;
533 }
534 if (asset_class != "us_equity" || !listed_exchange(exchange)) {
535 return refusal(
536 "instrument_not_listed",
537 symbol + " is a " + asset_class + " asset on " + exchange +
538 ": the Alpaca adapter trades US equities listed on a national exchange only, not OTC"
539 );
540 }
541 if (status != "active" || !tradable->as_bool()) {
542 return refusal("instrument_not_tradable", symbol + " is not active and tradable at Alpaca");
543 }
544 return std::nullopt;
545}
546
547} // namespace detail
548
567public:
576 ssl::context& context, AlpacaConfig config, network::HttpClientOptions options = {},
577 std::shared_ptr<network::TokenStore> store = nullptr
578 )
579 : config_(std::move(config)) {
580 static_cast<void>(store);
581 if (!options.rate_limit_) {
582 options.rate_limit_ = default_rate_limit();
583 }
584 trading_ = std::make_shared<network::AsyncHttpClient>(
585 ioc_.get_executor(), context, config_.trading_host(), config_.port(), options
586 );
587 data_ = std::make_shared<network::AsyncHttpClient>(
588 ioc_.get_executor(), context, config_.data_host(), config_.port(), options
589 );
590 }
591
597 return network::RateLimitBudget{2, 1, 1};
598 }
599
604 const AlpacaConfig& config() const noexcept {
605 return config_;
606 }
607
613 const auto* limiter = trading_->rate_limits();
614 return limiter ? &limiter->stats() : nullptr;
615 }
616
622 return attempt<std::vector<AlpacaAccountInfo>>([&] {
623 const auto reply = get_object(*trading_, "/v2/account", network::RateLimitGroup::ACCOUNT);
624 if (detail::text(reply, "currency") != "USD") {
625 throw std::runtime_error("the account is not in USD");
626 }
627 AlpacaAccountInfo account;
628 account.account_number_ = detail::text(reply, "account_number");
629 if (account.account_number_.empty()) {
630 throw std::runtime_error("the account has no account_number");
631 }
632 return std::vector<AlpacaAccountInfo>{std::move(account)};
633 });
634 }
635
642 if (auto refused = detail::unsupported_instrument(instrument)) {
643 return Result<QuoteSnapshot>(std::move(*refused));
644 }
645 return attempt<QuoteSnapshot>([&] {
646 const auto reply = get_object(
647 *data_, "/v2/stocks/" + broker_detail::query_encode(instrument.symbol_) + "/trades/latest?feed=iex",
649 );
650 const auto* row = reply.if_contains("trade");
651 if (row == nullptr || !row->is_object()) {
652 throw std::runtime_error("the latest trade has no trade");
653 }
655 quote.instrument_ = std::move(instrument);
656 quote.currency_ = Currency::usd();
657 quote.last_price_ = detail::required(row->as_object(), "p");
658 quote.exchange_time_ = detail::instant(row->as_object(), "t");
659 quote.received_at_ = clock_();
660 return quote;
661 });
662 }
663
676 if (auto refused = detail::validate_bar_query(query)) {
677 return Result<BarSeries>(std::move(*refused));
678 }
679 return attempt<BarSeries>([&] {
680 const auto now = clock_();
681 const auto end = query.before_ ? *query.before_ : now;
682 const auto length =
683 query.interval_ == BarInterval::ONE_DAY ? std::chrono::hours(24) : *bar_interval_length(query.interval_);
684 const auto reply = get_object(
685 *data_,
686 "/v2/stocks/" + broker_detail::query_encode(query.instrument_.symbol_) + "/bars?timeframe=" +
687 timeframe(query.interval_) + "&feed=iex&adjustment=" + (query.adjusted_ ? "all" : "raw") +
688 "&sort=desc&start=2015-01-01T00:00:00Z&end=" + format_iso8601_utc(end + std::chrono::seconds(1)) +
689 "&limit=" + std::to_string(query.count_ + 1),
691 );
692 BarSeries series;
693 series.instrument_ = query.instrument_;
694 series.interval_ = query.interval_;
695 series.stamp_ = BarStamp::OPEN;
696 series.currency_ = Currency::usd();
697 series.adjusted_ = query.adjusted_;
698 const auto* rows = reply.if_contains("bars");
699 if (rows != nullptr && !rows->is_null() && !rows->is_array()) {
700 throw std::runtime_error("the bars are not a list");
701 }
702 if (rows != nullptr && rows->is_array()) {
703 for (const auto& value : rows->as_array()) {
704 if (static_cast<int>(series.bars_.size()) == query.count_) {
705 break;
706 }
707 if (!value.is_object()) {
708 throw std::runtime_error("a bar is not an object");
709 }
710 const auto& row = value.as_object();
711 const auto stamp = detail::instant(row, "t");
712 if (!stamp) {
713 throw std::runtime_error("a bar has no time");
714 }
715 // A daily bar ends 24 hours after its New York midnight: New York's clock changes on a Sunday.
716 if (*stamp + length > now || end < *stamp) {
717 continue;
718 }
719 Bar bar;
720 bar.timestamp_ = *stamp;
721 bar.open_ = detail::number(row, "o");
722 bar.high_ = detail::required(row, "h");
723 bar.low_ = detail::required(row, "l");
724 bar.close_ = detail::required(row, "c");
725 bar.volume_ = detail::required(row, "v");
726 series.bars_.push_back(std::move(bar));
727 }
728 }
729 std::reverse(series.bars_.begin(), series.bars_.end());
730 if (!series.ascending()) {
731 throw std::runtime_error("the bars are out of order or repeated");
732 }
733 series.received_at_ = clock_();
734 return series;
735 });
736 }
737
750 static_cast<void>(account);
751 return attempt<HoldingsSnapshot>(
752 [&] {
753 const auto reply = get_json(*trading_, "/v2/positions", network::RateLimitGroup::ACCOUNT);
754 if (!reply.is_array()) {
755 throw std::runtime_error("the positions are not a list");
756 }
757 std::set<std::string> seen;
758 for (const auto& value : reply.as_array()) {
759 const auto* row = value.if_object();
760 const auto symbol = row ? detail::text(*row, "symbol") : std::string();
761 if (symbol.empty() || detail::text(*row, "asset_class").empty()) {
762 throw std::runtime_error("a position names no symbol or asset class");
763 }
764 if (!seen.insert(symbol).second) {
765 throw std::runtime_error("the positions list " + symbol + " twice");
766 }
767 }
768 HoldingsSnapshot snapshot;
769 for (const auto& value : reply.as_array()) {
770 const auto& row = value.as_object();
771 if (detail::text(row, "asset_class") != "us_equity") {
772 // Crypto and options: never an instrument this adapter sends.
773 continue;
774 }
775 if (detail::text(row, "side") != "long") {
776 throw std::runtime_error("a US equity position is not long: " + detail::text(row, "symbol"));
777 }
778 HoldingPosition position;
779 position.instrument_ = detail::instrument_of(detail::text(row, "symbol"));
780 position.quantity_ = detail::required(row, "qty");
781 position.sellable_quantity_ = detail::number(row, "qty_available");
782 position.average_purchase_price_ = detail::required(row, "avg_entry_price");
783 position.last_price_ = detail::required(row, "current_price");
784 position.purchase_value_ = Money{detail::required(row, "cost_basis"), Currency::usd()};
785 position.market_value_ = Money{detail::required(row, "market_value"), Currency::usd()};
786 position.unrealized_profit_loss_ = Money{detail::required(row, "unrealized_pl"), Currency::usd()};
787 position.unrealized_return_ = detail::required(row, "unrealized_plpc");
788 snapshot.positions_.push_back(std::move(position));
789 }
790 // **What `qty_available` is evidence of: a treatment, not a measurement**, as KIS states its `ord_psbl_qty`.
791 // Alpaca documents it as the shares "available minus open orders", one row per symbol (the duplicate check
792 // above enforces that). `DEDUCT` is safe whatever Alpaca does: deducting resting sells Alpaca had already
793 // deducted over-refuses a second sell while one rests, where the other error sells the same shares twice.
794 // Observed once on the paper account (2026-11-20): a resting sell lowered `qty_available` by its quantity, and
795 // its cancellation restored it. `verified_` stays false: one observation, and nothing in the library sets it.
796 snapshot.sellable_basis_ =
798 snapshot.received_at_ = clock_();
799 return snapshot;
800 },
801 "invalid_holdings_response"
802 );
803 }
804
816 if (auto refused = detail::unsupported_instrument(instrument)) {
817 return Result<Instrument>(std::move(*refused));
818 }
819 return attempt<Instrument>([&] {
820 const auto reply = get_object(
821 *trading_, "/v2/assets/" + broker_detail::query_encode(instrument.symbol_), network::RateLimitGroup::REFERENCE
822 );
823 if (auto refused = detail::unlisted_asset(reply, instrument.symbol_)) {
824 throw Failure{std::move(*refused)};
825 }
826 Instrument out;
827 out.id_ = detail::instrument_of(instrument.symbol_);
828 out.name_ = detail::text(reply, "name");
829 out.english_name_ = out.name_;
830 out.segment_ = market_segment(detail::text(reply, "exchange"));
831 out.status_ = InstrumentStatus::ACTIVE;
832 out.currency_ = Currency::usd();
833 out.lot_size_ = Decimal64::parse("1");
835 return out;
836 });
837 }
838
852 Result<TradingCalendar> calendar(Country country, std::optional<Date> from = std::nullopt) {
853 if (country != Country::US) {
854 return Result<TradingCalendar>(detail::refusal("market_unsupported", "Alpaca's calendar is the US market's"));
855 }
856 if (from && !is_valid_date(*from)) {
857 return Result<TradingCalendar>(detail::refusal("invalid_date", "the calendar needs a valid date"));
858 }
859 return attempt<TradingCalendar>(
860 [&] {
861 const auto first_day = from ?
862 detail::days_from_civil(*from) :
863 detail::days_from_civil(detail::utc_date(clock_())) - detail::calendar_days_back;
864 const auto last_day = first_day + detail::calendar_span_days;
865 const auto reply = get_object(
866 *trading_,
867 "/v3/calendar/XNYS?start=" + detail::iso_date(date_from_epoch_days(first_day)) +
868 "&end=" + detail::iso_date(date_from_epoch_days(last_day)) + "&timezone=UTC",
870 );
871 const auto* rows = reply.if_contains("calendar");
872 if (rows == nullptr || !rows->is_array()) {
873 throw std::runtime_error("the calendar has no list of days");
874 }
876 calendar.country_ = Country::US;
877 std::vector<std::optional<TradingDay>> listed(static_cast<std::size_t>(last_day - first_day + 1));
878 for (const auto& value : rows->as_array()) {
879 const auto* row = value.if_object();
880 const auto date = row ? detail::parse_date(detail::text(*row, "date")) : std::nullopt;
881 if (!date) {
883 continue;
884 }
885 const auto day = detail::days_from_civil(*date);
886 if (day < first_day || day > last_day) {
887 throw Failure{calendar_error("calendar_out_of_range", "the calendar lists a date outside the range asked")};
888 }
889 auto& slot = listed[static_cast<std::size_t>(day - first_day)];
890 if (slot) {
891 throw Failure{
892 calendar_error("calendar_duplicate_date", "the calendar lists " + detail::iso_date(*date) + " twice")
893 };
894 }
895 slot = TradingDay{*date, true};
896 slot->regular_ = session(*row, "core_start", "core_end");
897 if (slot->regular_) {
898 const auto span = session(*row, "pre_start", "post_end");
899 if (
900 span && span->opens_at_ <= slot->regular_->opens_at_ && slot->regular_->closes_at_ <= span->closes_at_
901 ) {
902 slot->extended_ = span;
903 }
904 }
905 }
906 for (auto day = first_day; day <= last_day; ++day) {
907 const auto& slot = listed[static_cast<std::size_t>(day - first_day)];
908 calendar.days_.push_back(slot ? *slot : TradingDay{date_from_epoch_days(day), false});
909 }
910 calendar.received_at_ = clock_();
911 return calendar;
912 },
913 "invalid_calendar_response"
914 );
915 }
916
936 static_cast<void>(account);
937 if (auto refused = detail::validate_order(order)) {
938 return Result<AlpacaOrderAck>(std::move(*refused));
939 }
940 if (auto refused = refuse_before_order(order)) {
941 return Result<AlpacaOrderAck>(std::move(*refused));
942 }
943 json::object body;
944 body["symbol"] = order.instrument_.symbol_;
945 body["qty"] = decimal_normalized(order.quantity_).str();
946 body["side"] = order.side_ == OrderSide::BUY ? "buy" : "sell";
947 body["type"] = order.type_ == OrderType::LIMIT ? "limit" : "market";
948 body["time_in_force"] = "day";
949 if (order.type_ == OrderType::LIMIT) {
950 body["limit_price"] = decimal_normalized(*order.price_).str();
951 }
952 if (order.client_order_id_) {
953 body["client_order_id"] = *order.client_order_id_;
954 }
955 return send_order(http::verb::post, "/v2/orders", json::serialize(body), Call::PLACE, std::string());
956 }
957
966 static_cast<void>(account);
967 if (!detail::valid_order_id(amendment.order_id_)) {
968 return Result<AlpacaOrderAck>(detail::invalid_order_id());
969 }
970 return send_order(
971 http::verb::delete_, "/v2/orders/" + broker_detail::query_encode(amendment.order_id_), std::string(),
972 Call::CANCEL, amendment.order_id_
973 );
974 }
975
986 static_cast<void>(account);
987 return attempt<AlpacaOpenOrders>(
988 [&] {
989 const auto reply =
990 get_json(*trading_, "/v2/orders?status=open&limit=500&direction=asc", network::RateLimitGroup::ACCOUNT);
991 if (!reply.is_array()) {
992 throw std::runtime_error("the orders are not a list");
993 }
994 if (reply.as_array().size() >= 500) {
995 throw std::runtime_error("Alpaca listed 500 open orders: the listing may be cut");
996 }
997 AlpacaOpenOrders open;
998 open.orders_ = orders_of(reply.as_array());
999 open.received_at_ = clock_();
1000 return open;
1001 },
1002 "invalid_orders_response"
1003 );
1004 }
1005
1012 Result<OrderSnapshot> order_by_id(AlpacaAccount account, const std::string& id) {
1013 static_cast<void>(account);
1014 if (!detail::valid_order_id(id)) {
1015 return Result<OrderSnapshot>(detail::invalid_order_id());
1016 }
1017 return attempt<OrderSnapshot>(
1018 [&] {
1019 const auto row =
1020 get_object(*trading_, "/v2/orders/" + broker_detail::query_encode(id), network::RateLimitGroup::ACCOUNT);
1021 if (detail::text(row, "asset_class") != "us_equity") {
1022 throw std::runtime_error("the order is not a US equity order");
1023 }
1024 return order_of(row);
1025 },
1026 "invalid_order_response"
1027 );
1028 }
1029
1042 static_cast<void>(account);
1043 return attempt<OrderPage>(
1044 [&] {
1045 const int limit = query.limit_ ? *query.limit_ : 500;
1046 std::string target = "/v2/orders?status=all&direction=desc&limit=" + std::to_string(limit);
1047 if (query.symbol_) {
1048 target += "&symbols=" + broker_detail::query_encode(*query.symbol_);
1049 }
1050 if (query.from_) {
1051 target += "&after=" + format_iso8601_utc(detail::eastern_midnight(*query.from_) - std::chrono::seconds(1));
1052 }
1053 if (query.cursor_) {
1054 target += "&until=" + broker_detail::query_encode(*query.cursor_);
1055 } else if (query.to_) {
1056 target += "&until=" + format_iso8601_utc(detail::eastern_midnight(*query.to_) + std::chrono::hours(24));
1057 }
1058 const auto reply = get_json(*trading_, target, network::RateLimitGroup::ACCOUNT);
1059 if (!reply.is_array()) {
1060 throw std::runtime_error("the orders are not a list");
1061 }
1062 OrderPage page;
1063 page.orders_ = orders_of(reply.as_array());
1064 if (limit > 0 && static_cast<int>(reply.as_array().size()) == limit) {
1065 const auto& last = reply.as_array().back().as_object();
1066 const auto submitted = detail::text(last, "submitted_at");
1067 if (submitted.empty()) {
1068 throw std::runtime_error("an order has no submission time: the next page cannot be asked");
1069 }
1070 page.next_cursor_ = submitted;
1071 }
1072 page.received_at_ = clock_();
1073 return page;
1074 },
1075 "invalid_orders_response"
1076 );
1077 }
1078
1079private:
1080 friend struct AlpacaClientTestAccess;
1081
1083 struct Failure {
1085 BrokerError error_;
1086 };
1087
1089 enum class Call {
1091 READ,
1093 PLACE,
1095 CANCEL,
1096 };
1097
1098 // Alpaca's timeframe for an interval `validate_bar_query` admits.
1099 static std::string timeframe(BarInterval interval) {
1100 switch (interval) {
1101 case BarInterval::ONE_MINUTE:
1102 return "1Min";
1104 return "5Min";
1106 return "15Min";
1108 return "30Min";
1110 return "1Hour";
1111 case BarInterval::ONE_DAY:
1112 case BarInterval::ONE_WEEK:
1113 case BarInterval::ONE_MONTH:
1114 case BarInterval::ONE_YEAR:
1115 break;
1116 }
1117 return "1Day";
1118 }
1119
1120 // A calendar reply that cannot be a calendar.
1121 static BrokerError calendar_error(std::string code, std::string message) {
1122 BrokerError error;
1124 error.broker_code_ = std::move(code);
1125 error.message_ = "Alpaca: " + std::move(message);
1126 return error;
1127 }
1128
1129 // A session's bounds from two RFC 3339 members, or none when either is missing or unreadable or they are not in
1130 // order.
1131 static std::optional<SessionHours> session(const json::object& row, const char* opens, const char* closes) {
1132 const auto start = parse_iso8601_timestamp(detail::text(row, opens));
1133 const auto end = parse_iso8601_timestamp(detail::text(row, closes));
1134 if (!start || !end || !(*start < *end)) {
1135 return std::nullopt;
1136 }
1137 return SessionHours{*start, *end};
1138 }
1139
1140 // The reads made before an order is sent: the asset, the position for a sell, and the clock last.
1141 std::optional<BrokerError> refuse_before_order(const OrderRequest& order) {
1142 const auto& symbol = order.instrument_.symbol_;
1143 const auto unsent = [](BrokerError error, const char* what) {
1144 error.reached_broker_ = false;
1145 error.message_ = std::string(what) + " could not be read before the order, so it was not sent: " + error.message_;
1146 return error;
1147 };
1148 auto asset = send(
1149 *trading_, http::verb::get, "/v2/assets/" + broker_detail::query_encode(symbol), {},
1151 );
1152 if (asset && asset.value().result_int() == 404) {
1153 return detail::refusal("instrument_not_listed", "Alpaca lists no asset " + symbol);
1154 }
1155 auto asset_reply = read_object(std::move(asset));
1156 if (!asset_reply) {
1157 return unsent(std::move(asset_reply.error()), "the asset");
1158 }
1159 if (auto refused = detail::unlisted_asset(asset_reply.value(), symbol)) {
1160 return refused;
1161 }
1162 if (order.side_ == OrderSide::SELL) {
1163 auto position = send(
1164 *trading_, http::verb::get, "/v2/positions/" + broker_detail::query_encode(symbol), {},
1166 );
1167 if (position && position.value().result_int() == 404) {
1168 return detail::refusal("no_position", "no position in " + symbol + ": a sell would open a short");
1169 }
1170 auto position_reply = read_object(std::move(position));
1171 if (!position_reply) {
1172 return unsent(std::move(position_reply.error()), "the position");
1173 }
1174 try {
1175 const auto& row = position_reply.value();
1176 if (detail::text(row, "symbol") != symbol || detail::text(row, "asset_class") != "us_equity") {
1177 BrokerError error;
1178 error.category_ = ErrorCategory::PROTOCOL;
1179 error.broker_code_ = "position_mismatch";
1180 error.message_ = "Alpaca's position reply is not the US equity position in " + symbol;
1181 return unsent(std::move(error), "the position");
1182 }
1183 const auto available = detail::number(row, "qty_available");
1184 const auto held = detail::required(row, "qty");
1185 if (
1186 detail::text(row, "side") != "long" || !available || !detail::positive(held) ||
1187 decimal_less(*available, order.quantity_) || decimal_less(held, order.quantity_)
1188 ) {
1189 return detail::refusal(
1190 "sell_exceeds_position", "the sell exceeds the position available in " + symbol + ": it would open a short"
1191 );
1192 }
1193 } catch (const std::exception& exception) {
1194 BrokerError error;
1195 error.category_ = ErrorCategory::PROTOCOL;
1196 error.broker_code_ = "invalid_position_response";
1197 error.message_ = exception.what();
1198 return unsent(std::move(error), "the position");
1199 }
1200 }
1201 return refuse_unless_core();
1202 }
1203
1204 // Reads Alpaca's clock for the New York Stock Exchange and refuses unless its phase is `core`.
1205 std::optional<BrokerError> refuse_unless_core() {
1206 auto reply =
1207 read_object(send(*trading_, http::verb::get, "/v3/clock?markets=XNYS", {}, network::RateLimitGroup::ACCOUNT));
1208 BrokerError error;
1209 error.reached_broker_ = false;
1210 if (!reply) {
1211 error = std::move(reply.error());
1212 error.reached_broker_ = false;
1213 error.message_ = "Alpaca's clock could not be read before the order, so it was not sent: " + error.message_;
1214 return error;
1215 }
1216 const json::object* clock = nullptr;
1217 int matches = 0;
1218 if (const auto* clocks = reply.value().if_contains("clocks"); clocks != nullptr && clocks->is_array()) {
1219 for (const auto& value : clocks->as_array()) {
1220 const auto* entry = value.if_object();
1221 const auto* market = entry ? entry->if_contains("market") : nullptr;
1222 if (market != nullptr && market->is_object() && detail::text(market->as_object(), "mic") == "XNYS") {
1223 clock = entry;
1224 ++matches;
1225 }
1226 }
1227 }
1228 const auto phase = clock ? detail::text(*clock, "phase") : std::string();
1229 if (matches != 1 || phase.empty()) {
1230 error.category_ = ErrorCategory::PROTOCOL;
1231 error.broker_code_ = "clock_unreadable";
1232 error.message_ = "Alpaca's clock did not give one phase for XNYS, so the order was not sent";
1233 return error;
1234 }
1235 if (phase != "core") {
1236 // Kept by a runner (a category it retries when nothing was sent), so a flatten refused here is offered again.
1237 error.category_ = ErrorCategory::CANCELLED;
1238 error.broker_code_ = "market_closed";
1239 error.message_ = "Alpaca's clock says the regular session is not on (phase " + phase + " until " +
1240 detail::text(*clock, "phase_until") +
1241 "): the order was not sent, since Alpaca would queue it for the next session";
1242 return error;
1243 }
1244 return std::nullopt;
1245 }
1246
1247 // Sends an order call; never sent again. A seen refusal is `INVALID_ARGUMENT`; anything else unknown.
1248 Result<AlpacaOrderAck> send_order(
1249 http::verb method, const std::string& target, std::string body, Call call, const std::string& asked_id
1250 ) {
1251 auto reply = send(*trading_, method, target, std::move(body), network::RateLimitGroup::TRADING);
1252 if (!reply) {
1253 return Result<AlpacaOrderAck>(std::move(reply.error()));
1254 }
1255 const auto& response = reply.value();
1256 const auto status = response.result_int();
1257 AlpacaOrderAck ack;
1258 ack.received_at_ = clock_();
1259 if (call == Call::CANCEL && status >= 200 && status < 300) {
1260 ack.order_id_ = asked_id;
1261 return Result<AlpacaOrderAck>(std::move(ack));
1262 }
1263 if (status < 200 || status >= 300) {
1264 return Result<AlpacaOrderAck>(reply_error(response, call));
1265 }
1266 BrokerError error;
1267 auto row = broker_detail::parse_object(response, error);
1268 if (!row) {
1269 return Result<AlpacaOrderAck>(std::move(error));
1270 }
1271 ack.order_id_ = detail::text(*row, "id");
1272 if (ack.order_id_.empty()) {
1273 error.category_ = ErrorCategory::PROTOCOL;
1274 error.http_status_ = static_cast<int>(status);
1275 error.broker_code_ = "missing_order_id";
1276 error.message_ = "Alpaca accepted an order and gave no id";
1277 return Result<AlpacaOrderAck>(std::move(error));
1278 }
1279 if (auto key = detail::text(*row, "client_order_id"); !key.empty()) {
1280 ack.client_order_id_ = std::move(key);
1281 }
1282 return Result<AlpacaOrderAck>(std::move(ack));
1283 }
1284
1285 // The error a reply with a failure status carries.
1286 BrokerError reply_error(const network::HttpResponse& response, Call call) const {
1287 BrokerError error;
1288 const auto status = static_cast<int>(response.result_int());
1289 error.http_status_ = status;
1290 boost::system::error_code ec;
1291 const auto value = json::parse(response.body(), ec);
1292 const auto* object = ec ? nullptr : value.if_object();
1293 if (object != nullptr) {
1294 error.message_ = "Alpaca: " + detail::text(*object, "message");
1295 // Read without a throwing conversion: a code that is not a whole number is left out.
1296 if (const auto* code = object->if_contains("code"); code != nullptr && code->is_int64()) {
1297 error.broker_code_ = std::to_string(code->as_int64());
1298 } else if (code != nullptr && code->is_uint64()) {
1299 error.broker_code_ = std::to_string(code->as_uint64());
1300 }
1301 } else {
1302 error.message_ = "Alpaca answered HTTP " + std::to_string(status) + " with a body that is not JSON";
1303 }
1304 if (status == 401) {
1305 // The gateway's refusal of the keys, before any route (seen on every host).
1306 error.category_ = ErrorCategory::AUTHENTICATION;
1307 } else if (status == 429 && call == Call::READ) {
1308 error.category_ = ErrorCategory::RATE_LIMIT;
1309 if (const auto reset = broker_detail::integer_header(response, "X-RateLimit-Reset")) {
1310 const auto now = std::chrono::duration_cast<std::chrono::seconds>(clock_().time_since_epoch()).count();
1311 error.retry_after_ = std::chrono::seconds(std::max<std::int64_t>(1, *reset - now));
1312 }
1313 } else if (call == Call::READ || status >= 500) {
1314 error.category_ = ErrorCategory::HTTP;
1315 } else if (
1316 (call == Call::PLACE &&
1317 ((status == 422 && error.broker_code_ == "42210000") || (status == 403 && error.broker_code_ == "40310000"))) ||
1318 (call == Call::CANCEL && status == 422 && error.broker_code_ == "42210000")
1319 ) {
1320 // Refusals seen on the paper host: the order was not placed, or not cancelled.
1321 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1322 } else {
1323 // A code not seen on an order call says nothing of the order (40010001 is also a duplicate client_order_id,
1324 // which says the order exists): read it back.
1325 error.category_ = ErrorCategory::PROTOCOL;
1326 }
1327 return error;
1328 }
1329
1330 // Runs a reader; any failure is the library's error.
1331 template <typename T, typename Make>
1332 Result<T> attempt(Make make, const char* code = "invalid_response") {
1333 try {
1334 return Result<T>(make());
1335 } catch (const Failure& failure) {
1336 return Result<T>(failure.error_);
1337 } catch (const std::exception& exception) {
1338 BrokerError error;
1339 error.category_ = ErrorCategory::PROTOCOL;
1340 error.broker_code_ = code;
1341 error.message_ = std::string("Alpaca: ") + exception.what();
1342 return Result<T>(std::move(error));
1343 }
1344 }
1345
1346 // A successful reply's body as JSON, or the error a failed one carries.
1347 Result<json::value> read_json(Result<network::HttpResponse> reply) const {
1348 if (!reply) {
1349 return Result<json::value>(std::move(reply.error()));
1350 }
1351 const auto& response = reply.value();
1352 if (response.result_int() < 200 || response.result_int() >= 300) {
1353 return Result<json::value>(reply_error(response, Call::READ));
1354 }
1355 boost::system::error_code ec;
1356 auto value = json::parse(response.body(), ec);
1357 if (ec) {
1358 BrokerError error;
1359 error.category_ = ErrorCategory::PROTOCOL;
1360 error.http_status_ = static_cast<int>(response.result_int());
1361 error.broker_code_ = "invalid_json";
1362 error.message_ = "Alpaca's reply is not JSON";
1363 return Result<json::value>(std::move(error));
1364 }
1365 return Result<json::value>(std::move(value));
1366 }
1367
1368 // A successful reply's body as a JSON object, or the error.
1369 Result<json::object> read_object(Result<network::HttpResponse> reply) const {
1370 auto value = read_json(std::move(reply));
1371 if (!value) {
1372 return Result<json::object>(std::move(value.error()));
1373 }
1374 if (!value.value().is_object()) {
1375 BrokerError error;
1376 error.category_ = ErrorCategory::PROTOCOL;
1377 error.broker_code_ = "invalid_json";
1378 error.message_ = "Alpaca's reply is not a JSON object";
1379 return Result<json::object>(std::move(error));
1380 }
1381 return Result<json::object>(std::move(value.value().as_object()));
1382 }
1383
1384 // GETs JSON, throwing the failure.
1385 json::value get_json(network::AsyncHttpClient& http, const std::string& target, network::RateLimitGroup group) {
1386 auto value = read_json(send(http, http::verb::get, target, {}, group));
1387 if (!value) {
1388 throw Failure{std::move(value.error())};
1389 }
1390 return std::move(value.value());
1391 }
1392
1393 // GETs a JSON object, throwing the failure.
1394 json::object get_object(network::AsyncHttpClient& http, const std::string& target, network::RateLimitGroup group) {
1395 auto value = read_object(send(http, http::verb::get, target, {}, group));
1396 if (!value) {
1397 throw Failure{std::move(value.error())};
1398 }
1399 return std::move(value.value());
1400 }
1401
1402 // The request with both keys; every request is built here.
1403 network::HttpRequest make_request(
1404 http::verb method, std::string target, std::string body, network::RateLimitGroup group
1405 ) const {
1406 network::HttpRequest request;
1407 request.method_ = method;
1408 request.target_ = std::move(target);
1409 request.headers_ = {{"APCA-API-KEY-ID", config_.key()}, {"APCA-API-SECRET-KEY", config_.secret()}};
1410 if (!body.empty()) {
1411 request.headers_.emplace_back("Content-Type", "application/json");
1412 }
1413 request.body_ = std::move(body);
1414 request.group_ = group;
1415 return request;
1416 }
1417
1418 // Sends one request and runs the private loop until it completes.
1419 Result<network::HttpResponse> send(
1420 network::AsyncHttpClient& http, http::verb method, std::string target, std::string body,
1422 ) {
1423 std::optional<Result<network::HttpResponse>> result;
1424 ioc_.restart();
1425 http.async_request(
1426 make_request(method, std::move(target), std::move(body), group), [&result](Result<network::HttpResponse> value) {
1427 result.emplace(std::move(value));
1428 }
1429 );
1430 ioc_.run();
1431 if (!result) {
1432 BrokerError error;
1433 error.category_ = ErrorCategory::TRANSPORT;
1434 error.broker_code_ = "event_loop_stopped";
1435 error.message_ = "the event loop stopped before the request completed";
1436 return Result<network::HttpResponse>(std::move(error));
1437 }
1438 return std::move(*result);
1439 }
1440
1441 // The US equity orders among rows, after checking that no id appears twice among all of them.
1442 static std::vector<OrderSnapshot> orders_of(const json::array& rows) {
1443 std::set<std::string> seen;
1444 for (const auto& value : rows) {
1445 const auto* row = value.if_object();
1446 const auto id = row ? detail::text(*row, "id") : std::string();
1447 // A multi-leg option order (`order_class` mleg) states no asset class; it is skipped below with the others.
1448 if (id.empty() || (detail::text(*row, "asset_class").empty() && detail::text(*row, "order_class") != "mleg")) {
1449 throw std::runtime_error("an order has no id or asset class");
1450 }
1451 if (!seen.insert(id).second) {
1452 throw std::runtime_error("the orders list " + id + " twice");
1453 }
1454 }
1455 std::vector<OrderSnapshot> orders;
1456 for (const auto& value : rows) {
1457 const auto& row = value.as_object();
1458 if (detail::text(row, "asset_class") != "us_equity") {
1459 // Crypto and options: never an order this adapter sends.
1460 continue;
1461 }
1462 orders.push_back(order_of(row));
1463 }
1464 return orders;
1465 }
1466
1467 // One order from Alpaca's order object.
1468 static OrderSnapshot order_of(const json::object& row) {
1469 OrderSnapshot order;
1470 order.order_id_ = detail::text(row, "id");
1471 if (order.order_id_.empty()) {
1472 throw std::runtime_error("an order has no id");
1473 }
1474 order.instrument_ = detail::instrument_of(detail::text(row, "symbol"));
1475 const auto side = detail::text(row, "side");
1476 if (side != "buy" && side != "sell") {
1477 throw std::runtime_error("an order's side cannot be read");
1478 }
1479 order.side_ = side == "buy" ? OrderSide::BUY : OrderSide::SELL;
1480 const auto type = detail::text(row, "type");
1481 order.type_ = type == "limit" ?
1483 type == "market" ?
1485 type == "stop_limit" ?
1487 OrderType::UNKNOWN;
1488 const auto condition = detail::text(row, "time_in_force");
1489 order.time_in_force_ = condition == "day" ?
1491 condition == "ioc" ?
1493 condition == "fok" ?
1495 TimeInForce::UNKNOWN;
1496 const auto* extended = row.if_contains("extended_hours");
1497 order.session_ =
1498 extended != nullptr && extended->is_bool() && extended->as_bool() ? OrderSession::UNKNOWN : OrderSession::REGULAR;
1499 order.status_ = detail::order_status(detail::text(row, "status"));
1500 order.price_ = detail::number(row, "limit_price");
1501 order.trigger_price_ = detail::number(row, "stop_price");
1502 order.quantity_ = detail::required(row, "qty");
1503 order.currency_ = Currency::usd();
1504 order.ordered_at_ = detail::instant(row, "submitted_at");
1505 order.canceled_at_ = detail::instant(row, "canceled_at");
1506 order.execution_.filled_quantity_ = detail::required(row, "filled_qty");
1507 order.execution_.average_filled_price_ = detail::number(row, "filled_avg_price");
1508 order.execution_.filled_at_ = detail::instant(row, "filled_at");
1509 return order;
1510 }
1511
1512 AlpacaConfig config_;
1513 net::io_context ioc_;
1514 std::shared_ptr<network::AsyncHttpClient> trading_;
1515 std::shared_ptr<network::AsyncHttpClient> data_;
1516 std::function<std::chrono::system_clock::time_point()> clock_{[] {
1517 return std::chrono::system_clock::now();
1518 }};
1519};
1520
1521} // namespace algotradelib::alpaca
static Currency usd()
Returns United States dollars.
Definition types.hpp:410
std::int64_t coefficient() const noexcept
Returns the coefficient.
Definition types.hpp:541
std::string str() const
Formats the value as a decimal string.
Definition types.hpp:557
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
const network::RateLimitStats * rate_limit_stats() const
Returns the trading connection's rate-limit statistics; read them between calls.
Definition client.hpp:612
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.
Definition client.hpp:575
static network::RateLimitBudget default_rate_limit() noexcept
The pacing each connection gets when the caller sets none.
Definition client.hpp:596
Result< Instrument > instrument(InstrumentId instrument)
Returns one instrument's reference data (/v2/assets/{symbol}), with lot 1, dollars and us::equity_pri...
Definition client.hpp:815
Result< HoldingsSnapshot > holdings(AlpacaAccount account={})
Returns the US equity positions (/v2/positions), in dollars.
Definition client.hpp:749
Result< OrderPage > order_history(AlpacaAccount account, OrderHistoryQuery query)
Returns US equity orders submitted from from_ to to_ (New York dates), newest first,...
Definition client.hpp:1041
Result< BarSeries > bars(BarQuery query)
Returns closed bars, oldest first: the newest count_ (1 to 9,999) at or before before_ (or now),...
Definition client.hpp:675
Result< AlpacaOrderAck > cancel_order(AlpacaAccount account, AlpacaAmendment amendment)
Cancels a whole order (DELETE /v2/orders/{id}; 204, also for an order already cancelled)....
Definition client.hpp:965
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns the last trade on the IEX feed, in dollars.
Definition client.hpp:641
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,...
Definition client.hpp:852
Result< AlpacaOrderAck > place_order(AlpacaAccount account, OrderRequest order)
Places an order (POST /v2/orders). The outcome can be unknown after an error.
Definition client.hpp:935
Result< AlpacaOpenOrders > working_orders(AlpacaAccount account={})
Returns the open US equity orders (/v2/orders?status=open, up to 499).
Definition client.hpp:985
const AlpacaConfig & config() const noexcept
Returns the configuration.
Definition client.hpp:604
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.
Definition client.hpp:1012
Result< std::vector< AlpacaAccountInfo > > accounts()
Returns the one account the keys drive (/v2/account).
Definition client.hpp:621
The Alpaca Trading API and Market Data API client: exchange-listed US equities, paper by default.
Definition client.hpp:33
RateLimitGroup
The traffic class of a request, for rate limiting and queue priority. The broker adapter that builds ...
@ MARKET_DATA
Quotes, bars, order book and trades.
@ ACCOUNT
Holdings, working orders, order history and buying power.
@ TRADING
Order placement, amendment and cancellation. HttpClientOptions::fresh_connection_for_orders_ applies ...
@ REFERENCE
Instrument reference data and trading calendars.
http::response< http::string_body > HttpResponse
The HTTP response type the transport clients return.
void phase(S &strategy, Ctx &context, const MarketPhase &event)
Calls strategy.on_phase(context, event) if the strategy declares on_phase; otherwise does nothing.
Definition concept.hpp:395
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
Definition concept.hpp:240
PriceRule equity_price_rule()
Returns the US equity price grid: $0.01 at or above $1, $0.0001 below (Regulation NMS Rule 612).
Definition us.hpp:18
@ OPEN
The timestamp is the first instant of the period.
constexpr std::optional< std::chrono::seconds > bar_interval_length(BarInterval interval) noexcept
Returns an interval's fixed length, for an intraday interval.
MarketSegment market_segment(std::string_view code)
Maps a broker's segment code to a MarketSegment.
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
std::optional< std::chrono::system_clock::time_point > parse_iso8601_timestamp(std::string_view value)
Parses an ISO 8601 timestamp, YYYY-MM-DDTHH:MM:SS[.fraction] followed by Z or a +hh:mm/-hh:mm offset.
Definition types.hpp:2766
@ RATE_LIMIT
The broker refused the request for its rate limit.
Definition types.hpp:958
@ HTTP
The broker answered with an HTTP error status (http_status_).
Definition types.hpp:954
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
Definition types.hpp:965
@ CANCELLED
The operation was cancelled, such as by closing the client or a local deadline.
Definition types.hpp:950
@ AUTHENTICATION
The credentials or token were refused.
Definition types.hpp:956
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
Definition types.hpp:952
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
Definition types.hpp:2007
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
Definition types.hpp:2009
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
Definition types.hpp:2005
@ MID_PRICE
중간가: priced at the midpoint of the spread.
Definition types.hpp:2011
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
Definition types.hpp:2013
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
Definition types.hpp:2015
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
Country
A country (market) the library supports.
Definition types.hpp:32
Decimal64 decimal_normalized(const Decimal64 &value)
Removes trailing fractional zeros, so equal numbers compare equal with ==.
Definition types.hpp:600
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
Date date_from_epoch_days(std::int64_t days)
Converts a day count since 1970-01-01 to a Gregorian date.
Definition types.hpp:1456
BarInterval
The period one bar covers.
@ FIVE_MINUTES
Five minutes.
@ THIRTY_MINUTES
Thirty minutes.
@ FIFTEEN_MINUTES
Fifteen minutes.
bool is_valid_date(const Date &date)
Tests whether a date exists in the Gregorian calendar, in years 1 to 9999.
Definition types.hpp:1480
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
Definition types.hpp:2095
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
Definition types.hpp:2093
std::string format_iso8601_utc(std::chrono::system_clock::time_point value)
Formats an instant as an ISO 8601 timestamp in UTC, such as 2026-10-06T00:30:00Z.
Definition types.hpp:2741
What bars to fetch.
InstrumentId instrument_
The instrument.
BarInterval interval_
The period of each bar; an interval the broker does not publish is refused.
int count_
How many bars to return in total, across pages.
std::optional< std::chrono::system_clock::time_point > before_
The newest bar time to return, inclusive; pass the oldest timestamp seen to page backwards.
bool adjusted_
Whether to ask for prices adjusted for corporate actions.
The bars of one instrument and interval, oldest first.
bool ascending() const
Tests whether the bars are strictly ascending in time.
std::chrono::system_clock::time_point received_at_
When the series was received, on this machine's clock.
BarInterval interval_
The period each bar covers.
Currency currency_
The currency of the prices.
bool adjusted_
Whether the prices are adjusted for corporate actions.
BarStamp stamp_
Which edge of its period each bar's timestamp marks.
InstrumentId instrument_
The instrument.
std::vector< Bar > bars_
The bars, oldest first.
One bar: the prices and volume of one period, as exact decimals.
The error a broker or transport operation returns.
Definition types.hpp:1003
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
A calendar date with no time of day or time zone.
Definition types.hpp:1412
unsigned month_
The month, 1-12; zero means unset.
Definition types.hpp:1416
int year_
The year.
Definition types.hpp:1414
unsigned day_
The day of the month, 1-31; zero means unset.
Definition types.hpp:1418
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
std::string symbol_
The symbol as the venue spells it, such as "005930".
Definition types.hpp:95
Reference data for one instrument.
InstrumentStatus status_
Listed, awaiting listing, or delisted.
Currency currency_
The currency it trades in.
InstrumentId id_
The instrument.
PriceRule price_rule_
The price grid, set by the adapter or the caller; kind UNKNOWN where it has no table.
MarketSegment segment_
The market segment.
std::optional< Decimal64 > lot_size_
The order quantity increment, if the broker publishes one.
std::string english_name_
The English name, or empty.
std::string name_
The local-language name, as the broker spells it.
The filter for an order-history inquiry.
Definition types.hpp:2617
std::optional< std::string > symbol_
Only this symbol, where the broker supports the filter.
Definition types.hpp:2623
std::optional< int > limit_
The most rows to return, where the broker supports a limit.
Definition types.hpp:2627
std::optional< std::string > cursor_
A previous page's next_cursor_, passed back unchanged.
Definition types.hpp:2625
std::optional< Date > from_
The first date to include; required where BrokerCaps::history_requires_range.
Definition types.hpp:2619
std::optional< Date > to_
The last date to include.
Definition types.hpp:2621
One page of an order listing.
Definition types.hpp:2369
std::vector< OrderSnapshot > orders_
The rows, in the broker's order.
Definition types.hpp:2371
std::optional< std::string > next_cursor_
The cursor for the next page, to pass back unchanged; empty if there is none.
Definition types.hpp:2373
std::chrono::system_clock::time_point received_at_
When the page was received, on this machine's clock.
Definition types.hpp:2375
An order to place, in broker-neutral form.
Definition types.hpp:2216
std::optional< std::string > client_order_id_
An idempotency key, if the broker offers one; never generated by the library.
Definition types.hpp:2257
Decimal64 quantity_
The quantity, in the instrument's units (shares).
Definition types.hpp:2241
OrderType type_
The price basis: limit, market, best-limit, and so on.
Definition types.hpp:2222
InstrumentId instrument_
The instrument; its venue_ is identity, and routing is this struct's venue_.
Definition types.hpp:2218
std::optional< Decimal64 > price_
The price; required when carries_caller_price(type_), refused otherwise.
Definition types.hpp:2243
OrderSide side_
Buy or sell.
Definition types.hpp:2220
std::optional< bool > on_tick(const Decimal64 &price) const
Tests whether a price is on the grid.
A quote: the last traded price of an instrument at a point in time.
Definition types.hpp:1143
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
Definition types.hpp:1197
@ DEDUCT
Subtract every resting sell from the figure.
Definition types.hpp:1215
The trading days a broker reported for one market, ascending by date.
Definition calendar.hpp:72
std::size_t unreadable_days_
How many rows from the broker had a date that could not be read.
Definition calendar.hpp:88
std::chrono::system_clock::time_point received_at_
When the calendar was received, on this machine's clock.
Definition calendar.hpp:78
std::vector< TradingDay > days_
The days the broker reported, ascending. A date outside them is uncovered, not closed.
Definition calendar.hpp:76
Country country_
The market this calendar is for.
Definition calendar.hpp:74
One calendar date and whether the market opens on it.
Definition calendar.hpp:31
std::optional< SessionHours > regular_
The exchange's regular session on an open day, where the adapter fills it.
Definition calendar.hpp:47
The one account Alpaca's /v2/account reports for the keys.
Definition client.hpp:59
std::string account_number_
The account number as Alpaca reported it, for display.
Definition client.hpp:61
The Alpaca account selector, which is empty: the keys name the account, and no call takes a number.
Definition client.hpp:48
friend bool operator==(const AlpacaAccount &, const AlpacaAccount &)
Compares two selectors (the arguments are not used); always equal, since one key pair drives one acco...
Definition client.hpp:53
A cancellation of one whole order (Alpaca replacements are refused by this adapter).
Definition client.hpp:75
std::string order_id_
The order id.
Definition client.hpp:77
Alpaca API keys (key id and secret key), paper or live account.
Definition config.hpp:30
const char * data_host() const noexcept
The market-data host, the same for both environments.
Definition config.hpp:172
const char * trading_host() const noexcept
The trading host for the selected environment.
Definition config.hpp:164
const char * port() const noexcept
The HTTPS port, the same for every host.
Definition config.hpp:180
The open US equity orders, before normalizing.
Definition client.hpp:81
std::vector< OrderSnapshot > orders_
The orders.
Definition client.hpp:83
std::chrono::system_clock::time_point received_at_
When the listing arrived, on this machine's clock.
Definition client.hpp:85
Alpaca's acknowledgement of a placement or cancellation.
Definition client.hpp:65
std::string order_id_
The order id.
Definition client.hpp:67
std::chrono::system_clock::time_point received_at_
When the acknowledgement arrived, on this machine's clock.
Definition client.hpp:71
std::optional< std::string > client_order_id_
The client_order_id Alpaca echoed, if any.
Definition client.hpp:69
The Alpaca broker tag: order references are typed by it, so an Alpaca reference works with no other b...
Definition client.hpp:42
static constexpr std::string_view name
The broker's name.
Definition client.hpp:44
Deadlines, size limits and pacing for an HTTP client.
The request rate a connection may use.
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...