Trading System API  3.0
Library for Simulating and Deploying Trading and Investment Strategies
TSADatabase.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_DATABASE__INCLUDED
15 #define TSA_DATABASE__INCLUDED
16 
17 #include <fstream>
18 #include <iostream>
19 #include <ostream>
20 #include <climits>
21 
22 #include "TSADBCore.h"
23 #include "TSALargeFile.h"
24 #include "TSASimBaseSeries.h"
25 #include "TSAPriceBar.h"
26 #include "TSASeriesTemplate.h"
27 #include "TSAStreams.h"
28 #include "TSAOS.h"
29 #include "TSADataDef.h"
30 #include "TSADBBase.h"
31 #include "TSADatabaseImp.h"
32 
33 namespace tsa {
34 
37 
43  dll_export enum open_db_flag_type {
44  create_db = 0x2,
45  no_create_db = 0x4,
46  truncate_db = 0x8
47  };
48 
56 
58 
59  namespace os {
60  class path;
61  }
62  class table_imp;
63  class large_file;
64  class mem_table;
65 
68 
70  namespace fast {
71 
72  /*
73  ** ====================================================
74  ** > > > class database < < <
75  ** ====================================================
76  */
77 
118  class dll_export database final : public data_base {
119  tsa_declare_testable;
120  friend class table_imp_ref;
121  friend class table_imp;
122  friend class table;
123  private:
124  friend class table_reader;
125  private:
126  class db_file_creator {
127  private:
128  friend class database;
129  db_file_creator(void);
130  db_file_creator(const std::string& db_name,
131  const os::path& dir, open_db_flag_type flag);
132  } m_db_file_maker;
133  static const std::string default_db_file_name;
134  public:
135  enum Result { success, table_does_not_exist, table_is_opened };
136  private:
137  db_page_file m_page_file;
138  db_storage_manager m_storage_man;
139  std::map<table_imp_ref*, table_imp_ref*> m_table_ptr_map;
140  private:
141  identifier_t m_database_ID;
142  std::map<std::string, table_imp*> m_name_to_table_map;
143  size_t __get_next_page_num_to_write(void) const;
144  std::string m_db_name;
145  os::path m_db_path;
146  public:
147  static bool invalid_shutdown;
148  private:
149  db_page_file* get_page_file_ptr(void);
150  size_t get_page_size(void) const;
151  public:
152  table_imp_ref get_table_object(const std::string&);
153  void save_table_object(const table_imp&);
154  size_t get_open_table_count(void) const;
155  private:
156  static bool can_open_file_exclusively(const os::path& path);
157  database(const std::string& data_file, const std::string& index_file, bool tst, bool _tst);
158  public:
159  virtual std::string type(void)const override;
160  public:
163 
238  database(const os::path& db_path, open_db_flag_type flag = create_db);
239 
243  virtual ~database(void);
245 
246  // Internal
247  database(const std::string& db_name, const os::path& db_dir, open_db_flag_type flag = create_db);
248  public:
251 
258  static bool exists(const os::path& db_path);
259 
266  static void remove(const os::path& db_path);
268  public:
269  // internal use
270  static void create_db_files(const std::string& name, const os::path& directory, bool bReplace = false);
271  static void remove_db_files(const std::string& name, const os::path& directory);
272  static bool db_files_exists(const std::string& name, const os::path& directory);
273  static void create_index_file(const std::string&);
274  static void create_data_file(const std::string&);
275  public:
276  std::string get_db_name(void) const;
277  os::path get_db_path(void) const;
278  public:
281 
294  table_imp_ref table(const std::string& table_name);
295 
302  void create_table(const std::string& table_name, const tsa::column_defs& columns);
303 
309  virtual void create_series_table(const std::string& name, const tsa::column_defs& columns)override;
310 
319  void create_table(const tsa::mem_table& mem_table, const std::string& db_table_name,
321 
328  void copy_table(const std::string& source_table_name, const std::string& copy_table_name);
329 
337  void drop_table(const std::string& table_name, missing_table_flag_type missing_table_flag = silent_on_missing);
338 
340  virtual bool drop_series_table(const std::string& table_name)override;
341 
347  virtual bool table_exists(const std::string& name) const override;
348 
355  bool table_exists_with_data(const std::string& table_name);
356 
362  bool table_is_open(const std::string& table_name);
363 
371  bool table_is_writeable(const std::string& name)const;
372 
380  bool table_is_readable(const std::string& name);
381 
388  tsa::column_defs table_column_defs(const std::string& table_name);
389 
394  size_t table_count(void) const;
395 
402  void rename_table(const std::string& table_name, const std::string& new_table_name);
403 
408  void table_names(std::vector<std::string>& table_name_arr) const;
410 
411  // IU
412  bool tables_are_equal(const std::string& name1, const std::string& name2);
413  // IU
414  std::string unused_table_name(void);
415  public:
416 
417  /* Internal
418  *
419  * Will silently replace an existing table if true, else throw an exception if table already
420  * exists. The Schema with @b schemaName must already exist! Schema definitions are created in
421  * the series_base via the Database::CreateSchema() member. This function will fail if a table
422  * with a given @b tableName already exists, unless @b replace flag is true.
423  */
424  void create_table_ex(const std::string& table_name, const std::string& column_defs_name);
425  public:
426  Result _DeleteTable(const std::string& tableName);
427  bool GetTableTimeSpanInfo(const std::string& tableName, size_t& numberOfRecords,
428  date_time& firstTimestamp, date_time& lastTimestamp);
429  table_metrics get_table_metrics(const std::string& tableName);
430  public:
431  virtual in_stream_adaptor* make_input_stream_adaptor(const std::string& stream)override;
432  virtual out_stream_adaptor* make_output_stream_adaptor(void)override;
433  public:
436  virtual date_time series_table_first_timestamp(const std::string& table_name)override;
437  virtual date_time series_table_last_timestamp(const std::string& table_name)override;
438  virtual bool table_has_data(const std::string& table_name)override;
439  virtual tsa::column_defs series_table_column_defs(const std::string& table_name)override;
440  virtual date_time series_table_closest_timestamp_LOE(const date_time& ts, const std::string& table_name)override;
441  virtual void series_load(const std::string& table_name, tsa::mem_table& data,
442  const date_time& from_timestamp, size_t num_records)override;
443  virtual void series_append(const std::string& table_name, const tsa::mem_table& data)override;
444  virtual void truncate_series_table(const std::string& table_name, const date_time& new_max_timestamp = date_time::min)override;
445  virtual bool table_record_count_is_known(void)const;
446  virtual int64_t table_record_count(const std::string& table_name);
448  public:
451 
459  void export_table(const std::string& name, const os::path& dir_path, bool replace = true);
460 
473  bool import_table(const os::path& dir_path, const std::string& file_name,
474 
476  bool replace = false, bool error_as_exception = true);
477 
479  public:
480 
483 
489  void print_table_report(std::ostream& stream);
490 
495  void print_table_names(std::ostream&);
496 
507  void print_table(const std::string& name, std::ostream& stream, size_t FPPrecision = 8,
508  size_t maxNumRec = tsa::print_no_limit, bool bPrintTimestamp = true);
509 
520  void save_table_html(const std::string& name, const os::path& path, size_t FPPrecision = 8,
521  size_t maxNumRec = tsa::print_no_limit, bool bPrintTimestamp = true);
522 
530  void print_table_csv(const std::string& name,
531  std::ostream& stream, size_t maxNumRec = tsa::print_no_limit);
532 
541  void print_table_csv(const std::string& name, const date_time& start,
542  const date_time& end, std::ostream& stream);
543 
552  void print_table_vertical(const std::string& name, std::ostream& stream,
553  bool inclTimestamp = true, size_t maxNumRecToPrint = tsa::print_no_limit);
554 
555  /*
556  * @brief Prints an (ascii) graph of the values found in a given @b column of a given @b table to @b Stream
557  *
558  * @param table The name of the table that contains the given @bcolumn name.
559  * @param [in,out] stream The stream to which the graph will be written.
560  * @param column The name of the column (field) which is to be graphed.
561  * @param width The width, in characters, of the resulting graph.
562  * @param height The height, in characters, of the resulting graph.
563  * @param start The lowest timestamp to be used (lower bound of data range)
564  * @param end The highest timestamp to be used (upper bound of data range)
565  */
566 
577  void print_graph(const std::string& table,
578  std::ostream& stream, const std::string& column,
579  size_t width = 70, size_t height = 20,
580  const date_time& start = date_time::min, const date_time& end = date_time::max
581  );
582 
583  /*
584  * @brief Print hlc graph.
585  *
586  * @param table The name of the table that contains the given 'high', 'low', 'close'
587  * fields.
588  * @param [in,out] stream The stream to which the graph will be written.
589  * @param width The width, in characters, of the resulting graph.
590  * @param height The height, in characters, of the resulting graph.
591  * @param start The lowest timestamp to be used (lower bound of data range)
592  * @param end The highest timestamp to be used (upper bound of data range)
593  */
594 
595  void print_hlc_graph(const std::string& table, std::ostream& stream,
596  size_t width = 70, size_t height = 20,
597  const date_time& start = date_time::min, const date_time& end = date_time::max
598  );
599  void print_table(const std::string& tableName,
600  std::ostream& S, TablePrinter& tablePrinter,
601  bool bPrintTimestamp, size_t maxNumRec = tsa::print_no_limit);
602 
604  public:
605  db_storage_manager* get_db_storage_manager(void);
606  db_record* create_record_object(const std::string& data_def_name);
607  public:
608  void create_data_def(const std::string& schemaName, const tsa::column_defs& schema);
609  bool data_def_exists(const std::string& name) const;
610  tsa::column_defs GetSchema(const std::string& schemaName) const;
611  private:
612  bool delete_data_def(const std::string& name);
613  void delete_unused_data_def(void);
614  std::string data_def_name_from_table_name(const std::string& tableName) const;
615  std::string get_unused_data_def_name(void) const;
616  void data_def_names_arr(std::vector<std::string>& schemaNameArray) const;
617  bool data_def_in_use(const std::string& schemaName) const;
618  void print_data_def_report(std::ostream& stream);
619  void init_data_def(tsa::column_defs& schema, const std::string& schemaName) const;
620  public:
621  size_t db_page_count(void) const;
622  size_t db_free_page_count(void) const;
623  private:
624  friend class tsa::mem_table;
625  void read_into_mem_table(tsa::mem_table& series, const std::string& tableID);
626  private: // Internal Use
627  void register_table_imp_ptr(table_imp_ref*);
628  void unregister_table_imp_ptr(table_imp_ref*);
629  void close_table(table_imp* ptable);
630  table_imp* LoadCorePtr(unsigned table_id);
631  void force_close_table_no_exception(table_imp* pSeries);
632  Result load_table(table_imp*&, const std::string& table_name);
633  table_imp* load_table(const std::string& table_name);
634  void print_db_table_info(std::ostream& Stream);
635  public:
636  void VerifyTableHasOHLCV_Fields(const std::string& tableName);
637  void verify_table_has_PV_fields(const std::string& tableName);
638  void verify_has_ohlcv_fields(const std::string& tableName);
639 
640  // @name TimeFrame Conversion
641  // @{
642 
643  void convert_tick_to_1min(const std::string& in_table_name,
644  const std::string& out_table_name,
645  const std::string& price_column_name = "last", const std::string& volume_column_name = "volume");
646 
647  void convert_tick_to_sec(const std::string& in_table_name,
648  size_t seconds_per_bar, const std::string& out_table_name);
649 
650  void convert_1min_to_multi_min(const std::string& in_table_name,
651  size_t minutes_per_bar, const std::string& out_table_name);
652 
653  void convert_to_daily(const std::string& in_table_name, const std::string& out_table_name);
654 
655  void convert_to_weekly(const std::string& in_table_name, const std::string& out_table_name);
656 
657  void convert_to_monthly(const std::string& in_table_name, const std::string& out_table_name);
658 
659  void convert_tick_to_multi_tick(const std::string& in_table_name,
660  size_t numTicksPerBar, const std::string& targetTable,
661  const std::string& price_column_name = "price", const std::string& volume_column_name = "");
662 
663  void convert_tick_to_volume(const std::string& source_table,
664  size_t volumePerBar, const std::string& out_table_name);
665  // @} END
666 
667  public:
668  //internal
669  void import_daily_data(const std::string& tableName,
670  const os::path& file,
671  const std::string& dateFormatString = "yyyymmdd",
672  char sep = ','
673  );
674 
675  // internal
676  void import_intraday_data(const std::string& tableName, const os::path& file,
677  const std::string& dateFormatString = "yyyymmdd",
678  const std::string& timeFormatString = "hh:mm:ss.f",
679  char sep = ',', bool fixDuplicateTime = false);
680 
681  // Internal, Describes the data to be imported from file.
682  struct import_info {
683  import_info(void) {
684  ;
685  }
686  os::path path;
687  variant table_name;
688  bool delete_existing_table = false;
689  variant date_format;
690  variant time_format;
691  bool timestamp_one_field = true;
692  char datetime_separator = ' ';
693  variant columns;
694  char separator = '\n';
695  bool fix_duplicate_timestamp = false;
696  };
697 
698  // Iternal
699  void import_file(const import_info& info);
700  };
701 
702  } // namespace fast
703 
705 
706 } // namespace tsa
707 #endif
Definition: TSATypeDef.h:106
Utility class to manipulate file system paths. This class is intended to fulfil the requirements of t...
Definition: TSAOS.h:36
class series is a template class representing a sequence of values.
Definition: TSASeriesProxy.h:24
Namespace for the &#39;Trading System API&#39; library.
Definition: original1.TSA3Core.cpp:20
const size_t print_no_limit
flag to print without limiting the number of lines printed.
Definition: TSATypeDef.h:78
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
Create the database if it does not already exist.
Definition: TSADatabase.h:44
missing_table_flag_type
Values that represent missing table flag types.
Definition: TSATypeDef.h:111
Defines the columnar structure of a table. Each column has a name, data type and field size...
Definition: TSADataDef.h:88
Raise an exception if database does not already exist.
Definition: TSADatabase.h:45
Parent class for &#39;in-stream adaptors&#39;. in_stream object rely on adaptors for access to underlying dat...
Definition: TSAStreams.h:52
Abstract base class for delegates of class out_stream.
Definition: TSAStreams.h:553
replace_flag_type
Replace / no-replace flag used by various objects.
Definition: TSATypeDef.h:105
static const date_time min
Constant representing the smallest allowed date_time.
Definition: TSATime.h:449
Definition: TSATypeDef.h:112
variant objects can represent values of different types.
Definition: TSAVariant.h:140
Replace existing target if it already exists.
Definition: TSAStreams.h:533
open_db_flag_type
Enumeration of Database constructor flags. Multiple flags can be combined via operator|.
Definition: TSADatabase.h:43
static const date_time max
Constant representing the largest allowed date_time.
Definition: TSATime.h:452
Clears all data in the database upon opening the database.
Definition: TSADatabase.h:46
Represents a database table in fast::database.
Definition: TSADBTable.h:41
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
Class mem_table represents a memory based table. mem_table objects can be used in strategies both for...
Definition: TSAMemTable.h:48
open_db_flag_type operator|(open_db_flag_type a, open_db_flag_type b)
Allows multiple fast::database constructor flags to be combined.
Definition: TSADatabase.cpp:40