algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
broker_session.hpp
1#pragma once
2
3#include "./broker_caps.hpp"
4#include "./broker_traits.hpp"
5#include "./calendar.hpp"
6#include "./instrument.hpp"
7
8#include "../network/rate_limit.hpp"
9
10#include <boost/asio/associated_executor.hpp>
11#include <boost/asio/async_result.hpp>
12#include <boost/asio/bind_executor.hpp>
13#include <boost/asio/post.hpp>
14#include <boost/asio/system_executor.hpp>
15
16#include <algorithm>
17#include <memory>
18#include <optional>
19#include <stdexcept>
20#include <string>
21#include <string_view>
22#include <utility>
23#include <vector>
24
25namespace algotradelib {
26
27namespace net = boost::asio;
28
29namespace port_detail {
30
31// Converts a broker's account listing into `AccountInfo` rows (shared by both sessions).
32template <typename Client, typename Items>
33Result<std::vector<AccountInfo<Client>>> to_account_info(Result<Items> raw) {
34 using Traits = BrokerTraits<Client>;
35 using Accounts = std::vector<AccountInfo<Client>>;
36 if (!raw) {
37 return Result<Accounts>(std::move(raw.error()));
38 }
39 Accounts listed;
40 listed.reserve(raw.value().size());
41 for (const auto& item : raw.value()) {
42 AccountInfo<Client> info;
43 info.display_number_ = Traits::display_of(item);
44 info.type_ = Traits::type_of(item);
45 info.selector_ = Traits::selector_of(item);
46 listed.push_back(std::move(info));
47 }
48 return Result<Accounts>(std::move(listed));
49}
50
63template <typename Client>
64std::optional<BrokerError> trigger_refusal(const std::optional<Decimal64>& trigger) {
66 return std::nullopt;
67 } else {
68 if (!trigger) {
69 return std::nullopt;
70 }
71 BrokerError error;
72 error.category_ = ErrorCategory::INVALID_ARGUMENT;
73 error.reached_broker_ = false;
74 error.broker_code_ = "unsupported_trigger_price";
75 error.message_ =
76 "this broker does not declare that it transmits a trigger price, so an order carrying one "
77 "would be sent without it; place the order without a trigger or through a broker whose "
78 "BrokerCaps::has_trigger_price is true";
79 return error;
80 }
81}
82
90template <typename Client>
91std::optional<BrokerError> prepare_place(const OrderRequest& order) {
92 if (auto refused = trigger_refusal<Client>(order.trigger_price_)) {
93 return refused;
94 }
95 return BrokerTraits<Client>::validate_place(order);
96}
97
107template <typename Client>
108Result<typename BrokerTraits<Client>::Amendment> prepare_replace(
109 const OrderRef<typename BrokerTraits<Client>::BrokerTag>& ref, const AmendInstruction& instruction
110) {
111 using Amendment = typename BrokerTraits<Client>::Amendment;
112 if (auto refused = trigger_refusal<Client>(amended_trigger_price(instruction))) {
113 return Result<Amendment>(std::move(*refused));
114 }
115 return BrokerTraits<Client>::to_replacement(ref, instruction);
116}
117
118} // namespace port_detail
119
134template <typename Client>
136public:
139
142
144 using Account = typename Traits::Account;
145
147 using Config = typename Traits::Config;
148
150 using BrokerTag = typename Traits::BrokerTag;
151
154
157
160
163
164 static_assert(
165 !Traits::blocking, "BrokerSession requires an asynchronous client; use BlockingSession for a blocking facade"
166 );
167
174 BrokerSession(std::shared_ptr<Client> client, Account account)
175 : client_(std::move(client)), account_(std::move(account)) {
176 if (!client_) {
177 throw std::invalid_argument("broker session requires a client");
178 }
179 }
180
185 static constexpr std::string_view broker_name() noexcept {
186 return Traits::name;
187 }
188
193 const Account& account() const noexcept {
194 return account_;
195 }
196
205 Client& client() noexcept {
206 return *client_;
207 }
208
213 const Client& client() const noexcept {
214 return *client_;
215 }
216
221 const std::shared_ptr<Client>& shared_client() const noexcept {
222 return client_;
223 }
224
239 return Traits::rate_limit_stats(*client_);
240 }
241
243 void close() {
244 client_->close();
245 }
246
256 template <typename CompletionToken>
257 auto async_quote(InstrumentId instrument, CompletionToken&& token) {
258 return translate<QuoteSnapshot>(
259 std::forward<CompletionToken>(token),
260 [client = client_, instrument = std::move(instrument)](auto&& sink) mutable {
261 Traits::quote(*client, std::move(instrument), std::forward<decltype(sink)>(sink));
262 },
263 [](Result<QuoteSnapshot> raw) {
264 return raw;
265 }
266 );
267 }
268
277 template <typename CompletionToken>
278 auto async_holdings(CompletionToken&& token) {
279 return translate<HoldingsSnapshot>(
280 std::forward<CompletionToken>(token),
281 [client = client_, account = account_](auto&& sink) mutable {
282 Traits::holdings(*client, account, std::forward<decltype(sink)>(sink));
283 },
285 return raw;
286 }
287 );
288 }
289
303 template <typename CompletionToken>
304 auto async_buying_power(Currency currency, CompletionToken&& token) {
305 if constexpr (Caps::has_buying_power) {
306 return translate<BuyingPower>(
307 std::forward<CompletionToken>(token),
308 [client = client_, account = account_, currency](auto&& sink) mutable {
309 Traits::buying_power(*client, account, currency, std::forward<decltype(sink)>(sink));
310 },
311 [](Result<BuyingPower> raw) {
312 return raw;
313 }
314 );
315 } else {
316 static_assert(
317 port_detail::dependent_false<Client>,
318 "this broker does not answer what the account may spend; gate the call with "
319 "BrokerCaps<Client>::has_buying_power"
320 );
321 }
322 }
323
336 template <typename CompletionToken>
337 auto async_sellable_quantity(InstrumentId instrument, CompletionToken&& token) {
339 return translate<Decimal64>(
340 std::forward<CompletionToken>(token),
341 [client = client_, account = account_, instrument = std::move(instrument)](auto&& sink) mutable {
342 Traits::sellable_quantity(*client, account, std::move(instrument), std::forward<decltype(sink)>(sink));
343 },
344 [](Result<Decimal64> raw) {
345 return raw;
346 }
347 );
348 } else {
349 static_assert(
350 port_detail::dependent_false<Client>,
351 "this broker has no separate sellable-quantity inquiry; read "
352 "HoldingPosition::sellable_quantity_ from the holdings snapshot, and gate on "
353 "BrokerCaps<Client>::sellable_source"
354 );
355 }
356 }
357
369 template <typename CompletionToken>
370 auto async_commissions(CompletionToken&& token) {
371 if constexpr (Caps::has_commission_schedule) {
372 return translate<CommissionSchedule>(
373 std::forward<CompletionToken>(token),
374 [client = client_, account = account_](auto&& sink) mutable {
375 Traits::commissions(*client, account, std::forward<decltype(sink)>(sink));
376 },
378 return raw;
379 }
380 );
381 } else {
382 static_assert(
383 port_detail::dependent_false<Client>,
384 "this broker publishes no commission schedule; gate the call with "
385 "BrokerCaps<Client>::has_commission_schedule"
386 );
387 }
388 }
389
407 template <typename CompletionToken>
408 auto async_place(OrderRequest order, CompletionToken&& token) {
409 if (auto refused = port_detail::prepare_place<Client>(order)) {
410 return complete_error<Placed>(std::forward<CompletionToken>(token), std::move(*refused));
411 }
412 return translate<Placed>(
413 std::forward<CompletionToken>(token),
414 [client = client_, account = account_, order = std::move(order)](auto&& sink) mutable {
415 Traits::place_order(*client, account, std::move(order), std::forward<decltype(sink)>(sink));
416 },
418 return Traits::normalize_place(std::move(raw));
419 }
420 );
421 }
422
439 template <typename CompletionToken>
440 auto async_replace(Ref ref, AmendInstruction instruction, CompletionToken&& token) {
441 auto amendment = port_detail::prepare_replace<Client>(ref, instruction);
442 if (!amendment) {
443 return complete_error<Placed>(std::forward<CompletionToken>(token), std::move(amendment.error()));
444 }
445 return translate<Placed>(
446 std::forward<CompletionToken>(token),
447 [client = client_, account = account_, value = std::move(amendment.value())](auto&& sink) mutable {
448 Traits::replace_order(*client, account, std::move(value), std::forward<decltype(sink)>(sink));
449 },
451 return Traits::normalize_place(std::move(raw));
452 }
453 );
454 }
455
476 template <typename CompletionToken>
477 auto async_cancel(Ref ref, AmendInstruction instruction, CompletionToken&& token) {
478 auto amendment = Traits::to_cancellation(ref, instruction);
479 if (!amendment) {
480 return complete_error<Placed>(std::forward<CompletionToken>(token), std::move(amendment.error()));
481 }
482 return translate<Placed>(
483 std::forward<CompletionToken>(token),
484 [client = client_, account = account_, value = std::move(amendment.value())](auto&& sink) mutable {
485 Traits::cancel_order(*client, account, std::move(value), std::forward<decltype(sink)>(sink));
486 },
488 return Traits::normalize_place(std::move(raw));
489 }
490 );
491 }
492
504 template <typename CompletionToken>
505 auto async_working_orders(CompletionToken&& token) {
506 if constexpr (Caps::has_working_orders) {
507 return translate<WorkingSet>(
508 std::forward<CompletionToken>(token),
509 [client = client_, account = account_](auto&& sink) mutable {
510 Traits::working_orders(*client, account, std::forward<decltype(sink)>(sink));
511 },
513 return Traits::normalize_working_orders(std::move(raw));
514 }
515 );
516 } else {
517 static_assert(
518 port_detail::dependent_false<Client>,
519 "this broker does not publish its amendable orders; gate the call with "
520 "BrokerCaps<Client>::has_working_orders"
521 );
522 }
523 }
524
535 template <typename CompletionToken>
536 auto async_order_history(OrderHistoryQuery query, CompletionToken&& token) {
537 auto converted = Traits::to_history_query(account_, query);
538 if (!converted) {
539 return complete_error<OrderPage>(std::forward<CompletionToken>(token), std::move(converted.error()));
540 }
541 return translate<OrderPage>(
542 std::forward<CompletionToken>(token),
543 [client = client_, account = account_, value = std::move(converted.value())](auto&& sink) mutable {
544 Traits::order_history(*client, account, std::move(value), std::forward<decltype(sink)>(sink));
545 },
546 [](Result<OrderPage> raw) {
547 return raw;
548 }
549 );
550 }
551
564 template <typename CompletionToken>
565 auto async_bars(BarQuery query, CompletionToken&& token) {
566 if (auto invalid = Traits::validate_bars(query)) {
567 return complete_error<BarSeries>(std::forward<CompletionToken>(token), std::move(*invalid));
568 }
569 return translate<BarSeries>(
570 std::forward<CompletionToken>(token),
571 [client = client_, query = std::move(query)](auto&& sink) mutable {
572 Traits::bars(*client, std::move(query), std::forward<decltype(sink)>(sink));
573 },
574 [](Result<BarSeries> raw) {
575 return raw;
576 }
577 );
578 }
579
592 template <typename CompletionToken>
593 auto async_instrument(InstrumentId instrument, CompletionToken&& token) {
594 if constexpr (Caps::has_reference_data) {
595 return translate<Instrument>(
596 std::forward<CompletionToken>(token),
597 [client = client_, instrument = std::move(instrument)](auto&& sink) mutable {
598 Traits::instrument(*client, std::move(instrument), std::forward<decltype(sink)>(sink));
599 },
600 [](Result<Instrument> raw) {
601 return raw;
602 }
603 );
604 } else {
605 static_assert(
606 port_detail::dependent_false<Client>,
607 "this broker does not publish instrument reference data; gate the call with "
608 "BrokerCaps<Client>::has_reference_data"
609 );
610 }
611 }
612
626 template <typename CompletionToken>
627 auto async_calendar(Country country, std::optional<Date> from, CompletionToken&& token) {
628 if constexpr (Caps::has_calendar) {
629 if (auto invalid = Traits::validate_calendar(country, from)) {
630 return complete_error<TradingCalendar>(std::forward<CompletionToken>(token), std::move(*invalid));
631 }
632 return translate<TradingCalendar>(
633 std::forward<CompletionToken>(token),
634 [client = client_, country, from](auto&& sink) mutable {
635 Traits::calendar(*client, country, from, std::forward<decltype(sink)>(sink));
636 },
638 return raw;
639 }
640 );
641 } else {
642 static_assert(
643 port_detail::dependent_false<Client>,
644 "this broker does not publish a trading calendar; gate the call with "
645 "BrokerCaps<Client>::has_calendar"
646 );
647 }
648 }
649
661 template <typename CompletionToken>
662 auto async_price_limits(InstrumentId instrument, CompletionToken&& token) {
663 if constexpr (Caps::has_price_limits) {
664 return translate<PriceLimits>(
665 std::forward<CompletionToken>(token),
666 [client = client_, instrument = std::move(instrument)](auto&& sink) mutable {
667 Traits::price_limits(*client, std::move(instrument), std::forward<decltype(sink)>(sink));
668 },
669 [](Result<PriceLimits> raw) {
670 return raw;
671 }
672 );
673 } else {
674 static_assert(
675 port_detail::dependent_false<Client>,
676 "this broker does not publish price limits; gate the call with "
677 "BrokerCaps<Client>::has_price_limits"
678 );
679 }
680 }
681
694 template <typename CompletionToken>
695 auto async_trades(InstrumentId instrument, int count, CompletionToken&& token) {
696 if constexpr (Caps::has_trade_prints) {
697 return translate<std::vector<TradePrint>>(
698 std::forward<CompletionToken>(token),
699 [client = client_, instrument = std::move(instrument), count](auto&& sink) mutable {
700 Traits::trades(*client, std::move(instrument), count, std::forward<decltype(sink)>(sink));
701 },
703 return raw;
704 }
705 );
706 } else {
707 static_assert(
708 port_detail::dependent_false<Client>,
709 "this broker does not publish recent executions; gate the call with "
710 "BrokerCaps<Client>::has_trade_prints"
711 );
712 }
713 }
714
726 template <typename CompletionToken>
727 auto async_prices(std::vector<InstrumentId> instruments, CompletionToken&& token) {
728 if constexpr (Caps::has_batch_prices) {
729 return translate<std::vector<QuoteSnapshot>>(
730 std::forward<CompletionToken>(token),
731 [client = client_, instruments = std::move(instruments)](auto&& sink) mutable {
732 Traits::prices(*client, std::move(instruments), std::forward<decltype(sink)>(sink));
733 },
735 return raw;
736 }
737 );
738 } else {
739 static_assert(
740 port_detail::dependent_false<Client>,
741 "this broker quotes one instrument per request; gate the call with "
742 "BrokerCaps<Client>::has_batch_prices and call async_quote per instrument"
743 );
744 }
745 }
746
758 template <typename CompletionToken>
759 auto async_depth(InstrumentId instrument, CompletionToken&& token) {
760 if constexpr (Caps::has_depth) {
761 return translate<DepthSnapshot>(
762 std::forward<CompletionToken>(token),
763 [client = client_, instrument = std::move(instrument)](auto&& sink) mutable {
764 Traits::depth(*client, std::move(instrument), std::forward<decltype(sink)>(sink));
765 },
766 [](Result<DepthSnapshot> raw) {
767 return raw;
768 }
769 );
770 } else {
771 static_assert(
772 port_detail::dependent_false<Client>,
773 "this broker does not publish an order book; gate the call with "
774 "BrokerCaps<Client>::has_depth"
775 );
776 }
777 }
778
790 template <typename CompletionToken>
791 auto async_order(Ref ref, CompletionToken&& token) {
792 if constexpr (Caps::has_order_by_id) {
793 return translate<OrderSnapshot>(
794 std::forward<CompletionToken>(token),
795 [client = client_, account = account_, id = ref.primary_](auto&& sink) mutable {
796 Traits::order_by_id(*client, account, std::move(id), std::forward<decltype(sink)>(sink));
797 },
798 [](Result<OrderSnapshot> raw) {
799 return raw;
800 }
801 );
802 } else {
803 static_assert(
804 port_detail::dependent_false<Client>,
805 "this broker does not retrieve one order by identifier; gate the call with "
806 "BrokerCaps<Client>::has_order_by_id and read the order from "
807 "async_working_orders or async_order_history instead"
808 );
809 }
810 }
811
812private:
813 // Initiates one client call; normalization and the handler run once, on the handler's executor.
814 template <typename Out, typename Token, typename Call, typename Normalize>
815 static auto translate(Token&& token, Call call, Normalize normalize) {
816 return net::async_initiate<Token, void(Result<Out>)>(
817 [call = std::move(call), normalize = std::move(normalize)](auto&& handler) mutable {
818 auto executor = net::get_associated_executor(handler);
819 call(
820 net::bind_executor(
821 executor,
822 [handler = std::forward<decltype(handler)>(handler), normalize = std::move(normalize)](auto raw) mutable {
823 std::move(handler)(normalize(std::move(raw)));
824 }
825 )
826 );
827 },
828 token
829 );
830 }
831
832 // Completes with a pre-flight error, posted (never inline) to the handler's executor, or the
833 // system executor if it has none.
834 template <typename Out, typename Token>
835 static auto complete_error(Token&& token, BrokerError error) {
836 return net::async_initiate<Token, void(Result<Out>)>(
837 [error = std::move(error)](auto&& handler) mutable {
838 auto executor = net::get_associated_executor(handler, net::system_executor());
839 net::post(executor, [handler = std::forward<decltype(handler)>(handler), error = std::move(error)]() mutable {
840 std::move(handler)(Result<Out>(std::move(error)));
841 });
842 },
843 token
844 );
845 }
846
847 std::shared_ptr<Client> client_;
848 Account account_;
849};
850
859template <typename Client>
861public:
864
867
869 using Account = typename Traits::Account;
870
872 using Config = typename Traits::Config;
873
875 using BrokerTag = typename Traits::BrokerTag;
876
879
882
885
888
889 static_assert(
890 Traits::blocking,
891 "BlockingSession requires a blocking client facade; use BrokerSession for an "
892 "asynchronous client"
893 );
894
901 BlockingSession(std::shared_ptr<Client> client, Account account)
902 : client_(std::move(client)), account_(std::move(account)) {
903 if (!client_) {
904 throw std::invalid_argument("broker session requires a client");
905 }
906 }
907
912 static constexpr std::string_view broker_name() noexcept {
913 return Traits::name;
914 }
915
920 const Account& account() const noexcept {
921 return account_;
922 }
923
928 Client& client() noexcept {
929 return *client_;
930 }
931
936 const Client& client() const noexcept {
937 return *client_;
938 }
939
950 return Traits::rate_limit_stats(*client_);
951 }
952
959 return Traits::quote(*client_, std::move(instrument));
960 }
961
967 return Traits::holdings(*client_, account_);
968 }
969
976 if constexpr (Caps::has_buying_power) {
977 return Traits::buying_power(*client_, account_, currency);
978 } else {
979 static_assert(
980 port_detail::dependent_false<Client>,
981 "this broker does not answer what the account may spend; gate the call with "
982 "BrokerCaps<Client>::has_buying_power"
983 );
984 }
985 }
986
994 return Traits::sellable_quantity(*client_, account_, std::move(instrument));
995 } else {
996 static_assert(
997 port_detail::dependent_false<Client>,
998 "this broker has no separate sellable-quantity inquiry; read "
999 "HoldingPosition::sellable_quantity_ from the holdings snapshot, and gate on "
1000 "BrokerCaps<Client>::sellable_source"
1001 );
1002 }
1003 }
1004
1010 if constexpr (Caps::has_commission_schedule) {
1011 return Traits::commissions(*client_, account_);
1012 } else {
1013 static_assert(
1014 port_detail::dependent_false<Client>,
1015 "this broker publishes no commission schedule; gate the call with "
1016 "BrokerCaps<Client>::has_commission_schedule"
1017 );
1018 }
1019 }
1020
1027 if constexpr (Caps::has_reference_data) {
1028 return Traits::instrument(*client_, std::move(subject));
1029 } else {
1030 static_assert(
1031 port_detail::dependent_false<Client>,
1032 "this broker does not publish instrument reference data; gate the call with "
1033 "BrokerCaps<Client>::has_reference_data"
1034 );
1035 }
1036 }
1037
1044 Result<TradingCalendar> calendar(Country country, std::optional<Date> from = std::nullopt) {
1045 if constexpr (Caps::has_calendar) {
1046 if (auto invalid = Traits::validate_calendar(country, from)) {
1047 return Result<TradingCalendar>(std::move(*invalid));
1048 }
1049 return Traits::calendar(*client_, country, from);
1050 } else {
1051 static_assert(
1052 port_detail::dependent_false<Client>,
1053 "this broker does not publish a trading calendar; gate the call with "
1054 "BrokerCaps<Client>::has_calendar"
1055 );
1056 }
1057 }
1058
1065 if constexpr (Caps::has_price_limits) {
1066 return Traits::price_limits(*client_, std::move(instrument));
1067 } else {
1068 static_assert(
1069 port_detail::dependent_false<Client>,
1070 "this broker does not publish price limits; gate the call with "
1071 "BrokerCaps<Client>::has_price_limits"
1072 );
1073 }
1074 }
1075
1083 if constexpr (Caps::has_trade_prints) {
1084 return Traits::trades(*client_, std::move(instrument), count);
1085 } else {
1086 static_assert(
1087 port_detail::dependent_false<Client>,
1088 "this broker does not publish recent executions; gate the call with "
1089 "BrokerCaps<Client>::has_trade_prints"
1090 );
1091 }
1092 }
1093
1099 Result<std::vector<QuoteSnapshot>> prices(std::vector<InstrumentId> instruments) {
1100 if constexpr (Caps::has_batch_prices) {
1101 return Traits::prices(*client_, std::move(instruments));
1102 } else {
1103 static_assert(
1104 port_detail::dependent_false<Client>,
1105 "this broker quotes one instrument per request; gate the call with "
1106 "BrokerCaps<Client>::has_batch_prices and call quote per instrument"
1107 );
1108 }
1109 }
1110
1117 if constexpr (Caps::has_depth) {
1118 return Traits::depth(*client_, std::move(instrument));
1119 } else {
1120 static_assert(
1121 port_detail::dependent_false<Client>,
1122 "this broker does not publish an order book; gate the call with "
1123 "BrokerCaps<Client>::has_depth"
1124 );
1125 }
1126 }
1127
1134 if (auto invalid = Traits::validate_bars(query)) {
1135 return Result<BarSeries>(std::move(*invalid));
1136 }
1137 return Traits::bars(*client_, std::move(query));
1138 }
1139
1152 if (auto refused = port_detail::prepare_place<Client>(order)) {
1153 return Result<Placed>(std::move(*refused));
1154 }
1155 return Traits::normalize_place(Traits::place_order(*client_, account_, std::move(order)));
1156 }
1157
1170 Result<Placed> replace(const Ref& ref, const AmendInstruction& instruction) {
1171 auto amendment = port_detail::prepare_replace<Client>(ref, instruction);
1172 if (!amendment) {
1173 return Result<Placed>(std::move(amendment.error()));
1174 }
1175 return Traits::normalize_place(Traits::replace_order(*client_, account_, std::move(amendment.value())));
1176 }
1177
1191 Result<Placed> cancel(const Ref& ref, const AmendInstruction& instruction) {
1192 auto amendment = Traits::to_cancellation(ref, instruction);
1193 if (!amendment) {
1194 return Result<Placed>(std::move(amendment.error()));
1195 }
1196 return Traits::normalize_place(Traits::cancel_order(*client_, account_, std::move(amendment.value())));
1197 }
1198
1204 if constexpr (Caps::has_working_orders) {
1205 return Traits::normalize_working_orders(Traits::working_orders(*client_, account_));
1206 } else {
1207 static_assert(
1208 port_detail::dependent_false<Client>,
1209 "this broker does not publish its amendable orders; gate the call with "
1210 "BrokerCaps<Client>::has_working_orders"
1211 );
1212 }
1213 }
1214
1221 auto converted = Traits::to_history_query(account_, query);
1222 if (!converted) {
1223 return Result<OrderPage>(std::move(converted.error()));
1224 }
1225 return Traits::order_history(*client_, account_, std::move(converted.value()));
1226 }
1227
1234 if constexpr (Caps::has_order_by_id) {
1235 return Traits::order_by_id(*client_, account_, ref.primary_);
1236 } else {
1237 static_assert(
1238 port_detail::dependent_false<Client>,
1239 "this broker does not retrieve one order by identifier; gate the call with "
1240 "BrokerCaps<Client>::has_order_by_id and read the order from working_orders or "
1241 "order_history instead"
1242 );
1243 }
1244 }
1245
1251 if constexpr (Caps::has_account_discovery) {
1252 return port_detail::to_account_info<Client>(Traits::accounts(*client_));
1253 } else {
1254 static_assert(
1255 port_detail::dependent_false<Client>,
1256 "this broker does not publish selectable accounts; its account selector comes from "
1257 "configuration, so gate the call with BrokerCaps<Client>::has_account_discovery"
1258 );
1259 }
1260 }
1261
1262private:
1263 std::shared_ptr<Client> client_;
1264 Account account_;
1265};
1266
1277template <typename Client, typename CompletionToken>
1278auto async_accounts(Client& client, CompletionToken&& token) {
1280 using Traits = BrokerTraits<Client>;
1281 using Accounts = std::vector<AccountInfo<Client>>;
1282 return net::async_initiate<CompletionToken, void(Result<Accounts>)>(
1283 [&client](auto&& handler) mutable {
1284 auto executor = net::get_associated_executor(handler);
1285 Traits::accounts(
1286 client, net::bind_executor(executor, [handler = std::forward<decltype(handler)>(handler)](auto raw) mutable {
1287 std::move(handler)(port_detail::to_account_info<Client>(std::move(raw)));
1288 })
1289 );
1290 },
1291 token
1292 );
1293 } else {
1294 static_assert(
1295 port_detail::dependent_false<Client>,
1296 "this broker does not publish selectable accounts; its account selector comes from "
1297 "configuration, so gate the call with BrokerCaps<Client>::has_account_discovery"
1298 );
1299 }
1300}
1301
1310template <typename Client>
1313 return port_detail::to_account_info<Client>(BrokerTraits<Client>::accounts(client));
1314 } else {
1315 static_assert(
1316 port_detail::dependent_false<Client>,
1317 "this broker does not publish selectable accounts; its account selector comes from "
1318 "configuration, so gate the call with BrokerCaps<Client>::has_account_discovery"
1319 );
1320 }
1321}
1322
1323namespace port_detail {
1324
1325// An account number without the separators `resolve_account` ignores.
1326inline std::string account_characters(std::string_view number) {
1327 std::string kept;
1328 for (const char c : number) {
1329 if (c != '-' && c != ' ' && c != '.' && c != '/') {
1330 kept.push_back(c);
1331 }
1332 }
1333 return kept;
1334}
1335
1336// A refusal of `resolve_account`.
1337inline BrokerError account_refusal(const char* code, std::string message, bool reached_broker) {
1338 BrokerError error;
1339 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1340 error.reached_broker_ = reached_broker;
1341 error.broker_code_ = code;
1342 error.message_ = std::move(message);
1343 return error;
1344}
1345
1346// Keeps the candidates `number` names; exactly one, with a number, must remain.
1347template <typename Client>
1348Result<AccountInfo<Client>> pick_account(
1349 std::vector<AccountInfo<Client>> candidates, std::string_view number, bool reached_broker
1350) {
1351 using Picked = Result<AccountInfo<Client>>;
1352 if (!number.empty()) {
1353 const auto wanted = account_characters(number);
1354 const auto unwanted = [&wanted](const AccountInfo<Client>& candidate) {
1355 return wanted.empty() || account_characters(candidate.display_number_) != wanted;
1356 };
1357 candidates.erase(std::remove_if(candidates.begin(), candidates.end(), unwanted), candidates.end());
1358 if (candidates.empty()) {
1359 return Picked(account_refusal("account_not_found", "no account has that number", reached_broker));
1360 }
1361 }
1362 if (candidates.size() > 1) {
1363 auto message = std::to_string(candidates.size()) + " accounts; choose one by its number:";
1364 for (const auto& candidate : candidates) {
1365 const auto shown = account_characters(candidate.display_number_);
1366 message += " ..." + shown.substr(shown.size() > 4 ? shown.size() - 4 : 0);
1367 message += candidate.type_.empty() ? std::string(";") : " (" + candidate.type_ + ");";
1368 }
1369 message.pop_back();
1370 return Picked(account_refusal("several_accounts", std::move(message), reached_broker));
1371 }
1372 if (account_characters(candidates.front().display_number_).empty()) {
1373 return Picked(account_refusal("account_without_number", "the account has no number", reached_broker));
1374 }
1375 return Picked(std::move(candidates.front()));
1376}
1377
1378} // namespace port_detail
1379
1398template <typename Client>
1400 Client& client, std::optional<typename BrokerTraits<Client>::Account> configured, std::string_view number = {}
1401) {
1402 using Resolved = Result<AccountInfo<Client>>;
1403 if constexpr (!BrokerTraits<Client>::blocking) {
1404 static_assert(port_detail::dependent_false<Client>, "resolve_account requires a blocking client");
1405 } else if constexpr (BrokerCaps<Client>::data_only) {
1406 static_assert(port_detail::dependent_false<Client>, "resolve_account: a data-only client acts for no account");
1407 } else if constexpr (BrokerCaps<Client>::has_account_discovery) {
1408 if (configured) {
1409 return Resolved(
1410 port_detail::account_refusal(
1411 "account_configured", "this broker lists its accounts, so a configured one is refused: choose by number",
1412 false
1413 )
1414 );
1415 }
1416 auto listed = list_accounts(client);
1417 if (!listed) {
1418 return Resolved(std::move(listed.error()));
1419 }
1420 if (listed.value().empty()) {
1421 return Resolved(port_detail::account_refusal("no_accounts", "the broker lists no account", true));
1422 }
1423 return port_detail::pick_account<Client>(std::move(listed.value()), number, true);
1424 } else {
1425 static_cast<void>(client);
1426 if (!configured) {
1427 return Resolved(port_detail::account_refusal("account_missing", "no account is configured", false));
1428 }
1429 // A braced list is evaluated left to right, so the number is read before the account is moved.
1430 std::vector<AccountInfo<Client>> candidates;
1431 candidates.push_back(
1432 AccountInfo<Client>{BrokerTraits<Client>::display_of(*configured), {}, std::move(*configured)}
1433 );
1434 return port_detail::pick_account<Client>(std::move(candidates), number, false);
1435 }
1436}
1437
1438} // namespace algotradelib
WorkingOrder< BrokerTag > Working
One working order of this broker.
Result< OrderPage > order_history(const OrderHistoryQuery &query)
Returns order history: placed orders and their executions.
Result< Placed > place(OrderRequest order)
Places a new order.
Result< WorkingSet > working_orders()
Returns the orders still open to modification or cancellation; requires Caps::has_working_orders.
typename Traits::Config Config
The broker's configuration type.
typename Traits::Account Account
The broker's account selector type.
Result< OrderSnapshot > order(const Ref &ref)
Returns one order by its reference; requires Caps::has_order_by_id.
Result< BarSeries > bars(BarQuery query)
Returns bars for an instrument, oldest first, paging until count_ bars are read.
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns the current quote for an instrument.
Result< Placed > replace(const Ref &ref, const AmendInstruction &instruction)
Modifies a working order.
BrokerCaps< Client > Caps
The client's capabilities.
Result< PriceLimits > price_limits(InstrumentId instrument)
Returns an instrument's price limits for today; requires Caps::has_price_limits.
Result< std::vector< TradePrint > > trades(InstrumentId instrument, int count)
Returns recent trades for an instrument, newest first; requires Caps::has_trade_prints.
Result< BuyingPower > buying_power(Currency currency)
Returns what the account may spend in a currency; requires Caps::has_buying_power.
Result< Placed > cancel(const Ref &ref, const AmendInstruction &instruction)
Cancels a working order, in full or in part.
Result< HoldingsSnapshot > holdings()
Returns the account's holdings.
const Client & client() const noexcept
Returns the broker client.
Result< Decimal64 > sellable_quantity(InstrumentId instrument)
Returns how much of an instrument the account may sell; only where Caps::sellable_source is INQUIRY.
const network::RateLimitStats * rate_limit_stats() const
Returns the client's request-pacing counters.
Client & client() noexcept
Returns the broker client, for broker-specific operations the session does not offer.
OrderRef< BrokerTag > Ref
The order reference type this session issues and accepts.
Result< DepthSnapshot > depth(InstrumentId instrument)
Returns an instrument's order book, best levels first; requires Caps::has_depth.
Result< TradingCalendar > calendar(Country country, std::optional< Date > from=std::nullopt)
Returns the trading calendar; requires Caps::has_calendar.
Result< CommissionSchedule > commissions()
Returns the account's commission rates; requires Caps::has_commission_schedule.
const Account & account() const noexcept
Returns the bound account.
BrokerTraits< Client > Traits
The client's traits.
static constexpr std::string_view broker_name() noexcept
Returns the broker's name.
WorkingOrders< BrokerTag > WorkingSet
A working-order listing of this broker.
BlockingSession(std::shared_ptr< Client > client, Account account)
Binds a blocking client and an account.
PlacedOrder< BrokerTag > Placed
What an order-writing call returns: acknowledgement and reference.
typename Traits::BrokerTag BrokerTag
The broker's tag type.
Result< std::vector< QuoteSnapshot > > prices(std::vector< InstrumentId > instruments)
Returns quotes for several instruments in one request; requires Caps::has_batch_prices.
Result< Instrument > instrument(InstrumentId subject)
Returns an instrument's reference data; requires Caps::has_reference_data.
Result< std::vector< AccountInfo< Client > > > accounts()
Lists the broker's accounts; requires Caps::has_account_discovery.
auto async_quote(InstrumentId instrument, CompletionToken &&token)
Requests the current quote for an instrument.
const network::RateLimitStats * rate_limit_stats() const
Returns the client's request-pacing counters.
auto async_order_history(OrderHistoryQuery query, CompletionToken &&token)
Requests order history: placed orders and their executions.
PlacedOrder< BrokerTag > Placed
What an order-writing call returns: acknowledgement and reference.
BrokerSession(std::shared_ptr< Client > client, Account account)
Binds a client and an account.
OrderRef< BrokerTag > Ref
The order reference type this session issues and accepts.
auto async_place(OrderRequest order, CompletionToken &&token)
Places a new order.
auto async_bars(BarQuery query, CompletionToken &&token)
Requests bars for an instrument, paging until count_ bars are read.
auto async_sellable_quantity(InstrumentId instrument, CompletionToken &&token)
Requests how much of an instrument the account may sell.
typename Traits::BrokerTag BrokerTag
The broker's tag type.
auto async_buying_power(Currency currency, CompletionToken &&token)
Requests what the account may spend in a currency.
BrokerCaps< Client > Caps
The client's capabilities.
auto async_price_limits(InstrumentId instrument, CompletionToken &&token)
Requests an instrument's price limits for today.
static constexpr std::string_view broker_name() noexcept
Returns the broker's name.
Client & client() noexcept
Returns the broker client, for broker-specific operations the session does not offer.
auto async_replace(Ref ref, AmendInstruction instruction, CompletionToken &&token)
Modifies a working order.
void close()
Cancels the client's transport work and queued operations.
typename Traits::Config Config
The broker's configuration type.
auto async_commissions(CompletionToken &&token)
Requests the account's commission rates.
typename Traits::Account Account
The broker's account selector type.
auto async_instrument(InstrumentId instrument, CompletionToken &&token)
Requests an instrument's reference data.
const std::shared_ptr< Client > & shared_client() const noexcept
Returns the shared client pointer, for binding a second session.
auto async_holdings(CompletionToken &&token)
Requests the account's holdings.
auto async_working_orders(CompletionToken &&token)
Requests the orders still open to modification or cancellation.
auto async_trades(InstrumentId instrument, int count, CompletionToken &&token)
Requests recent trades for an instrument, newest first.
WorkingOrder< BrokerTag > Working
One working order of this broker.
const Account & account() const noexcept
Returns the bound account.
const Client & client() const noexcept
Returns the broker client.
auto async_order(Ref ref, CompletionToken &&token)
Requests one order by its reference.
WorkingOrders< BrokerTag > WorkingSet
A working-order listing of this broker.
BrokerTraits< Client > Traits
The client's traits.
auto async_prices(std::vector< InstrumentId > instruments, CompletionToken &&token)
Requests quotes for several instruments in one request.
auto async_cancel(Ref ref, AmendInstruction instruction, CompletionToken &&token)
Cancels a working order, in full or in part.
auto async_calendar(Country country, std::optional< Date > from, CompletionToken &&token)
Requests the trading calendar.
auto async_depth(InstrumentId instrument, CompletionToken &&token)
Requests an instrument's order book, best levels first.
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
The library: broker-neutral types (core), and the modules below.
auto async_accounts(Client &client, CompletionToken &&token)
Lists a broker's accounts, before a session exists; requires BrokerCaps<Client>::has_account_discover...
Result< std::vector< AccountInfo< Client > > > list_accounts(Client &client)
Lists a broker's accounts with a blocking client, before a session exists; requires BrokerCaps<Client...
@ INQUIRY
From a per-instrument inquiry, made only where the snapshot has no figure.
Definition types.hpp:1366
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
Result< AccountInfo< Client > > resolve_account(Client &client, std::optional< typename BrokerTraits< Client >::Account > configured, std::string_view number={})
Names the one account a session should bind, or refuses; never guesses.
Country
A country (market) the library supports.
Definition types.hpp:32
std::optional< Decimal64 > amended_trigger_price(const AmendInstruction &instruction)
Returns the trigger price an amendment leaves the order with.
Definition types.hpp:2563
One account from a broker's account list.
A modification or cancellation of a working order.
Definition types.hpp:2532
What bars to fetch.
What one broker client implements, as compile-time constants.
static constexpr bool has_commission_schedule
Whether the broker publishes the account's commission rates.
static constexpr bool has_batch_prices
Whether the broker quotes several instruments in one request.
static constexpr bool has_price_limits
Whether the broker publishes the day's price limits.
static constexpr bool has_account_discovery
Whether the broker lists the selectable accounts.
static constexpr SellableSource sellable_source
Where the library gets the sellable quantity: HOLDINGS costs nothing, INQUIRY one request per instrum...
static constexpr bool has_reference_data
Whether the broker publishes instrument reference data.
static constexpr bool has_calendar
Whether the broker publishes the trading calendar.
static constexpr bool has_trade_prints
Whether the broker publishes recent trades.
static constexpr bool has_buying_power
Whether the broker reports buying power.
static constexpr bool has_order_by_id
Whether the broker can look up one order by its id.
static constexpr bool data_only
Whether the client is a market-data source that takes no orders (built on DataOnlyTraits).
static constexpr bool has_trigger_price
Whether the adapter sends trigger prices (stop-limit orders).
static constexpr bool has_depth
Whether the broker publishes the order book (depth).
static constexpr bool has_working_orders
Whether the broker lists the orders still open to amendment. A listing shows only what the broker's A...
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
The filter for an order-history inquiry.
Definition types.hpp:2617
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
An order still open to modification or cancellation.
Definition types.hpp:2582
The orders open to modification or cancellation at one point in time.
Definition types.hpp:2604
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...