· 7 years ago · Nov 08, 2018, 09:54 AM
1const db = require('sqlite3');
2
3const Logger = require('../logger/logger');
4
5const dataDir = process.env.DATA_DIR;
6const dbExt = process.env.DB_EXT;
7
8const DataManager = {
9 /**
10 * Constructor for OLOO style behavior delgation.
11 * @param {string} dbFile - data base file name
12 */
13 init: function (dbFile) {
14 if (!dbFile || !dataDir || !dbExt) {
15 Logger.error('Database or exchange is undefined');
16 } else {
17 this.dbFile = dbFile;
18 }
19
20 Logger.info('Data manager initialized.');
21 },
22
23 /**
24 * Returns a live sqlite connection
25 */
26 getDb: function () {
27 const dbConn = new db.Database(`${dataDir}${this.dbFile}${dbExt}`);
28 return dbConn;
29 },
30
31 /**
32 * Stores a batch of trades in the sqlite db
33 * @param {array} batch - batch of trades
34 */
35 storeTrades: async function (batch) {
36 try {
37 return new Promise(resolve => {
38 if (!this.dbFile) {
39 throw('Database file unspecified');
40 }
41
42 if (!batch || !batch.length) {
43 throw('Data must be specified and an array');
44 }
45
46 const dbConn = this.getDb();
47 const table = `[${batch[0].symbol}]`;
48 const query = `CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY AUTOINCREMENT, tradeId INTEGER, timestamp INTEGER, price REAL, quantity REAL)`;
49 dbConn.serialize(() => {
50 dbConn.run(query);
51 dbConn.run('BEGIN TRANSACTION');
52 const insertStmt = dbConn.prepare(`INSERT INTO ${table} (tradeId, timestamp, price, quantity) VALUES (?, ?, ?, ?)`);
53 batch.forEach(trade => insertStmt.run(trade.id, trade.timestamp, trade.info.p, trade.info.q));
54 insertStmt.finalize();
55 dbConn.run('COMMIT');
56 });
57
58 dbConn.close(resolve);
59 Logger.debug(`${batch.length} rows inserted into table`);
60 });
61 } catch (e) {
62 Logger.error(e.message);
63 }
64 }
65};