示例#1
1
function BackendUpdateDeposit()
{
    //	debuglog(__FUNCTION__);
    $btc = getdbosql('db_coins', "symbol='BTC'");
    if (!$btc) {
        return;
    }
    $remote = new Bitcoin($btc->rpcuser, $btc->rpcpasswd, $btc->rpchost, $btc->rpcport);
    $info = $remote->getinfo();
    if (!$info) {
        return;
    }
    if (!isset($info['blocks'])) {
        return;
    }
    $hash = $remote->getblockhash(intval($info['blocks']));
    if (!$hash) {
        return;
    }
    $block = $remote->getblock($hash);
    if (!$block) {
        return;
    }
    if (!isset($block['time'])) {
        return;
    }
    if ($block['time'] + 30 * 60 < time()) {
        return;
    }
    $list = $remote->listaccounts(1);
    foreach ($list as $r => $a) {
        if ($a == 0) {
            continue;
        }
        $b = preg_match('/renter-prod-([0-9]+)/', $r, $m);
        if (!$b) {
            continue;
        }
        $renter = getdbo('db_renters', $m[1]);
        if (!$renter) {
            continue;
        }
        $ts = $remote->listtransactions(yaamp_renter_account($renter), 1);
        if (!$ts || !isset($ts[0])) {
            continue;
        }
        $moved = $remote->move(yaamp_renter_account($renter), '', $a);
        if (!$moved) {
            continue;
        }
        debuglog("deposit {$renter->id} {$renter->address}, {$a}");
        $rentertx = new db_rentertxs();
        $rentertx->renterid = $renter->id;
        $rentertx->time = time();
        $rentertx->amount = $a;
        $rentertx->type = 'deposit';
        $rentertx->tx = isset($ts[0]['txid']) ? $ts[0]['txid'] : '';
        $rentertx->save();
        $renter->unconfirmed = 0;
        $renter->balance += $a;
        $renter->updated = time();
        $renter->save();
    }
    $list = $remote->listaccounts(0);
    foreach ($list as $r => $a) {
        if ($a == 0) {
            continue;
        }
        $b = preg_match('/renter-prod-([0-9]+)/', $r, $m);
        if (!$b) {
            continue;
        }
        $renter = getdbo('db_renters', $m[1]);
        if (!$renter) {
            continue;
        }
        debuglog("unconfirmed {$renter->id} {$renter->address}, {$a}");
        $renter->unconfirmed = $a;
        $renter->updated = time();
        $renter->save();
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    $received1 = $remote->getbalance('bittrex', 1);
    //nicehash payments
    if ($received1 > 0) {
        $moved = $remote->move('bittrex', '', $received1);
        debuglog("moved from bittrex {$received1}");
        dborun("update renters set balance=balance+{$received1} where id=7");
        dborun("update renters set custom_start=custom_start+{$received1} where id=7");
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    $fees = 0.0001;
    $list = getdbolist('db_rentertxs', "type='withdraw' and tx='scheduled'");
    foreach ($list as $tx) {
        $renter = getdbo('db_renters', $tx->renterid);
        if (!$renter) {
            continue;
        }
        //		debuglog("$renter->balance < $tx->amount + $fees");
        $tx->amount = bitcoinvaluetoa(min($tx->amount, $renter->balance - $fees));
        if ($tx->amount < $fees * 2) {
            $tx->tx = 'failed';
            $tx->save();
            continue;
        }
        debuglog("withdraw send {$renter->id} {$renter->address} sendtoaddress({$tx->address}, {$tx->amount})");
        $tx->tx = $remote->sendtoaddress($tx->address, round($tx->amount, 8));
        if (!$tx->tx) {
            $tx->tx = 'failed';
            $tx->save();
            continue;
        }
        $renter->balance -= $tx->amount + $fees;
        $renter->balance = max($renter->balance, 0);
        dborun("update renters set balance={$renter->balance} where id={$renter->id}");
        $tx->save();
        if ($renter->balance <= 0.0001) {
            dborun("update jobs set active=false, ready=false where id={$renter->id}");
        }
    }
}
示例#2
1
function doPoloniexTrading()
{
    //	debuglog('-------------- doPoloniexTrading()');
    $flushall = rand(0, 4) == 0;
    $poloniex = new poloniex();
    $tickers = $poloniex->get_ticker();
    if (!$tickers) {
        return;
    }
    // upgrade orders
    $coins = getdbolist('db_coins', "enable and id in (select distinct coinid from markets where name='poloniex')");
    foreach ($coins as $coin) {
        if ($coin->dontsell) {
            continue;
        }
        $pair = "BTC_{$coin->symbol}";
        if (!isset($tickers[$pair])) {
            continue;
        }
        $orders = $poloniex->get_open_orders($pair);
        if (!$orders || !isset($orders[0])) {
            dborun("delete from orders where coinid={$coin->id} and market='poloniex'");
            continue;
        }
        foreach ($orders as $order) {
            if (!isset($order['orderNumber'])) {
                debuglog($order);
                continue;
            }
            if ($order['rate'] > $tickers[$pair]['lowestAsk'] + 5.0E-8 || $flushall) {
                //				debuglog("poloniex cancel order for $pair {$order['orderNumber']}");
                $poloniex->cancel_order($pair, $order['orderNumber']);
                $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order['orderNumber']));
                if ($db_order) {
                    $db_order->delete();
                }
                sleep(1);
            } else {
                $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order['orderNumber']));
                if ($db_order) {
                    continue;
                }
                debuglog("poloniex adding order {$coin->symbol}");
                $db_order = new db_orders();
                $db_order->market = 'poloniex';
                $db_order->coinid = $coin->id;
                $db_order->amount = $order['amount'];
                $db_order->price = $order['rate'];
                $db_order->ask = $tickers[$pair]['lowestAsk'];
                $db_order->bid = $tickers[$pair]['highestBid'];
                $db_order->uuid = $order['orderNumber'];
                $db_order->created = time();
                $db_order->save();
            }
        }
        $list = getdbolist('db_orders', "coinid={$coin->id} and market='poloniex'");
        foreach ($list as $db_order) {
            $found = false;
            foreach ($orders as $order) {
                if (!isset($order['orderNumber'])) {
                    debuglog($order);
                    continue;
                }
                if ($order['orderNumber'] == $db_order->uuid) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                debuglog("poloniex deleting order {$coin->name} {$db_order->amount}");
                $db_order->delete();
            }
        }
    }
    // add orders
    $savebalance = getdbosql('db_balances', "name='poloniex'");
    $balances = $poloniex->get_balances();
    foreach ($balances as $symbol => $balance) {
        if (!$balance) {
            continue;
        }
        if ($symbol == 'BTC') {
            $savebalance->balance = $balance;
            $savebalance->save();
            continue;
        }
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
        if (!$coin || $coin->dontsell) {
            continue;
        }
        $market = getdbosql('db_markets', "coinid={$coin->id} and name='poloniex'");
        if ($market) {
            $market->lasttraded = time();
            $market->save();
        }
        $pair = "BTC_{$symbol}";
        if (!isset($tickers[$pair])) {
            continue;
        }
        $sellprice = $tickers[$pair]['highestBid'];
        if ($balance * $sellprice < 0.0001) {
            continue;
        }
        //		debuglog("poloniex selling $pair, $sellprice, $balance");
        $res = $poloniex->sell($pair, $sellprice, $balance);
        if (!isset($res['orderNumber'])) {
            debuglog($res, 5);
            continue;
        }
        if (!isset($tickers[$pair])) {
            continue;
        }
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
        if (!$coin) {
            continue;
        }
        $db_order = new db_orders();
        $db_order->market = 'poloniex';
        $db_order->coinid = $coin->id;
        $db_order->amount = $balance;
        $db_order->price = $sellprice;
        $db_order->ask = $tickers[$pair]['lowestAsk'];
        $db_order->bid = $tickers[$pair]['highestBid'];
        $db_order->uuid = $res['orderNumber'];
        $db_order->created = time();
        $db_order->save();
    }
    if ($savebalance->balance >= 0.2) {
        $btcaddr = YAAMP_BTCADDRESS;
        //'14LS7Uda6EZGXLtRrFEZ2kWmarrxobkyu9';
        $amount = $savebalance->balance;
        // - 0.0002;
        debuglog("poloniex withdraw {$amount} to {$btcaddr}");
        sleep(1);
        $res = $poloniex->withdraw('BTC', $amount, $btcaddr);
        debuglog($res);
        if ($res && $res->success) {
            $withdraw = new db_withdraws();
            $withdraw->market = 'poloniex';
            $withdraw->address = $btcaddr;
            $withdraw->amount = $amount;
            $withdraw->time = time();
            //	$withdraw->uuid = $res->result->uuid;
            $withdraw->save();
        }
    }
    //	debuglog('-------------- doPoloniexTrading() done');
}
示例#3
0
function getrenterparam($address)
{
    if (empty($address)) {
        return null;
    }
    $address = substr($address, 0, 34);
    $renter = getdbosql('db_renters', "address=:ad", array(':ad' => $address));
    return $renter;
}
示例#4
0
 public function __construct($coin, $marketname)
 {
     $this->coin = $coin;
     $this->marketname = $marketname;
     $this->market = getdbosql('db_markets', "coinid={$coin->id} and name='{$marketname}'");
     if (!$this->market) {
         return;
     }
 }
示例#5
0
<?php

/////////////////////////////////////////////////////////////////////////////////////////////////
$symbol = getparam('symbol');
$coin = null;
if ($symbol == 'all') {
    $users = getdbolist('db_accounts', "balance>.001 order by balance desc");
} else {
    $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
    if (!$coin) {
        return;
    }
    $users = getdbolist('db_accounts', "balance>.001 and coinid={$coin->id} order by balance desc");
}
//echo "<br><table class='dataGrid'>";
showTableSorter('maintable');
echo "<thead>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Wallet</th>";
echo "<th>Last</th>";
echo "<th align=right>Miners</th>";
echo "<th align=right>Hashrate</th>";
echo "<th align=right>Bad</th>";
echo "<th></th>";
echo "<th align=right>Blocks</th>";
echo "<th align=right>Diff/Paid</th>";
echo "<th align=right>Balance</th>";
echo "<th align=right>Total Paid</th>";
echo "<th></th>";
echo "</tr>";
示例#6
0
function yaamp_convert_earnings_user($user, $status)
{
    $refcoin = getdbo('db_coins', $user->coinid);
    if (!$refcoin) {
        $refcoin = getdbosql('db_coins', "symbol='BTC'");
    }
    if (!$refcoin || $refcoin->price2 <= 0) {
        return 0;
    }
    $value = dboscalar("select sum(amount*price) from earnings where {$status} and userid={$user->id}");
    $value = $value / $refcoin->price2;
    return $value;
}
示例#7
0
 public function actionAlgo()
 {
     $algo = substr(getparam('algo'), 0, 32);
     $a = getdbosql('db_algos', "name=:name", array(':name' => $algo));
     if ($a) {
         user()->setState('yaamp-algo', $a->name);
     } else {
         user()->setState('yaamp-algo', 'all');
     }
     $this->goback();
 }
