algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
client.hpp
1#pragma once
2
3#include "./market.hpp"
4
5#include <deque>
6#include <stdexcept>
7#include <string>
8#include <utility>
9
10namespace algotradelib {
11namespace mock {
12
14struct MockAccount {};
15
19 std::string order_id_;
20};
21
45
54public:
59 explicit MockClient(Market& market) : market_(&market) {}
60
65 static constexpr std::string_view environment() noexcept {
66 return mock::environment;
67 }
68
73 Market& market() const noexcept {
74 return *market_;
75 }
76
88 void fail_next(Call call, BrokerError error, int times = 1) {
89 if (times < 1) {
90 throw std::invalid_argument("a fault is scripted for at least one call");
91 }
92 for (int k = 0; k < times; ++k) {
93 faults_.push_back(Fault{call, error, Effect::FAIL});
94 }
95 }
96
105 if (call != Call::PLACE && call != Call::CANCEL) {
106 throw std::invalid_argument("only a placement or a cancellation has a reply to lose");
107 }
108 BrokerError error;
110 error.reached_broker_ = true;
111 error.broker_code_ = "reply_lost";
112 error.message_ = "the mock broker carried this out and lost the reply";
113 faults_.push_back(Fault{call, std::move(error), Effect::CARRY_OUT});
114 }
115
129 void repeat_last(Call call, int times = 1) {
130 if (
131 call != Call::HOLDINGS && call != Call::BUYING_POWER && call != Call::WORKING_ORDERS &&
132 call != Call::ORDER_HISTORY
133 ) {
134 throw std::invalid_argument("only a read of the account's state can be repeated");
135 }
136 if (times < 1) {
137 throw std::invalid_argument("a fault is scripted for at least one call");
138 }
139 for (int k = 0; k < times; ++k) {
140 faults_.push_back(Fault{call, BrokerError{}, Effect::REPEAT});
141 }
142 }
143
150 if (auto fault = take(Call::QUOTE)) {
151 return Result<QuoteSnapshot>(std::move(fault->error_));
152 }
153 return market_->quote(instrument);
154 }
155
162 if (auto fault = take(Call::INSTRUMENT)) {
163 return Result<Instrument>(std::move(fault->error_));
164 }
165 return market_->instrument(instrument);
166 }
167
174 if (auto fault = take(Call::CALENDAR)) {
175 return Result<TradingCalendar>(std::move(fault->error_));
176 }
177 return market_->calendar(country);
178 }
179
186 if (auto fault = take(Call::BARS)) {
187 return Result<BarSeries>(std::move(fault->error_));
188 }
189 return market_->bars(query);
190 }
191
197 return read(Call::HOLDINGS, last_holdings_, [this] {
198 return market_->holdings();
199 });
200 }
201
208 if (last_buying_power_ && !(last_buying_power_->cash_.currency_ == currency)) {
209 last_buying_power_.reset();
210 }
211 return read(Call::BUYING_POWER, last_buying_power_, [&] {
212 return market_->buying_power(currency);
213 });
214 }
215
222 auto fault = take(Call::PLACE);
223 if (fault && fault->effect_ == Effect::FAIL) {
224 return Result<PlacedOrder<Broker>>(std::move(fault->error_));
225 }
226 auto placed = market_->place(order);
227 if (fault) {
228 return Result<PlacedOrder<Broker>>(std::move(fault->error_));
229 }
230 return placed;
231 }
232
239 auto fault = take(Call::CANCEL);
240 if (fault && fault->effect_ == Effect::FAIL) {
241 return Result<PlacedOrder<Broker>>(std::move(fault->error_));
242 }
243 auto canceled = market_->cancel(amendment.order_id_);
244 if (fault) {
245 return Result<PlacedOrder<Broker>>(std::move(fault->error_));
246 }
247 return canceled;
248 }
249
255 return read(Call::WORKING_ORDERS, last_working_orders_, [this] {
256 return Result<WorkingOrders<Broker>>(market_->working_orders());
257 });
258 }
259
266 return read(Call::ORDER_HISTORY, last_history_, [&] {
267 return Result<OrderPage>(market_->order_history(query));
268 });
269 }
270
271private:
273 enum class Effect {
275 FAIL,
277 CARRY_OUT,
279 REPEAT,
280 };
281
283 struct Fault {
285 Call call_;
287 BrokerError error_;
289 Effect effect_;
290 };
291
293 template <typename T, typename Ask>
294 Result<T> read(Call call, std::optional<T>& last, Ask ask) {
295 auto fault = take(call);
296 if (fault && fault->effect_ == Effect::FAIL) {
297 return Result<T>(std::move(fault->error_));
298 }
299 if (fault && last) {
300 auto repeated = *last;
301 repeated.received_at_ = market_->now();
302 return Result<T>(std::move(repeated));
303 }
304 auto answer = ask();
305 if (answer) {
306 last = answer.value();
307 }
308 return answer;
309 }
310
312 std::optional<Fault> take(Call call) {
313 for (auto it = faults_.begin(); it != faults_.end(); ++it) {
314 if (it->call_ == call) {
315 auto fault = std::move(*it);
316 faults_.erase(it);
317 return fault;
318 }
319 }
320 return std::nullopt;
321 }
322
323 Market* market_;
324 std::deque<Fault> faults_;
325 std::optional<HoldingsSnapshot> last_holdings_;
326 std::optional<BuyingPower> last_buying_power_;
327 std::optional<WorkingOrders<Broker>> last_working_orders_;
328 std::optional<OrderPage> last_history_;
329};
330
331} // namespace mock
332} // namespace algotradelib
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
A market in memory: bars the caller gives, a clock the caller moves, one account's cash,...
Definition market.hpp:143
Result< HoldingsSnapshot > holdings()
Answers a holdings request.
Definition client.hpp:196
Result< Instrument > instrument(const InstrumentId &instrument)
Answers a reference-data request.
Definition client.hpp:161
Result< TradingCalendar > calendar(Country country)
Answers a calendar request.
Definition client.hpp:173
MockClient(Market &market)
Builds a client over a market.
Definition client.hpp:59
Market & market() const noexcept
Returns the market.
Definition client.hpp:73
void fail_next(Call call, BrokerError error, int times=1)
Answers the next calls of a kind with an error instead of asking the market.
Definition client.hpp:88
void lose_next_reply(Call call)
Carries out the next placement or cancellation in the market, then answers it with a transport error ...
Definition client.hpp:104
Result< OrderPage > order_history(const OrderHistoryQuery &query)
Answers an order-history request.
Definition client.hpp:265
Result< PlacedOrder< Broker > > cancel(const MockAmendment &amendment)
Cancels an order.
Definition client.hpp:238
static constexpr std::string_view environment() noexcept
Returns the environment this client trades in.
Definition client.hpp:65
Result< WorkingOrders< Broker > > working_orders()
Answers a working-order request.
Definition client.hpp:254
Result< PlacedOrder< Broker > > place(const OrderRequest &order)
Places an order.
Definition client.hpp:221
Result< BuyingPower > buying_power(const Currency &currency)
Answers a buying-power request.
Definition client.hpp:207
Result< BarSeries > bars(const BarQuery &query)
Answers a bar request.
Definition client.hpp:185
Result< QuoteSnapshot > quote(const InstrumentId &instrument)
Answers a quote request.
Definition client.hpp:149
void repeat_last(Call call, int times=1)
Answers the next reads of an account's state with what the last one answered, stamped now,...
Definition client.hpp:129
The mock broker: an in-memory market over bars the caller gives, bound like any broker.
Definition client.hpp:11
Call
A call to the mock broker, for scripting a fault (MockClient::fail_next).
Definition client.hpp:23
@ ORDER_HISTORY
order_history.
Definition client.hpp:43
@ WORKING_ORDERS
working_orders.
Definition client.hpp:41
@ BUYING_POWER
buying_power.
Definition client.hpp:35
@ INSTRUMENT
instrument.
Definition client.hpp:29
constexpr std::string_view environment
The environment the mock reports: always "mock", never "demo" or "real".
Definition market.hpp:42
The library: broker-neutral types (core), and the modules below.
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
Definition types.hpp:952
Country
A country (market) the library supports.
Definition types.hpp:32
What bars to fetch.
The error a broker or transport operation returns.
Definition types.hpp:1003
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:1033
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:1022
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:1014
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
The filter for an order-history inquiry.
Definition types.hpp:2617
An order to place, in broker-neutral form.
Definition types.hpp:2216
The mock broker's one account; it has no selector.
Definition client.hpp:14
A cancellation for the mock broker: the order id.
Definition client.hpp:17
std::string order_id_
The order id.
Definition client.hpp:19