algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
algotradelib::mock::Market Class Reference

A market in memory: bars the caller gives, a clock the caller moves, one account's cash, holdings and orders. More...

#include <algotradelib/src/brokers/mock/market.hpp>

Public Member Functions

 Market (std::vector< BarSeries > bars, MarketSettings settings, std::vector< Instrument > instruments={})
 Builds a market at settings.start_.
std::chrono::system_clock::time_point now () const noexcept
 Returns the market's clock.
const std::optional< std::string > & halted () const noexcept
 Returns why the market halted, if it did.
void advance_to (std::chrono::system_clock::time_point to)
 Moves the clock to an instant, applying every bar whose period end it reaches, in order of period end across instruments (ties in the order the series were given).
Result< BarSeries > bars (const BarQuery &query) const
 Answers a bar request: bars whose period has ended by now(), never a forming one.
Result< QuoteSnapshot > quote (const InstrumentId &instrument) const
 Answers a quote: the close of the instrument's last bar that has ended by now().
Result< Instrument > instrument (const InstrumentId &instrument) const
 Answers a reference-data request.
Result< TradingCalendar > calendar (Country country) const
 Answers a calendar request.
Result< HoldingsSnapshot > holdings () const
 Answers a holdings request.
Money cash () const
 Returns the account's cash, before what open buys reserve.
Result< BuyingPower > buying_power (const Currency &currency) const
 Answers a buying-power request: cash less what open buys reserve.
Result< PlacedOrder< Broker > > place (const OrderRequest &order)
 Places an order.
Result< PlacedOrder< Broker > > cancel (const std::string &order_id)
 Cancels the whole remainder of an open order.
WorkingOrders< Broker > working_orders () const
 Answers a working-order request.
OrderPage order_history (const OrderHistoryQuery &query) const
 Answers an order-history request: every order, oldest first, in one page.

Friends

class MarketFile

Detailed Description

A market in memory: bars the caller gives, a clock the caller moves, one account's cash, holdings and orders.

A bar is applied when the clock passes its period end. Orders fill by the backtest's rule (backtest::NextBarFillModel): an order trades against the first bar of its instrument whose period began at or after the instant the market accepted it, a market order at that bar's open (or at the price of the fill model's market-price rule, given the series' bar before it), a limit order if the bar's range reaches the limit, never partly; the fill is stamped at the bar's period end. A DAY order lives in the session of that first bar, and expires as a backtest's does: after a daily bar of its session, after an intraday bar ending at or after the session's close, or before a bar of a later date (a session whose closing bar is missing still ended). An immediate-or-cancel or fill-or-kill order expires after its first bar. Expired orders are CANCELED.

Unlike a backtest, the market never fills an order against a bar that began before the order was accepted, even where a backtest cannot tell and allows it (ReplayResult::unchecked_fill_causality_).

Not modelled: trading hours (an order is accepted at any instant; the calendar and the session window only date the market), price bands, partial fills, volume, settlement, short selling, interest. Cash is kept in one currency, and may go below zero when a market buy fills above the price it reserved.