示例#8
0
function BackendCoinPayments($coin)
{
    //	debuglog("BackendCoinPayments $coin->symbol");
    $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
    $info = $remote->getinfo();
    if (!$info) {
        debuglog("{$coin->symbol} cant connect to coin");
        return;
    }
    $min = 0.001;
    // 	if(date("w", time()) == 0 && date("H", time()) > 12)		// sunday afternoon
    // 		$min = 0.0001;
    $users = getdbolist('db_accounts', "balance>{$min} and coinid={$coin->id}");
    if ($coin->symbol == 'MUE' || $coin->symbol == 'DIME') {
        foreach ($users as $user) {
            $user = getdbo('db_accounts', $user->id);
            if (!$user) {
                continue;
            }
            $amount = $user->balance;
            while ($user->balance > $min && $amount > $min) {
                debuglog("{$coin->symbol} sendtoaddress {$user->username} {$amount}");
                $tx = $remote->sendtoaddress($user->username, round($amount, 8));
                if (!$tx) {
                    debuglog("error {$remote->error}, {$user->username}, {$amount}");
                    if ($remote->error == 'transaction too large' || $remote->error == 'invalid amount') {
                        $amount /= 2;
                        continue;
                    }
                    break;
                }
                $payout = new db_payouts();
                $payout->account_id = $user->id;
                $payout->time = time();
                $payout->amount = bitcoinvaluetoa($amount);
                $payout->fee = 0;
                $payout->tx = $tx;
                $payout->save();
                $user->balance -= $amount;
                $user->save();
            }
        }
        debuglog("payment done");
        return;
    }
    $total_to_pay = 0;
    $addresses = array();
    foreach ($users as $user) {
        $total_to_pay += round($user->balance, 8);
        $addresses[$user->username] = round($user->balance, 8);
    }
    if (!$total_to_pay) {
        //	debuglog("nothing to pay");
        return;
    }
    if ($info['balance'] - 0.001 < $total_to_pay) {
        debuglog("{$coin->symbol} wallet insufficient funds for payment {$info['balance']} < {$total_to_pay}");
        return;
    }
    if ($coin->symbol == 'BTC') {
        global $cold_wallet_table;
        $balance = $info['balance'];
        $stats = getdbosql('db_stats', "1 order by time desc");
        $renter = dboscalar("select sum(balance) from renters");
        $pie = $balance - $total_to_pay - $renter - 1;
        debuglog("pie to split is {$pie}");
        if ($pie > 0) {
            foreach ($cold_wallet_table as $coldwallet => $percent) {
                $coldamount = round($pie * $percent, 8);
                if ($coldamount < $min) {
                    break;
                }
                debuglog("paying cold wallet {$coldwallet} {$coldamount}");
                $addresses[$coldwallet] = $coldamount;
                $total_to_pay += $coldamount;
            }
        }
    }
    debuglog("paying {$total_to_pay} {$coin->symbol} min is {$min}");
    $tx = $remote->sendmany('', $addresses, 1, '');
    if (!$tx) {
        debuglog($remote->error);
        return;
    }
    foreach ($users as $user) {
        $user = getdbo('db_accounts', $user->id);
        if (!$user) {
            continue;
        }
        $payout = new db_payouts();
        $payout->account_id = $user->id;
        $payout->time = time();
        $payout->amount = bitcoinvaluetoa($user->balance);
        $payout->fee = 0;
        $payout->tx = $tx;
        $payout->save();
        $user->balance = 0;
        $user->save();
    }
    debuglog("payment done");
    sleep(5);
}
示例#9
0
function updateYobitMarkets()
{
    $res = yobit_api_query('info');
    if (!$res) {
        return;
    }
    foreach ($res->pairs as $i => $item) {
        $e = explode('_', $i);
        $symbol = strtoupper($e[0]);
        if ($e[1] != 'btc') {
            continue;
        }
        if ($symbol == 'BTC') {
            continue;
        }
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
        if (!$coin || !$coin->installed) {
            continue;
        }
        $market = getdbosql('db_markets', "coinid={$coin->id} and name='yobit'");
        if (!$market) {
            $market = new db_markets();
            $market->coinid = $coin->id;
            $market->name = 'yobit';
        }
        $pair = strtolower($coin->symbol) . '_btc';
        $ticker = yobit_api_query("ticker/{$pair}");
        if (!$ticker) {
            continue;
        }
        $price2 = ($ticker->{$pair}->buy + $ticker->{$pair}->sell) / 2;
        $market->price2 = AverageIncrement($market->price2, $price2);
        $market->price = AverageIncrement($market->price, $ticker->{$pair}->buy);
        $market->save();
    }
}
示例#10
0
            echo "main {$i} ";
        }
    }
}
echo "</span>";
$block_time = sectoa(time() - memcache_get($this->memcache->memcache, "cronjob_block_time_start"));
$loop2_time = sectoa(time() - memcache_get($this->memcache->memcache, "cronjob_loop2_time_start"));
$main_time2 = sectoa(time() - memcache_get($this->memcache->memcache, "cronjob_main_time_start"));
$main_time = sectoa(memcache_get($this->memcache->memcache, "cronjob_main_time"));
$main_text = cronstate2text($state_main);
echo "*** main  ({$main_time}) {$state_main} {$main_text} ({$main_time2}), loop2 ({$loop2_time}), block ({$block_time})<br>";
$topay = dboscalar("select sum(balance) from accounts where coinid={$btc->id}");
//here: take other currencies too
$topay2 = bitcoinvaluetoa(dboscalar("select sum(balance) from accounts where coinid={$btc->id} and balance>0.001"));
$renter = dboscalar("select sum(balance) from renters");
$stats = getdbosql('db_stats', "1 order by time desc");
$margin2 = bitcoinvaluetoa($btc->balance - $topay - $renter + $stats->balances + $stats->onsell + $stats->wallets);
$margin = bitcoinvaluetoa($btc->balance - $topay - $renter);
$topay = bitcoinvaluetoa($topay);
$renter = bitcoinvaluetoa($renter);
$immature = dboscalar("select sum(amount*price) from earnings where status=0");
$mints = dboscalar("select sum(mint*price) from coins where enable");
$off = $mints - $immature;
$immature = bitcoinvaluetoa($immature);
$mints = bitcoinvaluetoa($mints);
$off = bitcoinvaluetoa($off);
$btcaddr = YAAMP_BTCADDRESS;
//'14LS7Uda6EZGXLtRrFEZ2kWmarrxobkyu9';
echo "<a href='https://www.okcoin.com/market.do' target=_blank>Bitstamp {$mining->usdbtc}</a>, ";
echo "<a href='https://blockchain.info/address/{$btcaddr}' target=_blank>wallet {$btc->balance}</a>, next payout {$topay2}<br>";
echo "pay {$topay}, renter {$renter}, marg {$margin}, {$margin2}<br>";
示例#11
0
function BackendUpdateServices()
{
    //	debuglog(__FUNCTION__);
    $table = array(0 => 'scrypt', 1 => 'sha256', 2 => 'scryptn', 3 => 'x11', 4 => 'x13', 5 => 'keccak', 6 => 'x15', 7 => 'nist5', 8 => 'neoscrypt', 9 => 'lyra2', 10 => 'whirlx', 11 => 'qubit', 12 => 'quark', 111 => 'c11');
    $res = fetch_url('https://www.nicehash.com/api?method=stats.global.current');
    if (!$res) {
        return;
    }
    $a = json_decode($res);
    if (!$a || !isset($a->result)) {
        return;
    }
    foreach ($a->result->stats as $stat) {
        if ($stat->price <= 0) {
            continue;
        }
        if (!isset($table[$stat->algo])) {
            continue;
        }
        $algo = $table[$stat->algo];
        $service = getdbosql('db_services', "name='Nicehash' and algo=:algo", array(':algo' => $algo));
        if (!$service) {
            $service = new db_services();
            $service->name = 'Nicehash';
            $service->algo = $algo;
        }
        $service->price = $stat->price / 1000;
        $service->speed = $stat->speed * 1000000000;
        $service->save();
        $list = getdbolist('db_jobs', "percent>0 and algo=:algo and (host='stratum.westhash.com' or host='stratum.nicehash.com')", array(':algo' => $algo));
        foreach ($list as $job) {
            $job->price = round($service->price * 1000 * (100 - $job->percent) / 100, 2);
            $job->save();
        }
    }
    $list = getdbolist('db_renters', "custom_address is not null and custom_server is not null");
    foreach ($list as $renter) {
        $res = fetch_url("https://{$renter->custom_server}/api?method=stats.provider&addr={$renter->custom_address}");
        if (!$res) {
            continue;
        }
        $renter->custom_balance = 0;
        $renter->custom_accept = 0;
        $renter->custom_reject = 0;
        $a = json_decode($res);
        foreach ($a->result->stats as $stat) {
            if (!isset($table[$stat->algo])) {
                continue;
            }
            $algo = $table[$stat->algo];
            $renter->custom_balance += $stat->balance;
            $renter->custom_accept += $stat->accepted_speed * 1000000000;
            $renter->custom_reject += $stat->rejected_speed * 1000000000;
        }
        $renter->save();
    }
    ///////////////////////////////////////////////////////////////////////////
    // renting from nicehash
    if (!YAAMP_PRODUCTION) {
        return;
    }
    return;
    $apikey = 'c9534a11-0e4e-4d00-be64-a00e34cd927a';
    $apiid = '7215';
    $deposit = '1C23KmLeCaQSLLyKVykHEUse1R7jRDv9j9';
    $amount = '0.01';
    $res = fetch_url("https://www.nicehash.com/api?method=balance&id={$apiid}&key={$apikey}");
    $a = json_decode($res);
    $balance = $a->result->balance_confirmed;
    foreach ($table as $i => $algo) {
        $nicehash = getdbosql('db_nicehash', "algo=:algo", array(':algo' => $algo));
        if (!$nicehash) {
            $nicehash = new db_nicehash();
            $nicehash->active = false;
            $nicehash->algo = $algo;
        }
        if (!$nicehash->active) {
            if ($nicehash->orderid) {
                $res = fetch_url("https://www.nicehash.com/api?method=orders.remove&id={$apiid}&key={$apikey}&algo={$i}&order={$nicehash->orderid}");
                debuglog($res);
                $nicehash->orderid = null;
            }
            $nicehash->btc = null;
            $nicehash->price = null;
            $nicehash->speed = null;
            $nicehash->last_decrease = null;
            $nicehash->save();
            continue;
        }
        $price = dboscalar("select price from hashrate where algo=:algo order by time desc limit 1", array(':algo' => $algo));
        $minprice = $price * 0.5;
        $setprice = $price * 0.7;
        $maxprice = $price * 0.9;
        $cancelprice = $price * 1.1;
        $res = fetch_url("https://www.nicehash.com/api?method=orders.get&my&id={$apiid}&key={$apikey}&algo={$i}");
        if (!$res) {
            break;
        }
        $a = json_decode($res);
        if (count($a->result->orders) == 0) {
            if ($balance < $amount) {
                continue;
            }
            $port = getAlgoPort($algo);
            $res = fetch_url("https://www.nicehash.com/api?method=orders.create&id={$apiid}&key={$apikey}&algo={$i}&amount={$amount}&price={$setprice}&limit=0&pool_host=yaamp.com&pool_port={$port}&pool_user={$deposit}&pool_pass=xx");
            debuglog($res);
            $nicehash->last_decrease = time();
            $nicehash->save();
            continue;
        }
        $order = $a->result->orders[0];
        debuglog("{$algo} {$order->price} {$minprice} {$setprice} {$maxprice} {$cancelprice}");
        $nicehash->orderid = $order->id;
        $nicehash->btc = $order->btc_avail;
        $nicehash->workers = $order->workers;
        $nicehash->price = $order->price;
        $nicehash->speed = $order->limit_speed;
        $nicehash->accepted = $order->accepted_speed;
        $nicehash->rejected = $order->rejected_speed;
        if ($order->price > $cancelprice && $order->workers > 0) {
            debuglog("* cancel order {$algo}");
            $res = fetch_url("https://www.nicehash.com/api?method=orders.remove&id={$apiid}&key={$apikey}&algo={$i}&order={$order->id}");
            debuglog($res);
        } else {
            if ($order->price > $maxprice && $order->limit_speed == 0) {
                debuglog("* decrease speed {$algo}");
                $res = fetch_url("https://www.nicehash.com/api?method=orders.set.limit&id={$apiid}&key={$apikey}&algo={$i}&order={$order->id}&limit=0.05");
                debuglog($res);
            } else {
                if ($order->price > $maxprice && $nicehash->last_decrease + 10 * 60 < time()) {
                    debuglog("* decrease price {$algo}");
                    $res = fetch_url("https://www.nicehash.com/api?method=orders.set.price.decrease&id={$apiid}&key={$apikey}&algo={$i}&order={$order->id}");
                    debuglog($res);
                    $nicehash->last_decrease = time();
                } else {
                    if ($order->price < $minprice && $order->workers <= 0) {
                        debuglog("* increase price {$algo}");
                        $res = fetch_url("https://www.nicehash.com/api?method=orders.set.price&id={$apiid}&key={$apikey}&algo={$i}&order={$order->id}&price={$setprice}");
                        debuglog($res);
                    } else {
                        if ($order->price < $maxprice && $order->limit_speed == 0.05) {
                            debuglog("* increase speed {$algo}");
                            $res = fetch_url("https://www.nicehash.com/api?method=orders.set.limit&id={$apiid}&key={$apikey}&algo={$i}&order={$order->id}&limit=0");
                            debuglog($res);
                        }
                    }
                }
            }
        }
        $nicehash->save();
    }
}
示例#12
0
function updateRawCoin($marketname, $symbol, $name = 'unknown')
{
    if ($symbol == 'BTC') {
        return;
    }
    $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
    if (!$coin) {
        debuglog("new coin {$marketname} {$symbol} {$name}");
        $coin = new db_coins();
        $coin->txmessage = true;
        $coin->hassubmitblock = true;
        $coin->name = $name;
        $coin->symbol = $symbol;
        $coin->created = time();
        $coin->save();
        mail(YAAMP_ADMIN_EMAIL, "New coin {$symbol}", "new coin {$symbol} ({$name}) on {$marketname}");
        sleep(30);
    } else {
        if ($coin->name == 'unknown' && $name != 'unknown') {
            $coin->name = $name;
            $coin->save();
        }
    }
    $list = getdbolist('db_coins', "symbol=:symbol or symbol2=:symbol", array(':symbol' => $symbol));
    foreach ($list as $coin) {
        $market = getdbosql('db_markets', "coinid={$coin->id} and name='{$marketname}'");
        if (!$market) {
            $market = new db_markets();
            $market->coinid = $coin->id;
            $market->name = $marketname;
        }
        $market->deleted = false;
        $market->save();
    }
    /////////
    // 	if($coin->enable || !empty($coin->algo) || !empty($coin->errors) || $coin->name == 'unknown') return;
    // 	debuglog("http://www.cryptocoinrank.com/$coin->name");
    //  	$data = file_get_contents("http://www.cryptocoinrank.com/$coin->name");
    //  	if($data)
    //  	{
    // 	 	$b = preg_match('/Algo: <span class=\"d-gray\">(.*)<\/span>/', $data, $m);
    // 	 	if($b)
    // 	 	{
    // 	 		$coin->errors = trim($m[1]);
    // 			$coin->save();
    // 	 	}
    //  	}
}
示例#13
0
function doBleutradeTrading($quick = false)
{
    $flushall = rand(0, 4) == 0;
    if ($quick) {
        $flushall = false;
    }
    //	debuglog("-------------- dobleutradeTrading() flushall $flushall");
    $orders = bleutrade_api_query('market/getopenorders');
    if (!$orders) {
        return;
    }
    foreach ($orders->result as $order) {
        $e = explode('_', $order->Exchange);
        $symbol = $e[0];
        /// "Exchange" : "LTC_BTC",
        $pair = $order->Exchange;
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
        if (!$coin) {
            continue;
        }
        if ($coin->dontsell) {
            continue;
        }
        $ticker = bleutrade_api_query('public/getticker', "&market={$pair}");
        if (!$ticker || !$ticker->success || !isset($ticker->result[0])) {
            continue;
        }
        $ask = bitcoinvaluetoa($ticker->result[0]->Ask);
        $sellprice = bitcoinvaluetoa($order->Price);
        // flush orders not on the ask
        if ($ask + 5.0E-8 < $sellprice || $flushall) {
            //			debuglog("bleutrade cancel order $order->Exchange $sellprice -> $ask");
            bleutrade_api_query('market/cancel', "&orderid={$order->OrderId}");
            $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order->OrderId));
            if ($db_order) {
                $db_order->delete();
            }
            sleep(1);
        } else {
            $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order->OrderId));
            if ($db_order) {
                continue;
            }
            debuglog("bleutrade adding order {$coin->symbol}");
            //	$ticker = bleutrade_api_query('public/getticker', "&market=$pair");
            //	$sellprice = bitcoinvaluetoa($ticker->result->Ask);
            $db_order = new db_orders();
            $db_order->market = 'bleutrade';
            $db_order->coinid = $coin->id;
            $db_order->amount = $order->Quantity;
            $db_order->price = $sellprice;
            $db_order->ask = $ticker->result[0]->Ask;
            $db_order->bid = $ticker->result[0]->Bid;
            $db_order->uuid = $order->OrderId;
            $db_order->created = time();
            $db_order->save();
        }
    }
    // flush obsolete orders
    $list = getdbolist('db_orders', "market='bleutrade'");
    foreach ($list as $db_order) {
        $coin = getdbo('db_coins', $db_order->coinid);
        if (!$coin) {
            continue;
        }
        $found = false;
        foreach ($orders->result as $order) {
            if ($order->OrderId == $db_order->uuid) {
                $found = true;
                break;
            }
        }
        if (!$found) {
            debuglog("bleutrade deleting order {$coin->name} {$db_order->amount}");
            $db_order->delete();
        }
    }
    // 	if($flushall)
    // 	{
    //		debuglog("bleutrade flushall got here");
    // 		return;
    // 	}
    sleep(2);
    // add orders
    $balances = bleutrade_api_query('account/getbalances');
    //	debuglog($balances);
    if (!$balances || !isset($balances->result) || !$balances->success) {
        return;
    }
    $savebalance = getdbosql('db_balances', "name='bleutrade'");
    $savebalance->balance = 0;
    foreach ($balances->result as $balance) {
        if ($balance->Currency == 'BTC') {
            $savebalance->balance = $balance->Available;
            continue;
        }
        $amount = floatval($balance->Available);
        if (!$amount) {
            continue;
        }
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $balance->Currency));
        if (!$coin || $coin->dontsell) {
            continue;
        }
        $market = getdbosql('db_markets', "coinid={$coin->id} and name='bleutrade'");
        if ($market) {
            $market->lasttraded = time();
            $market->save();
        }
        if ($amount * $coin->price < 1.0E-5) {
            continue;
        }
        $pair = "{$balance->Currency}_BTC";
        $data = bleutrade_api_query('public/getorderbook', "&market={$pair}&type=BUY&depth=10");
        if (!$data) {
            continue;
        }
        //	if(!isset($data->result[0])) continue;
        for ($i = 0; $i < 5; $i++) {
            if (!isset($data->result->buy[$i])) {
                break;
            }
            $nextbuy = $data->result->buy[$i];
            if ($amount < $nextbuy->Quantity || $nextbuy->Quantity * $nextbuy->Rate < 1.0E-5) {
                break;
            }
            $sellprice = bitcoinvaluetoa($nextbuy->Rate);
            //			debuglog("bleutrade selling market $pair, $nextbuy->Quantity, $sellprice");
            $res = bleutrade_api_query('market/selllimit', "&market={$pair}&quantity={$nextbuy->Quantity}&rate={$sellprice}");
            if (!$res->success) {
                debuglog($res);
                break;
            }
            $amount -= $nextbuy->Quantity;
        }
        $ticker = bleutrade_api_query('public/getticker', "&market={$pair}");
        if (!$ticker || !$ticker->success || !isset($ticker->result[0])) {
            continue;
        }
        if ($coin->sellonbid) {
            $sellprice = bitcoinvaluetoa($ticker->result[0]->Bid);
        } else {
            $sellprice = bitcoinvaluetoa($ticker->result[0]->Ask);
        }
        if ($amount * $sellprice < 0.0005) {
            continue;
        }
        debuglog("bleutrade selling {$pair}, {$amount}, {$sellprice}");
        $res = bleutrade_api_query('market/selllimit', "&market={$pair}&quantity={$amount}&rate={$sellprice}");
        if (!$res || !$res->success || !isset($res->result)) {
            debuglog($res);
            continue;
        }
        $db_order = new db_orders();
        $db_order->market = 'bleutrade';
        $db_order->coinid = $coin->id;
        $db_order->amount = $amount;
        $db_order->price = $sellprice;
        $db_order->ask = $ticker->result[0]->Ask;
        $db_order->bid = $ticker->result[0]->Bid;
        $db_order->uuid = $res->result->orderid;
        $db_order->created = time();
        $db_order->save();
        sleep(1);
    }
    if ($savebalance->balance >= 0.2) {
        $btcaddr = YAAMP_BTCADDRESS;
        //'14LS7Uda6EZGXLtRrFEZ2kWmarrxobkyu9';
        $amount = $savebalance->balance;
        // - 0.0002;
        debuglog("bleutrade withdraw {$amount} to {$btcaddr}");
        sleep(1);
        $res = bleutrade_api_query('account/withdraw', "&currency=BTC&quantity={$amount}&address={$btcaddr}");
        debuglog($res);
        if ($res && $res->success) {
            $withdraw = new db_withdraws();
            $withdraw->market = 'bleutrade';
            $withdraw->address = $btcaddr;
            $withdraw->amount = $amount;
            $withdraw->time = time();
            $withdraw->uuid = $res->result->orderid;
            $withdraw->save();
            //	$savebalance->balance = 0;
        }
    }
    $savebalance->save();
    //	debuglog('-------------- dobleutradeTrading() done');
}
示例#14
0
function BackendUsersUpdate()
{
    $t1 = microtime(true);
    $list = getdbolist('db_accounts', "coinid is null or coinsymbol != ''");
    foreach ($list as $user) {
        //	debuglog("testing user $user->username, $user->coinsymbol");
        if (!empty($user->coinsymbol)) {
            $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $user->coinsymbol));
            $user->coinsymbol = '';
            if ($coin) {
                if ($user->coinid == $coin->id) {
                    $user->save();
                    continue;
                }
                $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
                $b = $remote->validateaddress($user->username);
                if ($b && isset($b['isvalid']) && $b['isvalid']) {
                    if ($user->balance > 0) {
                        $coinref = getdbo('db_coins', $user->coinid);
                        if (!$coinref) {
                            $coinref = getdbosql('db_coins', "symbol='BTC'");
                        }
                        $user->balance = $user->balance * $coinref->price / $coin->price;
                    }
                    $user->coinid = $coin->id;
                    $user->save();
                    debuglog("{$user->username} set to {$coin->symbol}, balance {$user->balance}");
                    continue;
                }
            }
        }
        $user->coinid = 0;
        $coins = getdbolist('db_coins', "enable order by difficulty desc");
        foreach ($coins as $coin) {
            $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
            $b = $remote->validateaddress($user->username);
            if (!$b || !isset($b['isvalid']) || !$b['isvalid']) {
                continue;
            }
            $user->balance = 0;
            $user->coinid = $coin->id;
            debuglog("{$user->username} set to {$coin->symbol}, balance {$user->balance}");
            break;
        }
        $user->save();
    }
    //	$delay=time()-60*60;
    // 	$list = dborun("update coins set dontsell=1 where id in (select coinid from accounts where balance>0 or last_login>$delay group by coinid)");
    // 	$list = dborun("update coins set dontsell=0 where id not in (select coinid from accounts where balance>0 or last_login>$delay group by coinid)");
    // 	$list = getdbolist('db_workers', "dns is null");
    // 	foreach($list as $worker)
    // 	{
    // 		$worker->dns = $worker->ip;
    // 		$res = system("resolveip $worker->ip");
    // 		if($res)
    // 		{
    // 			$a = explode(' ', $res);
    // 			if($a && isset($a[5]))
    // 				$worker->dns = $a[5];
    // 		}
    // 		$worker->save();
    // 	}
    $d1 = microtime(true) - $t1;
    controller()->memcache->add_monitoring_function(__METHOD__, $d1);
}
示例#15
0
function showPageHeader()
{
    echo "<div class='tabmenu-out'>";
    echo "<div class='tabmenu-inner'>";
    //	echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href='/'>Yet Another Anonymous Mining Pool</a>";
    echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    $action = controller()->action->id;
    $wallet = user()->getState('yaamp-wallet');
    $ad = isset($_GET['address']);
    showItemHeader(controller()->id == 'site' && $action == 'index' && !$ad, '/', 'Home');
    showItemHeader($action == 'mining', '/site/mining', 'Pool');
    showItemHeader(controller()->id == 'site' && ($action == 'index' || $action == 'wallet') && $ad, "/?address={$wallet}", 'Wallet');
    showItemHeader(controller()->id == 'stats', '/stats', 'Graphs');
    showItemHeader($action == 'miners', '/site/miners', 'Miners');
    showItemHeader(controller()->id == 'renting', '/renting', 'Rental');
    if (controller()->admin) {
        //		debuglog("admin {$_SERVER['REMOTE_ADDR']}");
        //		$algo = user()->getState('yaamp-algo');
        showItemHeader(controller()->id == 'explorer', '/explorer', 'Explorers');
        //		showItemHeader(controller()->id=='coin', '/coin', 'Coins');
        showItemHeader($action == 'common', '/site/common', 'Admin');
        showItemHeader(controller()->id == 'site' && $action == 'admin', "/site/admin", 'List');
        //		showItemHeader(controller()->id=='renting' && $action=='admin', '/renting/admin', 'Jobs');
        //		showItemHeader(controller()->id=='trading', '/trading', 'Trading');
        //		showItemHeader(controller()->id=='nicehash', '/nicehash', 'Nicehash');
    }
    echo "<span style='float: right;'>";
    $mining = getdbosql('db_mining');
    $nextpayment = date('H:i', $mining->last_payout + YAAMP_PAYMENTS_FREQ);
    echo "<span style='font-size: .8em;'>Next Payout: {$nextpayment} EUST</span>";
    echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&copy; yiimp.ccminer.org</span>";
    echo "</div>";
    echo "</div>";
}
示例#16
0
 public function actionRental_stop()
 {
     $key = getparam('key');
     $renter = getdbosql('db_renters', "apikey=:apikey", array(':apikey' => $key));
     if (!$renter) {
         return;
     }
     $jobid = getparam('jobid');
     $job = getdbo('db_jobs', $jobid);
     if ($job->renterid != $renter->id) {
         return;
     }
     $job->ready = false;
     $job->time = time();
     $job->save();
 }
