我用Excel公式解决了这个问题:
Avg. Cost = sumproduct(price series, qty series) / sum(qty series)
以下是PHP代码:
$order_book = json_decode($order_book, true);
$bids = ($order_book['bids']);
$ordered = 15; //n number of coins
$filled = 0;
$fill_array = array();
foreach ($bids as $PriceQty) {
$price = $PriceQty[0];
$qty = $PriceQty[1];
if ($ordered != $filled){
$required = $ordered - $filled;
if ($qty >= $required){
$fill_array[] = array($price,$required);
$filled = $filled + $required;
break;
}else{
$filled = $filled + $qty;
$fill_array[] = array($price,$qty);
}
}
}
$totalQty = 0;
$totalSum = 0;
foreach ($fill_array as $PriceQty) {
$totalSum = $totalSum + ($PriceQty[0] * $PriceQty[1]);
$totalQty = $totalQty + $PriceQty[1];
}
echo "$totalSum/$totalQty = ".($totalSum/$totalQty);
也许有更简单的方法,有人可以改进这个答案。目前,它产生了预期的平均值。