-
Notifications
You must be signed in to change notification settings - Fork 54
/
utils.js
57 lines (51 loc) · 1.47 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import fs from "fs";
import moment from "moment";
export function storeJson(fname, jsonObj) {
fs.writeFileSync(fname, JSON.stringify(jsonObj), function (err) {
if (err) {
logIT(err);
}
});
}
export function loadJson(fname, obj) {
if (fs.existsSync(fname)) {
const json_data = fs.readFileSync(fname, "utf8");
let jsonObj = JSON.parse(json_data);
Object.entries(jsonObj).forEach(([k, v]) => (obj[k] = v));
}
}
function jsonToCsv(json) {
const value = "null";
const items = json;
const replacer = (key, value) => (value === null ? "" : value); // specify how you want to handle null values here
const header = Object.keys(items[0]);
const csv = [
header.join(","), // header row first
...items.map((row) =>
header
.map((fieldName) => JSON.stringify(row[fieldName], replacer))
.join(",")
),
].join("\r\n");
return csv;
}
export function traceTrade(step, obj, fields) {
let csv_line = moment().local().toString() + "," + step;
fields.forEach((key) => (csv_line += "," + (obj[key] ?? "")));
csv_line += "\n";
if (!fs.existsSync("trades.csv")) {
let csv_header = "time, step";
fields.forEach((key) => (csv_header += "," + key));
csv_line = csv_header + "\n" + csv_line;
}
fs.appendFile(
"trades.csv",
csv_line.replace(/\u001b\[\d+m/g, ""),
function (err) {
if (err) {
logIT("Logging error: " + err);
return console.log("Logging error: " + err);
}
}
);
}