-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
367 lines (312 loc) · 11.6 KB
/
index.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
const m = require("moment");
const admin = require("firebase-admin");
const db = admin.firestore();
const { onUpdate } = require("../Firebase");
const { checkZoigbergKillSwitch } = require("../Zoidberg");
const { positionsCollection, farnsworthCollection } = require("../constants")
const { log, logNews, logError } = require("../helpers/log");
const { round } = require("../helpers/numbers")
/**
* Creates a new audit doc for Farnsworth.
* Note: this only fires on `update` of the `currentPosition` doc, not on `create`.
* @param {String} pairedAsset The asset pair (i.e. USD / EUR / PAX)
*/
exports.recordTrade = (isProd, pairedAsset) => {
let farnsworthCollectionId = isProd ? farnsworthCollection.prod : farnsworthCollection.dev;
let documentPath = (isProd ? positionsCollection.prod : positionsCollection.dev) + `/{currency}/{exchange}/${pairedAsset}-currentPosition`;
return onUpdate(documentPath, async (change, context) => {
let killSwitchIsActive = await checkZoigbergKillSwitch();
if (killSwitchIsActive) {
log({ message: "Zoidberg kill switch is active" })
return null
}
let newData = change.after.data();
let exchange = context.params.exchange;
let currency = context.params.currency;
// Only record trade when a done reason is recorded
if (newData.doneReason && newData.doneReason !== "") {
if (newData.hasPosition) {
let timeStamp = m(newData.buyTimeStamp.toDate()).toISOString();
return db
.collection(farnsworthCollectionId)
.doc(currency)
.collection(`${pairedAsset}-${exchange}`)
.doc(timeStamp)
.set(newData, { merge: true });
} else {
let oldData = change.before.data();
let timeStamp = m(oldData.buyTimeStamp.toDate()).toISOString();
return db
.collection(farnsworthCollectionId)
.doc(currency)
.collection(`${pairedAsset}-${exchange}`)
.doc(timeStamp)
.set(newData, { merge: true });
}
}
return null
});
};
/**
* Creates a new profits record for Farnsworth.
* Note: this only fires on `update` of the `currentWorkingCapital` doc, not on `create`.
* @param {String} pairedAsset The asset pair (i.e. USD / EUR / PAX)
*/
exports.recordProfit = (isProd, pairedAsset) => {
let farnsworthCollectionId = isProd ? farnsworthCollection.prod : farnsworthCollection.dev;
let documentPath = (isProd ? positionsCollection.prod : positionsCollection.dev) + `/{currency}/{exchange}/${pairedAsset}-currentWorkingCapital`;
return onUpdate(documentPath, async (change, context) => {
let killSwitchIsActive = await checkZoigbergKillSwitch();
if (killSwitchIsActive) {
log({ message: "Zoidberg kill switch is active" })
return false
}
let newData = change.after.data();
let newWC = newData.currentWC;
let newDefaultWC = newData.defaultWC;
if (Number(newWC) - Number(newDefaultWC) === 0) {
logNews({
title: "👴 Farnsworth",
message: `Default working capital === Current working capital (${newDefaultWC})`,
details: "Were profits recently taken? Double check working capital",
});
return false
}
let exchange = context.params.exchange;
let currency = context.params.currency;
let oldData = change.before.data();
let oldWC = oldData.currentWC;
let oldDefaultWC = oldData.defaultWC;
let profit = Number(newWC) - Number(oldWC);
let netRunningProfit = Number(newWC) - Number(oldDefaultWC);
logNews({
title: "👴 Farnsworth",
message: `We just made a *gross ${profit > 0 ? "profit" : "loss"}* of ${round(profit, 2)} ${pairedAsset}!, with a running net ${
netRunningProfit > 0 ? "profit" : "loss"
} of ${round(netRunningProfit, 2)} ${pairedAsset}`,
});
let timeStamp = admin.firestore.Timestamp.now();
let day = m(timeStamp.toDate()).format("YYYY-MM-DD");
let week = m(timeStamp.toDate()).format("YYYY-w");
let month = m(timeStamp.toDate()).format("YYYY-MM");
let refDaily = db
.collection(farnsworthCollectionId)
.doc("profits")
.collection("daily")
.doc(currency)
.collection(`${pairedAsset}-${exchange}`)
.doc(day);
let dailyDoc = await refDaily.get().catch(e => {
logError({ title: "Farnsworth error getting daily doc", message: e.message, details: e.stack })
return
});
if (dailyDoc.exists) {
refDaily.update({ profit: admin.firestore.FieldValue.increment(profit) });
} else {
refDaily.set({ profit });
}
let refWeekly = db
.collection(farnsworthCollectionId)
.doc("profits")
.collection("weekly")
.doc(currency)
.collection(`${pairedAsset}-${exchange}`)
.doc(week);
let weeklyDoc = await refWeekly.get().catch((e) => {
logError({ title: "Farnsworth error getting weekly doc", message: e.message, details: e.stack });
return
});
if (weeklyDoc.exists) {
refWeekly.update({ profit: admin.firestore.FieldValue.increment(profit) });
} else {
refWeekly.set({ profit });
}
let refMonthly = db
.collection(farnsworthCollectionId)
.doc("profits")
.collection("monthly")
.doc(currency)
.collection(`${pairedAsset}-${exchange}`)
.doc(month);
let monthlyDoc = await refMonthly.get().catch((e) => {
logError({ title: "Farnsworth error getting monthly doc", message: e.message, details: e.stack });
return
});
if (monthlyDoc.exists) {
refMonthly.update({ profit: admin.firestore.FieldValue.increment(profit) });
} else {
refMonthly.set({ profit });
}
return true;
});
}
// We always set the most optimal into production to be used immediately!
exports.recordOptimalTradeSettingResult = async (mostOptimal) => {
let pairedAssetFixed = mostOptimal.pairedAsset.length < 4 ? mostOptimal.pairedAsset : mostOptimal.pairedAsset.substring(0, 4)
if (pairedAssetFixed.slice(-1) === "-") {
pairedAssetFixed = mostOptimal.pairedAsset.substring(0, 3);
}
await db
.collection("farnsworth")
.doc("backtest-results")
.collection(`${mostOptimal.currency}-${pairedAssetFixed}-${mostOptimal.exchange}`)
.doc(`${Date.now()}`)
.set(mostOptimal)
.catch((e) => {
logError({ title: "Farnsworth error creating optimal trade setting result", message: e.message, details: e.stack });
});
}
// Only used by the emulators
exports.recordBacktestResult = async (isProd, currency, exchange, pairedAsset, startTime, startEntry, endEntry, settings, backtestIdPrefix) => {
let killSwitchIsActive = await checkZoigbergKillSwitch();
if (killSwitchIsActive) {
log({ message: "Zoidberg kill switch is active" });
return;
}
let positionsCollectionId = isProd ? positionsCollection.prod : positionsCollection.dev;
let doc = await db
.collection(positionsCollectionId)
.doc(currency)
.collection(exchange)
.doc(pairedAsset + "-currentWorkingCapital")
.get()
.catch((e) => {
logError({ title: "Farnsworth error recording backtest result", message: e.message, details: e.stack });
});
log({ message: "--- Backtesting completed ---" });
let startDate = m(startEntry.timeStamp);
let endDate = m(endEntry.timeStamp);
let fbStartDate = admin.firestore.Timestamp.fromDate(startDate.toDate());
let fbEndDate = admin.firestore.Timestamp.fromDate(endDate.toDate());
let endTime = Date.now();
let backtestTime = (endTime - startTime) / 1000 / 60;
let startPrice = startEntry.price;
let endPrice = endEntry.price;
let priceVolatilityRange = endPrice - startPrice;
let beta = (endPrice / startPrice - 1) * 100;
let data;
log({ message: `Backtesting results for ${startDate.toISOString()} to ${endDate.toISOString()}`, logDuringBacktest: true });
if (doc.exists) {
let tradeCounter = await db
.collection(positionsCollectionId)
.doc(currency)
.collection(exchange)
.doc(pairedAsset + "-tradeCounter")
.get()
.catch((e) => {
logError({ title: "Farnsworth error recording tradeCounter for backtest", message: e.message, details: e.stack });
});
let numberOfTrades = tradeCounter.exists ? tradeCounter.data().completed : 0;
let currentWC = doc.data().currentWC;
let defaultWC = doc.data().defaultWC;
let profit = currentWC - defaultWC;
let growth = (currentWC / defaultWC - 1) * 100;
if (growth === 0) {
growth = 1.0;
} // We didn't make or loose any money
let alpha = growth - beta;
log({ message: `Alpha: ${alpha}, Beta: ${beta}`, logDuringBacktest: true });
log({ message: `Profit: $${profit}, price volatility: $${priceVolatilityRange}`, logDuringBacktest: true });
log({ message: `Total number of completed trades: ${numberOfTrades}`, logDuringBacktest: true });
log({ message: `Backtest took ${backtestTime} minutes`, logDuringBacktest: true });
data = {
startDate: fbStartDate,
endDate: fbEndDate,
startWC: defaultWC,
endWC: currentWC,
backtestTime,
alpha,
beta,
priceVolatilityRange,
profit,
percentReturnWC: growth,
currency,
pairedAsset,
exchange,
numberOfTrades,
settings
};
} else {
log({ message: `Could not find ${pairedAsset + "-currentWorkingCapital"} doc. Looks like no trades happened!`, logDuringBacktest: true });
log({ message: `Alpha: ${1.0 - beta}, Beta: ${beta}`, logDuringBacktest: true });
log({ message: `Profit: $0.00, price volatility: $${priceVolatilityRange}`, logDuringBacktest: true });
log({ message: `Total number of completed trades: 0`, logDuringBacktest: true });
log({ message: `Backtest took ${backtestTime} minutes`, logDuringBacktest: true });
data = {
startDate: fbStartDate,
endDate: fbEndDate,
backtestTime,
alpha: 1.0 - beta,
beta,
priceVolatilityRange,
profit: 0,
percentReturnWC: 1.0,
currency,
pairedAsset,
exchange,
numberOfTrades: 0,
settings,
};
}
log({ message: `Settings: ${JSON.stringify(settings)}`, logDuringBacktest: true })
let pairedAssetFixed = pairedAsset.length < 4 ? pairedAsset : pairedAsset.substring(0, 4)
if (pairedAssetFixed.slice(-1) === "-") {
pairedAssetFixed = pairedAsset.substring(0, 3);
}
let farnsworthRef = db
.collection(farnsworthCollection.dev)
.doc(currency)
.collection(pairedAsset + "-" + exchange)
let tradeRecords = []
let tradeRecordsSnapshot = await farnsworthRef.get()
tradeRecordsSnapshot.forEach(doc => {
tradeRecords.push(doc.data())
});
data.tradeRecords = tradeRecords
await db
.collection("farnsworth")
.doc("backtest-results")
.collection(`${currency}-${pairedAssetFixed}-${exchange}`)
.doc(pairedAsset)
.set(data)
.catch((e) => {
logError({ title: "Farnsworth error creating backtest record result", message: e.message, details: e.stack });
});
log({ message: "--- Cleaning up post-backtesting ---" });
let ref = db
.collection(isProd ? positionsCollection.prod : positionsCollection.dev)
.doc(currency)
.collection(exchange);
log({ message: "Deleting records created during backtesting..." });
try {
await ref.doc(pairedAsset + "-currentWorkingCapital").delete();
await ref.doc(pairedAsset + "-currentPosition").delete();
await ref.doc(pairedAsset + "-prevAnchor").delete();
await ref.doc(pairedAsset + "-tradeCounter").delete();
if (tradeRecordsSnapshot && tradeRecordsSnapshot.size > 0) {
let batch = db.batch();
tradeRecordsSnapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit()
}
} catch (e) {
logError({ title: "Farnsworth error performing cleanup after backtest", message: e.message, details: e.stack });
}
log({ message: "--- Cleaning up complete ---" });
};
exports.getBacktestResults = async (currency, pairedAsset, exchange) => {
let snapshot = await db
.collection("farnsworth")
.doc("backtest-results")
.collection(`${currency}-${pairedAsset}-${exchange}`)
.get();
if (snapshot.empty) {
log({ message: `No backtest results found for ${currency}-${pairedAsset}-${exchange}`})
return null
}
let results = snapshot.docs.map(doc => {
return { ...doc.data(), id: doc.id, }
})
return results
}