我正在研究PHP中的比特币交易脚本。要对实时数据进行纸质交易,我必须从订单簿中确定买入/卖出价格,即买方价格。
订单簿实时json数据看起来像this
订单簿有两个主要阵列 - bid&问。每个买/卖数组的价格[0],数量[1]和第三个参数[2]无关:
买/卖样品数组
[0] => Array
(
[0] => 8848.99
[1] => 9.89850469
[2] => 7
)
[1] => Array
(
[0] => 8848.2
[1] => 0.05
[2] => 1
)
[2] => Array
(
[0] => 8848.02
[1] => 0.274203
[2] => 1
)
[3] => Array
(
[0] => 8848.01
[1] => 0.0012
[2] => 1
)
[4] => Array
(
[0] => 8847.47
[1] => 0.5
[2] => 1
)
[5] => Array
(
[0] => 8846.99
[1] => 0.28345
[2] => 1
)
[6] => Array
(
[0] => 8846.81
[1] => 0.75
[2] => 1
)
[7] => Array
(
[0] => 8846
[1] => 0.75181214
[2] => 2
)
[8] => Array
(
[0] => 8845.99
[1] => 26.57694043
[2] => 28
)
根据以上数据,如何计算PHP中15或n个硬币的平均价格?考虑到订单将从上到下填充/采用。
答案 0 :(得分:0)
我用这个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);
可能有更简单的方法,有人可以改善这个答案。目前它产生了预期的平均值。