If a fill cannot be costed (the fill model's commission has no rate for its date) or recorded (its amount does not fit an exact decimal), or a position cannot be valued at a bar's close, the market halts: advance_to throws std::runtime_error and keeps throwing, placements are refused (market_halted), and the clock stays at the period end of the bar it halted on. What was done before the failure stands, including fills of earlier orders on that bar; the order that failed stays PENDING. Reads answer that state.

Not thread-safe. Nothing is persisted unless the market is kept in a state file (MarketFile): a copy of a kept market is an ordinary market, which writes nothing, and assigning to a kept market or moving from it throws std::logic_error, leaving it as it was.

Definition at line 143 of file market.hpp.

Constructor & Destructor Documentation

◆ Market()

algotradelib::mock::Market::Market ( std::vector< BarSeries > bars,
MarketSettings settings,
std::vector< Instrument > instruments = {} )
inline

Builds a market at settings.start_.

Parameters
barsOne series per instrument, each strictly ascending, of a minute to daily interval; series may differ in interval, stamp and currency.
settingsThe starting cash, the first instant, the fill rule and the session window.
instrumentsReference data for some or all of the instruments, as instrument answers it and as a backtest is given it (backtest::ReplayConfig::instruments_). An instrument without one gets an active stock in its series' currency, a lot of one share and no price grid (PriceRule::unconstrained).
Exceptions
std::invalid_argumentfor two series of one instrument, a series not strictly ascending, a weekly, monthly or yearly series, a negative starting cash, or reference data for an instrument without bars.

Definition at line 158 of file market.hpp.

Member Function Documentation

◆ advance_to()

void algotradelib::mock::Market::advance_to ( std::chrono::system_clock::time_point to)
inline

Moves the clock to an instant, applying every bar whose period end it reaches, in order of period end across instruments (ties in the order the series were given).

Parameters
toThe instant; the clock never moves backwards.
Exceptions
std::invalid_argumentif to is before now().
std::runtime_errorif the market halts on this call (the clock then stays at the period end of the bar it halted on; see the class) or had halted.
MarketFileErrorif the market is kept in a file that could not record the move.

Definition at line 226 of file market.hpp.

◆ bars()

Result< BarSeries > algotradelib::mock::Market::bars ( const BarQuery & query) const
inline

Answers a bar request: bars whose period has ended by now(), never a forming one.

Parameters
queryThe instrument, the interval (the series' own), the count and the newest timestamp.
Returns
The last count_ such bars at or before before_, oldest first; INVALID_ARGUMENT with unknown_instrument, unsupported_interval or bars_count (a count below one).

Definition at line 266 of file market.hpp.

Referenced by Market().

◆ buying_power()

Result< BuyingPower > algotradelib::mock::Market::buying_power ( const Currency & currency) const
inline

Answers a buying-power request: cash less what open buys reserve.

An open limit buy reserves its quantity at its limit, an open market buy its quantity at the last close when it was placed. The figure can be negative after a market buy filled above that.

Parameters
currencyThe currency.
Returns
The figure; INVALID_ARGUMENT unknown_currency for a currency the market keeps no cash in, PROTOCOL out_of_range if the arithmetic does not fit.

Definition at line 423 of file market.hpp.

◆ calendar()

Result< TradingCalendar > algotradelib::mock::Market::calendar ( Country country) const
inline

Answers a calendar request.

Parameters
countryThe market.
Returns
The trading days (MarketSettings::calendar_, or those of the bars), received_at_ now; INVALID_ARGUMENT unsupported_market for another market.

Definition at line 357 of file market.hpp.

◆ cancel()

Result< PlacedOrder< Broker > > algotradelib::mock::Market::cancel ( const std::string & order_id)
inline

Cancels the whole remainder of an open order.

Parameters
order_idThe order id.
Returns
The acknowledgement; INVALID_ARGUMENT nothing_to_cancel (with reached_broker_ set) for an id that is unknown or already finished; for a kept market whose file could not record the cancellation, as place answers.

Definition at line 553 of file market.hpp.

◆ cash()

Money algotradelib::mock::Market::cash ( ) const
inline

Returns the account's cash, before what open buys reserve.

Returns
The cash, in the one currency the market keeps it in; below zero after a market buy filled above the price it reserved.

Definition at line 409 of file market.hpp.

Referenced by buying_power(), and place().

◆ halted()

const std::optional< std::string > & algotradelib::mock::Market::halted ( ) const
inlinenoexcept

Returns why the market halted, if it did.

Returns
The reason, or std::nullopt while it trades.

Definition at line 213 of file market.hpp.

◆ holdings()

Result< HoldingsSnapshot > algotradelib::mock::Market::holdings ( ) const
inline

Answers a holdings request.

Returns
Every position not flat, valued at its last applied bar's close, with per-currency totals. Every held share is sellable (basis: whole holding, resting sells to be deducted by the caller, unverified). PROTOCOL out_of_range if a row's cost or gain, or a total, does not fit an exact decimal.

Definition at line 373 of file market.hpp.

◆ instrument()

Result< Instrument > algotradelib::mock::Market::instrument ( const InstrumentId & instrument) const
inline

Answers a reference-data request.

Parameters
instrumentThe instrument.
Returns
Its reference data, as given or defaulted at construction; INVALID_ARGUMENT unknown_instrument.

Definition at line 343 of file market.hpp.

Referenced by instrument(), and quote().

◆ now()

std::chrono::system_clock::time_point algotradelib::mock::Market::now ( ) const
inlinenoexcept

Returns the market's clock.

Returns
The instant the market has reached.

Definition at line 205 of file market.hpp.

◆ order_history()

OrderPage algotradelib::mock::Market::order_history ( const OrderHistoryQuery & query) const
inline

Answers an order-history request: every order, oldest first, in one page.

Parameters
queryfrom_ and to_ keep orders accepted on those local dates (inclusive); the cursor, symbol and limit are not read.
Returns
The page, each order with its status (PENDING, FILLED or CANCELED) and execution.

Definition at line 602 of file market.hpp.

◆ place()

Result< PlacedOrder< Broker > > algotradelib::mock::Market::place ( const OrderRequest & order)
inline

Places an order.

Checked in this order, each refusal INVALID_ARGUMENT with reached_broker_ set: market_halted; unknown_instrument; unsupported_order_type (market and limit only); unsupported_time_in_force (DAY, immediate-or-cancel, fill-or-kill); invalid_quantity (not a positive whole number); invalid_price (a limit without a positive price, or a market order with one); no_price (a market buy before any bar of its instrument ended); insufficient_cash (a buy reserving more than the buying power, or in a currency without cash); insufficient_holdings (a sell of more than is held less open sells).

A kept market whose file could not record the order answers TRANSPORT: state_not_written without reached_broker_, or state_unconfirmed with it (reopening the file may accept the order).

Parameters
orderThe order; its venue is not used.
Returns
The acknowledgement, the order id "1", "2", ... in the order accepted.

Definition at line 459 of file market.hpp.

◆ quote()

Result< QuoteSnapshot > algotradelib::mock::Market::quote ( const InstrumentId & instrument) const
inline

Answers a quote: the close of the instrument's last bar that has ended by now().

Parameters
instrumentThe instrument.
Returns
The quote, exchange_time_ the bar's period end; INVALID_ARGUMENT unknown_instrument, or PROTOCOL no_price before any bar of it has ended.

Definition at line 315 of file market.hpp.

Referenced by quote().

◆ working_orders()

WorkingOrders< Broker > algotradelib::mock::Market::working_orders ( ) const
inline

Answers a working-order request.

Returns
The open orders, oldest first, each with its whole quantity amendable. A finished order leaves the list; read its outcome from order_history.

Definition at line 580 of file market.hpp.

◆ MarketFile

friend class MarketFile
friend

Definition at line 616 of file market.hpp.


The documentation for this class was generated from the following file: