При добавлении нового элемента APPLE код работает с уже имеющимся в массиве APPLE, а не создает новый. Нужно научить код присваивать уникальный идентификатор к каждому объекту правильно понимаю?
В примере ниже я добавил еще одну сделку 10 BUY и 10 SELL
<body>
<script>
let json = [{
"symbol": "ORANGE",
"id": 479640841,
"side": "SELL",
"price": "10",
"qty": "2",
"time": 1633371930706
},
{
"symbol": "ORANGE",
"id": 479640941,
"side": "SELL",
"price": "10",
"qty": "1",
"time": 1633371930899
},
{
"symbol": "ORANGE",
"id": 479640952,
"side": "BUY",
"price": "20",
"qty": "3",
"time": 1633371940488
},
{
"symbol": "APPLE",
"id": 193964871,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956055821
},
{
"symbol": "APPLE",
"id": 193964907,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956058086
},
{
"symbol": "APPLE",
"id": 193964908,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956058086
},
{
"symbol": "APPLE",
"id": 193965481,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956074364
},
{
"symbol": "APPLE",
"id": 193967061,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956209504
},
{
"symbol": "APPLE",
"id": 193967211,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956222593
},
{
"symbol": "APPLE",
"id": 193968864,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956403438
},
{
"symbol": "APPLE",
"id": 193969405,
"side": "SELL",
"price": "20",
"qty": "70",
"time": 1633956450685
},
{
"symbol": "APPLE",
"id": 193968888,
"side": "BUY",
"price": "15",
"qty": "10",
"time": 1633956403438
},
{
"symbol": "APPLE",
"id": 193969444,
"side": "SELL",
"price": "20",
"qty": "10",
"time": 1633956450685
}
];
let obj = json.reduce((ob, {
symbol,
id,
side,
price,
qty,
time
}) => {
side = side === "BUY" ? "LONG" : "SHORT";
if(!ob[symbol]) ob[symbol] = {
symbol,
id,
side,
open: 0,
profit: 0,
volume: 0,
openTime: time
};
ob[symbol].closedTime = time;
let period = ob[symbol].side;
price *= qty;
if (period === side) {
ob[symbol].open += +qty;
ob[symbol].volume += +qty;
ob[symbol].profit += price;
} else {
if (side === "LONG") ob[symbol].profit -= price;
else ob[symbol].profit = price - ob[symbol].profit;
ob[symbol].open -= qty;
}
return ob
}, {});
document.write(`<pre>${JSON.stringify(obj,'',1)}</pre>`, )
</script>
</body>