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"
14#include <boost/asio/io_context.hpp>
15#include <boost/json.hpp>
44 static constexpr std::string_view
name =
"alpaca";
91inline constexpr std::size_t client_order_id_limit = 128;
94inline constexpr int bar_count_limit = 9999;
97inline constexpr int calendar_days_back = 10;
100inline constexpr int calendar_span_days = 40;
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;
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();
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_;
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);
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);
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);
162 return utc_midnight - eastern_offset(utc_midnight + std::chrono::hours(4));
170inline std::string iso_date(
const Date& date) {
172 std::snprintf(buffer,
sizeof(buffer),
"%04d-%02u-%02u", date.year_, date.month_, date.day_);
181inline std::optional<Date> parse_date(std::string_view text) {
182 if (text.size() != 10 || text[4] !=
'-' || text[7] !=
'-') {
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;
192 if (!field(0, 4, year) || !field(5, 2, month) || !field(8, 2, day) || month < 1 || day < 1) {
195 const Date date{year,
static_cast<unsigned>(month),
static_cast<unsigned>(day)};
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()) {
219 if (value->is_string()) {
222 if (value->is_int64()) {
225 if (value->is_uint64()) {
228 if (value->is_double()) {
231 const double number = value->as_double();
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) {
243 }
catch (
const std::exception&) {
245 throw std::runtime_error(std::string(
"a field is not a number: ") + key);
255inline Decimal64 required(
const json::object&
object,
const char* key) {
256 auto value = number(
object, key);
258 throw std::runtime_error(std::string(
"a field is missing: ") + key);
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();
281inline std::optional<std::chrono::system_clock::time_point> instant(
const json::object&
object,
const char* key) {
282 const auto value = text(
object, key);
288 throw std::runtime_error(std::string(
"a time cannot be read: ") + key);
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;
306 if (status ==
"partially_filled") {
307 return OrderStatus::PARTIAL_FILLED;
309 if (status ==
"filled") {
310 return OrderStatus::FILLED;
312 if (status ==
"canceled" || status ==
"expired") {
313 return OrderStatus::CANCELED;
315 if (status ==
"rejected") {
316 return OrderStatus::REJECTED;
318 if (status ==
"pending_cancel") {
319 return OrderStatus::PENDING_CANCEL;
321 if (status ==
"pending_replace") {
322 return OrderStatus::PENDING_REPLACE;
324 if (status ==
"replaced") {
325 return OrderStatus::REPLACED;
327 return OrderStatus::UNKNOWN;
336inline BrokerError refusal(std::string code, std::string message) {
339 error.reached_broker_ =
false;
340 error.broker_code_ = std::move(code);
341 error.message_ = std::move(message);
350inline InstrumentId instrument_of(std::string symbol) {
351 return InstrumentId{Country::US, Venue::UNSPECIFIED, std::move(symbol)};
360inline std::optional<BrokerError> unsupported_instrument(
const InstrumentId& instrument) {
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
367 "instrument_unsupported",
368 "the Alpaca adapter takes US listings: Country::US, Venue::UNSPECIFIED and a symbol such as BRK.B"
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;
393inline BrokerError invalid_order_id() {
394 return refusal(
"invalid_reference",
"an Alpaca order id is 1 to 128 characters of letters, digits, - and _");
403inline std::optional<BrokerError> validate_bar_query(
const BarQuery& query) {
404 const auto interval = query.interval_;
410 return refusal(
"unsupported_interval",
"the Alpaca adapter serves 1m, 5m, 15m, 30m, 1h and 1d bars");
412 if (query.count_ <= 0 || query.count_ > bar_count_limit) {
413 return refusal(
"invalid_count",
"ask Alpaca for 1 to 9999 bars per call");
415 return unsupported_instrument(query.instrument_);
423inline bool positive(
const Decimal64& value) {
439inline std::optional<BrokerError> validate_order(
const OrderRequest& order) {
440 if (
auto refused = unsupported_instrument(order.instrument_)) {
443 if (order.venue_ != Venue::UNSPECIFIED) {
444 return refusal(
"venue_unsupported",
"Alpaca routes orders itself; leave the venue unspecified");
447 order.client_order_id_ &&
448 (order.client_order_id_->empty() || order.client_order_id_->size() > client_order_id_limit)
450 return refusal(
"invalid_client_order_id",
"Alpaca takes a client_order_id of 1 to 128 characters");
453 return refusal(
"time_in_force_unsupported",
"the Alpaca adapter sends day orders only");
456 return refusal(
"session_unsupported",
"the Alpaca adapter sends regular-session orders only, no extended hours");
458 if (order.trigger_price_) {
459 return refusal(
"order_type_unsupported",
"the Alpaca adapter sends no stop orders, so no trigger price");
461 switch (order.type_) {
463 if (!order.price_ || !positive(*order.price_)) {
464 return refusal(
"invalid_price",
"a limit order needs a positive 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)");
474 return refusal(
"invalid_price",
"a market order carries no price");
477 case OrderType::UNKNOWN:
484 return refusal(
"order_type_unsupported",
"the Alpaca adapter sends limit and market orders only");
487 if (quantity.coefficient() <= 0 || quantity.scale() != 0) {
488 return refusal(
"invalid_quantity",
"the Alpaca adapter sends whole, positive share quantities only");
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";
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);
528 if (tradable ==
nullptr || !tradable->is_bool() || asset_class.empty() || status.empty() || exchange.empty()) {
530 refusal(
"instrument_unreadable",
"Alpaca's asset reply for " + symbol +
" leaves out a field it needs");
534 if (asset_class !=
"us_equity" || !listed_exchange(exchange)) {
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"
541 if (status !=
"active" || !tradable->as_bool()) {
542 return refusal(
"instrument_not_tradable", symbol +
" is not active and tradable at Alpaca");
577 std::shared_ptr<network::TokenStore> store = nullptr
579 : config_(std::move(
config)) {
580 static_cast<void>(store);
581 if (!options.rate_limit_) {
582 options.rate_limit_ = default_rate_limit();
584 trading_ = std::make_shared<network::AsyncHttpClient>(
585 ioc_.get_executor(), context, config_.
trading_host(), config_.
port(), options
587 data_ = std::make_shared<network::AsyncHttpClient>(
588 ioc_.get_executor(), context, config_.
data_host(), config_.
port(), options
613 const auto* limiter = trading_->rate_limits();
614 return limiter ? &limiter->stats() :
nullptr;
622 return attempt<std::vector<AlpacaAccountInfo>>([&] {
624 if (detail::text(reply,
"currency") !=
"USD") {
625 throw std::runtime_error(
"the account is not in USD");
630 throw std::runtime_error(
"the account has no account_number");
632 return std::vector<AlpacaAccountInfo>{std::move(account)};
642 if (
auto refused = detail::unsupported_instrument(
instrument)) {
645 return attempt<QuoteSnapshot>([&] {
646 const auto reply = get_object(
647 *data_,
"/v2/stocks/" + broker_detail::query_encode(
instrument.
symbol_) +
"/trades/latest?feed=iex",
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");
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_();
676 if (
auto refused = detail::validate_bar_query(query)) {
679 return attempt<BarSeries>([&] {
680 const auto now = clock_();
684 const auto reply = get_object(
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),
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");
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_) {
707 if (!value.is_object()) {
708 throw std::runtime_error(
"a bar is not an object");
710 const auto& row = value.as_object();
711 const auto stamp = detail::instant(row,
"t");
713 throw std::runtime_error(
"a bar has no time");
716 if (*stamp + length > now || end < *stamp) {
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));
729 std::reverse(series.
bars_.begin(), series.
bars_.end());
731 throw std::runtime_error(
"the bars are out of order or repeated");
750 static_cast<void>(account);
751 return attempt<HoldingsSnapshot>(
754 if (!reply.is_array()) {
755 throw std::runtime_error(
"the positions are not a list");
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");
764 if (!seen.insert(symbol).second) {
765 throw std::runtime_error(
"the positions list " + symbol +
" twice");
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") {
775 if (detail::text(row,
"side") !=
"long") {
776 throw std::runtime_error(
"a US equity position is not long: " + detail::text(row,
"symbol"));
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));
796 snapshot.sellable_basis_ =
798 snapshot.received_at_ = clock_();
801 "invalid_holdings_response"
816 if (
auto refused = detail::unsupported_instrument(
instrument)) {
819 return attempt<Instrument>([&] {
820 const auto reply = get_object(
824 throw Failure{std::move(*refused)};
828 out.
name_ = detail::text(reply,
"name");
831 out.
status_ = InstrumentStatus::ACTIVE;
853 if (country != Country::US) {
859 return attempt<TradingCalendar>(
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(
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");
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;
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")};
889 auto& slot = listed[
static_cast<std::size_t
>(day - first_day)];
892 calendar_error(
"calendar_duplicate_date",
"the calendar lists " + detail::iso_date(*date) +
" twice")
896 slot->
regular_ = session(*row,
"core_start",
"core_end");
897 if (slot->regular_) {
898 const auto span = session(*row,
"pre_start",
"post_end");
900 span && span->opens_at_ <= slot->regular_->opens_at_ && slot->regular_->closes_at_ <= span->closes_at_
902 slot->extended_ = span;
906 for (
auto day = first_day; day <= last_day; ++day) {
907 const auto& slot = listed[
static_cast<std::size_t
>(day - first_day)];
913 "invalid_calendar_response"
936 static_cast<void>(account);
937 if (
auto refused = detail::validate_order(order)) {
940 if (
auto refused = refuse_before_order(order)) {
946 body[
"side"] = order.
side_ == OrderSide::BUY ?
"buy" :
"sell";
948 body[
"time_in_force"] =
"day";
955 return send_order(http::verb::post,
"/v2/orders", json::serialize(body), Call::PLACE, std::string());
966 static_cast<void>(account);
967 if (!detail::valid_order_id(amendment.
order_id_)) {
971 http::verb::delete_,
"/v2/orders/" + broker_detail::query_encode(amendment.
order_id_), std::string(),
986 static_cast<void>(account);
987 return attempt<AlpacaOpenOrders>(
991 if (!reply.is_array()) {
992 throw std::runtime_error(
"the orders are not a list");
994 if (reply.as_array().size() >= 500) {
995 throw std::runtime_error(
"Alpaca listed 500 open orders: the listing may be cut");
997 AlpacaOpenOrders open;
998 open.orders_ = orders_of(reply.as_array());
999 open.received_at_ = clock_();
1002 "invalid_orders_response"
1013 static_cast<void>(account);
1014 if (!detail::valid_order_id(
id)) {
1017 return attempt<OrderSnapshot>(
1021 if (detail::text(row,
"asset_class") !=
"us_equity") {
1022 throw std::runtime_error(
"the order is not a US equity order");
1024 return order_of(row);
1026 "invalid_order_response"
1042 static_cast<void>(account);
1043 return attempt<OrderPage>(
1046 std::string target =
"/v2/orders?status=all&direction=desc&limit=" + std::to_string(limit);
1048 target +=
"&symbols=" + broker_detail::query_encode(*query.
symbol_);
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));
1059 if (!reply.is_array()) {
1060 throw std::runtime_error(
"the orders are not a list");
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");
1075 "invalid_orders_response"
1080 friend struct AlpacaClientTestAccess;
1099 static std::string timeframe(
BarInterval interval) {
1101 case BarInterval::ONE_MINUTE:
1111 case BarInterval::ONE_DAY:
1112 case BarInterval::ONE_WEEK:
1113 case BarInterval::ONE_MONTH:
1114 case BarInterval::ONE_YEAR:
1121 static BrokerError calendar_error(std::string code, std::string message) {
1124 error.broker_code_ = std::move(code);
1125 error.message_ =
"Alpaca: " + std::move(message);
1131 static std::optional<SessionHours> session(
const json::object& row,
const char* opens,
const char* closes) {
1134 if (!start || !end || !(*start < *end)) {
1135 return std::nullopt;
1137 return SessionHours{*
start, *end};
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_;
1149 *trading_, http::verb::get,
"/v2/assets/" + broker_detail::query_encode(symbol), {},
1152 if (asset && asset.value().result_int() == 404) {
1153 return detail::refusal(
"instrument_not_listed",
"Alpaca lists no asset " + symbol);
1155 auto asset_reply = read_object(std::move(asset));
1157 return unsent(std::move(asset_reply.error()),
"the asset");
1159 if (
auto refused = detail::unlisted_asset(asset_reply.value(), symbol)) {
1162 if (order.side_ == OrderSide::SELL) {
1163 auto position = send(
1164 *trading_, http::verb::get,
"/v2/positions/" + broker_detail::query_encode(symbol), {},
1167 if (position && position.value().result_int() == 404) {
1168 return detail::refusal(
"no_position",
"no position in " + symbol +
": a sell would open a short");
1170 auto position_reply = read_object(std::move(position));
1171 if (!position_reply) {
1172 return unsent(std::move(position_reply.error()),
"the position");
1175 const auto& row = position_reply.value();
1176 if (detail::text(row,
"symbol") != symbol || detail::text(row,
"asset_class") !=
"us_equity") {
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");
1183 const auto available = detail::number(row,
"qty_available");
1184 const auto held = detail::required(row,
"qty");
1186 detail::text(row,
"side") !=
"long" || !available || !detail::positive(held) ||
1189 return detail::refusal(
1190 "sell_exceeds_position",
"the sell exceeds the position available in " + symbol +
": it would open a short"
1193 }
catch (
const std::exception& exception) {
1196 error.broker_code_ =
"invalid_position_response";
1197 error.message_ = exception.what();
1198 return unsent(std::move(error),
"the position");
1201 return refuse_unless_core();
1205 std::optional<BrokerError> refuse_unless_core() {
1209 error.reached_broker_ =
false;
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_;
1216 const json::object* clock =
nullptr;
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") {
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";
1235 if (phase !=
"core") {
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";
1244 return std::nullopt;
1248 Result<AlpacaOrderAck> send_order(
1249 http::verb method,
const std::string& target, std::string body, Call call,
const std::string& asked_id
1255 const auto& response = reply.value();
1256 const auto status = response.result_int();
1258 ack.received_at_ = clock_();
1259 if (call == Call::CANCEL && status >= 200 && status < 300) {
1260 ack.order_id_ = asked_id;
1263 if (status < 200 || status >= 300) {
1267 auto row = broker_detail::parse_object(response, error);
1271 ack.order_id_ = detail::text(*row,
"id");
1272 if (ack.order_id_.empty()) {
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";
1279 if (
auto key = detail::text(*row,
"client_order_id"); !key.empty()) {
1280 ack.client_order_id_ = std::move(key);
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");
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());
1302 error.message_ =
"Alpaca answered HTTP " + std::to_string(status) +
" with a body that is not JSON";
1304 if (status == 401) {
1307 }
else if (status == 429 && call == Call::READ) {
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));
1313 }
else if (call == Call::READ || status >= 500) {
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")
1331 template <
typename T,
typename Make>
1332 Result<T> attempt(Make make,
const char* code =
"invalid_response") {
1335 }
catch (
const Failure& failure) {
1337 }
catch (
const std::exception& exception) {
1340 error.broker_code_ = code;
1341 error.message_ = std::string(
"Alpaca: ") + exception.what();
1347 Result<json::value> read_json(Result<network::HttpResponse> reply)
const {
1349 return Result<json::value>(std::move(reply.error()));
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));
1355 boost::system::error_code ec;
1356 auto value = json::parse(response.body(), ec);
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));
1365 return Result<json::value>(std::move(value));
1369 Result<json::object> read_object(Result<network::HttpResponse> reply)
const {
1370 auto value = read_json(std::move(reply));
1372 return Result<json::object>(std::move(value.error()));
1374 if (!value.value().is_object()) {
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));
1381 return Result<json::object>(std::move(value.value().as_object()));
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));
1388 throw Failure{std::move(value.error())};
1390 return std::move(value.value());
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));
1397 throw Failure{std::move(value.error())};
1399 return std::move(value.value());
1403 network::HttpRequest make_request(
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");
1413 request.body_ = std::move(body);
1414 request.group_ = group;
1419 Result<network::HttpResponse> send(
1420 network::AsyncHttpClient& http, http::verb method, std::string target, std::string body,
1423 std::optional<Result<network::HttpResponse>> result;
1426 make_request(method, std::move(target), std::move(body), group), [&result](Result<network::HttpResponse> value) {
1427 result.emplace(std::move(value));
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));
1438 return std::move(*result);
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();
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");
1451 if (!seen.insert(
id).second) {
1452 throw std::runtime_error(
"the orders list " + id +
" twice");
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") {
1462 orders.push_back(order_of(row));
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");
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");
1479 order.side_ = side ==
"buy" ? OrderSide::BUY : OrderSide::SELL;
1480 const auto type = detail::text(row,
"type");
1481 order.type_ = type ==
"limit" ?
1485 type ==
"stop_limit" ?
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");
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");
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");
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();
static Currency usd()
Returns United States dollars.
std::int64_t coefficient() const noexcept
Returns the coefficient.
std::string str() const
Formats the value as a decimal string.
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Either a value or a BrokerError.
Result(T value)
Constructs a successful result.
const network::RateLimitStats * rate_limit_stats() const
Returns the trading connection's rate-limit statistics; read them between calls.
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.
static network::RateLimitBudget default_rate_limit() noexcept
The pacing each connection gets when the caller sets none.
Result< Instrument > instrument(InstrumentId instrument)
Returns one instrument's reference data (/v2/assets/{symbol}), with lot 1, dollars and us::equity_pri...
Result< HoldingsSnapshot > holdings(AlpacaAccount account={})
Returns the US equity positions (/v2/positions), in dollars.
Result< OrderPage > order_history(AlpacaAccount account, OrderHistoryQuery query)
Returns US equity orders submitted from from_ to to_ (New York dates), newest first,...
Result< BarSeries > bars(BarQuery query)
Returns closed bars, oldest first: the newest count_ (1 to 9,999) at or before before_ (or now),...
Result< AlpacaOrderAck > cancel_order(AlpacaAccount account, AlpacaAmendment amendment)
Cancels a whole order (DELETE /v2/orders/{id}; 204, also for an order already cancelled)....
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns the last trade on the IEX feed, in dollars.
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,...
Result< AlpacaOrderAck > place_order(AlpacaAccount account, OrderRequest order)
Places an order (POST /v2/orders). 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).
const AlpacaConfig & config() const noexcept
Returns the configuration.
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< std::vector< AlpacaAccountInfo > > accounts()
Returns the one account the keys drive (/v2/account).
The Alpaca Trading API and Market Data API client: exchange-listed US equities, paper by default.
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.
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
PriceRule equity_price_rule()
Returns the US equity price grid: $0.01 at or above $1, $0.0001 below (Regulation NMS Rule 612).
@ 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.
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.
@ RATE_LIMIT
The broker refused the request for its rate limit.
@ HTTP
The broker answered with an HTTP error status (http_status_).
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
@ CANCELLED
The operation was cancelled, such as by closing the client or a local deadline.
@ AUTHENTICATION
The credentials or token were refused.
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
@ LIMIT
지정가: fills at the stated price or better.
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
@ MID_PRICE
중간가: priced at the midpoint of the spread.
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
@ MARKET
시장가: fills at whatever the book offers.
Country
A country (market) the library supports.
Decimal64 decimal_normalized(const Decimal64 &value)
Removes trailing fractional zeros, so equal numbers compare equal with ==.
@ REGULAR
The continuous regular session.
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Date date_from_epoch_days(std::int64_t days)
Converts a day count since 1970-01-01 to a Gregorian date.
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.
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
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.
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.
ErrorCategory category_
The kind of failure; the field to branch on.
A calendar date with no time of day or time zone.
unsigned month_
The month, 1-12; zero means unset.
unsigned day_
The day of the month, 1-31; zero means unset.
Identifies an instrument: its country, venue and symbol.
std::string symbol_
The symbol as the venue spells it, such as "005930".
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.
std::optional< std::string > symbol_
Only this symbol, where the broker supports the filter.
std::optional< int > limit_
The most rows to return, where the broker supports a limit.
std::optional< std::string > cursor_
A previous page's next_cursor_, passed back unchanged.
std::optional< Date > from_
The first date to include; required where BrokerCaps::history_requires_range.
std::optional< Date > to_
The last date to include.
One page of an order listing.
std::vector< OrderSnapshot > orders_
The rows, in the broker's order.
std::optional< std::string > next_cursor_
The cursor for the next page, to pass back unchanged; empty if there is none.
std::chrono::system_clock::time_point received_at_
When the page was received, on this machine's clock.
An order to place, in broker-neutral form.
std::optional< std::string > client_order_id_
An idempotency key, if the broker offers one; never generated by the library.
Decimal64 quantity_
The quantity, in the instrument's units (shares).
OrderType type_
The price basis: limit, market, best-limit, and so on.
InstrumentId instrument_
The instrument; its venue_ is identity, and routing is this struct's venue_.
std::optional< Decimal64 > price_
The price; required when carries_caller_price(type_), refused otherwise.
OrderSide side_
Buy or sell.
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.
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
@ DEDUCT
Subtract every resting sell from the figure.
The trading days a broker reported for one market, ascending by date.
std::size_t unreadable_days_
How many rows from the broker had a date that could not be read.
std::chrono::system_clock::time_point received_at_
When the calendar was received, on this machine's clock.
std::vector< TradingDay > days_
The days the broker reported, ascending. A date outside them is uncovered, not closed.
Country country_
The market this calendar is for.
One calendar date and whether the market opens on it.
std::optional< SessionHours > regular_
The exchange's regular session on an open day, where the adapter fills it.
The one account Alpaca's /v2/account reports for the keys.
std::string account_number_
The account number as Alpaca reported it, for display.
The Alpaca account selector, which is empty: the keys name the account, and no call takes a number.
friend bool operator==(const AlpacaAccount &, const AlpacaAccount &)
Compares two selectors (the arguments are not used); always equal, since one key pair drives one acco...
A cancellation of one whole order (Alpaca replacements are refused by this adapter).
std::string order_id_
The order id.
Alpaca API keys (key id and secret key), paper or live account.
const char * data_host() const noexcept
The market-data host, the same for both environments.
const char * trading_host() const noexcept
The trading host for the selected environment.
const char * port() const noexcept
The HTTPS port, the same for every host.
The open US equity orders, before normalizing.
std::vector< OrderSnapshot > orders_
The orders.
std::chrono::system_clock::time_point received_at_
When the listing arrived, on this machine's clock.
Alpaca's acknowledgement of a placement or cancellation.
std::string order_id_
The order id.
std::chrono::system_clock::time_point received_at_
When the acknowledgement arrived, on this machine's clock.
std::optional< std::string > client_order_id_
The client_order_id Alpaca echoed, if any.
The Alpaca broker tag: order references are typed by it, so an Alpaca reference works with no other b...
static constexpr std::string_view name
The broker's name.
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...