algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
reconcile.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "./intent.hpp"
4#include "./portfolio.hpp"
5
6#include <algotradelib/core>
7
8#include <optional>
9#include <string>
10#include <utility>
11#include <vector>
12
13namespace algotradelib {
14namespace strategy {
15
27
95
101inline constexpr std::string_view reject_reason_name(RejectReason reason) noexcept {
102 switch (reason) {
104 return "no_reference_data";
106 return "unknown_price_grid";
108 return "no_price_available";
110 return "no_portfolio_value";
112 return "quantity_rounds_to_zero";
114 return "not_representable";
116 return "no_permitted_price";
118 return "broker_refused";
120 return "binding_refused";
122 return "trigger_off_grid";
124 return "stop_order_resting";
126 return "unsupported_weight";
128 return "negative_size";
129 }
130 return "unknown";
131}
132
142
191
200template <typename Broker>
201struct Plan {
203 std::vector<OrderRef<Broker>> cancel_;
205 std::vector<PlannedOrder> place_;
207 std::vector<Rejection> rejected_;
208
213 bool empty() const noexcept {
214 return cancel_.empty() && place_.empty() && rejected_.empty();
215 }
216};
217
235 std::optional<Decimal64> minimum_quantity_;
237 std::optional<Decimal64> minimum_notional_;
242 std::optional<Decimal64> minimum_fraction_of_working_;
243
248 bool stated() const noexcept {
249 return minimum_quantity_.has_value() || minimum_notional_.has_value() || minimum_fraction_of_working_.has_value();
250 }
251};
252
260 const Instrument* instrument_{nullptr};
262 std::optional<Decimal64> reference_price_;
264 std::optional<PriceLimits> limits_;
266 std::optional<Decimal64> portfolio_value_;
267
275 std::optional<Currency> portfolio_value_currency_;
290 const PortfolioRows* rows_{nullptr};
291};
292
293namespace reconcile_detail {
294
295// One instrument's working rows in a portfolio, in their order: from the pass's index when there is one, else
296// by a scan that skips every other instrument's rows. Iterated like the rows themselves.
297template <typename Broker>
298class WorkingRowsOf {
299public:
300 WorkingRowsOf(const Portfolio<Broker>& portfolio, const PortfolioRows* rows, const InstrumentId& instrument)
301 : working_(&portfolio.working_), instrument_(&instrument) {
302 if (rows != nullptr) {
303 const auto* found = rows->of(instrument);
304 places_ = found != nullptr ? &found->working_ : &none_;
305 }
306 }
307
308 class iterator {
309 public:
310 const WorkingOrder<Broker>& operator*() const {
311 return (*owner_->working_)[at_];
312 }
313 iterator& operator++() {
314 ++step_;
315 settle();
316 return *this;
317 }
318 friend bool operator!=(const iterator& lhs, const iterator& rhs) {
319 return lhs.step_ != rhs.step_;
320 }
321
322 private:
323 friend class WorkingRowsOf;
324 iterator(const WorkingRowsOf* owner, std::size_t step) : owner_(owner), step_(step) {
325 settle();
326 }
327 // Points `at_` at the row for `step_`: the step-th indexed place, or the next row of the instrument.
328 void settle() {
329 if (owner_->places_ != nullptr) {
330 if (step_ < owner_->places_->size()) {
331 at_ = (*owner_->places_)[step_];
332 }
333 return;
334 }
335 while (
336 step_ < owner_->working_->size() && !((*owner_->working_)[step_].order_.instrument_ == *owner_->instrument_)
337 ) {
338 ++step_;
339 }
340 at_ = step_;
341 }
342 const WorkingRowsOf* owner_;
343 std::size_t step_;
344 std::size_t at_{0};
345 };
346
347 iterator begin() const {
348 return iterator(this, 0);
349 }
350 iterator end() const {
351 return iterator(this, places_ != nullptr ? places_->size() : working_->size());
352 }
353
354 // What the rows still have to fill on `side`, as `Portfolio::working_quantity` sums it.
355 Decimal64 working_quantity(OrderSide side) const {
356 auto total = Decimal64(0, 0);
357 for (const auto& order : *this) {
358 portfolio_detail::add_working(total, order, side);
359 }
360 return total;
361 }
362
363private:
364 const std::vector<WorkingOrder<Broker>>* working_;
365 const InstrumentId* instrument_;
366 const std::vector<std::size_t>* places_{nullptr};
367 static inline const std::vector<std::size_t> none_{};
368};
369
370// An instrument's net quantity, as `Portfolio::net_quantity_of` sums it, from the pass's index when there is one.
371template <typename Broker>
372std::optional<Decimal64> net_quantity(
373 const Portfolio<Broker>& portfolio, const PortfolioRows* rows, const InstrumentId& instrument
374) {
375 if (rows == nullptr) {
376 return portfolio.net_quantity_of(instrument);
377 }
378 auto total = Decimal64(0, 0);
379 if (const auto* found = rows->of(instrument)) {
380 for (const auto at : found->positions_) {
381 if (!portfolio_detail::add_net(total, portfolio.positions_[at])) {
382 return std::nullopt;
383 }
384 }
385 }
386 return total;
387}
388
390inline std::optional<Decimal64> lot_of(const Instrument& instrument) {
391 if (!instrument.lot_size_) {
392 return std::nullopt;
393 }
394 if (instrument.lot_size_->coefficient() <= 0) {
395 return std::nullopt;
396 }
397 return instrument.lot_size_;
398}
399
412inline std::optional<Decimal64> round_to_lot(
413 const Decimal64& quantity, const std::optional<Decimal64>& lot, bool& adjusted
414) {
415 adjusted = false;
416 if (!lot) {
417 return quantity;
418 }
419 const auto rounded = decimal_floor_to_multiple(quantity, *lot);
420 if (!rounded) {
421 return std::nullopt;
422 }
423 adjusted = !(*rounded == quantity);
424 return rounded;
425}
426
438inline std::optional<Decimal64> clamp_to_limits(
439 const Decimal64& price, OrderSide side, const std::optional<PriceLimits>& limits, bool& adjusted
440) {
441 adjusted = false;
442 if (!limits) {
443 return price;
444 }
445 if (side == OrderSide::BUY && limits->upper_ && decimal_less(*limits->upper_, price)) {
446 adjusted = true;
447 return limits->upper_;
448 }
449 if (side == OrderSide::SELL && limits->lower_ && decimal_less(price, *limits->lower_)) {
450 adjusted = true;
451 return limits->lower_;
452 }
453 return price;
454}
455
464inline std::optional<Decimal64> prepare_price(
465 const Decimal64& wanted, OrderSide side, const PriceRule& rule, const std::optional<PriceLimits>& limits,
466 bool& clamped, bool& rounded
467) {
468 const auto within = clamp_to_limits(wanted, side, limits, clamped);
469 if (!within) {
470 return std::nullopt;
471 }
472 const auto on_grid = rule.round_to_tick(*within, side);
473 if (!on_grid) {
474 return std::nullopt;
475 }
476 rounded = !(*on_grid == *within);
477 return on_grid;
478}
479
487inline bool rounded_out_of_band(
488 const Decimal64& wanted, const Decimal64& priced, OrderSide side, const std::optional<PriceLimits>& limits
489) {
490 if (!limits) {
491 return false;
492 }
493 if (side == OrderSide::BUY) {
494 return limits->lower_ && decimal_less(priced, *limits->lower_) && !decimal_less(wanted, *limits->lower_);
495 }
496 return limits->upper_ && decimal_less(*limits->upper_, priced) && !decimal_less(*limits->upper_, wanted);
497}
498
506inline bool below_tolerance(const Decimal64& drift, const Decimal64& already_working, const ReconcileInputs& inputs) {
507 const auto& tolerance = inputs.tolerance_;
508
509 if (tolerance.minimum_quantity_ && decimal_less(drift, *tolerance.minimum_quantity_)) {
510 return true;
511 }
512
513 if (tolerance.minimum_notional_ && inputs.reference_price_) {
514 const auto value = decimal_multiply(drift, *inputs.reference_price_);
515 if (value && decimal_less(*value, *tolerance.minimum_notional_)) {
516 return true;
517 }
518 }
519
520 // Only meaningful against something resting: with nothing working there is no queue position to
521 // give up, so a drift is simply a new order and this floor has nothing to say about it.
522 if (tolerance.minimum_fraction_of_working_ && already_working.coefficient() > 0) {
523 // Six places, which resolves a fraction far finer than any threshold an operator would state.
524 const auto fraction = decimal_divide(drift, already_working, 6);
525 if (fraction && decimal_less(*fraction, *tolerance.minimum_fraction_of_working_)) {
526 return true;
527 }
528 }
529
530 return false;
531}
532
533} // namespace reconcile_detail
534
541inline bool is_stop_order(const OrderSnapshot& order) {
542 return carries_trigger_price(order.type_) || order.trigger_price_.has_value();
543}
544
572template <typename Broker>
574 const TargetPosition& target, const Portfolio<Broker>& portfolio, const ReconcileInputs& inputs
575) {
576 Plan<Broker> plan;
577 const auto reject = [&](RejectReason reason) {
578 plan.cancel_.clear();
579 plan.place_.clear();
580 plan.rejected_.push_back(Rejection{reason, target.instrument_, target.tag_});
581 return plan;
582 };
583
584 if (inputs.instrument_ == nullptr) {
585 return reject(RejectReason::NO_REFERENCE_DATA);
586 }
587
588 const auto zero = Decimal64(0, 0);
589 // Net across every position row, as the guards read it: a holding can be split across lots.
590 const auto net = reconcile_detail::net_quantity(portfolio, inputs.rows_, target.instrument_);
591 // This instrument's working rows, in order; the loops below read only these.
592 const reconcile_detail::WorkingRowsOf<Broker> rows(portfolio, inputs.rows_, target.instrument_);
593 if (!net) {
594 // A snapshot whose own rows will not add up cannot say what reaching a target would take, and
595 // `value_or(zero)` here would read a broken listing as flat and order the whole target.
596 return reject(RejectReason::NOT_REPRESENTABLE);
597 }
598 const auto held = *net;
599 const auto needed = decimal_subtract(target.target_quantity_, held);
600 if (!needed) {
601 return reject(RejectReason::NOT_REPRESENTABLE);
602 }
603
604 const bool buying = decimal_less(zero, *needed);
605 const bool selling = decimal_less(*needed, zero);
606 // A sale whose coefficient is INT64_MIN has no positive size: read as zero, it would return an empty plan, as if
607 // the target were met. Checked before the stops, so a target that cannot be sized withdraws nothing.
608 const auto magnitude = buying ? std::optional<Decimal64>(*needed) : decimal_subtract(zero, *needed);
609 if (!magnitude) {
610 return reject(RejectReason::NOT_REPRESENTABLE);
611 }
612
613 // **Stops first; see `RejectReason::STOP_ORDER_RESTING`.** A row is a stop when its basis says so
614 // or it carries a trigger -- an adapter records a positive trigger even on a row whose basis reads
615 // otherwise, and that row may be a released stop.
616 const auto is_stop = [](const OrderSnapshot& order) {
617 return is_stop_order(order);
618 };
619 bool stop_resting = false;
620 for (const auto& working : rows) {
621 if (
622 working.order_.instrument_ == target.instrument_ && order_is_open(working.order_.status_) &&
623 is_stop(working.order_)
624 ) {
625 stop_resting = true;
626 }
627 }
628 if (stop_resting) {
629 const bool met = !buying && !selling;
630 for (const auto& working : rows) {
631 if (!(working.order_.instrument_ == target.instrument_) || !order_is_open(working.order_.status_)) {
632 continue;
633 }
634 if (is_stop(working.order_)) {
635 // Withdrawn only when a trade is needed, and not again once its withdrawal is pending: a
636 // second request for an order already on its way out can only fail.
637 if (!met && !order_status_cancel_pending(working.order_.status_)) {
638 plan.cancel_.push_back(working.ref_);
639 }
640 } else if (met) {
641 // The holding meets the target, so every *other* working order is unwanted, as before.
642 plan.cancel_.push_back(working.ref_);
643 }
644 }
645 if (!met) {
647 }
648 return plan;
649 }
650
651 // Step 2: withdraw what works against the target. With nothing needed, that is everything.
652 //
653 // Only orders that can still trade are withdrawn. A snapshot may carry an order that has since
654 // filled or been cancelled, and asking a broker to cancel one of those is a request that can
655 // only fail -- noise on a path where a real cancellation failure has to be noticed.
656 for (const auto& working : rows) {
657 if (!(working.order_.instrument_ == target.instrument_) || !order_is_open(working.order_.status_)) {
658 continue;
659 }
660 const bool opposes = (buying && working.order_.side_ == OrderSide::SELL) ||
661 (selling && working.order_.side_ == OrderSide::BUY) || (!buying && !selling);
662 if (opposes) {
663 plan.cancel_.push_back(working.ref_);
664 }
665 }
666 if (!buying && !selling) {
667 return plan;
668 }
669
670 const OrderSide side = buying ? OrderSide::BUY : OrderSide::SELL;
671 const auto already = rows.working_quantity(side);
672
673 // Step 3: only the part not already in the market.
674 auto remaining = decimal_subtract(*magnitude, already);
675 if (!remaining) {
676 return reject(RejectReason::NOT_REPRESENTABLE);
677 }
678
679 // Step 3a: a drift smaller than the tolerance is not worth an instruction.
680 //
681 // Measured on the *drift* -- how far the in-flight position is from the target -- and not on what
682 // would be sent. Those differ exactly in the case the tolerance exists for: 100 working against a
683 // target of 99 would withdraw the side and re-place 99, so the quantity sent is 99 while the drift
684 // is one share.
685 //
686 // Suppressed only when nothing has already been queued for cancellation. An order working the
687 // *wrong way* still has to be withdrawn however small the drift, because leaving it resting works
688 // against the target rather than merely failing to reach it. And returning an empty plan rather
689 // than the accumulated one matters for the same reason: withdrawing a working order and then
690 // declining to replace it would leave the position further from the target than doing nothing.
691 if (inputs.tolerance_.stated() && plan.cancel_.empty()) {
692 const auto drift =
693 decimal_less(*remaining, zero) ? decimal_subtract(zero, *remaining) : std::optional<Decimal64>(*remaining);
694 if (drift && reconcile_detail::below_tolerance(*drift, already, inputs)) {
695 return Plan<Broker>{};
696 }
697 }
698
699 // Step 4: more working than wanted, so withdraw the side and send the whole remainder -- net of what
700 // this runner reserved for its own orders not yet shown by holdings, when those may have filled
701 // (`ReconcileInputs::reserved_rows_are_unconfirmed_`): their withdrawal is refused if they did, and a
702 // whole remainder beside them traded twice. One genuinely resting is withdrawn all the same;
703 // its history settles what it filled, and a later pass places the rest.
704 if (decimal_less(*remaining, zero)) {
705 Decimal64 reserved = zero;
706 for (const auto& working : rows) {
707 if (
708 working.order_.instrument_ == target.instrument_ && working.order_.side_ == side &&
709 order_is_open(working.order_.status_)
710 ) {
711 plan.cancel_.push_back(working.ref_);
712 if (inputs.reserved_rows_are_unconfirmed_ && working.reserved_) {
713 // A sum that will not compute refuses: undercounted, it would size the replacement larger.
714 const auto left = decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
715 if (!left) {
716 return reject(RejectReason::NOT_REPRESENTABLE);
717 }
718 if (decimal_less(zero, *left)) {
719 const auto sum = decimal_add(reserved, *left);
720 if (!sum) {
721 return reject(RejectReason::NOT_REPRESENTABLE);
722 }
723 reserved = *sum;
724 }
725 }
726 }
727 }
728 remaining = decimal_subtract(*magnitude, reserved);
729 if (!remaining) {
730 return reject(RejectReason::NOT_REPRESENTABLE);
731 }
732 if (!decimal_less(zero, *remaining)) {
733 return plan;
734 }
735 }
736 if (remaining->coefficient() == 0) {
737 return plan;
738 }
739
740 PlannedOrder order;
741 order.instrument_ = target.instrument_;
742 order.side_ = side;
744 order.tag_ = target.tag_;
745
746 const auto lot = reconcile_detail::lot_of(*inputs.instrument_);
747 const auto sized = reconcile_detail::round_to_lot(*remaining, lot, order.quantity_rounded_);
748 if (!sized) {
749 return reject(RejectReason::NOT_REPRESENTABLE);
750 }
751 if (sized->coefficient() == 0) {
752 // Rounded away entirely. A rejection rather than an empty plan, because the strategy asked
753 // for something and is getting nothing; silence here would look like a met target.
755 }
756 order.quantity_ = *sized;
757
758 if (target.limit_) {
759 const auto priced = reconcile_detail::prepare_price(
760 target.limit_->value(), side, inputs.instrument_->price_rule_, inputs.limits_, order.price_clamped_,
761 order.price_rounded_
762 );
763 if (!priced) {
765 }
766 if (reconcile_detail::rounded_out_of_band(target.limit_->value(), *priced, side, inputs.limits_)) {
768 }
769 order.type_ = OrderType::LIMIT;
770 order.price_ = priced;
771 } else {
772 order.type_ = OrderType::MARKET;
773 }
774
775 plan.place_.push_back(std::move(order));
776 return plan;
777}
778
795template <typename Broker>
796Plan<Broker> reconcile(const OrderIntent& intent, const Portfolio<Broker>& portfolio, const ReconcileInputs& inputs) {
797 (void)portfolio;
798 Plan<Broker> plan;
799 const auto reject = [&](RejectReason reason) {
800 plan.place_.clear();
801 plan.rejected_.push_back(Rejection{reason, intent.instrument(), intent.tag()});
802 return plan;
803 };
804
805 if (inputs.instrument_ == nullptr) {
806 return reject(RejectReason::NO_REFERENCE_DATA);
807 }
808
809 // A price to size against: the limit if there is one, otherwise whatever the runner supplied.
810 const auto sizing_price =
811 intent.limit() ? std::optional<Decimal64>(intent.limit()->value()) : inputs.reference_price_;
812
813 Decimal64 wanted;
814 switch (intent.size().kind()) {
816 if (intent.size().as_quantity().coefficient() < 0) {
817 return reject(RejectReason::NEGATIVE_SIZE);
818 }
819 wanted = intent.size().as_quantity();
820 break;
821 case SizeKind::NOTIONAL: {
822 if (intent.size().as_notional().amount_.coefficient() < 0) {
823 return reject(RejectReason::NEGATIVE_SIZE);
824 }
825 // Not positive is no price to size by: divided by a negative one, a buy became a negative quantity.
826 if (!sizing_price || sizing_price->coefficient() <= 0) {
828 }
829 const auto shares = decimal_divide(intent.size().as_notional().amount_, *sizing_price, 0);
830 if (!shares) {
831 return reject(RejectReason::NOT_REPRESENTABLE);
832 }
833 wanted = *shares;
834 break;
835 }
837 // The guards `weight_target` applies: a weight states a holding, which cannot be negative, and is
838 // a fraction of a value and sized by a price that must both be positive.
839 if (intent.size().as_target_weight().coefficient() < 0) {
841 }
842 if (!inputs.portfolio_value_ || inputs.portfolio_value_->coefficient() <= 0) {
844 }
845 if (!sizing_price || sizing_price->coefficient() <= 0) {
847 }
848 const auto allocation = decimal_multiply(inputs.portfolio_value_.value(), intent.size().as_target_weight());
849 if (!allocation) {
850 return reject(RejectReason::NOT_REPRESENTABLE);
851 }
852 const auto shares = decimal_divide(*allocation, *sizing_price, 0);
853 if (!shares) {
854 return reject(RejectReason::NOT_REPRESENTABLE);
855 }
856 wanted = *shares;
857 break;
858 }
859 }
860
861 PlannedOrder order;
862 order.instrument_ = intent.instrument();
863 order.side_ = intent.side();
864 order.time_in_force_ = intent.time_in_force();
865 order.tag_ = intent.tag();
866 order.client_order_id_ = intent.client_order_id();
867
868 const auto lot = reconcile_detail::lot_of(*inputs.instrument_);
869 const auto sized = reconcile_detail::round_to_lot(wanted, lot, order.quantity_rounded_);
870 if (!sized) {
871 return reject(RejectReason::NOT_REPRESENTABLE);
872 }
873 if (sized->coefficient() == 0) {
875 }
876 order.quantity_ = *sized;
877
878 if (intent.limit()) {
879 const auto priced = reconcile_detail::prepare_price(
880 intent.limit()->value(), intent.side(), inputs.instrument_->price_rule_, inputs.limits_, order.price_clamped_,
881 order.price_rounded_
882 );
883 if (!priced) {
885 }
886 if (reconcile_detail::rounded_out_of_band(intent.limit()->value(), *priced, intent.side(), inputs.limits_)) {
888 }
889 order.type_ = OrderType::LIMIT;
890 order.price_ = priced;
891 } else {
892 order.type_ = OrderType::MARKET;
893 }
894
895 if (intent.trigger()) {
896 // Checked, never moved; see `RejectReason::TRIGGER_OFF_GRID`. An unknown grid answers neither
897 // way and is refused as it is for a limit.
898 const auto aligned = inputs.instrument_->price_rule_.on_tick(intent.trigger()->value());
899 if (!aligned) {
901 }
902 if (!*aligned) {
903 return reject(RejectReason::TRIGGER_OFF_GRID);
904 }
906 order.trigger_price_ = intent.trigger()->value();
907 }
908
909 plan.place_.push_back(std::move(order));
910 return plan;
911}
912
916 std::optional<TargetPosition> target_;
918 std::optional<RejectReason> refused_;
919};
920
936inline WeightTarget weight_target(const OrderIntent& intent, const ReconcileInputs& inputs) {
937 WeightTarget out;
938 const auto refuse = [&](RejectReason reason) {
939 out.refused_ = reason;
940 return out;
941 };
942 const auto& weight = intent.size().as_target_weight();
943 if (
944 intent.side() != OrderSide::BUY || decimal_less(weight, Decimal64::parse("0")) || intent.trigger() ||
945 intent.time_in_force() != TimeInForce::DAY || intent.client_order_id()
946 ) {
948 }
949 if (inputs.instrument_ == nullptr) {
950 return refuse(RejectReason::NO_REFERENCE_DATA);
951 }
952 // A value of zero or less is not one a holding can be a fraction of: sized against it, a weight
953 // would become a liquidation (zero) or a short (negative) -- an account whose read failed and came
954 // back empty, or a replay that borrowed below zero equity, must not sell on that.
955 if (
956 !inputs.portfolio_value_ || inputs.portfolio_value_->coefficient() <= 0 ||
958 ) {
960 }
961 const auto price = intent.limit() ? std::optional<Decimal64>(intent.limit()->value()) : inputs.reference_price_;
962 if (!price || price->coefficient() <= 0) {
964 }
965 const auto allocation = decimal_multiply(*inputs.portfolio_value_, weight);
966 const auto shares = allocation ? decimal_divide(*allocation, *price, 0) : std::nullopt;
967 bool adjusted = false;
968 const auto wanted = shares ?
969 reconcile_detail::round_to_lot(*shares, reconcile_detail::lot_of(*inputs.instrument_), adjusted) :
970 std::nullopt;
971 if (!wanted) {
972 return refuse(RejectReason::NOT_REPRESENTABLE);
973 }
974 TargetPosition target;
975 target.instrument_ = intent.instrument();
976 target.target_quantity_ = *wanted;
977 target.limit_ = intent.limit();
978 target.tag_ = intent.tag();
979 out.target_ = std::move(target);
980 return out;
981}
982
983} // namespace strategy
984} // namespace algotradelib
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
std::int64_t coefficient() const noexcept
Returns the coefficient.
Definition types.hpp:541
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
One order a strategy asks the runner to place.
Definition intent.hpp:253
TimeInForce time_in_force() const noexcept
Returns how long the order stays valid.
Definition intent.hpp:385
const std::string & tag() const noexcept
Returns the tag.
Definition intent.hpp:417
const std::optional< std::string > & client_order_id() const noexcept
Returns the idempotency key.
Definition intent.hpp:425
const SizeSpec & size() const noexcept
Returns how much to trade.
Definition intent.hpp:393
const InstrumentId & instrument() const noexcept
Returns the instrument to trade.
Definition intent.hpp:361
OrderSide side() const noexcept
Returns the side.
Definition intent.hpp:369
const std::optional< Price > & trigger() const noexcept
Returns the trigger price.
Definition intent.hpp:409
static OrderIntent limit(InstrumentId instrument, OrderSide side, SizeSpec size, Price limit, TimeInForce time_in_force=TimeInForce::DAY)
Makes a limit order.
Definition intent.hpp:265
Where each instrument's rows are in one portfolio: its position rows and its working rows,...
const Decimal64 & as_target_weight() const
Returns the target weight.
Definition intent.hpp:229
const Decimal64 & as_quantity() const
Returns the quantity.
Definition intent.hpp:209
SizeKind kind() const noexcept
Returns how the size is expressed.
Definition intent.hpp:200
const Money & as_notional() const
Returns the notional amount.
Definition intent.hpp:219
What a strategy asks the runner for: orders (OrderIntent), target positions (TargetPosition) and canc...
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
constexpr std::string_view reject_reason_name(RejectReason reason) noexcept
Returns a lowercase name for a reason, such as "no_reference_data", for logs.
bool order_is_open(OrderStatus status)
Tests whether an order in a given status may still trade.
Definition portfolio.hpp:22
WeightTarget weight_target(const OrderIntent &intent, const ReconcileInputs &inputs)
Converts a weight-sized intent into the target position it states.
RejectReason
Why an instruction was not placed.
Definition reconcile.hpp:34
@ BROKER_REFUSED
The broker refused the instruction (a request was sent).
Definition reconcile.hpp:57
@ QUANTITY_ROUNDS_TO_ZERO
The quantity rounded down to zero on the lot.
Definition reconcile.hpp:44
@ NO_REFERENCE_DATA
No reference data for the instrument, so neither the tick grid nor the lot is known.
Definition reconcile.hpp:36
@ NOT_REPRESENTABLE
The decimal arithmetic did not fit, or the portfolio's rows did not add up.
Definition reconcile.hpp:46
@ STOP_ORDER_RESTING
A target needs a trade while a stop order rests on the instrument; the stop is cancelled first and no...
Definition reconcile.hpp:80
@ TRIGGER_OFF_GRID
A stop-limit order's trigger price is not on the instrument's tick grid.
Definition reconcile.hpp:71
@ UNSUPPORTED_WEIGHT
A weight-sized intent with something a holding cannot express: a sell, a negative weight,...
Definition reconcile.hpp:85
@ NO_PRICE_AVAILABLE
A price was needed to size the order and none was available.
Definition reconcile.hpp:40
@ BINDING_REFUSED
The binding refused to send the instruction, so no request was made.
Definition reconcile.hpp:64
@ NEGATIVE_SIZE
An intent's size is negative: a quantity or a notional amount below zero.
Definition reconcile.hpp:93
@ NO_PERMITTED_PRICE
Rounding the limit onto the grid, in the cautious direction, would move it out of the day's band: no ...
Definition reconcile.hpp:55
@ UNKNOWN_PRICE_GRID
The instrument's tick grid is unknown, so a limit price cannot be made valid.
Definition reconcile.hpp:38
@ NO_PORTFOLIO_VALUE
A weight needed the portfolio's value, and none (or a non-positive one, or one in another currency) w...
Definition reconcile.hpp:42
bool is_stop_order(const OrderSnapshot &order)
Tests whether a working order is a stop order: a trigger-price type, or one carrying a trigger price.
@ NOTIONAL
An amount of money; the runner divides it by a price.
Definition intent.hpp:112
@ QUANTITY
A number of shares or contracts.
Definition intent.hpp:110
@ TARGET_WEIGHT
A fraction of portfolio value to hold; the runner trades the difference.
Definition intent.hpp:114
Plan< Broker > reconcile(const TargetPosition &target, const Portfolio< Broker > &portfolio, const ReconcileInputs &inputs)
Plans the cancellations and the order that move a holding to a target position.
The library: broker-neutral types (core), and the modules below.
std::optional< Decimal64 > decimal_floor_to_multiple(const Decimal64 &value, const Decimal64 &step)
Rounds down to a multiple of a step (toward negative infinity).
Definition types.hpp:903
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
OrderType
How an order's price is decided (its price basis).
Definition types.hpp:1998
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
Definition types.hpp:2013
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
constexpr bool carries_trigger_price(OrderType type) noexcept
Tests whether an order type takes a trigger price.
Definition types.hpp:2065
constexpr bool order_status_cancel_pending(OrderStatus status) noexcept
Tests whether a cancellation of an order in this status is already on its way, so asking again can on...
Definition types.hpp:2190
OrderSession
The trading session an order is submitted into.
Definition types.hpp:2130
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
std::optional< Decimal64 > decimal_divide(const Decimal64 &lhs, const Decimal64 &rhs, std::uint8_t scale)
Divides two decimals, truncating toward zero at a given scale.
Definition types.hpp:860
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
Definition types.hpp:826
TimeInForce
How long an order stays valid and what happens to an unfilled remainder.
Definition types.hpp:2088
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
Reference data for one instrument.
Currency currency_
The currency it trades in.
PriceRule price_rule_
The price grid, set by the adapter or the caller; kind UNKNOWN where it has no table.
Decimal64 amount_
The amount.
Definition types.hpp:1170
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
OrderType type_
The price basis; UNKNOWN if the broker's code was not recognized.
Definition types.hpp:2309
std::optional< Decimal64 > trigger_price_
The trigger price, whenever the broker reports a positive one.
Definition types.hpp:2339
std::optional< bool > on_tick(const Decimal64 &price) const
Tests whether a price is on the grid.
What to send: first every cancellation, then every placement.
bool empty() const noexcept
Tests whether the plan is empty.
std::vector< PlannedOrder > place_
The orders to place, after the cancellations.
std::vector< Rejection > rejected_
The instructions not placed, with reasons.
std::vector< OrderRef< Broker > > cancel_
The orders to cancel, sent first.
One order the runner is to place.
TimeInForce time_in_force_
How long the order stays valid.
bool price_clamped_
Whether the price was clamped to the day's band (an aggressive limit beyond it).
OrderSession session_
The trading session.
std::optional< std::string > client_order_id_
The idempotency key, if the intent carried one.
Venue venue_
Where to route the order; see OrderRequest::venue_.
bool price_would_have_been_clamped_
Whether a price band was known but not applied (too old), and would have clamped this price.
std::string tag_
The tag of the intent or target the order came from.
bool quantity_rounded_
Whether the quantity was rounded down onto the lot.
bool price_rounded_
Whether the price was rounded onto the tick grid.
std::optional< Decimal64 > trigger_price_
The trigger price of a STOP_LIMIT order, exactly as stated; empty otherwise.
OrderType type_
The order type.
InstrumentId instrument_
The instrument to trade.
std::optional< Decimal64 > price_
The limit price, after clamping and rounding; empty for a market order.
Decimal64 quantity_
The quantity, after rounding onto the lot.
What the account holds and which orders are still working, as a strategy sees it.
Definition portfolio.hpp:82
What reconciliation needs besides the intent and the portfolio; the runner fills it in.
std::optional< Currency > portfolio_value_currency_
The currency of portfolio_value_; absent means the instrument's currency.
const PortfolioRows * rows_
Where each instrument's rows are in the portfolio being reconciled, or a null pointer to scan for the...
std::optional< Decimal64 > reference_price_
A price to size a notional or weight against, such as the last trade.
std::optional< PriceLimits > limits_
The day's price band, if the broker publishes one.
bool reserved_rows_are_unconfirmed_
Whether the portfolio's reserved rows (WorkingOrder::reserved_) are orders this runner sent that the ...
std::optional< Decimal64 > portfolio_value_
The total portfolio value, for weight sizing.
TradeTolerance tolerance_
How small a drift from a target is not worth an order.
const Instrument * instrument_
The instrument's reference data (tick grid, lot size, currency); required.
One instruction that was not placed, and why.
InstrumentId instrument_
The instrument it was for.
RejectReason reason_
Why it was not placed.
std::string tag_
The tag of the intent or target it came from.
The position a strategy wants to hold in one instrument.
Definition intent.hpp:451
InstrumentId instrument_
The instrument.
Definition intent.hpp:453
std::string tag_
A label carried to the orders and their fills.
Definition intent.hpp:459
Decimal64 target_quantity_
The position to hold, signed: negative is short, and zero means flat.
Definition intent.hpp:455
std::optional< Price > limit_
The limit price for the orders the runner places; without one they are market orders.
Definition intent.hpp:457
How small a difference from a target is not worth an order.
std::optional< Decimal64 > minimum_notional_
The smallest drift worth trading, valued at the reference price.
bool stated() const noexcept
Tests whether any floor is set.
std::optional< Decimal64 > minimum_quantity_
The smallest drift worth trading, in shares.
std::optional< Decimal64 > minimum_fraction_of_working_
The smallest drift worth trading, as a fraction of the quantity already working (0....
The result of weight_target: a target position or a refusal, exactly one of them.
std::optional< TargetPosition > target_
The target position, if the weight could be sized.
std::optional< RejectReason > refused_
Why it could not be, otherwise.