示例#17
0
function doCryptsyTrading($quick = false)
{
    $flushall = rand(0, 4) == 0;
    if ($quick) {
        $flushall = false;
    }
    //	debuglog("-------------- doCryptsyTrading() $flushall");
    $orders = cryptsy_api_query('allmyorders');
    if (!$orders) {
        return;
    }
    foreach ($orders['return'] as $order) {
        if (!isset($order['marketid'])) {
            continue;
        }
        if (!isset($order['orderid'])) {
            continue;
        }
        $market = getdbosql('db_markets', "marketid=:marketid", array(':marketid' => $order['marketid']));
        if (!$market) {
            continue;
        }
        $coin = getdbo('db_coins', $market->coinid);
        if (!$coin) {
            continue;
        }
        $symbol = $coin->symbol;
        $ticker = getCryptsyTicker($market->marketid);
        if (!$ticker || !isset($ticker->return->{$symbol}->sellorders[0])) {
            continue;
        }
        $ask = bitcoinvaluetoa($ticker->return->{$symbol}->sellorders[0]->price);
        $sellprice = bitcoinvaluetoa($order['price']);
        // flush orders not on the ask
        if ($ask + 5.0E-8 < $sellprice || $flushall) {
            // 			debuglog("cryptsy cancel order for $coin->symbol ($ask != $sellprice)");
            cryptsy_api_query('cancelorder', array('orderid' => $order['orderid']));
            $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order['orderid']));
            if ($db_order) {
                $db_order->delete();
            }
            sleep(1);
        } else {
            $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order['orderid']));
            if ($db_order) {
                continue;
            }
            debuglog("adding order {$coin->symbol}");
            $db_order = new db_orders();
            $db_order->market = 'cryptsy';
            $db_order->coinid = $coin->id;
            $db_order->amount = $order['quantity'];
            $db_order->price = $sellprice;
            $db_order->ask = $ticker->return->{$symbol}->sellorders[0]->price;
            $db_order->bid = isset($ticker->return->{$symbol}->buyorders) ? $ticker->return->{$symbol}->buyorders[0]->price : 0;
            $db_order->uuid = $order['orderid'];
            $db_order->created = time();
            $db_order->save();
        }
    }
    $list = getdbolist('db_orders', "market='cryptsy'");
    foreach ($list as $db_order) {
        $coin = getdbo('db_coins', $db_order->coinid);
        $found = false;
        foreach ($orders['return'] as $order) {
            if (!isset($order['orderid'])) {
                continue;
            }
            if ($order['orderid'] == $db_order->uuid) {
                $found = true;
                break;
            }
        }
        if (!$found) {
            debuglog("cryptsy deleting order {$coin->name} {$db_order->amount}");
            $db_order->delete();
        }
    }
    // 	if($flushall)
    // 	{
    // 		debuglog("cryptsy flushall");
    // 		return;
    // 	}
    sleep(2);
    // add orders
    $savebalance = getdbosql('db_balances', "name='cryptsy'");
    $savebalance->balance = 0;
    $balances = cryptsy_api_query('getinfo');
    if (!$balances) {
        return;
    }
    if (!isset($balances['return'])) {
        debuglog($balances);
        return;
    }
    foreach ($balances['return']['balances_available'] as $symbol => $balance) {
        if ($symbol == 'Points') {
            continue;
        }
        if ($symbol == 'BTC') {
            $savebalance->balance = floatval($balance);
            continue;
        }
        $balance = floatval($balance);
        if (!$balance) {
            continue;
        }
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
        if (!$coin || $coin->dontsell) {
            continue;
        }
        $market = getdbosql('db_markets', "coinid={$coin->id} and name='cryptsy'");
        if (!$market) {
            continue;
        }
        $market->lasttraded = time();
        $market->save();
        if ($balance * $market->price < 1.0E-5) {
            continue;
        }
        $ticker = getCryptsyTicker($market->marketid);
        if (!$ticker || !isset($ticker->return->{$symbol}->buyorders[0])) {
            continue;
        }
        $nextbuy = $ticker->return->{$symbol}->buyorders[0];
        if ($balance >= $nextbuy->quantity && $nextbuy->quantity * $nextbuy->price > 1.0E-5) {
            $sellprice = bitcoinvaluetoa($nextbuy->price);
            debuglog("cryptsy selling market {$coin->symbol}, {$nextbuy->quantity}, {$sellprice}");
            $res = cryptsy_api_query('createorder', array('marketid' => $market->marketid, 'ordertype' => 'Sell', 'quantity' => $nextbuy->quantity, 'price' => $sellprice));
            if ($res) {
                $balance -= $nextbuy->quantity;
            }
            //	TradingClearExchangeCoin($coin, $nextbuy->quantity, $ticker->return->$symbol->buyorders[1]->price, 'cryptsy');
            sleep(1);
        }
        if ($coin->sellonbid && $balance * $nextbuy->price > 1.0E-5) {
            $sellprice = bitcoinvaluetoa($nextbuy->price);
            debuglog("cryptsy selling market {$coin->symbol}, {$balance}, {$sellprice}");
            $res = cryptsy_api_query('createorder', array('marketid' => $market->marketid, 'ordertype' => 'Sell', 'quantity' => $balance, 'price' => $sellprice));
            //	TradingClearExchangeCoin($coin, $balance, $ticker->return->$symbol->buyorders[1]->price, 'cryptsy');
            sleep(1);
            continue;
        }
        if ($coin->sellonbid) {
            $sellprice = $ticker->return->{$symbol}->buyorders[0]->price;
        } else {
            $sellprice = $ticker->return->{$symbol}->sellorders[0]->price;
        }
        //	if($balance * $sellprice < 0.0001) continue;
        //		debuglog("cryptsy selling $coin->symbol, $sellprice, $balance");
        $res = cryptsy_api_query('createorder', array('marketid' => $market->marketid, 'ordertype' => 'Sell', 'quantity' => $balance, 'price' => $sellprice));
        if (!$res || !isset($res['orderid'])) {
            continue;
        }
        $db_order = new db_orders();
        $db_order->market = 'cryptsy';
        $db_order->coinid = $coin->id;
        $db_order->amount = $balance;
        $db_order->price = $sellprice;
        $db_order->ask = $ticker->return->{$symbol}->sellorders[0]->price;
        $db_order->bid = $ticker->return->{$symbol}->buyorders[0]->price;
        $db_order->uuid = $res['orderid'];
        $db_order->created = time();
        $db_order->save();
    }
    if ($savebalance->balance >= 0.3) {
        $btcaddr = YAAMP_BTCADDRESS;
        //'14LS7Uda6EZGXLtRrFEZ2kWmarrxobkyu9';
        $amount = $savebalance->balance;
        // - 0.001;
        debuglog("cryptsy withdraw {$amount} to {$btcaddr}");
        sleep(1);
        $res = cryptsy_api_query('makewithdrawal', array('address' => $btcaddr, 'amount' => $amount));
        debuglog($res);
        if ($res && $res['success']) {
            $withdraw = new db_withdraws();
            $withdraw->market = 'cryptsy';
            $withdraw->address = $btcaddr;
            $withdraw->amount = $amount;
            $withdraw->time = time();
            //	$withdraw->uuid = $res->result->uuid;
            $withdraw->save();
            //	$savebalance->balance = 0;
        }
    }
    $savebalance->save();
    //	debuglog('-------------- doCryptsyTrading() done');
}
示例#18
0
 public function actionRun()
 {
     //		debuglog(__METHOD__);
     set_time_limit(0);
     //		BackendRunCoinActions();
     $state = memcache_get($this->memcache->memcache, 'cronjob_main_state');
     if (!$state) {
         $state = 0;
     }
     memcache_set($this->memcache->memcache, 'cronjob_main_state', $state + 1);
     memcache_set($this->memcache->memcache, "cronjob_main_state_{$state}", 1);
     switch ($state) {
         case 0:
             updateRawcoins();
             $a = json_decode(fetch_url("https://www.bitstamp.net/api/ticker/"));
             if ($a && isset($a->last)) {
                 $mining = getdbosql('db_mining');
                 $mining->usdbtc = $a->last;
                 $mining->save();
             }
             break;
         case 1:
             if (!YAAMP_PRODUCTION) {
                 break;
             }
             doBittrexTrading();
             doCryptsyTrading();
             doBleutradeTrading();
             doPoloniexTrading();
             doYobitTrading();
             doCCexTrading();
             break;
         case 2:
             BackendPricesUpdate();
             break;
         case 3:
             BackendBlocksUpdate();
             break;
         case 4:
             TradingSellCoins();
             break;
         case 5:
             BackendBlockFind2();
             break;
         default:
             memcache_set($this->memcache->memcache, 'cronjob_main_state', 0);
             BackendQuickClean();
             //	sleep(120);
             $t = memcache_get($this->memcache->memcache, "cronjob_main_start_time");
             $n = time();
             memcache_set($this->memcache->memcache, "cronjob_main_time", $n - $t);
             memcache_set($this->memcache->memcache, "cronjob_main_start_time", $n);
     }
     debuglog(__METHOD__ . " {$state}");
     memcache_set($this->memcache->memcache, "cronjob_main_state_{$state}", 0);
     memcache_set($this->memcache->memcache, "cronjob_main_time_start", time());
     if (!YAAMP_PRODUCTION) {
         return;
     }
     ///////////////////////////////////////////////////////////////////
     $mining = getdbosql('db_mining');
     if ($mining->last_payout + YAAMP_PAYMENTS_FREQ > time()) {
         return;
     }
     debuglog("--------------------------------------------------------");
     $mining->last_payout = time();
     $mining->save();
     memcache_set($this->memcache->memcache, 'apache_locked', true);
     system("service nginx stop");
     sleep(10);
     BackendDoBackup();
     memcache_set($this->memcache->memcache, 'apache_locked', false);
     BackendPayments();
     BackendCleanDatabase();
     //	BackendOptimizeTables();
     debuglog('payments sequence done');
 }
示例#19
0
function BackendStatsUpdate2()
{
    //	debuglog('----------------------------------');
    //	debuglog(__FUNCTION__);
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    $step = 15;
    $t = floor(time() / $step / 60) * $step * 60;
    $list = dbolist("select userid, algo from shares where time>{$t} group by userid, algo");
    foreach ($list as $item) {
        $stats = getdbosql('db_hashuser', "time={$t} and algo=:algo and userid=:userid", array(':algo' => $item['algo'], ':userid' => $item['userid']));
        if (!$stats) {
            $stats = new db_hashuser();
            $stats->userid = $item['userid'];
            $stats->time = $t;
            $stats->hashrate = dboscalar("select hashrate from hashuser where algo=:algo and userid=:userid order by time desc limit 1", array(':algo' => $item['algo'], ':userid' => $item['userid']));
            $stats->hashrate_bad = 0;
            $stats->algo = $item['algo'];
        }
        $percent = 20;
        $user_rate = yaamp_user_rate($item['userid'], $item['algo']);
        $stats->hashrate = round(($stats->hashrate * (100 - $percent) + $user_rate * $percent) / 100);
        if ($stats->hashrate < 1000) {
            $stats->hashrate = 0;
        }
        $user_rate_bad = yaamp_user_rate_bad($item['userid'], $item['algo']);
        $stats->hashrate_bad = round(($stats->hashrate_bad * (100 - $percent) + $user_rate_bad * $percent) / 100);
        if ($stats->hashrate_bad < 1000) {
            $stats->hashrate_bad = 0;
        }
        $stats->save();
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    $step = 15;
    $t = floor(time() / $step / 60) * $step * 60;
    $list = dbolist("select distinct jobid from jobsubmits where time>{$t}");
    foreach ($list as $item) {
        $jobid = $item['jobid'];
        $stats = getdbosql('db_hashrenter', "time={$t} and jobid={$jobid}");
        if (!$stats) {
            $stats = new db_hashrenter();
            //	$stats->renterid = ;
            $stats->jobid = $item['jobid'];
            $stats->time = $t;
            $stats->hashrate = dboscalar("select hashrate from hashrenter where jobid=:jobid order by time desc limit 1", array(':jobid' => $jobid));
            $stats->hashrate_bad = 0;
            //dboscalar("select hashrate_bad from hashrenter where jobid=$jobid order by time desc limit 1");
        }
        $percent = 20;
        $job_rate = yaamp_job_rate($jobid);
        $stats->hashrate = round(($stats->hashrate * (100 - $percent) + $job_rate * $percent) / 100);
        if ($stats->hashrate < 1000) {
            $stats->hashrate = 0;
        }
        $job_rate_bad = yaamp_job_rate_bad($jobid);
        $stats->hashrate_bad = round(($stats->hashrate_bad * (100 - $percent) + $job_rate_bad * $percent) / 100);
        if ($stats->hashrate_bad < 1000) {
            $stats->hashrate_bad = 0;
        }
        $stats->save();
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    $t = floor(time() / $step / 60) * $step * 60;
    $d = time() - 24 * 60 * 60;
    $list = getdbolist('db_accounts', "balance>0 or last_login>{$d}");
    foreach ($list as $user) {
        $stats = getdbosql('db_balanceuser', "time={$t} and userid={$user->id}");
        if (!$stats) {
            $stats = new db_balanceuser();
            $stats->userid = $user->id;
            $stats->time = $t;
        }
        // 		$refcoin = getdbo('db_coins', $user->coinid);
        // 		if(!$refcoin) $refcoin = getdbosql('db_coins', "symbol='BTC'");
        // 		if(!$refcoin->price || !$refcoin->price2) continue;
        // 		$pending1 = dboscalar("select sum(amount*price) from earnings where coinid=$refcoin->id and status!=2 and userid=$user->id");
        // 		$pending2 = dboscalar("select sum(amount*price) from earnings where coinid!=$refcoin->id and status!=2 and userid=$user->id");
        $stats->pending = yaamp_convert_earnings_user($user, "status!=2");
        $stats->pending = bitcoinvaluetoa($stats->pending);
        $stats->balance = $user->balance;
        $stats->save();
        $id = dboscalar("select id from earnings where userid={$user->id} order by id desc limit 100, 1");
        if ($id) {
            dborun("delete from earnings where status=2 and userid={$user->id} and id<{$id}");
        }
    }
}
示例#20
0
function doCCexTrading($quick = false)
{
    $flushall = rand(0, 4) == 0;
    if ($quick) {
        $flushall = false;
    }
    //	debuglog("-------------- doCCexTrading() $flushall");
    $ccex = new CcexAPI();
    // upgrade orders
    $coins = getdbolist('db_coins', "enable and id in (select distinct coinid from markets where name='c-cex')");
    foreach ($coins as $coin) {
        if ($coin->dontsell) {
            continue;
        }
        $market2 = getdbosql('db_markets', "coinid={$coin->id} and (name='bittrex' or name='cryptsy')");
        if ($market2) {
            continue;
        }
        $pair = strtolower($coin->symbol) . '-btc';
        //		debuglog("c-cex list order for $pair");
        sleep(5);
        $orders = $ccex->getOrders($pair, 1);
        if (!$orders || isset($orders['error'])) {
            continue;
        }
        foreach ($orders['return'] as $uuid => $order) {
            $ticker = $ccex->getTickerInfo($pair);
            if (!$ticker) {
                continue;
            }
            if ($order['price'] > $ticker['sell'] + 5.0E-8 || $flushall) {
                //				debuglog("c-cex cancel order for $pair $uuid");
                sleep(5);
                $ccex->cancelOrder($uuid);
                $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $uuid));
                if ($db_order) {
                    $db_order->delete();
                }
                sleep(1);
            } else {
                $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $uuid));
                if ($db_order) {
                    continue;
                }
                debuglog("c-cex adding order {$coin->symbol}");
                $db_order = new db_orders();
                $db_order->market = 'c-cex';
                $db_order->coinid = $coin->id;
                $db_order->amount = $order['amount'];
                $db_order->price = $order['price'];
                $db_order->ask = $ticker['sell'];
                $db_order->bid = $ticker['buy'];
                $db_order->uuid = $uuid;
                $db_order->created = time();
                $db_order->save();
            }
        }
        $list = getdbolist('db_orders', "coinid={$coin->id} and market='c-cex'");
        foreach ($list as $db_order) {
            $found = false;
            foreach ($orders['return'] as $uuid => $order) {
                if ($uuid == $db_order->uuid) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                debuglog("c-cex deleting order {$coin->name} {$db_order->amount}");
                $db_order->delete();
            }
        }
    }
    sleep(2);
    //////////////////////////////////////////////////////////////////////////////////////////////////
    $savebalance = getdbosql('db_balances', "name='c-cex'");
    $savebalance->balance = 0;
    //	debuglog("c-cex getbalance");
    sleep(5);
    $balances = $ccex->getBalance();
    if (!$balances || !isset($balances['return'])) {
        return;
    }
    foreach ($balances['return'] as $balance) {
        foreach ($balance as $symbol => $amount) {
            if (!$amount) {
                continue;
            }
            if ($symbol == 'btc') {
                $savebalance->balance = $amount;
                continue;
            }
            $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
            if (!$coin || $coin->dontsell) {
                continue;
            }
            $market = getdbosql('db_markets', "coinid={$coin->id} and name='c-cex'");
            if ($market) {
                $market->lasttraded = time();
                $market->save();
            }
            if ($amount * $coin->price < 1.0E-5) {
                continue;
            }
            $pair = "{$symbol}-btc";
            ////////////////////////
            $maxprice = 0;
            $maxamount = 0;
            //		debuglog("c-cex list order for $pair all");
            sleep(5);
            $orders = $ccex->getOrders($pair, 0);
            foreach ($orders['return'] as $order) {
                if ($order['type'] == 'sell') {
                    continue;
                }
                if ($order['price'] > $maxprice) {
                    $maxprice = $order['price'];
                    $maxamount = $order['amount'];
                }
            }
            //	debuglog("maxbuy for $pair $maxamount $maxprice");
            if ($amount >= $maxamount && $maxamount * $maxprice > 1.0E-5) {
                $sellprice = bitcoinvaluetoa($maxprice);
                debuglog("c-cex selling market {$pair}, {$maxamount}, {$sellprice}");
                sleep(5);
                $res = $ccex->makeOrder('sell', $pair, $maxamount, $sellprice);
                if (!$res || !isset($res['return'])) {
                    debuglog($res);
                } else {
                    $amount -= $maxamount;
                }
                sleep(1);
            }
            ///
            $ticker = $ccex->getTickerInfo($pair);
            if (!$ticker) {
                continue;
            }
            $sellprice = bitcoinvaluetoa($ticker['sell']);
            //		debuglog("c-cex selling $pair, $amount, $sellprice");
            sleep(5);
            $res = $ccex->makeOrder('sell', $pair, $amount, $sellprice);
            if (!$res || !isset($res['return'])) {
                continue;
            }
            $db_order = new db_orders();
            $db_order->market = 'c-cex';
            $db_order->coinid = $coin->id;
            $db_order->amount = $amount;
            $db_order->price = $sellprice;
            $db_order->ask = $ticker['sell'];
            $db_order->bid = $ticker['buy'];
            $db_order->uuid = $res['return'];
            $db_order->created = time();
            $db_order->save();
        }
    }
    $savebalance->save();
    //	debuglog('-------------- doCCexTrading() done');
}
示例#21
0
$algo = user()->getState('yaamp-algo');
$total_rate = Itoa2(yaamp_pool_rate());
$list = getdbolist('db_coins', "enable and algo=:algo order by index_avg desc", array(':algo' => $algo));
$count = count($list);
$worker = getdbocount('db_workers', "algo=:algo", array(':algo' => $algo));
$services = getdbolist('db_services', "algo=:algo order by price desc", array(':algo' => $algo));
////////////
$table = array('scrypt' => 0, 'sha256' => 1, 'scryptn' => 2, 'x11' => 3, 'x13' => 4, 'x15' => 6, 'nist5' => 7, 'neoscrypt' => 8, 'lyra2' => 9);
$res = fetch_url("https://www.nicehash.com/api?method=orders.get&algo={$table[$algo]}");
if (!$res) {
    return;
}
$a = json_decode($res);
$niceorders = $a->result->orders;
$allorders = array();
$nicehash = getdbosql('db_nicehash', "algo=:algo and orderid!=0", array(':algo' => $algo));
if ($nicehash) {
    $index = $nicehash->price * 1000 + 1;
    $allorders[$index] = array();
    $allorders[$index]['speed'] = $nicehash->accepted;
    $allorders[$index]['price'] = $nicehash->price;
    $allorders[$index]['workers'] = $nicehash->workers;
    $allorders[$index]['btc'] = $nicehash->btc;
    $allorders[$index]['limit'] = $nicehash->speed;
    $allorders[$index]['me'] = true;
}
foreach ($niceorders as $order) {
    if (!$order->alive) {
        continue;
    }
    if (!$order->workers) {
示例#22
0
function doBittrexTrading($quick = false)
{
    $flushall = rand(0, 4) == 0;
    if ($quick) {
        $flushall = false;
    }
    //	debuglog("-------------- doBittrexTrading() flushall $flushall");
    $orders = bittrex_api_query('market/getopenorders');
    if (!$orders || !$orders->success) {
        return;
    }
    foreach ($orders->result as $order) {
        $symbol = substr($order->Exchange, 4);
        $pair = $order->Exchange;
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
        if (!$coin) {
            continue;
        }
        if ($coin->dontsell) {
            continue;
        }
        $ticker = bittrex_api_query('public/getticker', "&market={$order->Exchange}");
        if (!$ticker || !$ticker->success || !$ticker->result) {
            continue;
        }
        $ask = bitcoinvaluetoa($ticker->result->Ask);
        $sellprice = bitcoinvaluetoa($order->Limit);
        // flush orders not on the ask
        if ($ask + 5.0E-8 < $sellprice || $flushall) {
            // 			debuglog("bittrex cancel order $order->Exchange $sellprice -> $ask");
            bittrex_api_query('market/cancel', "&uuid={$order->OrderUuid}");
            $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order->OrderUuid));
            if ($db_order) {
                $db_order->delete();
            }
            sleep(1);
        } else {
            $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $order->OrderUuid));
            if ($db_order) {
                continue;
            }
            debuglog("adding order {$coin->symbol}");
            //	$ticker = bittrex_api_query('public/getticker', "&market=$pair");
            //	$sellprice = bitcoinvaluetoa($ticker->result->Ask);
            $db_order = new db_orders();
            $db_order->market = 'bittrex';
            $db_order->coinid = $coin->id;
            $db_order->amount = $order->Quantity;
            $db_order->price = $sellprice;
            $db_order->ask = $ticker->result->Ask;
            $db_order->bid = $ticker->result->Bid;
            $db_order->uuid = $order->OrderUuid;
            $db_order->created = time();
            $db_order->save();
        }
    }
    // flush obsolete orders
    $list = getdbolist('db_orders', "market='bittrex'");
    foreach ($list as $db_order) {
        $coin = getdbo('db_coins', $db_order->coinid);
        if (!$coin) {
            continue;
        }
        $found = false;
        foreach ($orders->result as $order) {
            if ($order->OrderUuid == $db_order->uuid) {
                $found = true;
                break;
            }
        }
        if (!$found) {
            debuglog("bittrex deleting order {$coin->name} {$db_order->amount}");
            $db_order->delete();
        }
    }
    // 	if($flushall)
    // 	{
    // 		debuglog("bittrex flushall");
    // 		return;
    // 	}
    sleep(2);
    // add orders
    $balances = bittrex_api_query('account/getbalances');
    if (!$balances || !isset($balances->result) || !$balances->success) {
        return;
    }
    $savebalance = getdbosql('db_balances', "name='bittrex'");
    $savebalance->balance = 0;
    foreach ($balances->result as $balance) {
        if ($balance->Currency == 'BTC') {
            $savebalance->balance = $balance->Available;
            continue;
        }
        $amount = floatval($balance->Available);
        if (!$amount) {
            continue;
        }
        //	debuglog($balance->Currency);
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $balance->Currency));
        if (!$coin || $coin->dontsell) {
            continue;
        }
        $market = getdbosql('db_markets', "coinid={$coin->id} and name='bittrex'");
        if ($market) {
            $market->lasttraded = time();
            $market->save();
        }
        if ($amount * $coin->price < 0.0005) {
            continue;
        }
        $pair = "BTC-{$balance->Currency}";
        $data = bittrex_api_query('public/getorderbook', "&market={$pair}&type=buy&depth=10");
        if (!$data || !$data->success) {
            continue;
        }
        for ($i = 0; $i < 5 && $amount >= 0; $i++) {
            if (!isset($data->result->buy[$i])) {
                break;
            }
            $nextbuy = $data->result->buy[$i];
            if ($amount * 1.1 < $nextbuy->Quantity) {
                break;
            }
            $sellprice = bitcoinvaluetoa($nextbuy->Rate);
            $sellamount = min($amount, $nextbuy->Quantity);
            if ($sellamount * $sellprice < 0.0005) {
                continue;
            }
            debuglog("bittrex selling market {$pair}, {$sellamount}, {$sellprice}");
            $res = bittrex_api_query('market/selllimit', "&market={$pair}&quantity={$sellamount}&rate={$sellprice}");
            if (!$res->success) {
                debuglog($res);
                break;
            }
            $amount -= $sellamount;
        }
        if ($amount <= 0) {
            continue;
        }
        $ticker = bittrex_api_query('public/getticker', "&market={$pair}");
        if (!$ticker || !$ticker->success || !$ticker->result) {
            continue;
        }
        if ($coin->sellonbid) {
            $sellprice = bitcoinvaluetoa($ticker->result->Bid);
        } else {
            $sellprice = bitcoinvaluetoa($ticker->result->Ask);
        }
        if ($amount * $sellprice < 0.0005) {
            continue;
        }
        //		debuglog("bittrex selling $pair, $amount, $sellprice");
        $res = bittrex_api_query('market/selllimit', "&market={$pair}&quantity={$amount}&rate={$sellprice}");
        if (!$res || !$res->success) {
            debuglog($res);
            continue;
        }
        $db_order = new db_orders();
        $db_order->market = 'bittrex';
        $db_order->coinid = $coin->id;
        $db_order->amount = $amount;
        $db_order->price = $sellprice;
        $db_order->ask = $ticker->result->Ask;
        $db_order->bid = $ticker->result->Bid;
        $db_order->uuid = $res->result->uuid;
        $db_order->created = time();
        $db_order->save();
        sleep(1);
    }
    if ($savebalance->balance >= 0.3) {
        $amount = $savebalance->balance;
        // - 0.0002;
        debuglog("bittrex withdraw {$amount} to 14LS7Uda6EZGXLtRrFEZ2kWmarrxobkyu9");
        sleep(1);
        $res = bittrex_api_query('account/withdraw', "&currency=BTC&quantity={$amount}&address=14LS7Uda6EZGXLtRrFEZ2kWmarrxobkyu9");
        debuglog($res);
        if ($res && $res->success) {
            $withdraw = new db_withdraws();
            $withdraw->market = 'bittrex';
            $withdraw->address = '14LS7Uda6EZGXLtRrFEZ2kWmarrxobkyu9';
            $withdraw->amount = $amount;
            $withdraw->time = time();
            $withdraw->uuid = $res->result->uuid;
            $withdraw->save();
            //	$savebalance->balance = 0;
        }
    }
    $savebalance->save();
    //	debuglog('-------------- doBittrexTrading() done');
}
示例#23
0
    echo "<div class='main-left-inner'>";
}
$mining = getdbosql('db_mining');
$defaultalgo = user()->getState('yaamp-algo');
$show_details = getparam('showdetails');
$user = getuserparam(getparam('address'));
if (!$user) {
    return;
}
WriteBoxHeader("Wallet: {$user->username}");
$refcoin = getdbo('db_coins', $user->coinid);
if (!$refcoin) {
    if ($user->coinid != null) {
        echo "<div style='color: red; padding: 10px; '>This wallet address is not valid. \r\n\t\t\tYou will not receive payments using this address.</div>";
    }
    $refcoin = getdbosql('db_coins', "symbol='BTC'");
}
echo "<table class='dataGrid2'>";
echo "<thead>";
echo "<tr>";
echo "<th></th>";
echo "<th>Name</th>";
echo "<th align=right>Immature</th>";
echo "<th align=right>Confirmed</th>";
echo "<th align=right>Total</th>";
echo "<th align=right>Value*</th>";
echo "</tr>";
echo "</thead>";
$total_pending = 0;
if ($show_details) {
    $t1 = microtime(true);
示例#24
0
 protected function loadBalances()
 {
     $balancetab = array();
     $balances = cryptsy_api_query('getinfo');
     if (!$balances) {
         return;
     }
     if (!isset($balances['return'])) {
         debuglog($balances);
         return $balancetab;
     }
     foreach ($balances['return']['balances_available'] as $symbol => $balance) {
         $balance = floatval($balance);
         if ($symbol == 'Points') {
             continue;
         }
         if ($symbol == 'BTC') {
             $this->balance_btc = floatval($balance);
             continue;
         }
         if ($symbol == 'LTC') {
             $this->balance_ltc = floatval($balance);
             continue;
         }
         if (!$balance) {
             continue;
         }
         $object = new object();
         $object->balance = $balance;
         $object->coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
         if (!$object->coin) {
             continue;
         }
         $balancetab[] = $object;
     }
     return $balancetab;
 }
示例#25
0
function MonitorBTC()
{
    //	debuglog(__FUNCTION__);
    $coin = getdbosql('db_coins', "symbol='BTC'");
    if (!$coin) {
        return;
    }
    $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
    if (!$remote) {
        return;
    }
    $mostrecent = 0;
    if ($coin->lastblock == null) {
        $coin->lastblock = '';
    }
    $list = $remote->listsinceblock($coin->lastblock);
    if (!$list) {
        return;
    }
    $coin->lastblock = $list['lastblock'];
    $coin->save();
    foreach ($list['transactions'] as $transaction) {
        if (!isset($transaction['blockhash'])) {
            continue;
        }
        if ($transaction['confirmations'] == 0) {
            continue;
        }
        if ($transaction['category'] != 'send') {
            continue;
        }
        if ($transaction['fee'] != -0.0001) {
            continue;
        }
        debuglog(__FUNCTION__);
        debuglog($transaction);
        $txurl = "https://blockchain.info/tx/{$transaction['txid']}";
        $b = mail(YAAMP_ADMIN_EMAIL, "withdraw {$transaction['amount']}", "<a href='{$txurl}'>{$transaction['address']}</a>");
        if (!$b) {
            debuglog('error sending email');
        }
    }
}
示例#26
0
    return;
}
$this->pageTitle = "{$renter->address} | yiimp";
echo "<div class='main-left-box'>";
echo "<div class='main-left-title'>Transactions from {$renter->address}</div>";
echo "<div class='main-left-inner'>";
echo "<table class='dataGrid2'>";
echo "<thead class=''>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Amount</th>";
echo "<th>Confirmations</th>";
echo "<th>Tx</th>";
echo "</tr>";
echo "</thead><tbody>";
$btc = getdbosql('db_coins', "symbol='BTC'");
if (!$btc) {
    return;
}
$remote = new Bitcoin($btc->rpcuser, $btc->rpcpasswd, $btc->rpchost, $btc->rpcport);
$ts = $remote->listtransactions(yaamp_renter_account($renter), 10);
$res_array = array();
foreach ($ts as $val) {
    $t = $val['time'];
    if ($t < $renter->created) {
        continue;
    }
    $res_array[$t] = $val;
}
krsort($res_array);
$total = 0;
示例#27
0
<?php

$mining = getdbosql('db_mining');
$algo = user()->getState('yaamp-algo');
if ($algo == 'all') {
    return;
}
echo "<div class='main-left-box'>";
echo "<div class='main-left-title'>Pool Stats ({$algo})</div>";
echo "<div class='main-left-inner'>";
echo "<table class='dataGrid2'>";
echo "<thead>";
echo "<tr>";
echo "<th></th>";
echo "<th>Name</th>";
echo "<th align=right>Last Hour</th>";
echo "<th align=right>Last 24 Hours</th>";
echo "<th align=right>Last 7 Days</th>";
echo "<th align=right>Last 30 Days</th>";
echo "</tr>";
echo "</thead>";
$t1 = time() - 60 * 60;
$t2 = time() - 24 * 60 * 60;
$t3 = time() - 7 * 24 * 60 * 60;
$t4 = time() - 30 * 24 * 60 * 60;
$total1 = 0;
$total2 = 0;
$total3 = 0;
$total4 = 0;
$algo = user()->getState('yaamp-algo');
$list = dbolist("SELECT coin_id FROM blocks where category!='orphan' and time>{$t4} and coin_id in (select id from coins where algo=:algo) group by coin_id order by id desc", array(':algo' => $algo));
示例#28
0
function doYobitTrading($quick = false)
{
    $flushall = rand(0, 4) == 0;
    if ($quick) {
        $flushall = false;
    }
    $coins = getdbolist('db_coins', "installed and id in (select distinct coinid from markets where name='yobit')");
    foreach ($coins as $coin) {
        if ($coin->dontsell) {
            continue;
        }
        $pair = strtolower("{$coin->symbol}_btc");
        $orders = yobit_api_query2('ActiveOrders', array('pair' => $pair));
        if (isset($orders['return'])) {
            foreach ($orders['return'] as $uuid => $order) {
                $ticker = yobit_api_query("ticker/{$pair}");
                if (!$ticker) {
                    continue;
                }
                if ($order['rate'] > $ticker->{$pair}->sell + 5.0E-8 || $flushall) {
                    //				debuglog("yobit cancel order for $pair $uuid");
                    $res = yobit_api_query2('CancelOrder', array('order_id' => $uuid));
                    $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $uuid));
                    if ($db_order) {
                        $db_order->delete();
                    }
                    sleep(1);
                } else {
                    $db_order = getdbosql('db_orders', "uuid=:uuid", array(':uuid' => $uuid));
                    if ($db_order) {
                        continue;
                    }
                    debuglog("yobit adding order {$coin->symbol}");
                    $db_order = new db_orders();
                    $db_order->market = 'yobit';
                    $db_order->coinid = $coin->id;
                    $db_order->amount = $order['amount'];
                    $db_order->price = $order['rate'];
                    $db_order->ask = $ticker->{$pair}->sell;
                    $db_order->bid = $ticker->{$pair}->buy;
                    $db_order->uuid = $uuid;
                    $db_order->created = time();
                    $db_order->save();
                }
            }
        }
        $list = getdbolist('db_orders', "coinid={$coin->id} and market='yobit'");
        foreach ($list as $db_order) {
            $found = false;
            if (isset($orders['return'])) {
                foreach ($orders['return'] as $uuid => $order) {
                    if ($uuid == $db_order->uuid) {
                        $found = true;
                        break;
                    }
                }
            }
            if (!$found) {
                debuglog("yobit deleting order {$coin->name} {$db_order->amount}");
                $db_order->delete();
            }
        }
    }
    sleep(2);
    //////////////////////////////////////////////////////////////////////////////////////////////////
    $savebalance = getdbosql('db_balances', "name='yobit'");
    if (!$savebalance) {
        return;
    }
    $savebalance->balance = 0;
    $balances = yobit_api_query2('getInfo');
    if (!$balances || !isset($balances['return'])) {
        return;
    }
    foreach ($balances['return']['funds'] as $symbol => $amount) {
        // 		debuglog("$symbol, $amount");
        $amount -= 0.0001;
        if ($amount <= 0) {
            continue;
        }
        if ($symbol == 'btc') {
            $savebalance->balance = $amount;
            continue;
        }
        $coin = getdbosql('db_coins', "symbol=:symbol", array(':symbol' => $symbol));
        if (!$coin || $coin->dontsell) {
            continue;
        }
        $market = getdbosql('db_markets', "coinid={$coin->id} and name='yobit'");
        if ($market) {
            $market->lasttraded = time();
            $market->save();
        }
        if ($amount * $coin->price < 1.0E-5) {
            continue;
        }
        $pair = "{$symbol}_btc";
        $data = yobit_api_query("depth/{$pair}?limit=11");
        if (!$data) {
            continue;
        }
        $sold_amount = 0;
        for ($i = 0; $i < 10 && $amount >= 0; $i++) {
            if (!isset($data->{$pair}->bids[$i])) {
                break;
            }
            $nextbuy = $data->{$pair}->bids[$i];
            if ($amount * 1.1 < $nextbuy[1]) {
                break;
            }
            $sellprice = bitcoinvaluetoa($nextbuy[0]);
            $sellamount = min($amount, $nextbuy[1]);
            if ($sellamount * $sellprice < 0.0001) {
                continue;
            }
            debuglog("yobit selling market {$pair}, {$sellamount}, {$sellprice}");
            $res = yobit_api_query2('Trade', array('pair' => $pair, 'type' => 'sell', 'rate' => $sellprice, 'amount' => $sellamount));
            if (!$res || !$res['success']) {
                debuglog($res);
                break;
            }
            $amount -= $sellamount;
            $sold_amount += $sellamount;
            // 			sleep(1);
        }
        $ticker = yobit_api_query("ticker/{$pair}");
        if (!$ticker) {
            continue;
        }
        //		if(!$coin->sellonbid && $sold_amount*$coin->price > 0.002)
        //		{
        //			sleep(5);
        //			$buyprice = bitcoinvaluetoa($ticker->$pair->sell);
        //			$buyamount = bitcoinvaluetoa(0.00011/$ticker->$pair->sell);
        //			debuglog("yobit buyback $pair, $buyamount, $buyprice");
        //			$res = yobit_api_query2('Trade', array('pair'=>$pair, 'type'=>'buy', 'rate'=>$buyprice, 'amount'=>$buyamount));
        //			sleep(5);
        //		}
        if ($amount <= 0) {
            continue;
        }
        if ($coin->sellonbid) {
            $sellprice = bitcoinvaluetoa($ticker->{$pair}->buy);
        } else {
            $sellprice = bitcoinvaluetoa($ticker->{$pair}->sell);
        }
        if ($amount * $sellprice < 0.0001) {
            continue;
        }
        // 		debuglog("yobit selling $pair, $amount, $sellprice");
        $res = yobit_api_query2('Trade', array('pair' => $pair, 'type' => 'sell', 'rate' => $sellprice, 'amount' => $amount));
        if (!$res || !$res['success']) {
            debuglog($res);
            continue;
        }
        $db_order = new db_orders();
        $db_order->market = 'yobit';
        $db_order->coinid = $coin->id;
        $db_order->amount = $amount;
        $db_order->price = $sellprice;
        $db_order->ask = $ticker->{$pair}->sell;
        $db_order->bid = $ticker->{$pair}->buy;
        $db_order->uuid = $res['return']['order_id'];
        $db_order->created = time();
        $db_order->save();
        sleep(1);
    }
    $savebalance->save();
}
示例#29
0
 public function actionWithdraw()
 {
     $fees = 0.0001;
     $deposit = user()->getState('yaamp-deposit');
     if (!$deposit) {
         $this->render('login');
         return;
     }
     $renter = getrenterparam($deposit);
     if (!$renter) {
         $this->render('login');
         return;
     }
     $amount = getparam('withdraw_amount');
     $address = getparam('withdraw_address');
     $amount = floatval(bitcoinvaluetoa(min($amount, $renter->balance - $fees)));
     if ($amount < 0.001) {
         user()->setFlash('error', 'Minimum withdraw is 0.001');
         $this->redirect("/renting");
         return;
     }
     $coin = getdbosql('db_coins', "symbol='BTC'");
     if (!$coin) {
         return;
     }
     $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
     $res = $remote->validateaddress($address);
     if (!$res || !isset($res['isvalid']) || !$res['isvalid']) {
         user()->setFlash('error', 'Invalid address');
         $this->redirect("/renting");
         return;
     }
     $rentertx = new db_rentertxs();
     $rentertx->renterid = $renter->id;
     $rentertx->time = time();
     $rentertx->amount = $amount;
     $rentertx->type = 'withdraw';
     $rentertx->address = $address;
     $rentertx->tx = 'scheduled';
     $rentertx->save();
     debuglog("withdraw scheduled {$renter->id} {$renter->address}, {$amount} to {$address}");
     user()->setFlash('message', "withdraw scheduled");
     $this->redirect("/renting");
 }
示例#30
0
function sellCoinToExchange($coin)
{
    if ($coin->dontsell) {
        return;
    }
    $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
    $info = $remote->getinfo();
    if (!$info || !$info['balance']) {
        return false;
    }
    if (!empty($coin->symbol2)) {
        $coin2 = getdbosql('db_coins', "symbol='{$coin->symbol2}'");
        if (!$coin2) {
            return;
        }
        $amount = $info['balance'] - $info['paytxfee'];
        $amount *= 0.9;
        //		debuglog("sending $amount $coin->symbol to main wallet");
        $tx = $remote->sendtoaddress($coin2->master_wallet, $amount);
        //		if(!$tx) debuglog($remote->error);
        return;
    }
    $market = getBestMarket($coin);
    if (!$market) {
        return;
    }
    if (!$coin->sellonbid && $market->lastsent != null && $market->lastsent > $market->lasttraded) {
        //		debuglog("*** not sending $coin->name to $market->name. last tx is late ***");
        return;
    }
    $deposit_address = $market->deposit_address;
    $marketname = $market->name;
    if (empty($deposit_address)) {
        return false;
    }
    $reserved1 = dboscalar("select sum(balance) from accounts where coinid={$coin->id}");
    $reserved2 = dboscalar("select sum(amount*price) from earnings\n\t\twhere status!=2 and userid in (select id from accounts where coinid={$coin->id})");
    $reserved = ($reserved1 + $reserved2) * 10;
    $amount = $info['balance'] - $info['paytxfee'] - $reserved;
    //	if($reserved>0)
    //	{
    //		debuglog("$reserved1 $reserved2 out of {$info['balance']}");
    //		debuglog("reserving $reserved $coin->symbol out of $coin->balance, available $amount");
    //	}
    if ($amount < $coin->reward / 4) {
        //	debuglog("not enough $coin->symbol to sell $amount < $coin->reward /4");
        return false;
    }
    $deposit_info = $remote->validateaddress($deposit_address);
    if (!$deposit_info || !isset($deposit_info['isvalid']) || !$deposit_info['isvalid']) {
        debuglog("sell invalid address {$deposit_address}");
        return;
    }
    $amount = round($amount, 8);
    //	debuglog("sending $amount $coin->symbol to $marketname, $deposit_address");
    $market->lastsent = time();
    $market->save();
    //	sleep(1);
    $tx = $remote->sendtoaddress($deposit_address, $amount);
    if (!$tx) {
        //	debuglog($remote->error);
        if ($coin->symbol == 'MUE') {
            $amount = min($amount, 5000);
        } else {
            if ($coin->symbol == 'DIME') {
                $amount = min($amount, 10000000);
            } else {
                if ($coin->symbol == 'CNOTE') {
                    $amount = min($amount, 10000);
                } else {
                    if ($coin->symbol == 'SRC') {
                        $amount = min($amount, 500);
                    } else {
                        $amount = round($amount * 0.99, 8);
                    }
                }
            }
        }
        //		debuglog("sending $amount $coin->symbol to $deposit_address");
        sleep(1);
        $tx = $remote->sendtoaddress($deposit_address, $amount);
        if (!$tx) {
            debuglog("sending {$amount} {$coin->symbol} to {$deposit_address}");
            debuglog($remote->error);
            return;
        }
    }
    $exchange = new db_exchange();
    $exchange->market = $marketname;
    $exchange->coinid = $coin->id;
    $exchange->send_time = time();
    $exchange->quantity = $amount;
    $exchange->price_estimate = $coin->price;
    $exchange->status = 'waiting';
    $exchange->tx = $tx;
    $exchange->save();
    return;
}