'Working on two-dimensional arrays to calculate win/lose
I am tracking my trading portfolio in two arrays of objects.
The sells and the buys for a specific trade currency as follows:
var sell {
sold_amount: sold,
bought_amount: bought,
price : price
}
var buy {
sold_amount: sold,
bought_amount: bought,
price : price
}
I am trying to the following:
Calculate my win-lose percentage in a LIFO manner. That means that I want to take the latest sell I made and start subtracting the price/amount from the latest buy and then move backwards.
If my sell was big enough, it would mean that I would need to look not only on the previous buy, but I would need to search an unknown number of previous buys until all my sell amount is exhausted so that I can calculate my win/lose.
My difficulty is that since sells and buys are done on different amount/prices, it is really difficult for me to calculate the result.
That means for example:
I bought 20 units of $javascript paying 32 units of $c++ ,
I bought 17 units of $javascript paying 29 units of $c++ ,
I sold 57 units of $c++ paying 31 units of $javascript,
I bought 22 units of $javascript paying 22 units of c++,
I sold 12 units of c++ paing 11 units of $javascript,
That means that at every sell I would need to look backwards and see the price I bought it recursively and calculate the win/lose according to the amount sold/bought.
I am not looking for a solution, just some guidelines or some advice.
Solution 1:[1]
If we think of LIFO trading we can translate that to the idea of elements in a data structure called a stack, which have the operations push/pop:
![]()
Each trade has five variables: buy amount, buy type, sell amount, sell type, and date.
function Trade(buyAmount, buyType, sellAmount, sellType, date) {
this.buyAmount = buyAmount;
this.buyType = buyType;
this.sellAmount = sellType;
this.date = date;
}
This is a JavaScript object constructor, and it can be called by saying:
var trade = new Trade("Bitcoin", 1.0, "Ethereum", 10.0, new Date("5/30/2018"));
The keyword new before a function call creates an object and this used in that function becomes a reference to that new object. The object is then assigned to the variable trade. (Research this it is very powerful.)
Anyway, next you would need to create an array sorted by date and create an algorithm that could keep trade of the gross profit of each trade related to the type of item sold, that is, an dictionary resembling:
var profit = { Bitcoin: 0, Ethereum: 0 }
This is is a good starting place, and I used this same kind of data structure to calculate the taxes for my cryptocurrency gains in 2017.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
