3#include <algotradelib/core>
110 "all_market_phases must list every MarketPhase"
124 std::chrono::minutes
open_{std::chrono::hours(9)};
126 std::chrono::minutes
close_{std::chrono::hours(15) + std::chrono::minutes(30)};
130 std::string
source_{
"KRX regular session, 09:00-15:30 KST (library default)"};
149 MarketPhase phase(std::chrono::system_clock::time_point now, std::optional<bool> trading_day)
const {
157 const auto since_midnight = std::chrono::duration_cast<std::chrono::minutes>(local - local_midnight(now));
158 if (since_midnight <
open_) {
161 if (
close_ <= since_midnight) {
177 using Days = std::chrono::duration<std::int64_t, std::ratio<86400>>;
178 return date_from_epoch_days(std::chrono::duration_cast<Days>(local_midnight(now).time_since_epoch()).count());
187 std::chrono::system_clock::time_point
opens_at(std::chrono::system_clock::time_point now)
const {
197 std::chrono::system_clock::time_point
closes_at(std::chrono::system_clock::time_point now)
const {
205 std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds> local_midnight(
206 std::chrono::system_clock::time_point now
208 using Days = std::chrono::duration<std::int64_t, std::ratio<86400>>;
209 return std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::floor<Days>(now +
utc_offset_));
239 const auto has_hours = [](
const TradingDay& day) {
240 return day.open_ && day.regular_ && day.regular_->opens_at_ < day.regular_->closes_at_;
242 const auto span_of = [](
const TradingDay& day) {
243 const auto& regular = *day.regular_;
245 day.extended_ && day.extended_->opens_at_ <= regular.opens_at_ && regular.closes_at_ <= day.extended_->closes_at_
247 return *day.extended_;
251 const auto& days = calendar.
days_;
252 for (std::size_t i = 0; i < days.size(); ++i) {
253 if (!has_hours(days[i])) {
256 const auto first = span_of(days[i]);
257 for (std::size_t j = i + 1; j < days.size(); ++j) {
258 if (!has_hours(days[j])) {
261 const auto second = span_of(days[j]);
262 if (first.opens_at_ < second.closes_at_ && second.opens_at_ < first.closes_at_) {
269 for (
const auto& day : days) {
270 if (!has_hours(day)) {
273 const auto& regular = *day.regular_;
274 const auto span = span_of(day);
275 if (regular.opens_at_ <= now && now < regular.closes_at_) {
278 if (span.opens_at_ <= now && now < span.closes_at_) {
281 if (span.closes_at_ <= now && (previous ==
nullptr || span_of(*previous).closes_at_ < span.closes_at_)) {
284 if (now < span.opens_at_ && (next ==
nullptr || span.opens_at_ < span_of(*next).opens_at_)) {
288 if (previous ==
nullptr || next ==
nullptr || !(previous->
date_ < next->
date_)) {
291 bool closed_between =
false;
292 for (
const auto& day : days) {
293 if (previous->
date_ < day.date_ && day.date_ < next->
date_) {
297 closed_between =
true;
345 return bar.timestamp_;
348 case BarInterval::ONE_MINUTE:
349 return bar.timestamp_ + std::chrono::minutes(1);
351 return bar.timestamp_ + std::chrono::minutes(5);
353 return bar.timestamp_ + std::chrono::minutes(15);
355 return bar.timestamp_ + std::chrono::minutes(30);
357 return bar.timestamp_ + std::chrono::hours(1);
358 case BarInterval::ONE_DAY:
359 return bar.timestamp_ + std::chrono::hours(24);
360 case BarInterval::ONE_WEEK:
361 return bar.timestamp_ + std::chrono::hours(24 * 7);
362 case BarInterval::ONE_MONTH:
364 return bar.timestamp_ + std::chrono::hours(24 * 31);
365 case BarInterval::ONE_YEAR:
366 return bar.timestamp_ + std::chrono::hours(24 * 366);
368 return bar.timestamp_;
383 event.interval_ = interval;
384 event.stamp_ = stamp;
386 event.bar_ = std::move(bar);
405 return event.bar_.timestamp_;
408 return event.period_end_ - *duration;
410 if (event.
interval_ == BarInterval::ONE_DAY) {
460 const auto end =
event.period_end_;
463 const auto open = session.
opens_at(start);
464 const auto close = session.
closes_at(start);
465 edge.
point_ = start == end;
466 const bool reaches = start < close && (open < end || (edge.
point_ && end == open));
467 const bool holds_close = start <= close && close <= end;
468 if (!reaches && !holds_close) {
472 if (reaches && !(opened_ && *opened_ == date)) {
477 if (holds_close && !(closed_ && *closed_ == date)) {
490 return opened_count_;
498 return closed_count_;
506 return outside_count_;
510 std::optional<Date> opened_;
511 std::optional<Date> closed_;
512 std::size_t opened_count_{0};
513 std::size_t closed_count_{0};
514 std::size_t outside_count_{0};
520namespace slice_detail {
529 SliceIndex() =
default;
530 SliceIndex(
const SliceIndex&)
noexcept {}
531 SliceIndex(SliceIndex&&) noexcept {}
532 SliceIndex& operator=(
const SliceIndex&)
noexcept {
536 SliceIndex& operator=(SliceIndex&&) noexcept {
542 friend struct strategy::BarSlice;
545 void forget() noexcept {
547 built_over_ =
nullptr;
551 id_detail::PositionTable table_;
552 const void* built_over_{
nullptr};
553 std::size_t count_{0};
587 if (!index_.table_.empty() && index_.built_over_ ==
bars_.data() && index_.count_ ==
bars_.size()) {
588 const auto at = index_.table_.find(
id, Ids{&
bars_});
589 return at ? &
bars_[*at] :
nullptr;
591 for (
const auto& event :
bars_) {
592 if (event.instrument_ ==
id) {
603 slice_detail::SliceIndex index_;
607 const std::vector<BarEvent>* bars_;
608 const InstrumentId& operator()(std::size_t at)
const noexcept {
609 return (*bars_)[at].instrument_;
616namespace slice_detail {
625 const BarSlice* slice_;
626 const InstrumentId& operator()(std::size_t at)
const noexcept {
627 return slice_->bars_[at].instrument_;
630 static SliceIds ids_of(
const BarSlice& slice)
noexcept {
631 return SliceIds{&slice};
636 Bucket(
const Bucket&) =
default;
637 Bucket(Bucket&&) =
default;
638 Bucket& operator=(Bucket&&) =
default;
641 Bucket& operator=(
const Bucket& other) {
642 if (
this != &other) {
644 *
this = std::move(copy);
650 bool empty() const noexcept {
651 return slices_.empty();
655 std::chrono::system_clock::time_point period_end() const noexcept {
660 bool holds(
const BarEvent& event)
const noexcept {
661 for (
const auto& slice : slices_) {
662 if (slice.interval_ == event.interval_) {
663 if (slice.bars_.size() > id_detail::scan_limit) {
664 if (
const auto* entry = wide(event.interval_)) {
665 return entry->table_.find(event.instrument_, ids_of(slice)).has_value();
668 return slice.find(event.instrument_) !=
nullptr;
680 void add_checked(
const BarEvent& event) {
681 if (slices_.empty()) {
682 period_end_ =
event.period_end_;
684 for (
auto& slice : slices_) {
685 if (slice.interval_ == event.interval_) {
686 slice.bars_.push_back(event);
691 slice.period_end_ =
event.period_end_;
692 slice.interval_ =
event.interval_;
693 slice.bars_.push_back(event);
694 slices_.push_back(std::move(slice));
698 void add(
const BarEvent& event) {
699 if (slices_.empty()) {
700 period_end_ =
event.period_end_;
702 for (
auto& slice : slices_) {
703 if (slice.interval_ == event.interval_) {
704 slice.bars_.push_back(event);
707 if (slice.bars_.size() == id_detail::scan_limit + 1) {
709 }
else if (slice.bars_.size() > id_detail::scan_limit) {
710 if (
auto* entry = wide(slice.interval_)) {
711 entry->table_.insert(event.instrument_, slice.bars_.size() - 1, ids_of(slice));
712 entry->count_ = slice.bars_.size();
716 slice.bars_.pop_back();
723 slice.period_end_ =
event.period_end_;
724 slice.interval_ =
event.interval_;
725 slice.bars_.push_back(event);
726 slices_.push_back(std::move(slice));
730 BarSlice take_first() {
732 BarSlice slice = std::move(slices_.front());
733 hand_index_to(slice);
734 slices_.erase(slices_.begin());
739 std::vector<BarSlice> take() {
740 for (
auto& slice : slices_) {
741 hand_index_to(slice);
743 std::vector<BarSlice> slices = std::move(slices_);
749 void clear() noexcept {
760 id_detail::PositionTable table_;
763 std::size_t count_{0};
766 const Wide* wide(BarInterval interval)
const noexcept {
767 for (
const auto& entry : wide_) {
768 if (entry.interval_ == interval) {
775 Wide* wide(BarInterval interval)
noexcept {
776 for (
auto& entry : wide_) {
777 if (entry.interval_ == interval) {
787 void hand_index_to(BarSlice& slice)
noexcept {
788 if (slice.bars_.size() <= id_detail::scan_limit) {
792 const auto* built = wide(slice.interval_);
793 if (built ==
nullptr || built->count_ != slice.bars_.size() || built->table_.empty()) {
800 if (
auto* entry = wide(slice.interval_)) {
801 slice.index_.table_ = std::move(entry->table_);
802 entry->table_.reset();
804 slice.index_.built_over_ = slice.bars_.data();
805 slice.index_.count_ = slice.bars_.size();
812 void widen(
const BarSlice& slice) {
813 Wide* entry = wide(slice.interval_);
814 if (entry ==
nullptr) {
815 wide_.push_back(Wide{slice.interval_, {}});
816 entry = &wide_.back();
818 entry->table_.reset();
821 for (std::size_t at = 0; at < slice.bars_.size(); ++at) {
822 entry->table_.insert(slice.bars_[at].instrument_, at, ids_of(slice));
825 entry->table_.reset();
828 entry->count_ = slice.bars_.size();
831 std::chrono::system_clock::time_point period_end_{};
832 std::vector<BarSlice> slices_;
834 std::vector<Wide> wide_;
900 std::chrono::system_clock::time_point
at_{};
An exact signed decimal: an int64 coefficient times 10^-scale.
Follows a strategy's bars and says which bar opens its session and which closes it,...
SessionEdge next(const BarEvent &event, const SessionWindow &session)
Decides whether the next bar opens or closes its session.
std::size_t opened() const noexcept
Returns how many sessions a bar has opened so far.
std::size_t outside() const noexcept
Returns how many bars lay wholly outside their session (before its open or after its close).
std::size_t closed() const noexcept
Returns how many sessions a bar has closed so far.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
MarketPhase
Where the clock stands relative to the trading session.
@ CLOSED
A date the market does not trade.
@ PRE_OPEN
A trading day, before the session opens; under filled session hours, the day's earlier stated session...
@ UNKNOWN
Nothing is known about this instant: the calendar does not cover its date, or the filled session hour...
@ POST_CLOSE
A trading day, after the session closed; under filled session hours, until the next day's first sessi...
@ OPEN
Inside the session.
constexpr std::array< MarketPhase, 5 > all_market_phases
Every MarketPhase, in declaration order.
constexpr std::string_view market_phase_name(MarketPhase phase) noexcept
Returns a lowercase name for a phase, such as "pre_open", for logs and display.
std::chrono::system_clock::time_point bar_period_end(const Bar &bar, BarInterval interval, BarStamp stamp)
Computes the instant a bar's period ended.
constexpr bool market_phase_session_ended(MarketPhase phase) noexcept
Tests whether a phase means the day's session is over (or never opened), so a day order no longer wor...
std::optional< std::chrono::system_clock::time_point > bar_period_start(const BarEvent &event, const SessionWindow &session)
Returns when a bar's period began, where the bar says so.
MarketPhase stated_session_phase(const TradingCalendar &calendar, std::chrono::system_clock::time_point now)
Returns the market phase at an instant from the session hours filled in a calendar.
The library: broker-neutral types (core), and the modules below.
BarStamp
Which edge of its period a bar's timestamp marks.
@ CLOSE
The timestamp is the instant the period ended.
@ OPEN
The timestamp is the first instant of the period.
constexpr std::optional< std::chrono::seconds > bar_interval_length(BarInterval interval) noexcept
Returns an interval's fixed length, for an intraday interval.
constexpr bool lists_every_value(const std::array< Enum, N > &values, IsEnumerator is_enumerator) noexcept
Tests whether a list holds every value of an enum exactly once, in any order.
Date date_from_epoch_days(std::int64_t days)
Converts a day count since 1970-01-01 to a Gregorian date.
BarInterval
The period one bar covers.
@ FIVE_MINUTES
Five minutes.
@ THIRTY_MINUTES
Thirty minutes.
@ FIFTEEN_MINUTES
Fifteen minutes.
OrderSide
The side of an order: its economic direction, buy or sell.
One bar: the prices and volume of one period, as exact decimals.
A calendar date with no time of day or time zone.
Identifies an instrument: its country, venue and symbol.
A quote: the last traded price of an instrument at a point in time.
The trading days a broker reported for one market, ascending by date.
std::size_t unreadable_days_
How many rows from the broker had a date that could not be read.
std::vector< TradingDay > days_
The days the broker reported, ascending. A date outside them is uncovered, not closed.
One calendar date and whether the market opens on it.
Date date_
The market's local calendar date, as the broker reports it.
One bar, delivered to on_bar.
BarStamp stamp_
Whether bar_.timestamp_ marks the period's open or close.
std::chrono::system_clock::time_point period_end_
When the bar's period ended: the earliest moment the bar could be known.
InstrumentId instrument_
The instrument the bar is for.
BarInterval interval_
The period length the bar covers.
Every instrument's bar of one interval for one period end, delivered to on_bars.
std::chrono::system_clock::time_point period_end_
When the period ended, shared by every bar in bars_.
const BarEvent * find(const InstrumentId &id) const noexcept
Finds an instrument's bar.
std::vector< BarEvent > bars_
The bars, one per instrument, in the order they were fed.
BarInterval interval_
The period length every bar in bars_ covers.
A record of data from outside the broker, delivered to on_data.
std::chrono::system_clock::time_point known_at_
When the record became known: the earliest moment a strategy may see it, as BarEvent::period_end_ is ...
One execution of an order the strategy placed, delivered to on_fill.
std::chrono::system_clock::time_point at_
When the execution happened.
InstrumentId instrument_
The instrument traded.
std::string tag_
The tag of the intent that produced the order.
OrderSide side_
The side of the order.
std::string order_id_
The id of the order that traded: the broker's, or in a backtest the replay's.
Decimal64 price_
The execution price.
Decimal64 quantity_
The quantity of this execution, not the order's running total.
A quote the runner has just read, delivered to on_quote.
QuoteSnapshot quote_
The quote, as the broker reported it.
Whether a bar opens or closes its session, as SessionEdges::next decided it.
bool opens_
The bar opens its session: the first bar of its market-local date that reaches into the session,...
bool closes_
The bar closes its session: the first bar of its date whose period holds the close,...
bool point_
The bar's period is empty: it is one price at one instant, such as a daily bar stamped at the open.
The intraday session of a market, as the operator states it.
std::chrono::minutes open_
The session open, in minutes from local midnight.
std::string source_
A description of where the window came from, for reports.
std::chrono::minutes utc_offset_
The market's offset from UTC.
MarketPhase phase(std::chrono::system_clock::time_point now, std::optional< bool > trading_day) const
Returns the market phase at an instant.
std::chrono::system_clock::time_point opens_at(std::chrono::system_clock::time_point now) const
Returns the instant the session opens on the local date of an instant.
std::chrono::minutes close_
The session close, in minutes from local midnight.
Date local_date(std::chrono::system_clock::time_point now) const
Returns the market's local date at an instant.
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
std::chrono::system_clock::time_point closes_at(std::chrono::system_clock::time_point now) const
Returns the instant the session closes on the local date of an instant.