general beautification and local time calculation, get rid of currency specific programs.

This commit is contained in:
Joe Tretter
2020-12-02 12:43:48 -06:00
parent a8eb927265
commit f96106a62d
3 changed files with 104 additions and 413 deletions

View File

@@ -9,130 +9,118 @@ const secret = 'UytAbgU8ty3n5a+JhaoIlcfh8zM4OBGY6PCC+Cfg2NI4waVzM52BBp9qmm
const KrakenClient = require('kraken-api');
const kraken = new KrakenClient(key, secret);
const fs = require('fs')
const storeData = (data, path) => {
try {
fs.writeFileSync(path, JSON.stringify(data));
} catch (err) {
console.error(err);
}
try {
fs.writeFileSync(path, JSON.stringify(data));
} catch (err) {
console.error("error in storeData ",err);
}
}
const loadData = (path) => {
try {
return JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (err) {
console.error(err);
return false;
}
try {
return JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (err) {
console.error("error in loadData ",err);
return false;
}
}
const utcToLocal = (utc) => {
return new Date(utc.getTime() - (utc.getTimezoneOffset() * 60000));
}
(async () => {
try {
let params={
ofs : 0
};
try {
// get the pair to process from the first parameter and fall back if not provided.
let thePair=process.argv[2];
if (thePair===undefined) {
thePair="XXMRZUSD";
}
thePair=thePair.toUpperCase(); // the pairs are always upper case.
console.log("Processing pair: ", thePair);
let maxTimestamp=0;
let allTrades=loadData("allTrades.json");
allTrades.forEach(dta=>{if (dta.time>maxTimestamp) {maxTimestamp=dta.time;} });
params.start=maxTimestamp;
console.log("Max-Timestamp",maxTimestamp);
let allTransactions = await kraken.api('TradesHistory', params);
let allTradeIDs=Object.keys(allTransactions.result.trades);
let numTrans=allTradeIDs.length;
console.log("Number of new Transactions: ",numTrans);
for (let i=0;i<numTrans;i++){
params.ofs+=1;
let theTrade=allTransactions.result.trades[allTradeIDs[i]];
// the timestamp is inclusive, therefore we have to skip that record.
if (theTrade.time === maxTimestamp) { continue; }
console.log(theTrade);
allTrades.push(theTrade);
if ((params.ofs % 50) == 0) { // Not really great style to update the for condition var here, but it works...
console.log("Load more results; offset ",params.ofs);
params.nonce = new Date() * 1000;
allTransactions = await kraken.api('TradesHistory', params);
allTradeIDs=allTradeIDs.concat(Object.keys(allTransactions.result.trades));
numTrans=allTradeIDs.length;
}
}
// sort the trades by time oldest first.
allTrades=allTrades.sort(function (a,b){return(a.time - b.time);});
storeData(allTrades,"allTrades.json");
let dailyResults = [];
let sumUSD=0;
let sumCommission=0;
let numTrades=0;
for (let i=0;i<allTrades.length;i++){
let theTrade=allTrades[i];
if (theTrade.pair===thePair) {
numTrades++;
let tradeLocalTime=new Date(theTrade.time * 1000);
//console.log(theTrade);
console.log(`${tradeLocalTime.toISOString()} [${theTrade.pair}] ${theTrade.type.substring(0,1)}#${Number(theTrade.vol).toFixed(4).padStart(8," ")}@${Number(theTrade.price).toFixed(2).padStart(8," ")} -> ${Number(theTrade.cost).toFixed(2).padStart(9," ")}(-${Number(theTrade.fee).toFixed(3).padStart(5," ")})`);//JSON.stringify(theTrade));
let multiplier=1;
if (theTrade.type==="buy") {
multiplier=-1;
}
sumUSD += Number(theTrade.cost) * multiplier;
sumCommission += Number(theTrade.fee);
let transactionTime = x=new Date(theTrade.time*1000);
let transactionDate = transactionTime.toISOString().split("T")[0];
if (dailyResults[transactionDate] === undefined) {
dailyResults[transactionDate] =0;
}
dailyResults[transactionDate] += (Number(theTrade.cost) * multiplier)
dailyResults[transactionDate] -= Number(theTrade.fee);
}
}
let allBalances=await kraken.api('Balance');
let pairQuote = await kraken.api('Ticker', { pair : thePair });
// find the currency by looking for "startsWith" match in the symbol in the pair.
let theCurrency=undefined;
Object.keys(allBalances.result).forEach((currency)=>{
if (thePair.indexOf(currency)===0) {
theCurrency=currency;
}
});
console.log("# trades : ", numTrades);
console.log("SUM USD : ", sumUSD);
console.log("SUM fees : ", sumCommission);
let netGain = sumUSD - sumCommission;
console.log("Net Gain : ", netGain);
let numCoinsHeld = Number(allBalances.result[theCurrency]);
console.log("# coins Held : ", numCoinsHeld, " [", theCurrency,"]");
let sellPrice = Number(pairQuote.result[thePair].b[0]);
console.log("Current Price : ", sellPrice);
let worthHeldCoins = numCoinsHeld * sellPrice;
console.log("Worth held coins : ", worthHeldCoins);
let netLiq = netGain + worthHeldCoins;
console.log("Net Liquidation Gain : " , netLiq);
} catch (ex) {
console.error("Error getting trade history: ", ex.message);
try {
// get the pair to process from the first parameter and fall back if not provided.
let thePair=process.argv[2];
if (thePair===undefined) {
thePair="XXMRZUSD";
}
thePair=thePair.toUpperCase(); // the pairs are always upper case.
console.log("Processing pair : ", thePair);
let allTrades=loadData("allTrades.json");
let params={ ofs : 0 };
let maxTimestamp=0;
allTrades.forEach(dta=>{if (dta.time>maxTimestamp) {maxTimestamp=dta.time;} });
params.start=maxTimestamp;
console.log("Max-Timestamp : ",maxTimestamp);
let allTransactions = await kraken.api('TradesHistory', params);
let allTradeIDs=Object.keys(allTransactions.result.trades);
let numTrans=allTradeIDs.length;
console.log("Number of new Transactions : ",numTrans);
for (let i=0;i<numTrans;i++){
params.ofs+=1;
let theTrade=allTransactions.result.trades[allTradeIDs[i]];
// the timestamp is inclusive, therefore we have to skip that record.
if (theTrade.time === maxTimestamp) { continue; }
console.log(theTrade);
allTrades.push(theTrade);
if ((params.ofs % 50) == 0) {
console.log("Load more results; offset ",params.ofs);
params.nonce = new Date() * 1000;
allTransactions = await kraken.api('TradesHistory', params);
allTradeIDs=allTradeIDs.concat(Object.keys(allTransactions.result.trades));
numTrans=allTradeIDs.length; // Not really great style to update the for condition var here, but it works...
}
}
// sort the trades by time; oldest first.
allTrades=allTrades.sort(function (a,b){return(a.time - b.time);});
storeData(allTrades,"allTrades.json");
let sumUSD=0;
let sumCommission=0;
let numTrades=0;
for (let i=0;i<allTrades.length;i++){
let theTrade=allTrades[i];
if (theTrade.pair===thePair) {
numTrades++;
let tradeLocalTime=utcToLocal(new Date(theTrade.time * 1000)).toISOString().substr(0,19).replace('T',' ');
console.log(`${tradeLocalTime} [${theTrade.pair}] ${theTrade.type.substring(0,1)}#${Number(theTrade.vol).toFixed(4).padStart(10," ")}@${Number(theTrade.price).toFixed(2).padStart(8," ")} -> ${Number(theTrade.cost).toFixed(2).padStart(9," ")}(-${Number(theTrade.fee).toFixed(3).padStart(5," ")})`);
// selling adds $$$ to our Account, buying takes money out of the account
let multiplier=theTrade.type==="buy"?-1:1;
sumUSD += Number(theTrade.cost) * multiplier;
sumCommission += Number(theTrade.fee);
}
}
let allBalances=await kraken.api('Balance');
let pairQuote = await kraken.api('Ticker', { pair : thePair });
// find the currency by looking for "startsWith" type match in the symbol in the pair.
// (not sure if that always works, but it works for all cases I checked it so far).
let theCurrency=undefined;
Object.keys(allBalances.result).forEach((currency)=>{
if (thePair.indexOf(currency)===0) {
theCurrency=currency;
}
});
console.log("# trades : ", numTrades);
console.log("SUM USD : ", sumUSD);
console.log("SUM fees : ", sumCommission);
let netGain = sumUSD - sumCommission;
console.log("Net Gain : ", netGain);
let numCoinsHeld = Number(allBalances.result[theCurrency]);
console.log("# coins Held : ", numCoinsHeld, " [", theCurrency,"]");
let sellPrice = Number(pairQuote.result[thePair].b[0]);
console.log("Current Price : ", sellPrice);
let worthHeldCoins = numCoinsHeld * sellPrice;
console.log("Worth held coins : ", worthHeldCoins);
let netLiq = netGain + worthHeldCoins;
console.log("Net Liquidation Gain : " , netLiq);
} catch (ex) {
console.error("Hit general Error-handler: ", ex.message, "\n", ex.stack);
console.error("General Error: ", ex.message, "\n", ex.stack);
}
})();