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}"); } } }
public function actionIndex() { if (isset($_COOKIE['mainbtc'])) { return; } if (!LimitRequest('explorer')) { return; } $id = getiparam('id'); $coin = getdbo('db_coins', $id); $height = getparam('height'); if ($coin && intval($height) > 0) { $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport); $hash = $remote->getblockhash(intval($height)); } else { $hash = getparam('hash'); } $txid = getparam('txid'); if ($coin && !empty($txid) && ctype_alnum($txid)) { $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport); $tx = $remote->getrawtransaction($txid, 1); $hash = $tx['blockhash']; } if ($coin && !empty($hash) && ctype_alnum($hash)) { $this->render('block', array('coin' => $coin, 'hash' => substr($hash, 0, 64))); } else { if ($coin) { $this->render('coin', array('coin' => $coin)); } else { $this->render('index'); } } }
function BackendClearEarnings() { // debuglog(__FUNCTION__); $delay = time() - 150 * 60; $total_cleared = 0; $list = getdbolist('db_earnings', "status=1 and mature_time<{$delay}"); foreach ($list as $earning) { $user = getdbo('db_accounts', $earning->userid); if (!$user) { $earning->delete(); continue; } $coin = getdbo('db_coins', $earning->coinid); if (!$coin) { $earning->delete(); continue; } $earning->status = 2; // cleared $earning->price = $coin->price; $earning->save(); // $refcoin = getdbo('db_coins', $user->coinid); // if($refcoin && $refcoin->price<=0) continue; // $value = $earning->amount * $coin->price / ($refcoin? $refcoin->price: 1); $value = yaamp_convert_amount_user($coin, $earning->amount, $user); $user->balance += $value; $user->save(); if ($user->coinid == 6) { $total_cleared += $value; } } if ($total_cleared > 0) { debuglog("total cleared from mining {$total_cleared} BTC"); } }
public function actionUpdate() { if (!$this->admin) { return; } $coin = getdbo('db_coins', getiparam('id')); if (isset($_POST['db_coins'])) { $coin->attributes = $_POST['db_coins']; if ($coin->save()) { $this->redirect(array('index')); } } $this->render('_form', array('coin' => $coin, 'update' => true)); }
public function actionStop() { if (!$this->admin) { return; } $id = getiparam('id'); $nicehash = getdbo('db_nicehash', $id); if (!$nicehash) { return; } $nicehash->active = false; $nicehash->save(); $this->goback(); }
function showUser($userid, $what) { $user = getdbo('db_accounts', $userid); if (!$user) { return; } $d = datetoa2($user->last_login); $balance = bitcoinvaluetoa($user->balance); $paid = dboscalar("select sum(amount) from payouts where account_id={$user->id}"); $paid = bitcoinvaluetoa($paid); $t = time() - 24 * 60 * 60; $miner_count = getdbocount('db_workers', "userid={$user->id}"); $share_count = getdbocount('db_shares', "userid={$user->id}"); $block_count = getdbocount('db_blocks', "userid={$user->id} and time>{$t}"); $coin = getdbo('db_coins', $user->coinid); echo "<tr class='ssrow'>"; if ($coin) { echo "<td><img src='{$coin->image}' width=16> {$coin->symbol}</td>"; } else { echo "<td></td>"; } echo "<td>{$user->id}</td>"; echo "<td><a href='/site?address={$user->username}'>{$user->username}</a></td>"; echo "<td>{$what}</td>"; echo "<td>{$d}</td>"; echo "<td>{$block_count}</td>"; echo "<td>{$balance}</td>"; if (intval($paid) > 0.01) { echo "<td><b>{$paid}</b></td>"; } else { echo "<td>{$paid}</td>"; } echo "<td>{$miner_count}</td>"; echo "<td>{$share_count}</td>"; if ($user->is_locked) { echo "<td>locked</td>"; echo "<td><a href='/site/unblockuser?wallet={$user->username}'>unblock</a></td>"; } else { echo "<td></td>"; echo "<td><a href='/site/blockuser?wallet={$user->username}'>block</a></td>"; } echo "</tr>"; }
function BackendProcessList() { $list = dbolist("show processlist"); foreach ($list as $item) { $conn = getdbo('db_connections', $item['Id']); if (!$conn) { $conn = new db_connections(); $conn->id = $item['Id']; $conn->user = $item['User']; $conn->host = $item['Host']; $conn->db = $item['db']; $conn->created = time(); } $conn->idle = $item['Time']; $conn->last = time(); $conn->save(); } $delay = time() - 5 * 60; dborun("delete from connections where last<{$delay}"); }
public function actionSellto() { if (!$this->admin) { return; } $market = getdbo('db_markets', getiparam('id')); $coin = getdbo('db_coins', $market->coinid); $amount = getparam('amount'); $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport); $info = $remote->getinfo(); if (!$info || !$info['balance']) { return false; } $deposit_info = $remote->validateaddress($market->deposit_address); if (!$deposit_info || !isset($deposit_info['isvalid']) || !$deposit_info['isvalid']) { user()->setFlash('error', "invalid address {$coin->name}, {$market->deposit_address}"); $this->redirect(array('site/coin', 'id' => $coin->id)); } $amount = min($amount, $info['balance'] - $info['paytxfee']); // $amount = max($amount, $info['balance'] - $info['paytxfee']); $amount = round($amount, 8); debuglog("selling ({$market->deposit_address}, {$amount})"); $tx = $remote->sendtoaddress($market->deposit_address, $amount); if (!$tx) { user()->setFlash('error', $remote->error); $this->redirect(array('site/coin', 'id' => $coin->id)); } $exchange = new db_exchange(); $exchange->market = $market->name; $exchange->coinid = $coin->id; $exchange->send_time = time(); $exchange->quantity = $amount; $exchange->price_estimate = $coin->price; $exchange->status = 'waiting'; $exchange->tx = $tx; $exchange->save(); $this->redirect(array('site/coin', 'id' => $coin->id)); }
function delete_block() { global $COLLATE; global $block_id; $dbo = getdbo(); $block_ids = array(); $block_ids[] = $block_id; $sql = "SELECT name FROM blocks WHERE id='{$block_id}'"; $result = $dbo->query($sql); if ($result->rowCount() != '1') { header("HTTP/1.1 400 Bad Request"); echo $COLLATE['languages']['selected']['selectblock']; exit; } $name = $result->fetchColumn(); collate_log("4", "Block {$name} has been deleted!"); if (find_child_blocks($block_id) !== false) { # this is a recursive function $block_ids = array_merge($block_ids, find_child_blocks($block_id)); } foreach ($block_ids as $block_id) { // First delete all static IPs $sql = "DELETE FROM statics WHERE subnet_id IN (SELECT id FROM subnets WHERE block_id='{$block_id}')"; $dbo->query($sql); // Next, remove the DHCP ACLs $sql = "DELETE FROM acl WHERE subnet_id IN (SELECT id FROM subnets WHERE block_id='{$block_id}')"; $dbo->query($sql); // Next, remove the subnets $sql = "DELETE FROM subnets WHERE block_id='{$block_id}'"; $dbo->query($sql); // Lastly, delete the IP block $sql = "DELETE FROM blocks WHERE id='{$block_id}'"; $dbo->query($sql); } # we don't output to the user on success. The row fades on the page to provide feedback. }
function BackendStatsUpdate() { // debuglog(__FUNCTION__); // $t1xx = microtime(true); $t = time() - 2 * 60; $errors = ''; $list = getdbolist('db_stratums', "time<{$t}"); foreach ($list as $stratum) { debuglog("stratum {$stratum->algo} terminated"); $errors .= "{$stratum->algo}, "; } if (!empty($errors)) { send_email_alert('stratums', "stratums restarted {$errors}", "stratums were restarted: {$errors}"); } dborun("delete from stratums where time<{$t}"); dborun("delete from workers where pid not in (select pid from stratums)"); ////////////////////////////////////////////////////////////////////////////////////////////////////// // long term stats $t = floor(time() / 60 / 60) * 60 * 60; foreach (yaamp_get_algos() as $algo) { $pool_rate = yaamp_pool_rate($algo); $stats = getdbosql('db_hashstats', "time={$t} and algo=:algo", array(':algo' => $algo)); if (!$stats) { $stats = new db_hashstats(); $stats->time = $t; $stats->hashrate = $pool_rate; $stats->algo = $algo; } else { $percent = 1; $stats->hashrate = round(($stats->hashrate * (100 - $percent) + $pool_rate * $percent) / 100); } $stats->earnings = dboscalar("select sum(amount*price) from blocks where time>{$t} and category!='orphan' and algo=:algo", array(':algo' => $algo)); $stats->save(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // short term stats $step = 15; $t = floor(time() / $step / 60) * $step * 60; foreach (yaamp_get_algos() as $algo) { $stats = getdbosql('db_hashrate', "time={$t} and algo=:algo", array(':algo' => $algo)); if (!$stats) { $stats = new db_hashrate(); $stats->time = $t; $stats->hashrate = dboscalar("select hashrate from hashrate where algo=:algo order by time desc limit 1", array(':algo' => $algo)); $stats->hashrate_bad = 0; //dboscalar("select hashrate_bad from hashrate where algo=:algo order by time desc limit 1", array(':algo'=>$algo)); $stats->price = dboscalar("select price from hashrate where algo=:algo order by time desc limit 1", array(':algo' => $algo)); $stats->rent = dboscalar("select rent from hashrate where algo=:algo order by time desc limit 1", array(':algo' => $algo)); $stats->algo = $algo; } $pool_rate = yaamp_pool_rate($algo); $stats->hashrate = $pool_rate; //round(($stats->hashrate*(100-$percent) + $pool_rate*$percent) / 100); $pool_rate_bad = yaamp_pool_rate_bad($algo); $stats->hashrate_bad = $pool_rate_bad; //round(($stats->hashrate_bad*(100-$percent) + $pool_rate_bad*$percent) / 100); if ($stats->hashrate < 1000) { $stats->hashrate = 0; } $t1 = time() - 5 * 60; $total_rentable = dboscalar("select sum(difficulty) from shares where valid and extranonce1 and algo=:algo and time>{$t1}", array(':algo' => $algo)); $total_diff = dboscalar("select sum(difficulty) from shares where valid and algo=:algo and time>{$t1}", array(':algo' => $algo)); $total_rented = 0; if (!$total_diff) { $t1 = time() - 15 * 60; $total_diff = dboscalar("select sum(difficulty) from shares where valid and algo=:algo and time>{$t1}", array(':algo' => $algo)); } if ($total_diff > 0) { $price = 0; $rent = 0; $list = dbolist("select coinid, sum(difficulty) as d from shares where valid and algo=:algo and time>{$t1} group by coinid", array(':algo' => $algo)); foreach ($list as $item) { if ($item['coinid'] == 0) { if (!$total_rentable) { continue; } $total_rented = $item['d']; $price += $stats->rent * $item['d'] / $total_diff; $rent += $stats->rent * $item['d'] / $total_rentable; } else { $coin = getdbo('db_coins', $item['coinid']); if (!$coin) { continue; } $btcghd = yaamp_profitability($coin); $price += $btcghd * $item['d'] / $total_diff; $rent += $btcghd * $item['d'] / $total_diff; } } $percent = 33; $rent = max($price, ($stats->rent * (100 - $percent) + $rent * $percent) / 100); $target = yaamp_hashrate_constant($algo); $interval = yaamp_hashrate_step(); $aa = $total_rentable * $target / $interval / 1000; $bb = dboscalar("select sum(speed) from jobs where active and ready and price>{$rent} and algo=:algo", array(':algo' => $algo)); if ($total_rented * 1.3 < $total_rentable || $bb > $aa) { $rent += $price * YAAMP_FEES_RENTING / 100; } else { $rent -= $price * YAAMP_FEES_RENTING / 100; } $stats->price = $price; $stats->rent = $rent; } else { $coin = getdbosql('db_coins', "enable and auto_ready and algo=:algo order by index_avg desc", array(':algo' => $algo)); if ($coin) { $btcghd = yaamp_profitability($coin); $stats->price = $btcghd; $stats->rent = $stats->price + $stats->price * YAAMP_FEES_RENTING / 100; } } if (YAAMP_LIMIT_ESTIMATE) { $t1 = time() - 24 * 60 * 60; $avg = dboscalar("select avg(price) from hashrate where time>{$t1} and algo=:algo", array(':algo' => $algo)); if ($avg) { $stats->price = min($stats->price, $avg * 1.5); } } $stats->difficulty = dboscalar("select sum(difficulty) from coins where enable and auto_ready and algo=:algo", array(':algo' => $algo)); $stats->save(); } ////////////////////////////////////////////////////////////// $step = 15; $t = floor(time() / $step / 60) * $step * 60; $btc = getdbosql('db_coins', "symbol='BTC'"); $topay = dboscalar("select sum(balance) from accounts where coinid={$btc->id}"); //here: take other currencies too $margin = $btc->balance - $topay; $balances = dboscalar("select sum(balance) from balances"); $onsell = dboscalar("select sum(amount*bid) from orders"); $immature = dboscalar("select sum(amount*price) from earnings where status=0"); $confirmed = dboscalar("select sum(amount*price) from earnings where status=1"); $wallets = dboscalar("select sum(balance*price) from coins where enable and symbol!='BTC'"); $renters = dboscalar("select sum(balance) from renters"); $mints = dboscalar("select sum(mint*price) from coins where enable"); $off = $mints - $immature; // debuglog("mint $mints $immature $off"); $total_profit = $btc->balance + $balances + $onsell + $wallets - $topay - $renters; $stats = getdbosql('db_stats', "time={$t}"); if (!$stats) { $stats = new db_stats(); $stats->time = $t; } $stats->profit = $total_profit; $stats->wallet = $btc->balance; $stats->wallets = $wallets; $stats->margin = $margin; $stats->balances = $balances; $stats->onsell = $onsell; $stats->immature = $immature; $stats->waiting = $confirmed; $stats->renters = $renters; $stats->save(); ///////////////////////////////////////////////////////////////////////////// foreach (yaamp_get_algos() as $algo) { $factor = yaamp_get_algo_norm($algo); $dbalgo = getdbosql('db_algos', "name='{$algo}'"); if (!$dbalgo) { $dbalgo = new db_algos(); $dbalgo->name = $algo; } $dbalgo->profit = dboscalar("select price from hashrate where algo=:algo order by time desc limit 1", array(':algo' => $algo)); $dbalgo->rent = dboscalar("select rent from hashrate where algo=:algo order by time desc limit 1", array(':algo' => $algo)); $dbalgo->factor = $factor; $dbalgo->save(); } // $d1 = microtime(true) - $t1xx; // controller()->memcache->add_monitoring_function(__METHOD__, $d1); }
function updateJubiMarkets() { $btc = jubi_api_query('ticker', "?coin=btc"); if (!$btc) { continue; } $list = getdbolist('db_markets', "name='jubi'"); foreach ($list as $market) { $coin = getdbo('db_coins', $market->coinid); if (!$coin) { continue; } $lowsymbol = strtolower($coin->symbol); $ticker = jubi_api_query('ticker', "?coin={$lowsymbol}"); if (!$ticker) { continue; } $ticker->buy /= $btc->sell; $ticker->sell /= $btc->buy; $price2 = ($ticker->buy + $ticker->sell) / 2; $market->price2 = AverageIncrement($market->price2, $price2); $market->price = AverageIncrement($market->price, $ticker->buy * 0.95); $market->save(); } }
<?php echo "<br><table class='dataGrid'>"; echo "<thead>"; echo "<tr>"; echo "<th>Coin</th>"; echo "<th>Market</th>"; echo "<th>Price</th>"; echo "<th>Message</th>"; echo "<th>Deposit</th>"; echo "</tr>"; echo "</thead><tbody>"; $list = dbolist("SELECT coins.id as coinid, markets.id as marketid FROM coins, markets WHERE coins.installed AND \r\n\tcoins.id=markets.coinid AND (markets.deposit_address IS NULL or (message is not null and message!='')) order by markets.id desc"); foreach ($list as $item) { $coin = getdbo('db_coins', $item['coinid']); $market = getdbo('db_markets', $item['marketid']); echo "<tr class='ssrow'>"; echo "<td><a href='/site/coin?id={$coin->id}'>{$coin->name}</a></td>"; echo "<td>{$market->name}</td>"; echo "<td>{$market->price}</td>"; echo "<td>{$market->message}</td>"; echo "<td>{$market->deposit_address}</td>"; echo "</tr>"; } echo "</tbody></table>"; echo '<br><br><br><br><br><br><br><br><br><br>'; echo '<br><br><br><br><br><br><br><br><br><br>';
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', "¤cy=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'); }
<div class="main-left-title">Search Wallet:</div> <div class="main-left-inner"> <form action="/" method="get" style="padding: 10px;"> <input type="text" name="address" class="main-text-input" placeholder="Wallet Address"> <input type="submit" value="Submit" class="main-submit-button" ><br><br> END; echo "<table class='dataGrid2'>"; foreach ($recents as $address) { if (empty($address)) { continue; } $user = getuserparam($address); if (!$user) { continue; } $coin = getdbo('db_coins', $user->coinid); if ($user->username == $username) { echo "<tr style='background-color: #e0d3e8;'><td width=24>"; } else { echo "<tr class='ssrow'><td width=24>"; } if ($coin) { echo "<img width=16 src='{$coin->image}'>"; } else { echo "<img width=16 src='/images/base/delete.png'>"; } echo "</td><td><a href='/?address={$address}' style='font-family: monospace; font-size: 1.1em;'>{$address}</a></td>"; $balance = bitcoinvaluetoa($user->balance); if ($coin) { $balance = $balance > 0 ? "{$balance} {$coin->symbol}" : ''; } else {
function delete_acl() { global $COLLATE; $dbo = getdbo(); $acl_id = isset($_GET['acl_id']) && is_numeric($_GET['acl_id']) ? $_GET['acl_id'] : ''; if (empty($acl_id)) { header("HTTP/1.1 400 Bad Request"); echo $COLLATE['languages']['selected']['invalidrequest']; exit; } $sql = "SELECT name FROM subnets WHERE id=(SELECT subnet_id FROM acl WHERE id='{$acl_id}')"; $result = $dbo->query($sql); if ($result->rowCount() != '1') { header("HTTP/1.1 400 Bad Request"); echo $COLLATE['languages']['selected']['invalidrequest']; exit; } $subnet_name = $result->fetchColumn(); collate_log('3', "ACL Statement #{$acl_id} deleted in {$subnet_name} subnet"); $sql = "DELETE FROM acl WHERE id='{$acl_id}'"; $dbo->query($sql); exit; }
echo "<th width=20></th>"; echo "<th>Name</th>"; echo "<th>Time</th>"; echo "<th>Height</th>"; echo "<th>Amount</th>"; echo "<th>Status</th>"; echo "<th>Difficulty</th>"; echo "<th>Found Diff</th>"; echo "<th>Blockhash</th>"; echo "</tr>"; echo "</thead><tbody>"; foreach ($db_blocks as $db_block) { if (!$db_block->coin_id) { continue; } $coin = getdbo('db_coins', $db_block->coin_id); if (!$coin) { continue; } // $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport); // $blockext = $remote->getblock($db_block->blockhash); // $tx = $remote->gettransaction($blockext['tx'][0]); // $db_block->category = $tx['details'][0]['category']; if ($db_block->category == 'immature') { echo "<tr style='background-color: #e0d3e8;'>"; } else { echo "<tr class='ssrow'>"; } echo "<td><img width=16 src='{$coin->image}'></td>"; echo "<td><b>{$coin->name} ({$coin->symbol})</b></td>"; // $db_block->confirmations = $blockext['confirmations'];
echo "<br><table class='dataGrid'>"; echo "<thead>"; echo "<tr>"; echo "<th width=20></th>"; echo "<th>Name</th>"; echo "<th>Market</th>"; echo "<th>Created</th>"; echo "<th>Quantity</th>"; echo "<th>Estimate</th>"; echo "<th>Sold Price</th>"; echo "<th>Value</th>"; echo "<th></th>"; echo "</tr>"; echo "</thead><tbody>"; foreach ($exchanges as $exchange) { $coin = getdbo('db_coins', $exchange->coinid); $lowsymbol = strtolower($coin->symbol); if ($exchange->market == 'cryptsy') { $marketurl = "https://www.cryptsy.com/markets/view/{$coin->symbol}_BTC"; } else { if ($exchange->market == 'bittrex') { $marketurl = "https://bittrex.com/Market/Index?MarketName=BTC-{$coin->symbol}"; } else { if ($exchange->market == 'mintpal') { $marketurl = "https://www.mintpal.com/market/{$coin->symbol}/BTC"; } else { if ($exchange->market == 'poloniex') { $marketurl = "https://poloniex.com/exchange/btc_{$coin->symbol}"; } else { if ($exchange->market == 'c-cex') { $marketurl = "https://c-cex.com/?p={$lowsymbol}-btc";
echo "<th>Algo</th>"; echo "<th>Host</th>"; echo "<th>Max Price</th>"; echo "<th>Max Hash</th>"; echo "<th>Current Hash</th>"; echo "<th>Difficulty</th>"; echo "<th>Ready</th>"; echo "<th>Active</th>"; echo "</tr>"; echo "</thead><tbody>"; $list = getdbolist('db_jobs', "ready"); foreach ($list as $job) { $hashrate = yaamp_job_rate($job->id); $hashrate = $hashrate ? Itoa2($hashrate) . 'h/s' : ''; $speed = Itoa2($job->speed) . 'h/s'; $renter = getdbo('db_renters', $job->renterid); if (!$renter) { continue; } if ($deposit == $renter->address) { echo "<tr class='ssrow' style='background-color: #dfd'>"; } else { echo "<tr class='ssrow'>"; } echo "<td>{$job->renterid}</td>"; echo "<td>{$job->id}</td>"; echo "<td><a href='/renting?address={$renter->address}'>{$renter->address}</a></td>"; echo "<td>{$job->algo}</td>"; echo "<td>{$job->host}:{$job->port}</td>"; echo "<td>{$job->price}</td>"; echo "<td>{$speed}</td>";
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); }
protected function loadOrders() { $ordertab = array(); $orders = cryptsy_api_query('allmyorders'); if (!$orders) { return $ordertab; } if (!isset($orders['return'])) { return $ordertab; } foreach ($orders['return'] as $order) { if (!isset($order['marketid'])) { continue; } if (!isset($order['orderid'])) { continue; } $object = new object(); $object->orderid = $order['orderid']; $object->price = $order['price']; $object->amount = $order['quantity']; $object->marketid = $order['marketid']; $market = getdbosql('db_markets', "marketid={$object->marketid}"); if (!$market) { continue; } $object->coin = getdbo('db_coins', $market->coinid); if (!$object->coin) { continue; } $ordertab[] = $object; } return $ordertab; }
public function actionRunExchange() { $id = getiparam('id'); $balance = getdbo('db_balances', $id); if ($balance) { switch ($balance->name) { case 'cryptsy': doCryptsyTrading(true); updateCryptsyMarkets(); break; case 'bittrex': doBittrexTrading(true); updateBittrexMarkets(); break; case 'c-cex': doCCexTrading(true); updateCCexMarkets(); break; case 'yobit': doYobitTrading(true); updateYobitMarkets(); break; case 'bleutrade': doBleutradeTrading(true); updateBleutradeMarkets(); break; case 'poloniex': doPoloniexTrading(true); updatePoloniexMarkets(); break; } } debuglog("runexchange done"); $this->redirect("/site/common"); }
function validate_network($subnet, $network_type = "subnet", $table_id = null, $overlapok = false) { $dbo = getdbo(); $function_return = array(); if (!strstr($subnet, '/')) { # invalid mask $function_return['0'] = false; $function_return['error'] = 'invalidmask'; return $function_return; } list($ip, $mask) = explode('/', $subnet); $long_ip = ip2decimal($ip); if ($long_ip === false) { # invalid ip $function_return['0'] = false; $function_return['error'] = 'invalidip'; return $function_return; } if (!strstr($mask, '.') && is_numeric($mask) && $mask > '0' && $mask < '32') { # number of mask bits $bin = str_pad('', $mask, '1'); $bin = str_pad($bin, '32', '0'); $mask = bindec(substr($bin, 0, 8)) . "." . bindec(substr($bin, 8, 8)) . "." . bindec(substr($bin, 16, 8)) . "." . bindec(substr($bin, 24, 8)); $mask = long2ip(ip2decimal($mask)); } $long_mask = ip2decimal($mask); if (!validate_netmask($mask) || $long_mask === false) { #invalid mask $function_return['0'] = false; $function_return['error'] = 'invalidmask'; return $function_return; } $long_start_ip = $long_ip & $long_mask; // This makes sure they entered the network address and not an IP inside the network $start_ip = long2ip($long_start_ip); $long_end_ip = $long_ip | ~$long_mask; $end_ip = long2ip($long_end_ip); if ($network_type == 'block') { # make sure we don't overlap other blocks $overlap_check_sql = "SELECT id FROM blocks WHERE \n ((CAST(start_ip & 0xFFFFFFFF AS UNSIGNED) <= CAST('{$long_start_ip}' & 0xFFFFFFFF AS UNSIGNED) AND \n\t CAST(end_ip & 0xFFFFFFFF AS UNSIGNED) >= CAST('{$long_start_ip}' & 0xFFFFFFFF AS UNSIGNED)) \n\tOR \n (CAST(start_ip & 0xFFFFFFFF AS UNSIGNED) <= CAST('{$long_end_ip}' & 0xFFFFFFFF AS UNSIGNED) AND \n\t CAST(end_ip & 0xFFFFFFFF AS UNSIGNED) >= CAST('{$long_end_ip}' & 0xFFFFFFFF AS UNSIGNED)) \n\tOR\n (CAST(start_ip & 0xFFFFFFFF AS UNSIGNED) >= CAST('{$long_start_ip}' & 0xFFFFFFFF AS UNSIGNED) AND \n\t CAST(end_ip & 0xFFFFFFFF AS UNSIGNED) <= CAST('{$long_end_ip}' & 0xFFFFFFFF AS UNSIGNED)))"; $overlap_check_sql .= $table_id !== NULL ? " AND id!='{$table_id}'" : ''; $result = $dbo->query($overlap_check_sql); if ($result->rowcount() != '0') { $function_return['0'] = false; $function_return['error'] = 'blockoverlap-notice'; return $function_return; } } elseif ($overlapok === false) { # make sure we don't overlap other subnets $sql = "SELECT id FROM subnets WHERE \n\t CAST('{$long_start_ip}' & 0xFFFFFFFF AS UNSIGNED) & CAST(mask & 0xFFFFFFFF AS UNSIGNED) = CAST(start_ip & 0xFFFFFFFF AS UNSIGNED) OR \n\t CAST(start_ip & 0xFFFFFFFF AS UNSIGNED) & CAST('{$long_mask}' & 0xFFFFFFFF AS UNSIGNED) = CAST('{$long_start_ip}' & 0xFFFFFFFF AS UNSIGNED)"; $result = $dbo->query($sql); if ($result->rowcount() != '0') { # subnet overlap $function_return['0'] = false; $function_return['error'] = 'subnetoverlap-notice'; return $function_return; } } # everything is ok if we get here $function_return['0'] = true; $function_return['start_ip'] = $start_ip; $function_return['long_start_ip'] = $long_start_ip; $function_return['end_ip'] = $end_ip; $function_return['long_end_ip'] = $long_end_ip; $function_return['mask'] = $mask; $function_return['long_mask'] = $long_mask; return $function_return; }
$_ARG[$reg[1]] = $reg[2]; } elseif (ereg('-([a-zA-Z0-9])', $arg, $reg)) { $_ARG[$reg[1]] = true; } } if (isset($_ARG['h']) || isset($_ARG['help'])) { echo "\r\n" . "This script takes three options: \r\n" . " -h (or --help): Outputs this message \r\n" . " -v (or --verbose): Outputs detail about the progress of the script \r\n" . " -n (or --numeric): Skip name resolution when adding hosts \r\n" . "\r\n" . "Please read the documenation for this script at http://code.google.com/p/collate-network/w/list before running \r\n" . "this on a schedule. \r\n" . "\r\n"; exit; } if (isset($_ARG['v']) || isset($_ARG['verbose'])) { $verbose = 'on'; } else { $verbose = 'off'; } require_once '../include/db_connect.php'; $dbo = getdbo(); // Create array containing all unreserved IPs in all reserved subnets excluding ACL'd IP space // loop whole operation over each subnet $pingedhosts = '0'; $newhosts = '0'; $sql = "SELECT id, start_ip, end_ip FROM subnets"; $subnet_results = $dbo->query($sql); while (list($subnet_id, $long_subnet_start_ip, $long_subnet_end_ip) = $subnet_results->fetch(PDO::FETCH_NUM)) { $first_usable = $long_subnet_start_ip; $last_usable = $long_subnet_end_ip - '1'; $subnet = range($first_usable, $last_usable); // exclude ACL'd IPs from this array $sql = "SELECT start_ip, end_ip FROM acl where subnet_id = '{$subnet_id}'"; $results = $dbo->query($sql); while (list($start_ip, $end_ip) = $results->fetch(PDO::FETCH_NUM)) { $acl = range($start_ip, $end_ip);
function yaamp_job_rate_bad($jobid) { $job = getdbo('db_jobs', $jobid); if (!$job) { return 0; } $target = yaamp_hashrate_constant($job->algo); $interval = yaamp_hashrate_step(); $delay = time() - $interval; $rate = controller()->memcache->get_database_scalar("yaamp_job_rate_bad-{$jobid}", "select sum(difficulty) * {$target} / {$interval} / 1000 from jobsubmits where not valid and time>{$delay} and jobid={$jobid}"); return $rate; }
function find_free_statics($subnet_id) { global $dbo; # This function returns an array containing all free IP addresses in a subnet # after excluding ACL'd ranges and already used addresses. If an IP is supplied, # it will return an array with a truth value an an error message $dbo = getdbo(); $sql = "SELECT name, start_ip, end_ip, mask FROM subnets WHERE id='{$subnet_id}'"; $results = $dbo->query($sql); $return = array(); if ($results->rowCount() != '1') { $return['0'] = false; $return['1'] = "subnet not found"; return $return; } list($subnet_name, $long_subnet_start_ip, $long_subnet_end_ip, $long_mask) = $results->fetch(PDO::FETCH_NUM); $first_usable = $long_subnet_start_ip; $last_usable = $long_subnet_end_ip - '1'; $whole_subnet = range($first_usable, $last_usable); $ipspace = $whole_subnet; $sql = "SELECT start_ip, end_ip FROM acl WHERE subnet_id='{$subnet_id}'"; $results = $dbo->query($sql); while (list($start_ip, $end_ip) = $results->fetch(PDO::FETCH_NUM)) { $acl = range($start_ip, $end_ip); $ipspace = array_diff($ipspace, $acl); } $sql = "SELECT ip FROM statics WHERE subnet_id='{$subnet_id}'"; $results = $dbo->query($sql); if ($results->rowCount() > '0') { $statics = array(); while ($static_ip = $results->fetch(PDO::FETCH_NUM)) { array_push($statics, $static_ip['0']); } $ipspace = array_diff($ipspace, $statics); } $ipspace = array_reverse($ipspace); array_pop($ipspace); # remove the network address from the array $return['0'] = true; $return['ipspace'] = $ipspace; $return['subnet_name'] = $subnet_name; $return['long_start_ip'] = $long_subnet_start_ip; $return['long_mask'] = $long_mask; return $return; }
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)); foreach ($list as $item) { $coin = getdbo('db_coins', $item['coin_id']); if ($coin->symbol == 'BTC') { continue; } $res1 = controller()->memcache->get_database_row("history_item1-{$coin->id}-{$algo}", "select count(*) as a, sum(amount*price) as b from blocks where category!='orphan' and time>{$t1} and coin_id={$coin->id} and algo=:algo", array(':algo' => $algo)); $res2 = controller()->memcache->get_database_row("history_item2-{$coin->id}-{$algo}", "select count(*) as a, sum(amount*price) as b from blocks where category!='orphan' and time>{$t2} and coin_id={$coin->id} and algo=:algo", array(':algo' => $algo)); $res3 = controller()->memcache->get_database_row("history_item3-{$coin->id}-{$algo}", "select count(*) as a, sum(amount*price) as b from blocks where category!='orphan' and time>{$t3} and coin_id={$coin->id} and algo=:algo", array(':algo' => $algo)); $res4 = controller()->memcache->get_database_row("history_item4-{$coin->id}-{$algo}", "select count(*) as a, sum(amount*price) as b from blocks where category!='orphan' and time>{$t4} and coin_id={$coin->id} and algo=:algo", array(':algo' => $algo)); $total1 += $res1['b']; $total2 += $res2['b']; $total3 += $res3['b']; $total4 += $res4['b']; $name = substr($coin->name, 0, 12); echo "<tr class='ssrow'>"; echo "<td width=18><img width=16 src='{$coin->image}'></td>"; echo "<td><b><a href='/site/block?id={$coin->id}'>{$name}</a></b></td>";
function BackendBlocksUpdate() { // debuglog(__METHOD__); $t1 = microtime(true); $list = getdbolist('db_blocks', "category='immature' order by time"); foreach ($list as $block) { $coin = getdbo('db_coins', $block->coin_id); if (!$coin || !$coin->enable) { $block->delete(); continue; } $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport); if (empty($block->txhash)) { $blockext = $remote->getblock($block->blockhash); if (!$blockext || !isset($blockext['tx'][0])) { continue; } $block->txhash = $blockext['tx'][0]; } $tx = $remote->gettransaction($block->txhash); if (!$tx) { continue; } $block->confirmations = $tx['confirmations']; if ($block->confirmations == -1) { $block->category = 'orphan'; } else { if (isset($tx['details']) && isset($tx['details'][0])) { $block->category = $tx['details'][0]['category']; } else { if (isset($tx['category'])) { $block->category = $tx['category']; } } } $block->save(); if ($block->category == 'generate') { dborun("update earnings set status=1, mature_time=UNIX_TIMESTAMP() where blockid={$block->id}"); } else { if ($block->category != 'immature') { dborun("delete from earnings where blockid={$block->id}"); } } } $d1 = microtime(true) - $t1; controller()->memcache->add_monitoring_function(__METHOD__, $d1); }
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'); }
public function actionOrderDialog() { $renter = getrenterparam(getparam('address')); if (!$renter) { return; } $a = 'x11'; $server = ''; $username = ''; $password = '******'; $percent = ''; $price = ''; $speed = ''; $id = 0; $job = getdbo('db_jobs', getiparam('id')); if ($job) { $id = $job->id; $a = $job->algo; $server = "{$job->host}:{$job->port}"; $username = $job->username; $password = $job->password; $percent = $job->percent; $price = mbitcoinvaluetoa($job->price); $speed = $job->speed / 1000000; } echo <<<end <form id='order-edit-form' action='/renting/ordersave' method='post'> <input type="hidden" value='{$id}' name="order_id"> <input type="hidden" value='{$renter->id}' name="order_renterid"> <input type="hidden" value='{$renter->address}' name="order_address"> \t\t <p>Enter your job information below and click Submit when you are ready.</p> \t\t <table cellspacing=10 width=100%> <tr><td>Algo:</td><td><select class="main-text-input" name="order_algo"> end; foreach (yaamp_get_algos() as $algo) { if (!controller()->admin && $algo == 'sha256') { continue; } if (!controller()->admin && $algo == 'scryptn') { continue; } $selected = $algo == $a ? 'selected' : ''; echo "<option {$selected} value='{$algo}'>{$algo}</option>"; } echo <<<end </select></td></tr> <tr><td>Server:</td><td><input type="text" value='{$server}' name="order_host" class="main-text-input" placeholder="stratum.server.com:3333"></td></tr> <tr><td>Username:</td><td><input type="text" value='{$username}' name="order_username" class="main-text-input" placeholder="wallet_address"></td></tr> <tr><td>Password:</td><td><input type="text" value='{$password}' name="order_password" class="main-text-input"></td></tr> <tr><td>Max Price<br><span style='font-size: .8em;'>(mBTC/mh/day)</span>:</td><td><input type="text" value='{$price}' name="order_price" class="main-text-input" placeholder=""></td></tr> <tr><td width=110>Max Hashrate<br><span style='font-size: .8em;'>(Mh/s)</span>:</td><td><input type="text" value='{$speed}' name="order_speed" class="main-text-input" placeholder=""></td></tr> end; if (controller()->admin) { echo "<tr><td>Percent:</td><td><input type=text value='{$percent}' name=order_percent class=main-text-input></td></tr>"; } echo "</table></form>"; }
$earnings = getdbolist('db_earnings', "userid={$user->id} order by create_time desc limit :count", array(':count' => $count)); echo "<table class='dataGrid2'>"; echo "<thead>"; echo "<tr>"; echo "<td></td>"; echo "<th>Name</th>"; echo "<th align=right>Amount</th>"; echo "<th align=right>Percent</th>"; echo "<th align=right>mBTC</th>"; echo "<th align=right>Time</th>"; echo "<th align=right>Status</th>"; echo "</tr>"; echo "</thead>"; foreach ($earnings as $earning) { $coin = getdbo('db_coins', $earning->coinid); $block = getdbo('db_blocks', $earning->blockid); $d = datetoa2($earning->create_time); if (!$coin) { $reward = bitcoinvaluetoa($earning->amount); $value = altcoinvaluetoa($earning->amount * 1000); $percent = $block ? mbitcoinvaluetoa($earning->amount * 100 / $block->amount) : ''; $algo = $block ? $block->algo : ''; echo "<tr class='ssrow'>"; echo "<td width=18><img width=16 src='/images/btc.png'></td>"; echo "<td><b>Rental</b><span style='font-size: .8em'> ({$algo})</span></td>"; echo "<td align=right style='font-size: .8em'><b>{$reward} BTC</b></td>"; echo "<td align=right style='font-size: .8em'>{$percent}%</td>"; echo "<td align=right style='font-size: .8em'>{$value}</td>"; echo "<td align=right style='font-size: .8em'>{$d} ago</td>"; echo "<td align=right style='font-size: .8em'>Cleared</td>"; echo "</tr>";