<?php
// app/api/accounts/portafolio

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","action");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out = new stdClass;
    $sessionid = $_GET['sessionid'];
    $action = $_GET['action'];
    $currencyid = "";
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    // Filtramos las cuentas por las acciones que pueden realizar
    /* 1 = Intercambio(Compra/Venta) (Debe existir en un PAR)
    *  2 = Deposito
    *  3 = Retiro
    *  4 = Transferencia
    */
    switch(intval($action)){
        case 1:
            // Intercambio
            $actionFilter = " AND (SELECT COUNT(pairs.currencyid) ".
            "                       FROM pairs ";
            if(isset($_GET['currencyid']) && $_GET['currencyid'] != '')
                $actionFilter.="                       WHERE (pairs.currencyid = cur.id) AND pairs.status = 1 ) > 0 ";
            else
                $actionFilter.="                       WHERE (pairs.refcurrencyid = cur.id) AND pairs.status = 1 ) > 0 ";
            break;
        case 2:
            // Deposito
            $actionFilter = " AND cur.interface != 3 AND cur.interface != 0 ";
            break;
        case 3:
            // Retiro
            $actionFilter = " AND cur.interface != 3 AND cur.interface != 0 ";
            break;
        case 4:
            // Transferencia
            $actionFilter = " AND cur.interface != 3 AND cur.interface != 0 AND cur.xfer = 1 ";
            break;
        default:
            badEnd("500",array('msg'=>'El action debe ser 1, 2, 3 o 4'));
    }
    
    // Si se envia el currencyid, se arma el query
    if(isset($_GET['currencyid']) && $_GET['currencyid'] != ''){
        // Si se envia una moneda base, buscaremos las cuentas por las monedas ref de los pares donde se encuentre
        
        // Consultaremos las monedas ref de los pares donde esta la moneda base
        $sql = "SELECT refcurrencyid, currencyid ".
        "       FROM pairs ".
        "       WHERE status=1 ".
        "       AND refcurrencyid = ".$_GET['currencyid'];//.
        //"       OR currencyid =".$_GET['currencyid'];
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $count = 0;
        $currencyid .= " AND (";
        
        // Con las monedas recogidas armamos la condicion
        while($row = $rs->fetch_assoc()){
            
            if($count == 0){
                $currencyid .= " cur.id = ".$row['currencyid'];//($_GET['currencyid'] == $row['currencyid'] ? $row['refcurrencyid'] : $row['currencyid']);
                $count++;
            }else{
                $currencyid .= " OR cur.id = ".$row['currencyid'];//($_GET['currencyid'] == $row['currencyid'] ? $row['refcurrencyid'] : $row['currencyid']);
            }
            
        }
        
        $currencyid .= " ) ";
    }else{
        // Si no se envia una moneda base, buscaremos las cuentas por las monedas base de los pares que existan
        /*
        // Consultaremos las monedas ref de los pares donde esta la moneda base
        $sql = "SELECT refcurrencyid, currencyid ".
        "       FROM pairs ";
        //"       WHERE refcurrencyid = ".$_GET['currencyid'].
        //"       OR currencyid =".$_GET['currencyid'];
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $count = 0;
        $currencyid .= " AND (";
        
        // Con las monedas recogidas armamos la condicion
        while($row = $rs->fetch_assoc()){
            
            if($count == 0){
                $currencyid .= " cur.id = ".$row['refcurrencyid'];//($_GET['currencyid'] == $row['currencyid'] ? $row['refcurrencyid'] : $row['currencyid']);
                $count++;
            }else{
                $currencyid .= " OR cur.id = ".$row['refcurrencyid'];//($_GET['currencyid'] == $row['currencyid'] ? $row['refcurrencyid'] : $row['currencyid']);
            }
            
        }
        
        $currencyid .= " ) ";*/
    }
    
    // Consultamos la cantidad de cuentas a retornar
    $sql = "SELECT COUNT(accounts.id) AS qty ".
    "       FROM accounts, currencies cur ".
    "       WHERE accounts.userid = ".$userid.
    "       AND accounts.currencyid = cur.id ".
    "       AND cur.status = 1 ".
    "       AND accounts.paymentmethodid = -1 ".
    "       ".$actionFilter.
    "       ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    $out->numofrecords = (int)$row['qty'];
    
    // Consultamos las cuentas junto a la moneda
    $sql = "SELECT accounts.id AS accountid, ".
    "       accounts.status AS accountstatus, ".
    "       cur.id AS currencyid, ".
    "       cur.symbol AS currencysymbol, ".
    "       cur.name AS currencyname, ".
    "       cur.decimals AS decimals, ".
    "       cur.xfer AS xfer, ".
    "       cur.interface AS interface ".
    "       FROM accounts, currencies cur ".
    "       WHERE accounts.userid = ".$userid.
    "       AND accounts.currencyid = cur.id ".
    "       AND cur.status = 1 ".
    "       AND accounts.paymentmethodid = -1 ".
    "       ".$actionFilter.
    "       ".$currencyid;
    $sqlprint = $sql;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    // Retornamos los datos de la cuenta
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row['accountid'];
        
        // Datos de la moneda
        $record->currency = new stdClass();
        $record->currency->id = (int)$row['currencyid'];
        $record->currency->dsc = $row['currencyname'];
        $record->currency->symbol = $row['currencysymbol'];
        $record->currency->decimals = (int)$row['decimals'];
        $record->currency->interface = (int)$row['interface'];
        $record->currency->xfer = (int)$row['xfer'];
        
        //Consultamos el balance disponible
        //Balance de la cuenta
        $sql = "SELECT SUM(amount) - ABS(IF(( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$record->id.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1) IS NOT NULL,  ".
    	"               ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$record->id.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1), 0)".
        "       + IF(( ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$record->id.
        "           AND orders.accountid = ".$record->id.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1) IS NOT NULL, ( ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$record->id.
        "           AND orders.accountid = ".$record->id.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1),0) ".
    	"      + IF ((SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$record->id.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)) IS NOT NULL, ".
    	"           (SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$record->id.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)), 0)".
    	"      ) as qty FROM transactions WHERE accountid = ".$record->id.
        "       AND paypending = 0";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $balancetx = $res->fetch_assoc();
            
        // Balance retenido por ordenes de intercambios
        $sql = "SELECT SUM(amount) AS qty ".
        "       FROM ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$record->id.
        "           AND orders.canceled IS NULL ".
        "           AND orders.type != 1 ".
        "       UNION ALL ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$record->id.
        "           AND orders.accountid = ".$record->id.
        "           AND orders.canceled IS NULL ".
        "           AND transactions.amount < 0 ".
        "           AND orders.type != 1 ".
        "       UNION ALL ".
        "           SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
        "           FROM transactions  ".
        "           WHERE transactions.paypending = 1".
        "           AND transactions.accountid = ".$record->id.
        "           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)".
        "      UNION ALL ".
        "           SELECT SUM(ABS(withdrawals.amount) + ABS(withdrawals.fee)) AS amount ".
        "           FROM transactions, withdrawals ".
        "           WHERE transactions.id = withdrawals.transactionid ".
        "           AND transactions.accountid = ".$record->id.
        "           AND withdrawals.valid IS NUll ".
        "           AND withdrawals.rejected IS NULL ".
        "       ) amount";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $balanceorder = $res->fetch_assoc();
            
        //Balance disponible
        $record->avaliable = new stdClass();
        
        $record->avaliable->number = bcdiv(number_format( ($balancetx["qty"]) ,13, '.', ''), '1',$row["decimals"]);
        $record->avaliable->number = $record->avaliable->number <0 ? 0 : $record->avaliable->number;
        $record->avaliable->formatted = numberFormatt($record->avaliable->number,$row["decimals"]);
            
        //Balance retenido
        $record->committed = new stdClass();
        $record->committed->number = (float)number_format($balanceorder["qty"],$row["decimals"],'.','');
        $record->committed->formatted = numberFormatt($record->committed->number,$row["decimals"]);
        
        //Balance pendiente de la cuenta
        $sql = "SELECT SUM(deposits.amount - deposits.fee) as qty ".
        "       FROM accounts, transactions".
        "       LEFT JOIN deposits ON transactions.id = deposits.transactionid ".
        "       AND deposits.rejected IS NULL AND deposits.valid IS NULL".
	    "       WHERE accounts.id = transactions.accountid AND accounts.id = ".$record->id.
	    "       AND transactions.amountghost >= 0";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $balance = $res->fetch_assoc();
        
        //Balance pendiente 
        $record->deferred = new stdClass();
        $record->deferred->number = (float)number_format($balance["qty"],$row["decimals"],'.','');
        $record->deferred->formatted = numberFormatt($record->deferred->number,$row["decimals"]);
        
        // Balanace total
        $record->total = new stdClass();
        $record->total->number = (float)number_format($record->deferred->number + $record->committed->number + $record->avaliable->number,$row["decimals"],'.','');
        $record->total->number = $record->total->number < 0 ? 0 : $record->total->number;
        $record->total->formatted = numberFormatt($record->total->number,$row["decimals"]);
        
        // Estado de la cuenta
        $record->status = (int)$row['accountstatus'];
        
        // Validamos para retornar el maxbuy
        if($action != 1 || $currencyid == ''){
            $record->maxbuy = null;
        }else{
            
            // Consultamos el par para saber de donde contar la cantidad
            $sql = "SELECT COUNT(id) AS qty ".
            "       FROM pairs ".
            "       WHERE (currencyid = ".$_GET['currencyid'].
            "       AND refcurrencyid =".$record->currency->id." ) ";/*
            "       OR (currencyid = ".$record->currency->id.
            "       AND refcurrencyid = ".$_GET['currencyid']." ) ";*/
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
        
            $max = $res->fetch_assoc();
            
            // Validamos que exista un par
            if($max['qty'] > 0){
                
                //COnsultamos los datos del par
                $sql = "SELECT id, refcurrencyid, currencyid ".
                "       FROM pairs ".
                "       WHERE (currencyid = ".$_GET['currencyid'].
                "       AND refcurrencyid =".$record->currency->id." ) ";/*
                "       OR (currencyid = ".$record->currency->id.
                "       AND refcurrencyid = ".$_GET['currencyid']." ) ";*/
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
        
                $max = $res->fetch_assoc();
                
                // Obtenemos los decimales para el par
                $sql = "SELECT decimals FROM currencies WHERE id = ".$max['currencyid'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
        
                $decimals = $res->fetch_assoc();
                
                //Consultamos la ultima venta
                $sql = "SELECT o.quantity AS qty, o.id AS grouptx, ".
                "       o.price, o.side, o.id, o.total".
                "       FROM orders o".
                "       WHERE o.side = 1 AND o.canceled IS NULL AND o.pairid = ".$max['id'].
                "       AND (CASE ".
                "           WHEN o.canceled IS NOT NULL THEN -1 ".
                "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
                "               AND o.canceled IS NULL THEN 1 ".
                "           ELSE 0 ".
                "       END) = 0 ".
                "       ORDER BY o.price ASC".
                "       LIMIT 1";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $ask = $res->fetch_assoc();
        
                // Retornamos el ask del par
                $refPrice = (float)$ask['price'];
                
                $sql = "SELECT SUM(o.quantity) AS qty, COUNT(o.id) AS grouptx, o.price AS price, ".
                "       IF( ".
                "           (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) IS NOT NULL, ".
                "           (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)), ".
                "           0 ".
                "       ) AS totallyfilled ".
                "       FROM orders o".
                "       WHERE o.side = 2 AND o.canceled IS NULL AND o.pairid = ".$max['id'].
                "       AND (CASE ".
                "           WHEN o.canceled IS NOT NULL THEN -1 ".
                "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
                "               AND o.canceled IS NULL THEN 1 ".
                "           ELSE 0 ".
                "       END) = 0 ".
                "       GROUP BY o.price".
                "       ORDER BY o.price DESC, o.date DESC";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    
                $acum = $record->avaliable->number;
                $total = 0;
                while($pairquantity = $res->fetch_assoc()){
                    // Sacamos lo que tiene la orden en total con su precio para ver si podemos completarla toda o no
                    //$tempRate = (($pairquantity["qty"] - $pairquantity['totallyfilled']) * 100) / $pairquantity["qty"];
                    $temptotal = 0;
                    $tempRate = $pairquantity["qty"] - $pairquantity['totallyfilled'];
                        
                    if($tempRate < $acum){
                        $acum = $acum - $tempRate;
                        
                        $tmpPct = ($tempRate * $pairquantity['price']);
                        $record->temprate3[] = $tmpPct;
                        
                        $temptotal = $tmpPct;
                        $record->totaltmp [] = $temptotal; 
                            
                        $total += $temptotal;
                            
                    }else if($acum > 0){
                        
                        //$tempRate = $;
                        $tmpPct = $acum;
                        $record->temprate3[] = $acum;
                        
                        $temptotal = $tmpPct * $pairquantity["price"];
                        $record->totaltmp [] = $temptotal." 2"; 
                    
                        $total += $temptotal;
                        $acum -= $acum;
                    }
                }
                
                $record->maxbuy = new stdClass();
                $record->maxbuy->number = (float)number_format($total,$decimals['decimals'],".","");;
                $record->maxbuy->formatted = number_format($record->maxbuy->number,$decimals['decimals'],",",".");
            }else{
                
                // Consultamos el par para saber de donde contar la cantidad
                $sql = "SELECT COUNT(id) AS qty ".
                "       FROM pairs ".
                "       WHERE (refcurrencyid = ".$_GET['currencyid'].
                "       AND currencyid =".$record->currency->id." ) ";/*
                "       OR (currencyid = ".$record->currency->id.
                "       AND refcurrencyid = ".$_GET['currencyid']." ) ";*/
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
            
                $max = $res->fetch_assoc();
                
                // Validamos que exista un par
                if($max['qty'] > 0){
                    
                    //COnsultamos los datos del par
                    $sql = "SELECT id, refcurrencyid, currencyid ".
                    "       FROM pairs ".
                    "       WHERE (refcurrencyid = ".$_GET['currencyid'].
                    "       AND currencyid =".$record->currency->id." ) ";/*
                    "       OR (currencyid = ".$record->currency->id.
                    "       AND refcurrencyid = ".$_GET['currencyid']." ) ";*/
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
            
                    $max = $res->fetch_assoc();
                    
                    // Obtenemos los decimales para el par
                    $sql = "SELECT decimals FROM currencies WHERE id = ".$max['refcurrencyid'];
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
            
                    $decimals = $res->fetch_assoc();
                    
                    //Consultamos la ultima venta
                    $sql = "SELECT o.quantity AS qty, o.id AS grouptx, ".
                    "       o.price, o.side, o.id, o.total".
                    "       FROM orders o".
                    "       WHERE o.side = 1 AND o.canceled IS NULL AND o.pairid = ".$max['id'].
                    "       AND (CASE ".
                    "           WHEN o.canceled IS NOT NULL THEN -1 ".
                    "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
                    "               FROM transactions, orders ".
                    "               WHERE orders.id = transactions.orderid ".
                    "               AND orders.id = o.id ".
                    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
                    "               AND o.canceled IS NULL THEN 1 ".
                    "           ELSE 0 ".
                    "       END) = 0 ".
                    "       ORDER BY o.price ASC".
                    "       LIMIT 1";
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                        
                    $ask = $res->fetch_assoc();
            
                    // Retornamos el ask del par
                    $refPrice = (float)$ask['price'];
                    
                    $sql = "SELECT SUM(o.quantity) AS qty, COUNT(o.id) AS grouptx, o.price AS price, ".
                    "       IF( ".
                    "           (SELECT SUM(ABS(transactions.amount)) ".
                    "               FROM transactions, orders ".
                    "               WHERE orders.id = transactions.orderid ".
                    "               AND orders.id = o.id ".
                    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) IS NOT NULL, ".
                    "           (SELECT SUM(ABS(transactions.amount)) ".
                    "               FROM transactions, orders ".
                    "               WHERE orders.id = transactions.orderid ".
                    "               AND orders.id = o.id ".
                    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)), ".
                    "           0 ".
                    "       ) AS totallyfilled ".
                    "       FROM orders o".
                    "       WHERE o.side = 1 AND o.canceled IS NULL AND o.pairid = ".$max['id'].
                    "       AND (CASE ".
                    "           WHEN o.canceled IS NOT NULL THEN -1 ".
                    "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
                    "               FROM transactions, orders ".
                    "               WHERE orders.id = transactions.orderid ".
                    "               AND orders.id = o.id ".
                    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
                    "               AND o.canceled IS NULL THEN 1 ".
                    "           ELSE 0 ".
                    "       END) = 0 ".
                    "       GROUP BY o.price".
                    "       ORDER BY o.price ASC, o.date DESC";
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                        
                        
                    $acum = $record->avaliable->number;
                    $total = 0;
                    while($pairquantity = $res->fetch_assoc()){
                        
                        // Sacamos lo que tiene la orden en total con su precio para ver si podemos completarla toda o no
                        $tempRate = $refPrice * ($pairquantity["qty"] - $pairquantity['totallyfilled']);
                        $temptotal = 0;
                        
                        $record->qtys [] = $pairquantity['qty'];
                        $record->acum [] = $acum;
                        // Si la tasa es menor podemos completarla toda, restamos la orden
                        if($tempRate < $acum){
                            $acum = $acum - $tempRate;
                            
                            $temptotal = (float)($pairquantity["qty"] - $pairquantity['totallyfilled']);
                    
                            $total += $temptotal;
                            $record->menor [] = $temptotal;
                            
                        }else if($acum > 0){
                            // Si no, con lo que nos resta sacamos lo que podemos sacarle a la orden
                            $temptotal = (float)($acum / $refPrice);
                            
                            if($temptotal > $pairquantity["qty"] - $pairquantity['totallyfilled']){
                                $ttotal += $pairquantity["qty"] - $pairquantity['totallyfilled'];
                            }else{
                                $total += $temptotal;
                            }
                            
                            $acum = $acum - $refPrice;
                        }
                    }
                    
                    $record->maxbuy = new stdClass();
                    $record->maxbuy->number = (float)number_format($total,$decimals['decimals'],".","");;
                    $record->maxbuy->formatted = number_format($record->maxbuy->number,$decimals['decimals'],",",".");
                }
            }
        }
        
        $records [] = $record;
    }
    
    $out->records = $records;
    $out->sqlprint = $sqlprint;
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
