-
Notifications
You must be signed in to change notification settings - Fork 3
/
manager.js
499 lines (478 loc) · 21.5 KB
/
manager.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#!/usr/bin/env node
function Manager(b) {
const prompt = require('prompt-sync')({sigint: true});
const newAlloc = require('./allocation.js');
const Bot = require('./bot.js');
const Balancer = require('./balancer.js');
const Web = require('./web.js');
// const HServer =
let bot = b,
web,
cmdList = [],
waiter = 0,
auto = 0,
delay = 60,
auto_on_hold = false,
portfolio = false,
listener = null,
savings = null,
myTotal = 0;
function run() {
doCommands(['report']); //.catch((err) => { catcher(578,err); });
console.log("Safemode is on. `safe` toggles it.");
}
process.stdin.setEncoding('utf8');
if(!process.TESTING) {
process.on('uncaughtException', function (err) {
catcher(0,err);
});
}
async function init(pw = "") {
if(this.already) return;
Manager.s = this;
portfolio = await bot.init(pw);
web = Web(this);
savings = require('./savings.js');
/*if(!process.TESTING)*/ await bot.report(true);
savings().setTickers(Bot.tickers);
if(!process.TESTING || process.argv.length > 2) listen();
else {
console.log("42:",portfolio);
this.already = true;
return portfolio;
}
this.already = true;
}
function ignore() { process.stdin.removeListener(listener); }
function listen() {
let cmd = '';
listener = process.stdin.on('readable', () => {
// clearInterval(auto);
let data = '';
while(null != (data = process.stdin.read())) cmd += data;
// console.log("Last char in cmd was: ", cmd.charCodeAt(cmd.length-1));
// });
// process.stdin.on('end', () => {
if(/^quit/.test(cmd)) {
process.exit(0);
} else if(/(\r|\n)$/.test(cmd)) {
clearTimeout(waiter);
waiter = setTimeout(async () => {
// Do we need to stop this listener from
// listening while doCommands runs?
if(cmdList.length > 0) {
await doCommands();
bot.showState(auto > 0 ? 'A' : '.');
process.stdout.write('>');
}
cmdList = [];
},100);
cmd.replace(/[\r\n]+/g,'\r').split('\r').forEach(e => cmdList.push(e));
// That leaves one empty string at the end of cmdList. Remove it:
cmdList.pop();
cmd = '';
}
});
}
function catcher(line,err) {
//if(/ETIMEDOUT/.test(err.code)) return; // We can ignore timeout errors.
console.log("Line "+line+";\n",err);
clearInterval(auto);
auto = 0;
}
function whoami() { return whoami.caller.name; }
/*
Note that handleArgs handles string arguments as collected from process.stdin.
This means that true and 1, as args, are strings, not a boolean and a number.
*/
async function handleArgs(bot, args, uref = 0, p = portfolio) {
if(['args',whoami()].includes(process.TESTING))
console.log(whoami(),"called with ",arguments);
let buysell,xmrbtc,price,amt,posP;
if(/^(buy|sell)$/.test(args[0])) {
let pair;
[buysell,xmrbtc,price,amt,posP] = args;
pair = Bot.findPair(xmrbtc, p.Numeraire, -1);
if(pair) xmrbtc = pair[1].base;
if( 'undefined' == typeof(p[xmrbtc]) ) {
// Try the asset's altname
// -----------------------
if('undefined' == typeof(p[Bot.alts[xmrbtc]]))
throw new Error(xmrbtc+" is not a recognized symbol. Try 'asset' command.");
console.log("Using",Bot.alts[xmrbtc],"instead of",xmrbtc);
xmrbtc = Bot.alts[xmrbtc];
}
let total=price*amt;
if(total > 100000) return total+" is too much for code to "+buysell;
// console.log(buysell+"ing "+amt+xmrbtc+" for "+price+".");
// Do we need leverage?
// --------------------
let lev = bot.getLev(p,buysell,price,amt,xmrbtc,posP);
let cPrice = !isNaN(p['G'][uref])
? p['G'][uref][buysell=='buy'?'sell':'buy'] : 0;
// Without a record of a closing price, use the last one we found.
// ---------------------------------------------------------------
if(!cPrice) cPrice = p[xmrbtc][1];
// When passing 1 as close, it will mean close at 1 (if Risky)
// or at current price (without Risky)
// -----------------------------------------------------------
let closeO = posP ? (posP !== 'true' // posP is a number, not the boolean
? (posP !== '1' || bot.risky ? posP : cPrice) // use the number unless it's 1 and Risky is off
: cPrice) : null; // NaN, so current price or nothing.
let ret = await bot.order(buysell,pair[0],price,amt,lev,uref,closeO);
console.log("New order: "+ret);
return;
} else if(args[0] == 'set') {
await bot.set(p, args[1], args[2], args[3]);
} else if(args[0] == 'reset') {
p['G'] = [];
await bot.listOpens();
} else if(args[0] == 'delev') {
await bot.deleverage(p['O'],args[1]-1);
} else if(args[0] == 'addlev') {
await bot.deleverage(p['O'],args[1]-1,true);
} else if(args[0] == 'refnum') {
await bot.refnum(p['O'],args[1]-1,args[2]);
} else if(args[0] == 'list') {
await bot.list(args);
} else if(/^(less|more)$/.test(args[0])) {
await bot.lessmore('less'==args[0],args[1]-1,args[2],'all'==args[3]);
} else if(args[0] == 'asset') {
if(args.length == 1) {
console.log("Usage: asset ticker units [label] ask");
console.log(" or asset REMOVE ticker [label] ask");
console.log(" or asset REMOVE ACCOUNT label ask");
console.log("To avoid asking for confirmation, pass 'false' as ask.");
return;
}
let label = args[3] ? args[3] : "default",
tkr = 'REMOVE' == args[1] ? args[2] : args[1],
account = p.Savings.find(a => a.label == label);
if(Bot.alts[tkr]) tkr = Bot.alts[tkr];
if(!account) {
if('REMOVE' == args[1]) {
console.log("Non-existent account:",label);
return;
}
if(isNaN(args[2])) {
console.log(args[2],"is not a number.");
return;
}
account = savings({
label:label,
assets:[{ticker:tkr,amount:Number(args[2])}]
});
console.log("Created new account, ", label);
p.Savings.push(JSON.parse(account.save()));
if(args[3]) account.labelMe(args[3]);
} else {
account = savings(account);
}
if('REMOVE' == args[1]) {
if('ACCOUNT' == args[2].toUpperCase()) {
let smaller = p.Savings.filter(x => x.label != args[3]);
p.Savings = smaller;
bot.save();
console.log("Account",label,"has been removed.");
} else {
account.remove(args[2]); //tkr might be different/an alt.
bot.save();
}
return;
}
if(isNaN(args[2])) {
console.log(args[2],"is not a number.");
return;
}
if(account.updateAsset(args[1],Number(args[2]),args[4]!=='false')) {
bot.save();
}
} else if(args[0] == 'assets') {
let sav,pnum = p.Numeraire;
ret = p.Savings.length + ': ';
for(h=0;h < p.Savings.length; ++h) {
sav = savings(p.Savings[h]);
if(!(args[1]) || sav.label == args[1])
console.log(h, sav.list());
else if(args[1]) {
let a = sav.get(args[1]);
if( a > '' ) console.log(sav.label,a);
}
}
// Include the assets on the Exchange
// ----------------------------------
sav = savings({ label:'OnExchange', assets:
[{ticker:pnum, amount:p[pnum][0]}]});
return ret;
} else if(args[0] == 'allocation') {
let d = await getAllocation(true),c; // Desired
if(args[1]) {
c = await getAllocation(false, args[1].toLowerCase()=='fresh'); // Current
if('?' == args[1]) { console.log("Usage: Allocation [cmd]\n"
+ "If cmd is 'fresh' we compare the current allocation, after\n"
+ "updating it, to the desired allocation.\n"
+ "If cmd is missing, we compare the current allocation, without\n"
+ "first updating it, to the desired allocation.\n"
+ "Use 'allocate' to change your desired allocation.");
}
} else c = await getAllocation(false, false);
let alisting = d
? d.list({name:'Now',alloc:c})
: (c.list() + "Use allocate to set targets.");
if(!args[1] || args[1].toLowerCase() != 'quiet') console.log(alisting);
return {desired:d,current:c};
} else if(args[0] == 'allocate') {
let a = await getAllocation(true);
if(!args[1]) {
console.log("This will let you start from scratch.\n"
+"Use 'allocate (Ticker) [+/-](amount)' to adjust and 'allocation' to\n"
+"see your current and desired allocations.\n");
if(a) old = prompt("Erase current allocation (y/n)?")
.toLowerCase() == 'y';
if(!a || old) a = await getAllocation(false);
console.log(a.list());
await setAlloc(a);
} else if(isNaN(args[2]) || !Bot.tickers.includes(args[1])) {
console.log(args[2],"isn't a number or",args[1],
"isn't a recognized ticker.");
} else {
let tkr = args[1],
amt = Number(args[2])/100;
if(false == a) a = getAllocation(false);
if(amt<0 || args[2][0]=='+') { // Relative adjustment
let rel = a.get(tkr).target;
if(!isNaN(rel)) amt += rel;
}
a.addAsset(tkr,amt);
bot.save();
}
} else if(args[0] == 'balance') {
if(args[1]) {
let a = await getAllocation(true); // Get desired allocation.
let b = Balancer(a);
b.setTrades(args[1],args[2]?args[2].toUpperCase():''); // Tolerance, Ticker
} else {
console.log("Usage: balance tolerance [ticker]\n"
+ "tolerance is 0.0000 - 1, indicating how far away\n"
+ "from the target an asset can be before a trade is\n"
+ "triggered.\n"
+ "ticker is optional and only that asset will be\n"
+ "set up if present.");
}
} else if(args[0] == 'adjust') {
let d = await getAllocation(true),
alloc = d.get(args[1]),
ctargp = 100*d.get(0).target,
a = Number(args[2]),
p = Number(args[3]), t,
usage = "Usage: adjust ticker apct ppct\n" +
"apct is the percent of your allocation that you want\n" +
"to move into cash as the price of the asset goes up.\n" +
"ppct is the percent of the price over which you want\n" +
"to do it.";
if('undefined' == typeof(alloc)
|| isNaN(p) || isNaN(a)) {
console.log(usage);
} else if(a<0||p<0||a>100*(1-alloc.target)||p>100) {
console.log("apct must be between 0 and",100-100*alloc.target,
"and ppct must be between zero and 100.");
} else {
t = alloc.ticker;
await d.adjust(t,a/100,p/100);
await bot.save();
}
} else if(args[0] == 'limits') {
if(args.length < 3 || isNaN(args[1]) || isNaN(args[2])) {
console.log("Usage: limits AtLeast AtMost\n" +
"The allocation command will make trades only if the\n" +
"amount in "+p.Numeraire+" is at least the \n" +
"AtLeast amount and no more than the AtMost amount.\n" +
"If AtMost is -1, there is no upper limit (dangerous!).");
} else if(Number(args[1]) > Number(args[2]) && -1 != Number(args[2])) {
console.log("Doing nothing becuase you seem to have\n" +
"switched the arguments.");
} else {
p.limits = [Number(args[1]),Number(args[2])];
bot.save();
}
} else if(args[0] == 'test') {
// Put some test code here if you want
// -----------------------------------
let d = await getAllocation(true);
await d.adjust('XXMR', 0.05, 0.2);
} else if(/^(y|Y)/.test(prompt("Try "+args[0]+" raw?"))) {
let raw = await bot.kapi(args);
console.log(392,raw);
} else {
if(/^(y|Y)/.test(prompt("Set process.TESTING to "+args[0]+"?"))) {
process.TESTING = ('notest' == args[0] ? false : args[0]);
process.USECACHE = /^(y|Y)/.test(prompt("Use caching?"));
}
console.log("process.TESTING is",process.TESTING,
"and caching",(process.USECACHE?"will":"will not"),"be used.");
}
}
async function doCommands(cl=cmdList) {
let cmds = cl.map((x) => { return x.trim(); }),
cdx = 0, ret = false;
cmdList = []; // So a throw doesn't repeat the command that caused it.
auto_on_hold = auto>0;
console.log("Got "+(cmds.length)+" commands...");
while(cdx < cmds.length) {
let args = cmds[cdx++].split(' ').map((x) => { return x.trim(); });
console.log("...("+cdx+")> "+args.join(' '));
//try {
if(args[0] == 'kill') await bot.kill(args[1],portfolio['O']);
else if(args[0] == "keys") { await bot.keys(); }
else if(args[0] == "ws") {
if(kwsCheck) console.log("Kraken WebSocket heartbeat at "+kwsCheck);
if(!kwsCheck || (new Date()).valueOf() > 10000+kwsCheck.valueOf()) {
openSocket();
}
} else if(args[0] == "report" || args[0] == "") {
await bot.report();
} else if(/^(manual)$/.test(args[0])) {
clearInterval(auto);
auto = 0;
} else if(args[0] == "auto") {
clearInterval(auto);
if(args[1]&&!isNaN(args[1])) delay = args[1];
let counter = 2; // Wait 2 seconds before first run.
auto = setInterval(async function() {
if(0 == --counter) {
if(!auto_on_hold) {
await bot.report(false);
}
bot.showState(auto > 0 ? 'A' : '.');
counter = delay;
}
},1000);
} else if(args[0] == "risky") {
bot.FLAGS.risky = !bot.FLAGS.risky;
console.log("Risky Mode is "+(bot.FLAGS.risky
? 'on - Experimental additions will be tried' : 'off'));
} else if(args[0] == "safe") {
bot.FLAGS.safe = !bot.FLAGS.safe;
console.log("Safe Mode is "+(bot.FLAGS.safe
? 'on - Orders will be displayed but not placed' : 'off'));
if(process.TESTING && !bot.FLAGS.safe) {
setTimeout(() => {bot.FLAGS.safe=true;},1500);
console.log("...only for 1500ms.");
}
} else if(args[0] == "verbose") {
bot.FLAGS.verbose = !bot.FLAGS.verbose;
console.log("Verbose is "+(bot.FLAGS.verbose ? 'on' : 'off'));
} else if(args[0] == 'margin') {
await bot.marginReport();
} else if(args[0] == 'show') {
if(args[2]) console.log(args[2],{value:portfolio[args[1]][args[2]]});
else if(args[1]) console.log(args[1],{value:portfolio[args[1]]});
else console.log({Portfolio:portfolio,Bot});
} else if(args[0] == 'web') {
if(args[1]) {
if(args[1].toUpperCase() == 'ON')
args[2]?web.start(args[2]):web.start();
else if(args[1].toUpperCase() == 'OFF') web.stop();
} else {
console.log("Usage: web [on|off]\n"
+ "This starts the web interface or stops it.");
}
} else {
ret = await handleArgs(bot, args, 0);
if(bot.FLAGS.verbose) console.log(ret);
}
//}
// Wait a sec for the nonce
// -------------------------
// await bot.sleep(1000); (moved to kapi).
}
//console.log("Try CRTL-C while I sleep for a minute...");
//await sleep(1000);
auto_on_hold = false;
return ret;
}
// By default this returns the current allocation.
// When desired is true, it returns the desired
// allocation or false if there isn't one yet.
// ------------------------------------------------------
async function getAllocation(desired = false, refresh = true) {
if(['args',whoami()].includes(process.TESTING))
console.log(whoami(),"called with ",arguments);
if(desired) {
return (portfolio.Allocation && portfolio.Allocation.size() > 0)
? portfolio.Allocation
: false;
}
if(refresh) {
console.log("350 refreshing...");
await Bot.s.report(false);
}
// If user added something to desired allocation and hasn't got
// any, we want to list it as 0 in "current" allocation.
portfolio.Allocation.assets.forEach(async a => {
if(!portfolio[a.ticker] && a.target > 0) {
let p = await Bot.s.getPrice(a.ticker);
portfolio[a.ticker] = [0,p,0,0];
}
});
let total = savings();
let sym;
// Add savings to total.
// ---------------------
portfolio.Savings.forEach(sav => {total.add(savings(sav))});
// console.log(total.list("OffExchange", true));
// Add Exchange assets to total.
// -----------------------------
for(sym in portfolio) {
if(total.validTicker(sym)) {
let tndx = (sym==portfolio.Numeraire?0:3);
total.updateAsset(sym,portfolio[sym][tndx],false,true);
} // else console.log("Skipping",sym);
}
let ret = await total.getAlloc(portfolio.Numeraire || 'ZUSD',
bot.numerairesFromPairs());
myTotal = total.getTotal();
return ret;
}
function getTotal() { return myTotal; }
async function setAlloc(alloc) {
let answer;
while( (answer = prompt(
"Enter N or a ticker to adjust this allocation: ").toUpperCase())
!= "N") {
if(Bot.alts[answer]) answer = Bot.alts[answer];
let tik = alloc.get(answer);
// console.log("Found",tik);
if('undefined' == typeof(tik)) {
console.log("Enter a ticker from the list above"
+ " or N to quit managing your allocation: ");
} else if(portfolio.Numeraire == answer) {
console.log(answer + " is your default asset. Its allocation"
+ " will be whatever is left over after all the others are set.\n");
if("OK" != (answer = prompt("Enter your new default asset,"
+ " or OK to continue: ").toUpperCase())) {
if(Bot.Numeraires.includes(answer)) {
alloc.setNumeraire(answer);
} else {
console.log(answer+" is not supported as a default asset.");
}
}
} else {
answer = prompt("Change "+answer+" to what percentage "
+ "(0.0-100.0 or use + or - for relative changes): ");
if(isNaN(answer)) console.log("Only numbers work here.");
else if(['+','-'].includes(answer[0])) {
answer = Number(answer) + 100*tik.target;
}
if(!isNaN(answer)) alloc.addAsset(tik.ticker, answer/100);
}
console.log(alloc.list());
portfolio.Allocation = alloc;
bot.save();
}
}
function getAuto() { return auto>0 ? delay : -1; }
return({ catcher, run, doCommands, getAllocation,
init, listen, ignore, getTotal, getAuto });
}
module.exports = Manager;