Trading System API  3.0
Library for Simulating and Deploying Trading and Investment Strategies
TSAStrategy.h
1 /* ===================================================================
2 *
3 * T R A D I N G S Y S T E M A P I ™
4 * Copyright © 1999 - 2014 by Peter Ritter ( TradingSystemAPI.com )
5 * A L L R I G H T S R E S E R V E D
6 *
7 * Consult your license regarding permissions and restrictions.
8 * You may obtain a copy of the License at:
9 * http://www.TradingSystemAPI.com/licenses/LICENSE-TSAPI-3.0.html
10 *
11 * ====================================================================
12 */
13 
14 #ifndef TSA_STRATEGY__INCLUDED
15 #define TSA_STRATEGY__INCLUDED
16 
17 #include <ostream>
18 
19 #include "TSATypeDef.h"
20 #include "TSAVariant.h"
21 #include "TSAOrder.h"
22 #include "TSAError.h"
23 #include "TSARandGen.h"
24 #include "TSALogs.h"
25 #include "TSASeriesManaged.h"
26 #include "TSAMemTable.h"
27 #include "TSAMetrics.h"
28 #include "TSAMetrics2.h"
29 #include "TSAInstrument.h"
30 #include "TSAOS.h"
31 #include "TSASupport.h"
32 #include "TSAPlatformMsg.h"
33 #include "TSAJSON.h"
34 
35 
40 namespace tsa {
41 
42  class instrument;
43  class in_stream;
44  class strategy_delegate;
45  class order_manager;
46  class trade_manager;
47  class equity_metrics;
48  class trade_metrics;
49  class platform_proxy;
50  class transaction;
51  class data_base;
52  class json;
53  namespace net{
54  class socket_base;
55  }
56 
61  struct reject_info {
65  };
66 
73 #define on_bar_close on_next
74 
75  /*
76  ** ====================================================
77  ** >>> class strategy <<<
78  ** ====================================================
79  */
80 
108  class dll_export strategy : public object, public metrics_source {
109  tsa_declare_testable;
110  friend class instrument;
111  friend class series_core;
112  friend class function_state;
113  friend class strategy_delegate;
114  private:
115  friend void order_manager::ON_TRANSACTION(const transaction&);
116  strategy_delegate* m_strat_delegate_ptr;
117  double m_risk_free_annual_rate_of_return;
118  double m_drawdown_multiplier;
119  size_t m_bars_per_year;
120  size_t m_min_series_freeze_size;
121  size_t m_series_analyze_period_length;
122  public:
123  rand_gen m_Rng;
124  public:
125  strategy_state_type state();
126  private:
127  void touch_series_states(size_t _idx);
128  void try_freeze_series_sizes(size_t min_ser_len);
129  void delete_series_states(void);
130  std::vector<managed_series*> m_series;
131  void create_managed_series(identifier_t, type_t);
132  bool managed_series_exists(identifier_t) const;
133  const managed_series* const_series_ptr(long ID) const;
134  managed_series* series_ptr(identifier_t ID);
135  void PrintVectorStateObjects(std::ostream&, long _ID) const;
136  public:
137  size_t series_count(void) const;
138  size_t m_managed_series_counter;
139  size_t m_nNumCallsOf_EVALUATE_member;
140  bool m_disallow_new_managed_series;
141  bool m_completed_first_bar_with_no_lookback_exception;
142  bool m_is_operational;
143  size_t m_operational_bar;
144  bool m_all_series_finalized;
145  size_t m_strategy_lookback;
146  bool m_managed_code_ran_clean;
147  size_t m_managed_code_ran_clean_count;
148  size_t m_min_series_length;
149  bool m_has_managed_code;
150  bool m_first_on_next_completed;
151  named_values m_property_map;
152  tsa::json m_json;
153  duration m_backfill_duration;
154  date_time m_timestamp_of_first_bar_with_no_lookback_exception;
155  date_time m_operational_timestamp;
156  mutable std::mutex m_BAR_Mutex;
157  //identifier_t m_platform__strategy_ID=0;
158  public:
159  bool all_series_length_frozen(void) const;
160  size_t managed_series_count(void) const;
161  void socket__strategy_pos(int pos);
162  size_t socket__strategy_pos(void)const;
163  void strategy_ID(identifier_t id);
164  identifier_t strategy_ID(void)const;
165  private:
166  void increment_series_state_counter(void);
167  size_t GetNumCallsOf_BAR_Member(void) const;
168  void invoke_virtual_evaluate_on_all_components(bool _pre);
169  void _EVALUATE(void);
170  private:
171  void raise_series_bounds_error(void);
172  public:
173  log_type_t get_log_type(void) const;
174  strategy_delegate& get_strategy_delegate(void);
175  private:
176  strategy(strategy&) = delete;
177  strategy(const std::string&, const date_time& _t);
178  void operator= (strategy&) = delete;
179  private:
180  void register_instrument(instrument*);
181  public:
182  void note_platform_destroyed(platform_proxy*);
183  public:
184  //===================================
187  //===================================
189  strategy(void);
191  ~strategy(void);
192 
200  void args(const tsa::json& json_obj);
201 
208  const tsa::json& args(void)const;
209 
215  bool arg_exists(const std::string& arg_name);
216 
222  auto_cast_variant arg(const std::string& arg_name)const;
223 
224  //=================
226  //=================
227 
228  void initialize(series_base*);
229  public:
230  //============================
231 
239  void name(const std::string& name);
240 
242  const std::string& name(void) const;
243  //=================
245  //=================
246  public:
247  //============================
253  //============================
254 
260  virtual void on_command(const tsa::json&);
261 
262  // internal
263  virtual void on_message(const tsa::json&);
264  // internal
265  virtual void on_signal(const std::string& signal_string);
266  // internal
267  virtual void on_error(const tsa::json&);
268 
273  virtual void on_start(void);
274 
280  virtual void on_end(void);
281 
286  strategy_end_type end_type(void)const;
287 
295  virtual void on_next(void);
296 
303  virtual void on_transaction(const transaction& t);
304 
311  virtual void on_order_filled(const order_ref& oref, const transaction& t);
312 
319  virtual void on_order_partially_filled(order_ref& o_ref, const transaction& t);
320 
325  virtual void on_order_status_changed(order_ref& o_ref);
326 
333  virtual void on_order_cancel_rejected(order_ref& o_ref, const reject_info& r_info);
334 
341  virtual void on_order_replace_rejected(order_ref&, const reject_info&);
342 
348  virtual void on_order_rejected(order_ref& o_ref, const reject_info& r_info);
349 
364  virtual void on_exception(const tsa::exception& e);
365 
379  virtual void on_prepare(void);
380 
384  virtual void on_pre_managed_code(void);
385 
394  virtual void on_timer(const std::string& timer_name);
395 
400  virtual void on_live(void);
401 
406  bool is_live(void)const;
407 
408 
409  //=================
411  //=================
412 
413  public:
414  void assume_functor_ownership(functor::functor_parent_base*);
415  //IU For platform deployment
416  void on_platform_transaction(const transaction&);
417  public:
418  bool is_current(void);
419  public:
426  void on_series_bounds_error_terminate(void);
427 
438  void catch_series_bounds_errors(bool flag = true);
439  private:
440  bool m_terminate_on_series_bounds_error;
441  private:
442  void make_current(void);
443  void release_current(void);
444  private:
445  mutable date_time m_tmp_metrics_source_end_timestamp;
446  public: //metrics_source overrides
447  virtual const date_time& metrics_source__begin_timestamp(void) const override;
448  virtual const date_time& metrics_source__end_timestamp(void) const override;
449  virtual bool is_contract(void) const override { return false; }
450  virtual std::string metric_source_name(void) const override { return name(); }
451  public:
452  //============================
457  //============================
458 
468  void min_series_length(size_t min_size);
469 
474  size_t min_series_length(void) const;
475 
481  void series_analyze_period(size_t num_bars);
482 
487  size_t series_analyze_period(void) const;
488  //=================
490  //=================
491  public:
492  //============================
498  //============================
499 
508  void create_timer(const std::string& name, const duration& repeat_duration);
509 
510  /* NOT IMPLEMENTED
511 
512  * @brief Creates a named timer that will cause strategy::on_timer() to be invoked at given @a
513  * trigger_timestamp. Timer events must be uniquely named. Timers can only be created when the
514  * strategy is attached to a platform or socket and is intended to run on real-time events.
515  * @param name The timer name.
516  * @param trigger_timestamp The trigger timestamp.
517  */
518  //void create_timer(const std::string& name, const date_time& trigger_timestamp);
519 
522  void remove_timer(const std::string& name);
523 
524  //=================
526  //=================
527  public:
528  //============================
531  //============================
532 
533  // @brief Same as strategy::timestamp().
534  // @return A date_time&amp;
535  const date_time& bar_timestamp(void) const;
536 
546  const date_time& timestamp(void) const;
547 
554  size_t count(void) const;
555 
557  size_t bar_count(void) const;
559  size_t interval_count(void) const;
560 
571  bool first(void) const;
572 
577  double net_profit(void) const;
578 
579  // deprecated
580  void require_bar_count(size_t bar_count);
581 
582  //=================
584  //=================
585  public:
586 
595  size_t order_count(void) const;
596 
602  size_t order_count_inclusive(void) const;
603 
610  void cancel_order(identifier_t order_id, identifier_t instrument_id);
611 
618  order_ref get_order_ref(identifier_t order_id) const;
619 
627  order* order_ptr(identifier_t order_id) const;
628  //=================
630  //=================
631  public:
632  //============================
633 
643  size_t instrument_count(void) const;
644 
654  std::vector<instrument*>& instruments(void) const;
655 
664  instrument* instrument_ptr(size_t position) const;
665 
666  //=================
668  //=================
669 
670  //IU Returns true if the strategy is operational..
671  bool is_operational(void) const;
672 
673  //IU Returns the number of bars that were processed before the strategy reached 'operational status'.
674  size_t operational_bar(void) const;
675 
676  const date_time& operational_timestamp(void) const;
677  public:
678  //===================================
681  //===================================
682 
689  void attach(net::socket_base& p);
690 
699  void attach(platform_proxy& p);
700 
706  bool is_platform_driven(void) const;
707 
713  platform_proxy* platform_proxy_ptr(void)const;
714  //=================
716  //=================
717 
718  void process_message_from_platform(net::message& msg);
719 
720  private:
721  platform_proxy* m_platform_proxy_ptr = nullptr;
722  public:
723  //===================================
726  //===================================
727 
735  bool is_attached_to(const std::string& data_base_name);
736 
737  // internal
738  data_base* get_data_source_ptr(const std::string& data_store_name);
739 
747  void attach(tsa::data_base& db);
748 
756  void attach_as(const std::string& db_name, tsa::data_base& db);
757  //=================
759  //=================
760 
761  void log_db(tsa::fast::database&); //internal
762  void register_component(component*); //internal
763 
764  public:
765  //=================================================
768  //=================================================
769 
780  void backfill(const duration& dur);
781 
786  void begin(const date_time& begin_time_point);
787 
794  void end(const date_time& time_point);
795 
800  const date_time& begin(void) const;
801 
806  const date_time& end(void) const;
807 
814  void period(const date_time& start_time_point, const date_time& end_time_point);
815 
821  void run(void);
822 
829  void run(const date_time& start_time_point, const date_time& end_time_point);
830 
837  void run(const date_time& start_time_point);
838 
846  void exit(void);
847 
854  bool is_finalized(void) const;
855 
863  void verbose(std::ostream& stream, int verbose_level = 1);
864 
865  //=================
867  //=================
868  //
869 
870  // future use
871  void start(const date_time& start_timestamp = date_time());
872  // future use
873  void next(const date_time&);
874  // future use
875  void stop(void);
876  public:
877  //======================
880  //======================
881 
888  bool is_auto_scheduled(void) const;
889 
897  bool schedule_was_set(void) const;
898 
903  std::string scheduler_name(void) const;
904 
910  void schedule_with(const in_stream& instream);
911 
917  void schedule_with(instrument& instr);
918 
925  void schedule_with(time_point_stream& stream);
926 
932  void auto_schedule(const duration& dur);
933 
934  //=================
936  //=================
937  public:
938 
939  void terminate(void);
940  bool evaluation_started(void) const;
941  bool evaluate_bar(void);
942  bool evaluate_bar(std::istream& stream);
943  bool GetPostBacktestUpdateWasCompleted(void) const;
944  void verify_finalized(void) const;
945  void verify_eval_not_started(void) const;
946  bool is_scheduled_by_series(void) const;
947 
948  //================================
949  // Platform
950  //================================
951  void platform__initialize(void);
952  void platform__run(void);
953  bool platform__evaluate_bar(const date_time&);
954  private:
955  time_point_stream* m_schedule_sequence_ptr;
956  auto_time_point_stream m_scheduler_intra;
957  public:
958  //================================
961  //================================
962 
969  os::path output_base_path(void) const;
970 
978  os::path output_path(void) const;
979 
995  void output_base_path(const os::path& base_path, bool replace_existing_strategy_dir = false) const;
996 
1003  void enable_reports(void);
1004 
1011  void auto_open_reports(bool flag = true);
1012 
1017  bool auto_open_reports_enabled(void) const;
1018 
1019  // deprecated
1020  void report(const os::path& report_dir, bool replace_existing = false);
1021 
1022  // deprecated
1023  void save_performance_report(const os::path& directory,
1024  const std::string& name = "", bool replace = true);
1025 
1033  void risk_free_annual_rate_of_return(double rate);
1034 
1036  double risk_free_annual_rate_of_return(void) const;
1037 
1039  void drawdown_multiplier(double multiplier);
1040 
1042  double drawdown_multiplier(void) const;
1043 
1044  // Returns the 'number of bars per year'. This number is used by internal volatility calculations.
1045  size_t num_bars_per_year(void) const;
1046  //=================
1048  //=================
1049  public:
1050  //================================
1053  //================================
1054 
1055  /* obsolete
1056  * @brief Returns the metric corresponding to the given @a metric_type and @a aggregation_type.
1057  * Only invoke this member once the strategy had been finalized (see strategy::is_finalized()).
1058  * These metrics are the same metrics as can be found on the 'Strategy Performance Report'. (see
1059  * strategy::enable_reporting()).
1060  * @param metric_type Type of metric.
1061  * @param aggregation_type Type of metric aggregation.
1062  * @return The metric. The metric is returns as a variant since different metrics have different
1063  * types.
1064  */
1065  variant get_metric(perf_metric_type metric_type, trade_grouping gr = all_trades) const;
1066 
1078  variant metric(const std::string& metric_name, trade_grouping trade_group = tsa::all_trades) const;
1079 
1080 
1081  /* obsolete
1082  * @brief Returns a metrics object containing all the strategy's performance properties. Only
1083  * invoke this member once the strategy had been 'finalized'.
1084  *
1085  * Multiple metrics objects from different strategies can be aggregated into aggregated
1086  * portfolio metrics.
1087  * @return The metrics object.
1088  */
1089  const tsa::metrics& metrics(void) const;
1090 
1101  const tsa::metrics2& metrics2(void) const;
1102 
1103  //=================
1105  //=================
1106  protected:
1107  void report(log_type_t logTypes,
1108  const os::path& report_dir, bool replace_existing = false);
1109  public:
1110  fast::database* log_db_ptr(void) const;
1111  virtual void daily_cash_flow(mem_table& mt) const;
1112  void daily_equity_vector(std::vector<double>& vector) const;
1113  void num_bars_per_year(size_t nNumBars);
1114  //size_t total_bars_processed() const;
1115  double simulation_period_in_years(void) const;
1116  double simulation_period_in_days(void) const;
1117  //double GetNumUnitsTraded_Other(trade_grouping direction = all_trades) const;
1118  double annualized_volatility(double start_account_equity, size_t bars_per_year) const;
1119  bool is_in_drawdown(void) const;
1120  //double GetCurrentDrawdown(void) const;
1121  };
1122 
1124 
1125 } // namespace tsa
1126 
1127 #endif
Utility class to manipulate file system paths. This class is intended to fulfil the requirements of t...
Definition: TSAOS.h:36
Class order is the library&#39;s internal order representation. Users are not intended to interact with t...
Definition: TSAOrder.h:49
Namespace for the &#39;Trading System API&#39; library.
Definition: original1.TSA3Core.cpp:20
identifier_t order_id
The &#39;id&#39; of the order ID related to this &#39;reject&#39;.
Definition: TSAStrategy.h:63
Class for managing native timeseries database files. Extremely high speed data access.
Definition: TSADatabase.h:118
Base class for all other database classes such as:
Definition: TSADBBase.h:47
Base class for classes that can produce metrics.
Definition: TSAMetrics.h:44
perf_metric_type
Values that represent performance metric types.
Definition: TSATypeDef.h:216
strategy_state_type
Values that represent strategy state ts.
Definition: TSATypeDef.h:84
structure defining all the metric names. For example, you can pass metric::trade_count as metric_name...
Definition: TSATypeDef.h:297
Strategy performance metrics.
Definition: TSAMetrics.h:367
Definition: TSAVariant.h:656
log_type_t
Log type enumeration. Multiple log types can be combined by using operator|.
Definition: TSATypeDef.h:424
variant objects can represent values of different types.
Definition: TSAVariant.h:140
Represents a reference to an internally managed order object. Working with class order directly is no...
Definition: TSAOrder.h:422
Represents a duration - the difference between two date_time values.
Definition: TSATime.h:945
Replace existing target if it already exists.
Definition: TSAStreams.h:533
_value_types_type
Data type enumeration used throughout the library. Intended to be used via type_t.
Definition: TSATypeDef.h:166
Class tsa::exception used by most classes of the Trading System API library. The class inherits from ...
Definition: TSAError.h:37
Parent class for many library classes.
Definition: TSATypeDef.h:462
Represents a transaction that occurred on an exchange or as part of a simulation when an order is fil...
Definition: TSATransaction.h:40
trade_grouping
Trade aggregation types used by reporting functionality.
Definition: TSATypeDef.h:208
Definition: TSATypeDef.h:107
The strategy &#39;net profit&#39; (after slippage + commission).
All trades.
Definition: TSATypeDef.h:211
Record stream class. Represents a standardised interface to all data sources. Instances rely on deleg...
Definition: TSAStreams.h:336
A class representing JSON objects.
Definition: TSAJSON.h:81
Class strategy represents a trading or investment strategy.
Definition: TSAStrategy.h:108
Definition: TSAPlatformSocket.h:46
Class representing a gregorian-date and time-of-day combination. The time component has microsecond r...
Definition: TSATime.h:428
int64_t identifier_t
type for ID&#39;s
Definition: TSATypeDef.h:117
std::string info
The reason for the reject, if available.
Definition: TSAStrategy.h:64
Base class for components such as series_base adaptors.
Definition: TSAComponent.h:34
Class instrument represents a tradeable security such as a stock, option, futures contract...
Definition: TSAInstrument.h:64
Class mem_table represents a memory based table. mem_table objects can be used in strategies both for...
Definition: TSAMemTable.h:48
Parent class to classes generating a strategy scheduling sequences. (see strategy::schedule_with()) ...
Definition: TSAIntraday.h:45
Structure containing informations about rejects.
Definition: TSAStrategy.h:62