代码之家  ›  专栏  ›  技术社区  ›  Jsp

从买卖订单簿中确定买方价格

  •  0
  • Jsp  · 技术社区  · 6 年前

    我正在用PHP编写比特币交易脚本。要在实时数据上进行纸面交易,我必须根据订单确定买入/卖出价格,即买方价格。

    Order book live json数据如下所示 this

    订单簿有两个主要数组-bids和;问。每个买卖数组都有价格[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个硬币的平均价格?考虑到订单将按照从上到下的顺序完成。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jsp    6 年前

    我用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);
    

    也许有更简单的方法,有人可以改进这个答案。目前,它产生了预期的平均值。