algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
traits.hpp
1#pragma once
2
8#define ATL_BROKER_ADAPTER_PRESENT 1
9
10#include "./client.hpp"
11
12#include "../../core/broker_session.hpp"
13#include "../../core/broker_traits.hpp"
14
15#include <optional>
16#include <string>
17#include <string_view>
18#include <utility>
19#include <vector>
20
21namespace algotradelib {
22
32template <>
33struct BrokerTraits<alpaca::AlpacaBlockingClient> {
36
39
42
45
48
51
54
57
60
62 static constexpr std::string_view name = alpaca::Broker::name;
63
65 static constexpr bool blocking = true;
66
68 static constexpr bool data_only = false;
69
71 static constexpr bool has_account_discovery = true;
72
74 static constexpr bool has_client_order_id = true;
75
77 static constexpr bool has_working_orders = true;
78
80 static constexpr bool has_amendable_quantity = true;
81
83 static constexpr bool working_orders_state_terminal = false;
84
86 static constexpr bool has_trigger_price = false;
87
89 static constexpr bool has_order_by_id = true;
90
92 static constexpr bool has_partial_cancel = false;
93
95 static constexpr bool history_requires_range = false;
96
98 static constexpr bool has_history_cursor = true;
99
101 static constexpr bool has_history_limit = true;
102
104 static constexpr int history_limit = 500;
105
107 static constexpr bool has_history_symbol_filter = true;
108
110 static constexpr bool has_depth = false;
111
113 static constexpr bool has_price_limits = false;
114
116 static constexpr bool has_trade_prints = false;
117
119 static constexpr bool has_batch_prices = false;
120
127 static constexpr bool has_buying_power = false;
128
130 static constexpr bool has_buying_power_quantity = false;
131
134
136 static constexpr bool has_commission_schedule = false;
137
139 static constexpr bool has_reference_data = true;
140
142 static constexpr bool has_batch_reference_data = false;
143
145 static constexpr bool has_calendar = true;
146
148 static constexpr bool has_calendar_range = true;
149
154 static constexpr bool has_calendar_sessions = true;
155
161 static constexpr bool supports_interval(BarInterval interval) {
162 return interval == BarInterval::ONE_MINUTE || interval == BarInterval::FIVE_MINUTES ||
164 interval == BarInterval::ONE_HOUR || interval == BarInterval::ONE_DAY;
165 }
166
171 static constexpr Venue effective_route(Venue) noexcept {
172 return Venue::UNSPECIFIED;
173 }
174
180 static std::optional<BrokerError> validate_bars(const BarQuery& query) {
181 return alpaca::detail::validate_bar_query(query);
182 }
183
190 static std::optional<BrokerError> validate_calendar(Country country, std::optional<Date> from) {
191 if (country != Country::US) {
192 return alpaca::detail::refusal("market_unsupported", "Alpaca's calendar is the US market's");
193 }
194 if (from && !is_valid_date(*from)) {
195 return alpaca::detail::refusal("invalid_date", "the calendar needs a valid date");
196 }
197 return std::nullopt;
198 }
199
206 static std::optional<BrokerError> validate_place(const OrderRequest& order) {
207 return alpaca::detail::validate_order(order);
208 }
209
216 if (!raw) {
217 return Result<PlacedOrder<alpaca::Broker>>(std::move(raw.error()));
218 }
220 placed.ack_.order_id_ = raw.value().order_id_;
221 placed.ack_.client_order_id_ = raw.value().client_order_id_;
222 placed.ack_.accepted_at_ = raw.value().received_at_;
223 placed.ref_.primary_ = raw.value().order_id_;
224 return Result<PlacedOrder<alpaca::Broker>>(std::move(placed));
225 }
226
233 if (!raw) {
234 return Result<WorkingOrders<alpaca::Broker>>(std::move(raw.error()));
235 }
237 orders.received_at_ = raw.value().received_at_;
238 for (auto& open : raw.value().orders_) {
240 working.ref_.primary_ = open.order_id_;
241 working.amendable_quantity_ = decimal_subtract(open.quantity_, open.execution_.filled_quantity_);
242 working.order_ = std::move(open);
243 orders.orders_.push_back(std::move(working));
244 }
245 return Result<WorkingOrders<alpaca::Broker>>(std::move(orders));
246 }
247
254 return Result<Amendment>(
255 alpaca::detail::refusal("replace_unsupported", "the Alpaca adapter does not replace orders; cancel and place")
256 );
257 }
258
266 if (!instruction.all_remaining_) {
267 return Result<Amendment>(
268 alpaca::detail::refusal("partial_cancel_unsupported", "Alpaca cancels the whole order only")
269 );
270 }
271 if (!alpaca::detail::valid_order_id(ref.primary_)) {
272 return Result<Amendment>(alpaca::detail::invalid_order_id());
273 }
275 }
276
283 if (query.limit_ && (*query.limit_ <= 0 || *query.limit_ > history_limit)) {
284 return Result<HistoryQuery>(alpaca::detail::refusal("invalid_limit", "Alpaca's order list takes 1 to 500 rows"));
285 }
286 if ((query.from_ && !is_valid_date(*query.from_)) || (query.to_ && !is_valid_date(*query.to_))) {
287 return Result<HistoryQuery>(alpaca::detail::refusal("invalid_date", "the history range needs valid dates"));
288 }
289 return Result<HistoryQuery>(query);
290 }
291
297 return Account{};
298 }
299
305 static std::string display_of(const AccountListItem& account) {
306 return account.account_number_;
307 }
308
313 static std::string type_of(const AccountListItem&) {
314 return {};
315 }
316
322 static const network::RateLimitStats* rate_limit_stats(const Client& client) {
323 return client.rate_limit_stats();
324 }
325
333 return client.quote(std::move(instrument));
334 }
335
342 static Result<BarSeries> bars(Client& client, BarQuery query) {
343 return client.bars(std::move(query));
344 }
345
353 return client.instrument(std::move(subject));
354 }
355
363 static Result<TradingCalendar> calendar(Client& client, Country country, std::optional<Date> from) {
364 return client.calendar(country, from);
365 }
366
373 return client.accounts();
374 }
375
382 static Result<HoldingsSnapshot> holdings(Client& client, const Account& account) {
383 return client.holdings(account);
384 }
385
393 static Result<PlaceAck> place_order(Client& client, const Account& account, OrderRequest order) {
394 return client.place_order(account, std::move(order));
395 }
396
402 return Result<PlaceAck>(
403 alpaca::detail::refusal("replace_unsupported", "the Alpaca adapter does not replace orders; cancel and place")
404 );
405 }
406
414 static Result<PlaceAck> cancel_order(Client& client, const Account& account, Amendment amendment) {
415 return client.cancel_order(account, std::move(amendment));
416 }
417
425 return client.working_orders(account);
426 }
427
435 static Result<OrderSnapshot> order_by_id(Client& client, const Account& account, const std::string& id) {
436 return client.order_by_id(account, id);
437 }
438
446 static Result<OrderPage> order_history(Client& client, const Account& account, HistoryQuery query) {
447 return client.order_history(account, std::move(query));
448 }
449};
450
451} // namespace algotradelib
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
BrokerError & error()
Returns the error.
Definition types.hpp:1111
T & value()
Returns the value.
Definition types.hpp:1093
A blocking client for Alpaca's Trading API and Market Data API: exchange-listed US equities,...
Definition client.hpp:566
const network::RateLimitStats * rate_limit_stats() const
Returns the trading connection's rate-limit statistics; read them between calls.
Definition client.hpp:612
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
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
The library: broker-neutral types (core), and the modules below.
SellableSource
Where the library gets a broker's sellable quantity.
Definition types.hpp:1362
@ HOLDINGS
On the holdings snapshot, at no extra request.
Definition types.hpp:1364
Country
A country (market) the library supports.
Definition types.hpp:32
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
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
A modification or cancellation of a working order.
Definition types.hpp:2532
bool all_remaining_
Whether the whole remaining quantity is affected, rather than quantity_.
Definition types.hpp:2544
What bars to fetch.
static constexpr bool has_price_limits
false: no daily price band is published for US equities.
Definition traits.hpp:113
static Result< OrderSnapshot > order_by_id(Client &client, const Account &account, const std::string &id)
Returns one order by its id.
Definition traits.hpp:435
static Result< WorkingOrders< alpaca::Broker > > normalize_working_orders(Result< WorkingOrdersResult > raw)
Converts the open orders into working orders, each amendable for its unfilled quantity.
Definition traits.hpp:232
static constexpr SellableSource sellable_source
HOLDINGS: each position's qty_available, with the basis AlpacaBlockingClient::holdings states.
Definition traits.hpp:133
static constexpr bool has_working_orders
true: /v2/orders?status=open.
Definition traits.hpp:77
static Result< QuoteSnapshot > quote(Client &client, InstrumentId instrument)
Returns a quote.
Definition traits.hpp:332
static Account selector_of(const AccountListItem &)
Returns the account selector a session binds, which is empty. The argument is not used.
Definition traits.hpp:296
static std::optional< BrokerError > validate_bars(const BarQuery &query)
Refuses a bar request this adapter cannot answer as asked, before any I/O.
Definition traits.hpp:180
static constexpr Venue effective_route(Venue) noexcept
Returns where an order goes: Alpaca routes it, and no venue can be asked for.
Definition traits.hpp:171
static Result< std::vector< AccountListItem > > accounts(Client &client)
Returns the one account the keys drive.
Definition traits.hpp:372
static constexpr bool has_trade_prints
false: served by Alpaca, not adapted.
Definition traits.hpp:116
static Result< OrderPage > order_history(Client &client, const Account &account, HistoryQuery query)
Returns a page of order history.
Definition traits.hpp:446
static constexpr bool has_order_by_id
true: /v2/orders/{id}.
Definition traits.hpp:89
static Result< WorkingOrdersResult > working_orders(Client &client, const Account &account)
Returns the open orders.
Definition traits.hpp:424
static constexpr bool has_history_limit
true: up to history_limit rows a page.
Definition traits.hpp:101
static constexpr std::string_view name
The broker's name.
Definition traits.hpp:62
static constexpr bool has_calendar
true: /v3/calendar/XNYS.
Definition traits.hpp:145
static std::optional< BrokerError > validate_place(const OrderRequest &order)
Refuses an order this adapter does not send as described, before any I/O; the same check the client's...
Definition traits.hpp:206
static Result< Instrument > instrument(Client &client, InstrumentId subject)
Returns reference data for one instrument.
Definition traits.hpp:352
static constexpr bool history_requires_range
false: a range is optional.
Definition traits.hpp:95
static constexpr bool has_history_cursor
true: a full page carries its last row's submission time, sent back as Alpaca's until.
Definition traits.hpp:98
static constexpr bool has_trigger_price
false: this adapter sends no stop orders.
Definition traits.hpp:86
static constexpr bool has_amendable_quantity
true: each order's qty less its filled_qty.
Definition traits.hpp:80
static constexpr int history_limit
The most rows one history page may ask for.
Definition traits.hpp:104
alpaca::AlpacaOrderAck PlaceAck
Alpaca's acknowledgement of a placement or cancellation.
Definition traits.hpp:50
static constexpr bool has_history_symbol_filter
true: Alpaca filters by symbols=.
Definition traits.hpp:107
static constexpr bool has_buying_power
false: no Alpaca figure is cash net of resting buys without credit (buying_power counts margin),...
Definition traits.hpp:127
static Result< BarSeries > bars(Client &client, BarQuery query)
Returns bars.
Definition traits.hpp:342
static std::string display_of(const AccountListItem &account)
Returns the account number as Alpaca reports it.
Definition traits.hpp:305
static constexpr bool has_buying_power_quantity
false: there is no buying power to express in shares.
Definition traits.hpp:130
alpaca::AlpacaAccount Account
The account selector, which carries nothing.
Definition traits.hpp:41
static constexpr bool has_calendar_range
true: one request covers the whole range.
Definition traits.hpp:148
OrderHistoryQuery HistoryQuery
The history query, the library's own.
Definition traits.hpp:56
static constexpr bool has_batch_reference_data
false: one instrument a request.
Definition traits.hpp:142
static constexpr bool has_calendar_sessions
true: the adapter fills each open day's regular session and, where stated, its extended span,...
Definition traits.hpp:154
alpaca::AlpacaBlockingClient Client
The client type.
Definition traits.hpp:35
static Result< Amendment > to_replacement(const OrderRef< alpaca::Broker > &, const AmendInstruction &)
Refuses every replacement: Alpaca's replacement is a new order that drops the client_order_id,...
Definition traits.hpp:253
alpaca::AlpacaOpenOrders WorkingOrdersResult
The open orders, before normalizing.
Definition traits.hpp:59
static Result< PlaceAck > replace_order(Client &, const Account &, Amendment)
Refuses a replacement; to_replacement refuses first, so a session never calls it.
Definition traits.hpp:401
static Result< HoldingsSnapshot > holdings(Client &client, const Account &account)
Returns the holdings.
Definition traits.hpp:382
static constexpr bool has_partial_cancel
false: Alpaca cancels the whole order.
Definition traits.hpp:92
static Result< PlacedOrder< alpaca::Broker > > normalize_place(Result< PlaceAck > raw)
Normalizes Alpaca's acknowledgement; the reference is the order id.
Definition traits.hpp:215
static constexpr bool working_orders_state_terminal
false: the open listing shows open orders only.
Definition traits.hpp:83
static constexpr bool has_client_order_id
true: client_order_id, 1 to 128 characters, unique for the account.
Definition traits.hpp:74
static Result< TradingCalendar > calendar(Client &client, Country country, std::optional< Date > from)
Returns the trading calendar.
Definition traits.hpp:363
static constexpr bool has_depth
false: served by Alpaca, not adapted.
Definition traits.hpp:110
static constexpr bool data_only
A broker that takes orders, not a market-data source.
Definition traits.hpp:68
static std::optional< BrokerError > validate_calendar(Country country, std::optional< Date > from)
Refuses a calendar for any market but the US, or with an invalid date.
Definition traits.hpp:190
static constexpr bool supports_interval(BarInterval interval)
Tests whether this adapter serves bars at an interval.
Definition traits.hpp:161
static Result< Amendment > to_cancellation(const OrderRef< alpaca::Broker > &ref, const AmendInstruction &instruction)
Converts a cancellation of the whole order; a stated quantity is refused.
Definition traits.hpp:265
static Result< PlaceAck > place_order(Client &client, const Account &account, OrderRequest order)
Places an order.
Definition traits.hpp:393
static Result< PlaceAck > cancel_order(Client &client, const Account &account, Amendment amendment)
Cancels an order.
Definition traits.hpp:414
static std::string type_of(const AccountListItem &)
Returns the account type, which this adapter does not read (the argument is not used).
Definition traits.hpp:313
static Result< HistoryQuery > to_history_query(const Account &, const OrderHistoryQuery &query)
Admits a history query with a limit of 1 to 500 and valid dates.
Definition traits.hpp:282
static constexpr bool has_reference_data
true: /v2/assets/{symbol}.
Definition traits.hpp:139
alpaca::AlpacaAmendment Amendment
A cancellation of one whole order.
Definition traits.hpp:53
static constexpr bool blocking
true: requests return their result directly.
Definition traits.hpp:65
alpaca::AlpacaConfig Config
The keys and environment.
Definition traits.hpp:38
static const network::RateLimitStats * rate_limit_stats(const Client &client)
Returns the trading connection's rate-limit statistics.
Definition traits.hpp:322
static constexpr bool has_commission_schedule
false: commission-free, and the per-share FINRA fee on sells has no CommissionRate shape.
Definition traits.hpp:136
alpaca::AlpacaAccountInfo AccountListItem
Item type of the broker's own account listing.
Definition traits.hpp:44
static constexpr bool has_account_discovery
true: /v2/account reports the one account the keys drive.
Definition traits.hpp:71
static constexpr bool has_batch_prices
false: one instrument a request.
Definition traits.hpp:119
Describes one broker client to the library: its types, capabilities, call thunks and normalizers.
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
std::optional< std::string > client_order_id_
The idempotency key, if the broker echoed one.
Definition types.hpp:2387
std::chrono::system_clock::time_point accepted_at_
When the acknowledgement was received.
Definition types.hpp:2389
std::string order_id_
The order number the broker assigned.
Definition types.hpp:2385
The filter for an order-history inquiry.
Definition types.hpp:2617
std::optional< int > limit_
The most rows to return, where the broker supports a limit.
Definition types.hpp:2627
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
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
std::string primary_
The order number or id.
Definition types.hpp:2404
An order to place, in broker-neutral form.
Definition types.hpp:2216
An accepted order: the acknowledgement and the reference to address it with.
Definition types.hpp:2460
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2464
OrderAck ack_
The acknowledgement.
Definition types.hpp:2462
An order still open to modification or cancellation.
Definition types.hpp:2582
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2586
std::optional< Decimal64 > amendable_quantity_
How much the broker says may still be amended. Empty means it stated none, not zero.
Definition types.hpp:2588
OrderSnapshot order_
The order's state.
Definition types.hpp:2584
The orders open to modification or cancellation at one point in time.
Definition types.hpp:2604
std::vector< WorkingOrder< Broker > > orders_
The open orders.
Definition types.hpp:2606
std::chrono::system_clock::time_point received_at_
When the listing was received, on this machine's clock.
Definition types.hpp:2608
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
A cancellation of one whole order (Alpaca replacements are refused by this adapter).
Definition client.hpp:75
Alpaca API keys (key id and secret key), paper or live account.
Definition config.hpp:30
The open US equity orders, before normalizing.
Definition client.hpp:81
Alpaca's acknowledgement of a placement or cancellation.
Definition client.hpp:65
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
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...