Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GuntharDeNiro/4ae7e58ca4398a6662afed67f47c24dd to your computer and use it in GitHub Desktop.
Save GuntharDeNiro/4ae7e58ca4398a6662afed67f47c24dd to your computer and use it in GitHub Desktop.
calculateSpotMarketPnL(orders) {
let accumulatedProfit = 0;
let startCalculatingPnL = false;
let accumulatedAmount = 0;
Object.values(orders).map((item, index) => {
const nextIdx = index + 1;
if (item.type === 'buy') {
accumulatedAmount = parseFloat(accumulatedAmount) + parseFloat(item.amount);
accumulatedAmount = accumulatedAmount.toPrecision(8);
accumulatedProfit += item.costProceed;
// item.costUnit = Math.abs(item.costProceed) / item.amount;
// accumulatedCostPerUnit += item.costUnit;
startCalculatingPnL = true;
}
if (item.type === 'sell') {
if (startCalculatingPnL) {
accumulatedAmount = parseFloat(accumulatedAmount) - parseFloat(item.amount);
accumulatedAmount = accumulatedAmount.toPrecision(8);
// item.costUnit = -(Math.abs(item.costProceed) / item.amount);
item.pnl = accumulatedProfit + item.costProceed;
// item.pnl = accumulatedCostPerUnit + item.costUnit;
if (orders[nextIdx] && orders[nextIdx].type === 'sell') {
item.pnl = 0;
accumulatedProfit += item.costProceed;
// accumulatedCostPerUnit += item.costUnit;
}
}
// Check if we need to reset the accumulatedProfit
if (orders[nextIdx] && orders[nextIdx].type === 'buy') {
accumulatedProfit = 0;
accumulatedAmount = 0;
// accumulatedCostPerUnit = 0;
}
orders[index].pnl = item.pnl;
}
// console.log('accumulatedAmount', parseFloat(accumulatedAmount), item.type, item.time);
});
//console.log(orders)
return orders;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment