· 7 years ago · Nov 12, 2018, 02:18 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 this.dataDir = dataDir;
19 this.dbExt = dbExt;
20 }
21
22 Logger.info('Data manager initialized.');
23 },
24
25 /**
26 * Returns a live sqlite connection
27 */
28 getDb: function() {
29 const dbConn = new db.Database(
30 `${this.dataDir}${this.dbFile}${this.dbExt}`
31 );
32 dbConn.run("PRAGMA journal_mode = WAL");
33 return dbConn;
34 },
35
36 /**
37 * Stores a batch of trades in the sqlite db
38 * @param {array} batch - batch of trades
39 */
40 storeTrades: async function (batch) {
41 try {
42 return new Promise(resolve => {
43 if (!this.dbFile) {
44 throw('Database file unspecified');
45 }
46
47 if (!batch || !batch.length) {
48 throw('Data must be specified and an array');
49 }
50
51 const dbConn = this.getDb();
52 const table = `[${batch[0].symbol}]`;
53 const query = `CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY AUTOINCREMENT, tradeId INTEGER, timestamp INTEGER, price REAL, quantity REAL)`;
54 dbConn.serialize(() => {
55 dbConn.run(query);
56 dbConn.run('BEGIN TRANSACTION');
57 const insertStmt = dbConn.prepare(`INSERT INTO ${table} (tradeId, timestamp, price, quantity) VALUES (?, ?, ?, ?)`);
58 batch.forEach(trade => insertStmt.run(trade.id, trade.timestamp, trade.info.p, trade.info.q));
59 insertStmt.finalize();
60 dbConn.run('COMMIT');
61 });
62
63 dbConn.close(resolve);
64 Logger.debug(`${batch.length} rows inserted into table`);
65 });
66 } catch (e) {
67 Logger.error(e.message);
68 }
69 }
70};