![]() |
Trading System API
3.0
Library for Simulating and Deploying Trading and Investment Strategies
|
Class strategy represents a trading or investment strategy. More...
#include <TSAStrategy.h>
Public Member Functions | |
void | cancel_order (identifier_t order_id, identifier_t instrument_id) |
Cancels an order with a given order_id and contract_id. Use this function if there is no corresponding order_ref object. Use order_ref::cancel() otherwise. More... | |
void | catch_series_bounds_errors (bool flag=true) |
A series function that is unable to access enough data to perform the calculation it was intended for will cause a series_bounds_error exception to be thrown. This will immediately terminate the strategy unless the users explicitly instructs the strategy to silently handle such series_bounds_error exceptions, by catching the exception. Note that this member is intended to be used as part of the definition of strategy::on_next() and that it any code after the statement that cause the exception will be skipped. More... | |
order_ref | get_order_ref (identifier_t order_id) const |
Returns a reference to the order with the given order_id. Throws an exception if the order does not exist. More... | |
size_t | instrument_count (void) const |
Returns the number of instruments that are part of the strategy. Instruments are added as strategy members. More... | |
instrument * | instrument_ptr (size_t position) const |
Returns a pointer to the instrument at the given position. Positions start at 0. Instruments cannot be removed from a strategy. The function will throw an exception if the given instrument identifier is not valid. Use the strategy::instrument_count() member to determine how many valid instruments there are. More... | |
std::vector< instrument * > & | instruments (void) const |
Returns a container with pointers to all instrument member objects registered with the strategy. More... | |
void | name (const std::string &name) |
Sets the strategy name. The strategy name is displayed on reports and is used as part of the strategy's output directory name to which reports and charts are written. If no strategy name is given, the strategy will be given a default name based on the current system time. More... | |
const std::string & | name (void) const |
Returns the strategy name. | |
void | on_series_bounds_error_terminate (void) |
This member explicitly disallows exceptions of type series_bounds_error to be handled by the strategy. After a call to this member, any series_bounds_error will be immediately re- throwns by the strategy, which will result in the invovation of the on_execption() even handler, and the likely termination of the strategy. | |
size_t | order_count (void) const |
Returns the number of 'active' orders. 'Active' orders are orders that have been dispatched and which have not been confirmed cancelled or filled. Note that in addition to the number of orders returned by this member, there may exist any number of 'inactive' orders. Inactive orders are only marked for deletion once their reference count has gone to zero. See class order_ref. More... | |
size_t | order_count_inclusive (void) const |
Returns the comprehensive number of orders including both 'inactive' and 'active' orders. More... | |
order * | order_ptr (identifier_t order_id) const |
Returns a pointer to an order with given order_id. Normally orders are handled via instances of class order_ref. Direct access to order objects may only be required during special situations. More... | |
![]() | |
object (void) | |
Constructor. | |
virtual | ~object (void) |
Destructor. | |
const char * | class_name (void) const |
Returns the class name as returned by the 'Real Time Type Information' (RTTI) mechanism. More... | |
bool | has_same_class_as (const object &other) const |
Returns true if self has the same type as other object. More... | |
Constructors / Initialization | |
strategy (void) | |
Constructor. | |
~strategy (void) | |
Destructor. | |
void | args (const tsa::json &json_obj) |
Sets a json object as strategy arguments. These are values that can be accessed by name while the strategy is initializing or evaluating. This allows users to set simple name- value pairs but there is no restriction on the complexity of the data passed as json, and so it is entirely possible to pass arrays and nested objects as well. More... | |
const tsa::json & | args (void) const |
Returns all strategy arguments as a json object. Use the strategy::arg() member to access simple values. Complex arrays and json objects cannot however be returned as a variant and so you will need to extract this directly // from the original json object. More... | |
bool | arg_exists (const std::string &arg_name) |
Returns true if a strategy argument with given arg_name exists. More... | |
auto_cast_variant | arg (const std::string &arg_name) const |
Returns the value corresponding to an argument with given arg_name. More... | |
Event Handlers | |
The following members are event handlers intended to be overridden by derived strategy classes. At a minimum the on_next() member (also known as on_bar_close()) should be overridden to provide the new class with trading logic. There is no requirement to override any of the other members. | |
virtual void | on_command (const tsa::json &) |
This event handler is triggered when a JSON command is received. Strategies can thus respond to ad-hoc command sent to it from elsewhere during real time deployment. More... | |
virtual void | on_message (const tsa::json &) |
virtual void | on_signal (const std::string &signal_string) |
virtual void | on_error (const tsa::json &) |
virtual void | on_start (void) |
This member is invoked once, at strategy startup, and can be used to perform various initialization tasks, such as connecting streams to a data source. | |
virtual void | on_end (void) |
This member is invoked when a strategy reaches the end of the scheduling sequence, or else receives a shutdown command. It can be used to perform various clean up tasks such as disconnecting from a service, or notifying users. | |
strategy_end_type | end_type (void) const |
This member returns a value corresponding to the cause of the strategy shutdown. More... | |
virtual void | on_next (void) |
This member is invoked repeatedly, once for every new price bar, or whenever a price bar is received by the scheduling sequence during real time deployment. The on_next() member definition usually comprises the bulk of a strategy's trading logic. More... | |
virtual void | on_transaction (const transaction &t) |
This member is invoked by the strategy every time a transaction is confirmed (fill or partial-fill). Use it to cancel or place related orders or to adjust active order quantities, or any other relevant task. See also: strategy::on_filled(), strategy::on_partially_filled(). More... | |
virtual void | on_order_filled (const order_ref &oref, const transaction &t) |
This member is invoked by the strategy every time an order in filled in its entirety. See also: on_partial_fill();. More... | |
virtual void | on_order_partially_filled (order_ref &o_ref, const transaction &t) |
This member is invoked by the strategy every time an order in partially filled. See also: on_order_filled(). More... | |
virtual void | on_order_status_changed (order_ref &o_ref) |
This member is invoked when the status of an order changes. More... | |
virtual void | on_order_cancel_rejected (order_ref &o_ref, const reject_info &r_info) |
This member is called when an order cancel request is rejected, presumably because the order is already filled. More... | |
virtual void | on_order_replace_rejected (order_ref &, const reject_info &) |
This member is called when an order replace request is rejected, presumably because the order is already filled. More... | |
virtual void | on_order_rejected (order_ref &o_ref, const reject_info &r_info) |
This member is called when an order is rejected. More... | |
virtual void | on_exception (const tsa::exception &e) |
This member is invoked in the event of an exception. Note that tsa::series_bounds_error exceptions may be handled silently by the strategy and won't trigger the on_exception() event handler if strategy::catch_series_bounds_error(true) was previously invoked. More... | |
virtual void | on_prepare (void) |
The Trading System API library implements a Domain Specific Language (DSL) that greatly simplifies time series logic. The availability of DSL essentially means that the C++ language has been extended through the use of operator overloading and templates to more specifically handle timeseries logic. See the TS-API User Guide for more information and examples. More... | |
virtual void | on_pre_managed_code (void) |
CHECK managed code signals. | |
virtual void | on_timer (const std::string &timer_name) |
Override this member to respond to timer events. Check the name of the timer before executing the appropriate logic. Timers are only available when the strategy is attached to a platform. Normal backtesting is performed at the maximum speed allowed by the hardware and timers are henceforth not useful in such circumstances. See also: strategy::create_repeat_timer(), strategy::create_timer(), strategy::remove_timer() More... | |
virtual void | on_live (void) |
This event handler is invoked when the strategy switches from evaluating 'backfill' data to 'live' data during live deployment. strategy::is_live subsequently returns true. | |
bool | is_live (void) const |
Returns true if the strategy is now running on 'live' data. See strategy::on_live();. More... | |
Series Management | |
The strategy automatically manages the memory allocated by series not explicly declared as strategy members. The following functions allow some level of control over series capacity. | |
void | min_series_length (size_t min_size) |
Sets the minimum length that any series is allowed to have. Note that after a strategy has been running for some time, the size of of series is capped to however much memory is required by the strategy logic. Series won't grow thereafter and the existing memory is continuously reused. If you know that your logic will eventually end up wanting to look back in time further than anticipated by the internal logic, such requirement can be accomodated by calling this member. More... | |
size_t | min_series_length (void) const |
Returns the minimum series length. See: strategy::min_series_length(size_t);. More... | |
void | series_analyze_period (size_t num_bars) |
Sets the number of bars over which a strategy will analyze series memory usage before attempting to freeze the size of all managed series. More... | |
size_t | series_analyze_period (void) const |
Returns the series analyze period. See: stratgy::series_analyze_period(size_t) More... | |
Timer Events | |
The following functions generate 'repeat' and 'once only' timer events. A timer event will result in a call to strategy::on_timer(). Developers must override strategy::on_timer() and check for the name of the timer before executing whatever logic is appropriate. | |
void | create_timer (const std::string &name, const duration &repeat_duration) |
Creates a new repeat timer generator. Timer events will then repeatedly invoke strategy::on_timer() after a given repeat_duration. Timer events must be uniquely named. Timers can only be created when the strategy is attached to a platform or socket and is intended to run on real-time events. More... | |
void | remove_timer (const std::string &name) |
Removes a previously created timer with given name. More... | |
Evaluation Status | |
const date_time & | bar_timestamp (void) const |
const date_time & | timestamp (void) const |
Returns the timestamp of the current strategy bar (end of interval). More... | |
size_t | count (void) const |
Strategy intervals (bars) are numbered sequentially starting at 1. This member returns the ordinal number of the current interval. Note that bar_count() has identical functionality to count() More... | |
size_t | bar_count (void) const |
This member has the same functionality as count(). | |
size_t | interval_count (void) const |
This member has the same functionality as count(). | |
bool | first (void) const |
Returns true if the strategy is currently invoking its on_next() member for the first time. Note that this does not necessarily correspond to the strategy's first interval if strategy::on_prepare() has been defined, as the internal DSL structures created by strategy::on_prepare() may required any number of interval iterations before the strategy can proceed to invoke strategy::on_next() for the first time. strategy::first() can be used to perform 'one-time' functionality. Note: Any strategy initializations should be performed by overriding strategy::on_start(). More... | |
double | net_profit (void) const |
Returns the cumulative net profit accumulated by the strategy thus far. More... | |
void | require_bar_count (size_t bar_count) |
Platform / Connectivity | |
void | attach (net::socket_base &p) |
Connects the strategy to a net::socket_base derived class. Such a class will primarily be class net::socket which allows connectivity between a strategy client and the strategy server for passing order related messages as well as streaming data. More... | |
void | attach (platform_proxy &p) |
Connects the strategy to a platform_proxy derived class which acts as a source of data and provides order processing services. Once attached to a platform_proxy, all data stream requests as well as all orders and related messages are forwarded to the platform_proxy. strategy::is_platform_driven() returns true after the attachment was successful. A platform_proxy derived class is useful when developers want to implement their own connectivity. More... | |
bool | is_platform_driven (void) const |
Returns true if the strategy is attached to either a platform_proxy or a net::socket_base derived class. More... | |
platform_proxy * | platform_proxy_ptr (void) const |
Returns a pointer to the platform to which the strategy object is attached. This may be a std::nullptr if the strategy is not attached to a platform. More... | |
Database | |
bool | is_attached_to (const std::string &data_base_name) |
A strategy can be connected to multiple data_base objects. This member returns true if the strategy object is attached to a data_base with given data_base_name. See attach(const std::string& db_name, tsa::data_base& db) More... | |
data_base * | get_data_source_ptr (const std::string &data_store_name) |
void | attach (tsa::data_base &db) |
Attaches the given data_base to the strategy object. Any streams or instruments trying connect to a data table will implicitly do so in the given database.The internal data_base name will be set to 'default'. It is also possible to explicitly name a database at the point of attachment. See attach_as(const std::string& db_name, tsa::data_base& db). More... | |
void | attach_as (const std::string &db_name, tsa::data_base &db) |
Same functionality as attach(tsa::data_base& db) with the additional option of naming each attached database. This is useful when a strategy needs to access data in multiple data sources. More... | |
Strategy Launch and Evaluation Control | |
void | backfill (const duration &dur) |
When deploying a strategy on real time data, it is usually necessary to 'warm up' various indicators before accurate results can be calculated. To ensure that the strategy can start trading immediately, the strategy needs to be started at some point in the past. While evaluating backfill data (historical data), the strategy does not trade. As soon as the backfill data has been evaluated the on_live() event handler is called, and the strategy is henceforth considered 'live'. More... | |
void | begin (const date_time &begin_time_point) |
Sets the time_point on which the strategy simulation/deployment should start. More... | |
void | end (const date_time &time_point) |
Sets the timepoint on which the strategy simulation should end. Pass date_time::max if the strategy should run without an explicit end time_point. The exit() member can be used to exit a strategy at any one point. More... | |
const date_time & | begin (void) const |
Returns the strategy begin timepoint. More... | |
const date_time & | end (void) const |
Returns the strategy end timepoint. More... | |
void | period (const date_time &start_time_point, const date_time &end_time_point) |
Sets both the strategy start_time_point and end_time_point. Invoking start() and end() separately has the same effect. More... | |
void | run (void) |
Evaluates the strategy by iterating over every strategy interval (bar) between the timepoints set via begin() and end() or period(). If no time_points were set explicitly, then the strategy will attempt to find range information from the data source (if available). | |
void | run (const date_time &start_time_point, const date_time &end_time_point) |
Evaluates the strategy by iterating over every strategy interval (bar) between the given start_time_point and end_time_point. More... | |
void | run (const date_time &start_time_point) |
Evaluates the strategy from the given start_time_point onwards. Runs until the end of the data source is reached, or indefinitely if the strategy is auto-scheduled, or until exit() is called. More... | |
void | exit (void) |
Exits the strategy prematurely before the simulation reaches the predefined end timepoint. If this member is invoked as part of on_next(), then the strategy will stop evaluation AFTER the current call to on_next() has finished evaluating. exit() thus does not exit immediately but rather completes processing the current bar, and then exits gracefully after 'finalizing' the strategy. See is_finalized(). | |
bool | is_finalized (void) const |
Returns true if the strategy has been 'finalized'. In other words, the simulation or deployment is terminated. Once 'finalized', a strategy can not be evaluated any further as all metrics and logs have been create and all connections have been closed. More... | |
void | verbose (std::ostream &stream, int verbose_level=1) |
Runs the strategy in verbose mode. This prints select information about the current strategy evaluation status to the given stream. The only supported verbose_level is currently 1. More... | |
Scheduling | |
bool | is_auto_scheduled (void) const |
Returns 'true' if the strategy generates its own 'scheduling sequence'. Returns 'false' if the scheduling sequence is received from an external source, such as a data_base table or a record stream. More... | |
bool | schedule_was_set (void) const |
Returns true if the 'scheduling sequence' has been defined. A strategy cannot be evaluated without such a scheduling sequence. If the strategy has instrument or in_stream members, then the first such member will be automatically set as the strategy's scheduling sequence unless explicitly set with strategy::schedule_with(). More... | |
std::string | scheduler_name (void) const |
Returns the name of the strategy's scheduling timepoint sequence. More... | |
void | schedule_with (const in_stream &instream) |
Instructs the strategy to use the given in_stream object as 'scheduler'. A scheduler produces a timepoint sequence that define the strategy's intervals, also known as 'bars'. More... | |
void | schedule_with (instrument &instr) |
Instructs the strategy to use the given instrument object as 'scheduler'. A scheduler produces a timepoint sequence that define the strategy's intervals, also known as 'bars'. More... | |
void | schedule_with (time_point_stream &stream) |
Instructs the strategy to use a given time_point_stream as the source for its 'scheduling sequence'. class time_point_stream can be used as a base class for custom timepoint sequence generators. More... | |
void | auto_schedule (const duration &dur) |
Instructs the strategy to internally allocate a time_point_stream with the given fixed duration as interval (bar) length. More... | |
Reporting and Metrics | |
os::path | output_base_path (void) const |
Returns the current value of the strategy-output-base path. The strategy output base path is the path where the strategy creates its strategy specific output path for the purpose of writing reports and charts. More... | |
os::path | output_path (void) const |
Returns the strategy output-path, which corresponds to the directory that the strategy creates to write reports and other output. The output-path is a combination of the output-base-path and the strategy-name, and a possible postfix to make the directory name unique. More... | |
void | output_base_path (const os::path &base_path, bool replace_existing_strategy_dir=false) const |
Sets the strategy-base-path (which must be an existing directory). This is where the strategy will create its own output sub-directory. More... | |
void | enable_reports (void) |
Calling this member causes the strategy to print a set of HTML reports and logs describing strategy performance and other metrics and charts. These are written to disk in a dedicated strategy directory, the path of this directory can be accessed via strategy::output_path(). | |
void | auto_open_reports (bool flag=true) |
Passing a 'true' argument to this member cause browser to automatically open the HTML reports produced by this strategy upon completion of the simulation. If reporting was not enabled by a previous call the strategy::enable_reports(), then this member will do this as well. More... | |
bool | auto_open_reports_enabled (void) const |
Returns true if strategy::auto_open_reports(true) was previously invoked. More... | |
void | report (const os::path &report_dir, bool replace_existing=false) |
void | save_performance_report (const os::path &directory, const std::string &name="", bool replace=true) |
void | risk_free_annual_rate_of_return (double rate) |
Sets the risk free rate of return per annum (0.0 percent by default). This value is used when calculating the 'Sharpe Ratio'. This number should represent the average risk free rate of return over the simulation period. Give a value of 0.03 if the annual risk free rate of return is 3.0 percent. More... | |
double | risk_free_annual_rate_of_return (void) const |
Returns the (user defined) risk free rate of return. (3.5 percent by default) | |
void | drawdown_multiplier (double multiplier) |
double | drawdown_multiplier (void) const |
size_t | num_bars_per_year (void) const |
variant | get_metric (perf_metric_type metric_type, trade_grouping gr=all_trades) const |
variant | metric (const std::string &metric_name, trade_grouping trade_group=tsa::all_trades) const |
Returns the metric corresponding to the given metric_type and trade_group. Only invoke this member once the strategy has been finalized (see strategy::is_finalized()). These metrics are the same metrics that can be found on the 'Strategy Performance Report'. (see strategy::enable_reporting()). Individual metrics are returns as a variant objects since not all metrics share the same type. See the tsa::metric structure for a listing of all possible metric names and types. More... | |
const tsa::metrics & | metrics (void) const |
const tsa::metrics2 & | metrics2 (void) const |
Returns a metrics object containing all the strategy's performance properties. More... | |
Class strategy represents a trading or investment strategy.
Class strategy is the central class of this library. A strategy object is used to simulate trading systems by applying trading rules to historic data. Once a strategy shows satisfactory performance it can then the be deployed on live data. To implement a new trading strategy, users must define their own strategy derived classes. This primarily involves overriding various virtual members, also referred to as 'event- handlers'. Only override the event handlers that are relevant to your strategy. Almost all strategies will define on_start() as this is where data connections are defined. A strategy can connect to any number of data stream but one must be declared as 'strategy scheduler'. See the strategy::schedule_with(). A strategy can also internaly generate its own scheduling sequence in which case the process is referred to as 'internal scheduling'. Internal scheduling can be useful when using computational methods such as monte-carlo simulations.
Most custom strategy logic will be found in the on_next() event handler, also known as on_bar_close(). This event handler is called when a new price bar arrives via the 'scheduling' data stream.
The actual connection to the data source is normally held by instances of class instrument. Instruments are capable of receiving streamed data as well as sending and receiving order related messages. A strategy can have any number of instrument members.
Please refer to the 'Trading System API - User Guide' for comprehensive tutorials on how to derive your own strategy classes.
test link Extensibility.
auto_cast_variant tsa::strategy::arg | ( | const std::string & | arg_name | ) | const |
Returns the value corresponding to an argument with given arg_name.
arg_name | Name of the argument. |
bool tsa::strategy::arg_exists | ( | const std::string & | arg_name | ) |
Returns true if a strategy argument with given arg_name exists.
arg_name | Name of the argument. |
void tsa::strategy::args | ( | const tsa::json & | json_obj | ) |
Sets a json object as strategy arguments. These are values that can be accessed by name while the strategy is initializing or evaluating. This allows users to set simple name- value pairs but there is no restriction on the complexity of the data passed as json, and so it is entirely possible to pass arrays and nested objects as well.
json_obj | The first parameter. |
const tsa::json & tsa::strategy::args | ( | void | ) | const |
Returns all strategy arguments as a json object. Use the strategy::arg() member to access simple values. Complex arrays and json objects cannot however be returned as a variant and so you will need to extract this directly // from the original json object.
void tsa::strategy::attach | ( | net::socket_base & | p | ) |
Connects the strategy to a net::socket_base derived class. Such a class will primarily be class net::socket which allows connectivity between a strategy client and the strategy server for passing order related messages as well as streaming data.
[in,out] | p | The net::socket_base. |
void tsa::strategy::attach | ( | platform_proxy & | p | ) |
Connects the strategy to a platform_proxy derived class which acts as a source of data and provides order processing services. Once attached to a platform_proxy, all data stream requests as well as all orders and related messages are forwarded to the platform_proxy. strategy::is_platform_driven() returns true after the attachment was successful. A platform_proxy derived class is useful when developers want to implement their own connectivity.
[in,out] | p | The platform reference. |
void tsa::strategy::attach | ( | tsa::data_base & | db | ) |
Attaches the given data_base to the strategy object. Any streams or instruments trying connect to a data table will implicitly do so in the given database.The internal data_base name will be set to 'default'. It is also possible to explicitly name a database at the point of attachment. See attach_as(const std::string& db_name, tsa::data_base& db).
[in,out] | db | The data_base. |
void tsa::strategy::attach_as | ( | const std::string & | db_name, |
tsa::data_base & | db | ||
) |
Same functionality as attach(tsa::data_base& db) with the additional option of naming each attached database. This is useful when a strategy needs to access data in multiple data sources.
db_name | Name of the database. | |
[in,out] | db | The database. |
void tsa::strategy::auto_open_reports | ( | bool | flag = true | ) |
Passing a 'true' argument to this member cause browser to automatically open the HTML reports produced by this strategy upon completion of the simulation. If reporting was not enabled by a previous call the strategy::enable_reports(), then this member will do this as well.
flag | true to b. |
bool tsa::strategy::auto_open_reports_enabled | ( | void | ) | const |
Returns true if strategy::auto_open_reports(true) was previously invoked.
void tsa::strategy::auto_schedule | ( | const duration & | dur | ) |
Instructs the strategy to internally allocate a time_point_stream with the given fixed duration as interval (bar) length.
dur | The duration between timepoints. |
void tsa::strategy::backfill | ( | const duration & | dur | ) |
When deploying a strategy on real time data, it is usually necessary to 'warm up' various indicators before accurate results can be calculated. To ensure that the strategy can start trading immediately, the strategy needs to be started at some point in the past. While evaluating backfill data (historical data), the strategy does not trade. As soon as the backfill data has been evaluated the on_live() event handler is called, and the strategy is henceforth considered 'live'.
dur | The duration between the current time and the time the strategy is supposed to start evaluation. E.g duration::minutes(10). |
void tsa::strategy::begin | ( | const date_time & | begin_time_point | ) |
Sets the time_point on which the strategy simulation/deployment should start.
time_point | The start time_point. |
const date_time & tsa::strategy::begin | ( | void | ) | const |
Returns the strategy begin timepoint.
void tsa::strategy::cancel_order | ( | identifier_t | order_id, |
identifier_t | instrument_id | ||
) |
Cancels an order with a given order_id and contract_id. Use this function if there is no corresponding order_ref object. Use order_ref::cancel() otherwise.
order_id | Identifier for the order. |
contract_id | Identifier for the instrument. |
void tsa::strategy::catch_series_bounds_errors | ( | bool | flag = true | ) |
A series function that is unable to access enough data to perform the calculation it was intended for will cause a series_bounds_error exception to be thrown. This will immediately terminate the strategy unless the users explicitly instructs the strategy to silently handle such series_bounds_error exceptions, by catching the exception. Note that this member is intended to be used as part of the definition of strategy::on_next() and that it any code after the statement that cause the exception will be skipped.
flag | Set to 'true' to silently catch series bounds errors, and to 'false' to disable. |
size_t tsa::strategy::count | ( | void | ) | const |
Strategy intervals (bars) are numbered sequentially starting at 1. This member returns the ordinal number of the current interval. Note that bar_count() has identical functionality to count()
void tsa::strategy::create_timer | ( | const std::string & | name, |
const duration & | repeat_duration | ||
) |
Creates a new repeat timer generator. Timer events will then repeatedly invoke strategy::on_timer() after a given repeat_duration. Timer events must be uniquely named. Timers can only be created when the strategy is attached to a platform or socket and is intended to run on real-time events.
name | The timer name. |
repeat_duration | The duration between timer events. |
void tsa::strategy::end | ( | const date_time & | time_point | ) |
Sets the timepoint on which the strategy simulation should end. Pass date_time::max if the strategy should run without an explicit end time_point. The exit() member can be used to exit a strategy at any one point.
time_point | The timestamp of the last bar the strategy will evaluate before exiting. |
const date_time & tsa::strategy::end | ( | void | ) | const |
Returns the strategy end timepoint.
strategy_end_type tsa::strategy::end_type | ( | void | ) | const |
This member returns a value corresponding to the cause of the strategy shutdown.
bool tsa::strategy::first | ( | void | ) | const |
Returns true if the strategy is currently invoking its on_next() member for the first time. Note that this does not necessarily correspond to the strategy's first interval if strategy::on_prepare() has been defined, as the internal DSL structures created by strategy::on_prepare() may required any number of interval iterations before the strategy can proceed to invoke strategy::on_next() for the first time. strategy::first() can be used to perform 'one-time' functionality. Note: Any strategy initializations should be performed by overriding strategy::on_start().
order_ref tsa::strategy::get_order_ref | ( | identifier_t | order_id | ) | const |
Returns a reference to the order with the given order_id. Throws an exception if the order does not exist.
order_id | Identifier for the order. |
size_t tsa::strategy::instrument_count | ( | void | ) | const |
Returns the number of instruments that are part of the strategy. Instruments are added as strategy members.
Note: The strategy object becomes aware of instruments members only after the instrument has either connected to a datasource or has been identified by symbol, at which point it registers with the strategy.
instrument * tsa::strategy::instrument_ptr | ( | size_t | position | ) | const |
Returns a pointer to the instrument at the given position. Positions start at 0. Instruments cannot be removed from a strategy. The function will throw an exception if the given instrument identifier is not valid. Use the strategy::instrument_count() member to determine how many valid instruments there are.
position | The instrument position. |
std::vector< instrument * > & tsa::strategy::instruments | ( | void | ) | const |
Returns a container with pointers to all instrument member objects registered with the strategy.
Note: The strategy object becomes aware of instruments members only after the instrument has either connected to a datasource or has been identified by symbol, at which point it registers with the strategy.
bool tsa::strategy::is_attached_to | ( | const std::string & | data_base_name | ) |
A strategy can be connected to multiple data_base objects. This member returns true if the strategy object is attached to a data_base with given data_base_name. See attach(const std::string& db_name, tsa::data_base& db)
data_base_name | Name of the data base. |
bool tsa::strategy::is_auto_scheduled | ( | void | ) | const |
Returns 'true' if the strategy generates its own 'scheduling sequence'. Returns 'false' if the scheduling sequence is received from an external source, such as a data_base table or a record stream.
|
virtual |
Returns true if the strategy has been 'finalized'. In other words, the simulation or deployment is terminated. Once 'finalized', a strategy can not be evaluated any further as all metrics and logs have been create and all connections have been closed.
Implements tsa::metrics_source.
bool tsa::strategy::is_live | ( | void | ) | const |
Returns true if the strategy is now running on 'live' data. See strategy::on_live();.
bool tsa::strategy::is_platform_driven | ( | void | ) | const |
Returns true if the strategy is attached to either a platform_proxy or a net::socket_base derived class.
|
virtual |
Returns the metric corresponding to the given metric_type and trade_group. Only invoke this member once the strategy has been finalized (see strategy::is_finalized()). These metrics are the same metrics that can be found on the 'Strategy Performance Report'. (see strategy::enable_reporting()). Individual metrics are returns as a variant objects since not all metrics share the same type. See the tsa::metric structure for a listing of all possible metric names and types.
metric_name | The metric name. See tsa::metric. |
trade_group | Type of trade grouping. |
Implements tsa::metrics_source.
const tsa::metrics2 & tsa::strategy::metrics2 | ( | void | ) | const |
Returns a metrics object containing all the strategy's performance properties.
Only invoke this member once the strategy had been 'finalized'. The metrics object returned can be saved to disk, read from disk, as well as merged with other metrics objects. This is extremely useful as this makes it possible to combine multiple trading strategies into a combined strategy.
void tsa::strategy::min_series_length | ( | size_t | min_size | ) |
Sets the minimum length that any series is allowed to have. Note that after a strategy has been running for some time, the size of of series is capped to however much memory is required by the strategy logic. Series won't grow thereafter and the existing memory is continuously reused. If you know that your logic will eventually end up wanting to look back in time further than anticipated by the internal logic, such requirement can be accomodated by calling this member.
min_size | The minimum series capacity. |
size_t tsa::strategy::min_series_length | ( | void | ) | const |
Returns the minimum series length. See: strategy::min_series_length(size_t);.
void tsa::strategy::name | ( | const std::string & | name | ) |
Sets the strategy name. The strategy name is displayed on reports and is used as part of the strategy's output directory name to which reports and charts are written. If no strategy name is given, the strategy will be given a default name based on the current system time.
name | The name. |
double tsa::strategy::net_profit | ( | void | ) | const |
Returns the cumulative net profit accumulated by the strategy thus far.
|
virtual |
This event handler is triggered when a JSON command is received. Strategies can thus respond to ad-hoc command sent to it from elsewhere during real time deployment.
parameter1 | The first parameter. |
|
virtual |
This member is invoked in the event of an exception. Note that tsa::series_bounds_error exceptions may be handled silently by the strategy and won't trigger the on_exception() event handler if strategy::catch_series_bounds_error(true) was previously invoked.
The default implementation of this member simply re-throws the exception! Strategies should not normally throw any exceptions during evaluation. Override the on_exception() member to write relevant strategy information to a log. Be sure not to cause any other exceptions! Once the desired actions have been performed, on_exception() must re-throw the exception as its last act! If the exception is not rethrown the system assumes that the exception was succesfully handled.
e | The first parameter. |
|
virtual |
This member is invoked repeatedly, once for every new price bar, or whenever a price bar is received by the scheduling sequence during real time deployment. The on_next() member definition usually comprises the bulk of a strategy's trading logic.
Note: The on_bar_close() macro is defined as a synonym for on_next().
|
virtual |
This member is called when an order cancel request is rejected, presumably because the order is already filled.
[in,out] | o_ref | A reference to the order related to the rejection. |
r_info | Information about the rejection. |
|
virtual |
This member is invoked by the strategy every time an order in filled in its entirety. See also: on_partial_fill();.
oref | A reference to the filled order. |
t | A reference to the transaction that filled the order. |
|
virtual |
This member is invoked by the strategy every time an order in partially filled. See also: on_order_filled().
[in,out] | o_ref | A reference to the partially filled order. |
t | A reference to the transaction that partially filled the order. |
|
virtual |
This member is called when an order is rejected.
[in,out] | o_ref | A reference to the order related to the rejection. |
r_info | Information about the rejection. |
|
virtual |
This member is called when an order replace request is rejected, presumably because the order is already filled.
[in,out] | parameter1 | The first parameter. |
parameter2 | The second parameter. |
|
virtual |
This member is invoked when the status of an order changes.
[in,out] | o_ref | A reference to the order whose status has changed. |
|
virtual |
The Trading System API library implements a Domain Specific Language (DSL) that greatly simplifies time series logic. The availability of DSL essentially means that the C++ language has been extended through the use of operator overloading and templates to more specifically handle timeseries logic. See the TS-API User Guide for more information and examples.
All DSL code must be called from within the strategy::on_prepare() member. DSL code called from outside strategy::on_prepare() will otherwise cause an exception. Note that strategy::on_prepare() is only invoked once, at strategy start-up, and its role is to 'translate' the given DSL logic into data structures that will actually evaluate the given logic at strategy run-time. You can think of it as a form of compilation.
|
virtual |
Override this member to respond to timer events. Check the name of the timer before executing the appropriate logic. Timers are only available when the strategy is attached to a platform. Normal backtesting is performed at the maximum speed allowed by the hardware and timers are henceforth not useful in such circumstances. See also: strategy::create_repeat_timer(), strategy::create_timer(), strategy::remove_timer()
timer_name | Name of the timer. |
|
virtual |
This member is invoked by the strategy every time a transaction is confirmed (fill or partial-fill). Use it to cancel or place related orders or to adjust active order quantities, or any other relevant task. See also: strategy::on_filled(), strategy::on_partially_filled().
t | The transaction. |
size_t tsa::strategy::order_count | ( | void | ) | const |
Returns the number of 'active' orders. 'Active' orders are orders that have been dispatched and which have not been confirmed cancelled or filled. Note that in addition to the number of orders returned by this member, there may exist any number of 'inactive' orders. Inactive orders are only marked for deletion once their reference count has gone to zero. See class order_ref.
size_t tsa::strategy::order_count_inclusive | ( | void | ) | const |
Returns the comprehensive number of orders including both 'inactive' and 'active' orders.
order * tsa::strategy::order_ptr | ( | identifier_t | order_id | ) | const |
Returns a pointer to an order with given order_id. Normally orders are handled via instances of class order_ref. Direct access to order objects may only be required during special situations.
order_id | Identifier for the order. |
os::path tsa::strategy::output_base_path | ( | void | ) | const |
Returns the current value of the strategy-output-base path. The strategy output base path is the path where the strategy creates its strategy specific output path for the purpose of writing reports and charts.
void tsa::strategy::output_base_path | ( | const os::path & | base_path, |
bool | replace_existing_strategy_dir = false |
||
) | const |
Sets the strategy-base-path (which must be an existing directory). This is where the strategy will create its own output sub-directory.
The output directory that the strategy creates in the given base_path will be named after the strategy itself. This is why it is recommended to give the strategy a meaningful name via strategy::name(). The default strategy name is based on the strategy's creation date-time. The replace_existing_strategy_dir flag is set to false by default which causes the strategy to potentially append a number to the strategy directory to make it unique.
Note: Reports are only generated if strategy::enable_reports() was invoked before the strategy is evaluated.
base_path | Path to an existing directory. |
replace_existing_strategy_dir | true to replace existing strategy dir. |
os::path tsa::strategy::output_path | ( | void | ) | const |
Returns the strategy output-path, which corresponds to the directory that the strategy creates to write reports and other output. The output-path is a combination of the output-base-path and the strategy-name, and a possible postfix to make the directory name unique.
Sets both the strategy start_time_point and end_time_point. Invoking start() and end() separately has the same effect.
start_time_point | The start time point. |
end_time_point | The end time point. |
platform_proxy * tsa::strategy::platform_proxy_ptr | ( | void | ) | const |
Returns a pointer to the platform to which the strategy object is attached. This may be a std::nullptr if the strategy is not attached to a platform.
void tsa::strategy::remove_timer | ( | const std::string & | name | ) |
Removes a previously created timer with given name.
name | The timer name. |
void tsa::strategy::report | ( | const os::path & | _report_dir, |
bool | _replace_existing = false |
||
) |
Use report_dir to specify where reports are to be saved to. By default the reports are written to a directory created in the current working directory. This directory name is derived from the strategy name!
The 'Strategy Performance Report' is saved in the top directory. Sub-directories are created for each traded instrument (share, future, ccy, etc.) and the corresponding reports are saved in it.
Use the replace_existing flag to determin whether the strategy should silently replace an existing report directory of the same name.
void tsa::strategy::risk_free_annual_rate_of_return | ( | double | rate | ) |
Sets the risk free rate of return per annum (0.0 percent by default). This value is used when calculating the 'Sharpe Ratio'. This number should represent the average risk free rate of return over the simulation period. Give a value of 0.03 if the annual risk free rate of return is 3.0 percent.
rate | The risk free rate. |
Evaluates the strategy by iterating over every strategy interval (bar) between the given start_time_point and end_time_point.
start_time_point | The start time point. |
end_time_point | The end time point. |
void tsa::strategy::run | ( | const date_time & | start_time_point | ) |
Evaluates the strategy from the given start_time_point onwards. Runs until the end of the data source is reached, or indefinitely if the strategy is auto-scheduled, or until exit() is called.
start_time_point | The start time point. |
bool tsa::strategy::schedule_was_set | ( | void | ) | const |
Returns true if the 'scheduling sequence' has been defined. A strategy cannot be evaluated without such a scheduling sequence. If the strategy has instrument or in_stream members, then the first such member will be automatically set as the strategy's scheduling sequence unless explicitly set with strategy::schedule_with().
void tsa::strategy::schedule_with | ( | const in_stream & | instream | ) |
void tsa::strategy::schedule_with | ( | instrument & | instr | ) |
Instructs the strategy to use the given instrument object as 'scheduler'. A scheduler produces a timepoint sequence that define the strategy's intervals, also known as 'bars'.
[in,out] | instr | The instrument object. |
void tsa::strategy::schedule_with | ( | time_point_stream & | stream | ) |
Instructs the strategy to use a given time_point_stream as the source for its 'scheduling sequence'. class time_point_stream can be used as a base class for custom timepoint sequence generators.
[in,out] | stream | The time_point_stream object. |
std::string tsa::strategy::scheduler_name | ( | void | ) | const |
Returns the name of the strategy's scheduling timepoint sequence.
void tsa::strategy::series_analyze_period | ( | size_t | num_bars | ) |
Sets the number of bars over which a strategy will analyze series memory usage before attempting to freeze the size of all managed series.
num_bars | Number of bars to analyze. |
size_t tsa::strategy::series_analyze_period | ( | void | ) | const |
Returns the series analyze period. See: stratgy::series_analyze_period(size_t)
const date_time & tsa::strategy::timestamp | ( | void | ) | const |
Returns the timestamp of the current strategy bar (end of interval).
The strategy timestamp always corresponds to the current timestamp of the record stream that provides the scheduling-sequence. See the strategy::schedule_with() member. Other record streams may have different timescales and may be more or less out of date with the current scheduling-sequence.
void tsa::strategy::verbose | ( | std::ostream & | stream, |
int | verbose_level = 1 |
||
) |
Runs the strategy in verbose mode. This prints select information about the current strategy evaluation status to the given stream. The only supported verbose_level is currently 1.
[in,out] | stream | The first parameter. |
verbose_level | The verbose level. Only '1' is currently supporte. |