fix: 全模块Critical安全修复 — 防重入+锁+精度+XSS

This commit is contained in:
testadmin
2026-04-29 01:05:00 +08:00
parent 2b4adc5124
commit 664d4d9572
93 changed files with 25144 additions and 0 deletions
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace App\Console\Commands;
use App\AutoList;
use App\CurrencyQuotation;
use App\MarketHour;
use App\Setting;
use App\TransactionComplete;
use App\UsersWallet;
use Carbon\Carbon;
use Faker\Factory;
use App\Users;
use App\AiCurrency;
use App\AiOrder;
use App\AccountLog;
use App\Currency;
use Illuminate\Support\Facades\Cache;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoAiOrder extends Command
{
protected $signature = "auto_ai_order";
protected $description = "AI量化订单";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$nowday = date('Ymd',time());
// ->where('startdate','<=',date('Y-m-d',time()))
// where('expire','>=',date('Y-m-d',time()))
$Ai_orderend = AiOrder::where('expire','<=',date('Y-m-d H:i:s',time()))->where('status',0)->where('today','<>',$nowday)->get();
foreach ($Ai_orderend as $Ai_order){
$AiCurrency = AiCurrency::where('id',$Ai_order->ai_id)->first();
$currency_id = $AiCurrency->currency_id;
$exercise_price = $AiCurrency->exercise_price;
$type = $AiCurrency->type;
$now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价
$amount = $Ai_order->amount;
$totalincome = $Ai_order->totalincome;
$rates = explode('-',$Ai_order->rate);
$rate = AiOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数
$Ai_order->todayincome = bcdiv($rate*$amount,100,2);
$Ai_order->totalincome = $totalincome+$Ai_order->todayincome;
// $money = $amount + $totalincome+$Ai_order->todayincome;
$money = $amount + $Ai_order->todayincome;
$user_walllet=UsersWallet::where("user_id",$Ai_order->user_id)->where("currency",3)->first();
change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_AI_ORDER_RETURN,'AI量化结算');// . $user_walllet->name
$data['user_id'] = $Ai_order->user_id;
$data['order_id'] = $Ai_order->id;
$data['day'] = $Ai_order->day;
$data['rate'] = $Ai_order->order_rate;
$data['amount'] = $Ai_order->todayincome;
$data['addtime'] = time();
DB::table('ai_list')->insert($data);
$Ai_order->status = 1; //修改状态为已结算
$Ai_order->today = $nowday;
$Ai_order->save();
}
$Ai_orders = AiOrder::where('startdate','<=',date('Y-m-d H:i:s',time()))->where('expire','>',date('Y-m-d H:i:s',time()))->where('today','<>',$nowday)->where('status',0)->get();
foreach ($Ai_orders as $Ai_order){
$AiCurrency = AiCurrency::where('id',$Ai_order->ai_id)->first();
$currency_id = $AiCurrency->currency_id;
$exercise_price = $AiCurrency->exercise_price;
$type = $AiCurrency->type;
$now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价
$amount = $Ai_order->amount;
$Ai_order->startdate = date('Y-m-d H:i:s',strtotime($Ai_order->startdate)+86400);
// $id = $Ai_order->id;
$today = $Ai_order->today;
$totalincome = $Ai_order->totalincome;
// $rate = $Ai_order->order_rate;
$rates = explode('-',$Ai_order->rate);
$rate = AiOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数
$Ai_order->todayincome = bcdiv($rate*$amount,100,2);
$Ai_order->totalincome = $totalincome+$Ai_order->todayincome;
$money = $Ai_order->todayincome;
$user_walllet=UsersWallet::where("user_id",$Ai_order->user_id)->where("currency",3)->first();
change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_AI_ORDER_RETURN,'AI量化结算');// . $user_walllet->name
$data['user_id'] = $Ai_order->user_id;
$data['order_id'] = $Ai_order->id;
$data['day'] = $Ai_order->day;
$data['rate'] = $Ai_order->order_rate;
$data['amount'] = $money;
$data['addtime'] = time();
DB::table('ai_list')->insert($data);
$Ai_order->today = $nowday;
$Ai_order->save();
}
echo '已结算 '.PHP_EOL;
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Console\Commands;
use App\AutoList;
use App\CurrencyQuotation;
use App\MarketHour;
use App\Setting;
use App\TransactionComplete;
use App\UsersWallet;
use Carbon\Carbon;
use Faker\Factory;
use App\Users;
use App\BalanceList;
use App\AccountLog;
use App\Currency;
use Illuminate\Support\Facades\Cache;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoBalance extends Command
{
protected $signature = "auto_balance";
protected $description = "用户资产汇总";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$nowday = date('Y-m-d H:i:s',time());
$list = Users::where('id','>',1)->get();
foreach ($list as $u){
$currency_name='';
$user_id = $data['user_id']=$u->id;
$change_wallet['usdt_totle'] =0;
$change_wallet['balance'] = UsersWallet::where('user_id', $user_id)
->where('change_balance', '>=', 0)
->whereHas('currencyCoin', function ($query) use ($currency_name) {
empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%');
})->get(['id', 'currency', 'change_balance', 'lock_change_balance'])
->toArray();
foreach ($change_wallet['balance'] as $k => $v) {
$num = $v['change_balance'] + $v['lock_change_balance'];
$change_wallet['usdt_totle'] += $num * $v['usdt_price'];
}
$lever_wallet['usdt_totle'] =0;
$lever_wallet['balance'] = UsersWallet::where('user_id', $user_id)
->where('lever_balance', '>=', 0)
->whereHas('currencyCoin', function ($query) use ($currency_name) {
empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%');
$query->where("is_lever", 1);
})->get(['id', 'currency', 'lever_balance', 'lock_lever_balance'])->toArray();
foreach ($lever_wallet['balance'] as $k => $v) {
$num = $v['lever_balance'] + $v['lock_lever_balance'];
$lever_wallet['usdt_totle'] += $num * $v['usdt_price'];
}
$micro_wallet['usdt_totle'] =0;
$micro_wallet['balance'] = UsersWallet::where('user_id', $user_id)
->where('micro_balance', '>=', 0)
->whereHas('currencyCoin', function ($query) use ($currency_name) {
empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%');
// $query->where("is_micro", 1);
})->get(['id', 'currency', 'micro_balance', 'lock_micro_balance'])
->toArray();
foreach ($micro_wallet['balance'] as $k => $v) {
$num = $v['micro_balance'] + $v['lock_micro_balance'];
$micro_wallet['usdt_totle'] += $num * $v['usdt_price'];
}
$legal_wallet['usdt_totle'] =0;
$legal_wallet['balance'] = UsersWallet::where('user_id', $user_id)
->where('legal_balance', '>=', 0)
->whereHas('currencyCoin', function ($query) use ($currency_name) {
empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%');
//$query->where("is_legal", 1)->where('show_legal', 1);
$query->where("is_legal", 1);
})
->get(['id', 'currency', 'legal_balance', 'lock_legal_balance'])
->toArray();
foreach ($legal_wallet['balance'] as $k => $v) {
$num = $v['legal_balance'] + $v['lock_legal_balance'];
$legal_wallet['usdt_totle'] += $num * $v['usdt_price'];
}
$data['user_id'] =$user_id;
$data['amount'] = $micro_wallet['usdt_totle'] + $lever_wallet['usdt_totle'] + $change_wallet['usdt_totle'] +$legal_wallet['usdt_totle'];
$data['addtime'] = $nowday;
// $bl = BalanceList::where('user_id',$user_id)->where('addtime',$nowday)->first();
//if(empty($bl)){
// print_r( $data);
BalanceList::insert($data);
// } //else{
// BalanceList::where('user_id',$user_id)->where('addtime',$nowday)->update($data);
// }
}
echo '已汇总 '.PHP_EOL;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\C2cDeal;
use App\C2cDealSend;
use App\UsersWallet;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoCancelC2C extends Command
{
protected $signature = "auto_cancel_c2c";
protected $description = "自动取消24小时C2C发布";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$now = Carbon::now();
$this->info('开始执行自动取消C2C发布脚本-' . $now->toDateTimeString());
$twenty_four = $now->subHours(24)->timestamp;
$results = C2cDealSend::where('create_time', '<=', $twenty_four)->where('is_done', 0)->get();
$count = count($results);
$this->info('共有 ' . $count . ' 条可取消C2C发布');
try {
DB::beginTransaction();
if (!empty($results)) {
$i = 1;
foreach ($results as $result) {
$this->info('执行第 ' . $i . ' 条记录');
$legal_deal_send = C2cDealSend::lockForUpdate()->find($result->id);
$wallet = UsersWallet::where('user_id', $legal_deal_send->seller_id)->where('currency', $legal_deal_send->currency_id)->lockForUpdate()->first();
if ($legal_deal_send->type == 'sell') {
$data_wallet1 = ['balance_type' => 2, 'wallet_id' => $wallet->id, 'lock_type' => 0, 'create_time' => time(), 'before' => $wallet->change_balance, 'change' => $legal_deal_send->total_number, 'after' => bc_add($wallet->change_balance, $legal_deal_send->total_number, 5)];
$data_wallet2 = ['balance_type' => 2, 'wallet_id' => $wallet->id, 'lock_type' => 1, 'create_time' => time(), 'before' => $wallet->lock_change_balance, 'change' => -1 * $legal_deal_send->total_number, 'after' => bc_sub($wallet->lock_change_balance, $legal_deal_send->total_number, 5)];
$wallet->change_balance = bc_add($wallet->change_balance, $legal_deal_send->total_number, 5);
$wallet->lock_change_balance = bc_sub($wallet->lock_change_balance, $legal_deal_send->total_number, 5);
$wallet->save();
AccountLog::insertLog(['user_id' => $legal_deal_send->seller_id, 'value' => $legal_deal_send->total_number, 'info' => '24小时未交易,发布取消,增加余额', 'type' => AccountLog::C2C_POST_AUTO_CANCEL, 'currency' => $legal_deal_send->currency_id], $data_wallet1);
AccountLog::insertLog(['user_id' => $legal_deal_send->seller_id, 'value' => $legal_deal_send->total_number * -1, 'info' => '24小时未交易,发布取消,锁定余额减少', 'type' => AccountLog::C2C_POST_AUTO_CANCEL, 'currency' => $legal_deal_send->currency_id], $data_wallet2);
}
$legal_deal_send->is_done = 2;
$legal_deal_send->save();
$i++;
}
}
DB::commit();
$this->info('执行成功');
} catch (\Exception $exception) {
DB::rollback();
$this->error($exception->getMessage());
}
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\C2cDeal;
use App\C2cDealSend;
use App\UsersWallet;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoCancelC2CDeal extends Command
{
protected $signature = "auto_cancel_c2c_deal";
protected $description = "15分钟自动取消C2C交易";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$now = Carbon::now();
$this->info('开始执行15分钟自动取消C2C交易脚本-' . $now->toDateTimeString());
$fiveteen = $now->subMinutes(15)->timestamp;
$results = C2cDeal::where('create_time', '<=', $fiveteen)->where('is_sure', 0)->get();
$count = count($results);
$this->info('共有 ' . $count . ' 条可取消的记录');
try {
DB::beginTransaction();
if (!empty($results)) {
$i = 1;
foreach ($results as $result) {
$this->info('执行第 ' . $i . ' 条记录');
C2cDeal::cancelLegalDealById($result->id, AccountLog::C2C_DEAL_AUTO_CANCEL);
$i++;
}
}
DB::commit();
$this->info('执行成功');
} catch (\Exception $exception) {
DB::rollback();
$this->error($exception->getMessage());
}
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\LegalDeal;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoCancelLegal extends Command
{
protected $signature = "auto_cancel_legal";
protected $description = "自动取消 24 小时法币交易";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$now = Carbon::now();
$this->info('开始执行自动取消法币交易脚本-' . $now->toDateTimeString());
$twenty_four = $now->subHours(24)->timestamp;
$results = LegalDeal::where('create_time', '<=', $twenty_four)->where('is_sure', 0)->get();
$count = count($results);
$this->info('共有 ' . $count . ' 条超时记录');
DB::beginTransaction();
try {
if (!empty($results)) {
$i = 1;
foreach ($results as $result) {
$this->info('执行第 ' . $i . ' 条记录');
LegalDeal::cancelLegalDealById($result->id, AccountLog::LEGAL_DEAL_AUTO_CANCEL);
$i++;
}
}
DB::commit();
$this->info('执行成功');
} catch (\Exception $exception) {
DB::rollback();
$this->error($exception->getMessage());
}
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace App\Console\Commands;
use App\AutoList;
use App\CurrencyQuotation;
use App\MarketHour;
use App\Setting;
use App\TransactionComplete;
use App\UsersWallet;
use Carbon\Carbon;
use Faker\Factory;
use App\Users;
use App\DualCurrency;
use App\DualOrder;
use App\AccountLog;
use App\Currency;
use Illuminate\Support\Facades\Cache;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoDualOrder extends Command
{
protected $signature = "auto_dual_order";
protected $description = "结算双币订单";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$nowday = date('Ymd',time());
// ->where('startdate','<=',date('Y-m-d',time()))
// where('expire','>=',date('Y-m-d',time()))
$dual_orderend = DualOrder::where('expire','<=',date('Y-m-d H:i:s',time()))->where('status',0)->where('today','<>',$nowday)->get();
foreach ($dual_orderend as $dual_order){
$DualCurrency = DualCurrency::where('id',$dual_order->dual_id)->first();
$currency_id = $DualCurrency->currency_id;
$exercise_price = $DualCurrency->exercise_price;
$type = $DualCurrency->type;
$now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价
$amount = $dual_order->amount;
$totalincome = $dual_order->totalincome;
$rates = explode('-',$dual_order->rate);
$rate = DualOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数
$dual_order->todayincome = bcdiv($rate*$amount,100,2);
$dual_order->totalincome = $totalincome+$dual_order->todayincome;
// $money = $amount + $totalincome+$dual_order->todayincome;
$money = $amount + $dual_order->todayincome;
$user_walllet=UsersWallet::where("user_id",$dual_order->user_id)->where("currency",3)->first();
change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_DUAL_ORDER_RETURN,'组合投资理财结算');// . $user_walllet->name
$data['user_id'] = $dual_order->user_id;
$data['order_id'] = $dual_order->id;
$data['day'] = $dual_order->day;
$data['rate'] = $dual_order->order_rate;
$data['amount'] = $dual_order->todayincome;
$data['addtime'] = time();
DB::table('dual_list')->insert($data);
$dual_order->status = 1; //修改状态为已结算
$dual_order->today = $nowday;
$dual_order->save();
}
$dual_orders = DualOrder::where('startdate','<=',date('Y-m-d H:i:s',time()))->where('expire','>',date('Y-m-d H:i:s',time()))->where('today','<>',$nowday)->where('status',0)->get();
foreach ($dual_orders as $dual_order){
$DualCurrency = DualCurrency::where('id',$dual_order->dual_id)->first();
$currency_id = $DualCurrency->currency_id;
$exercise_price = $DualCurrency->exercise_price;
$type = $DualCurrency->type;
$now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价
$amount = $dual_order->amount;
$dual_order->startdate = date('Y-m-d H:i:s',strtotime($dual_order->startdate)+86400);
// $id = $dual_order->id;
$today = $dual_order->today;
$totalincome = $dual_order->totalincome;
// $rate = $dual_order->order_rate;
$rates = explode('-',$dual_order->rate);
$rate = DualOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数
$dual_order->todayincome = bcdiv($rate*$amount,100,2);
$dual_order->totalincome = $totalincome+$dual_order->todayincome;
$money = $dual_order->todayincome;
$user_walllet=UsersWallet::where("user_id",$dual_order->user_id)->where("currency",3)->first();
change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_DUAL_ORDER_RETURN,'组合投资理财结算');// . $user_walllet->name
$data['user_id'] = $dual_order->user_id;
$data['order_id'] = $dual_order->id;
$data['day'] = $dual_order->day;
$data['rate'] = $dual_order->order_rate;
$data['amount'] = $money;
$data['addtime'] = time();
DB::table('dual_list')->insert($data);
$dual_order->today = $nowday;
$dual_order->save();
}
echo '已结算 '.PHP_EOL;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Console\Commands;
use App\AutoList;
use App\CurrencyQuotation;
use App\MarketHour;
use App\Setting;
use App\TransactionComplete;
use App\UsersWallet;
use Carbon\Carbon;
use Faker\Factory;
use App\Users;
use App\DualCurrency;
use App\DualOrder;
use App\AccountLog;
use App\Currency;
use Illuminate\Support\Facades\Cache;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoLixi extends Command
{
protected $signature = "auto_lixi";
protected $description = "结算量化本息";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$nowday = date('Ymd',time());
// ->where('startdate','<=',date('Y-m-d',time()))
// where('expire','>=',date('Y-m-d',time()))
$dual_orderend = UsersWallet::where('micro_balance','>',0)->where('today','<>',$nowday)->get();
foreach ($dual_orderend as $dual_order){
$amount = $dual_order->micro_balance;
$rates = 0.6;
// $rate = DualOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数
$money = bcdiv($rates*$amount,100,2);
$user_walllet=UsersWallet::where("user_id",$dual_order->user_id)->where("currency",3)->first();
change_wallet_balance($user_walllet , 4 , $money , AccountLog::USER_DUAL_ORDER_RETURN,'earned by currency');// . $user_walllet->name
// $dual_order->status = 1; //修改状态为已结算
$dual_order->today = $nowday;
$dual_order->save();
}
echo '已结算 '.PHP_EOL;
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Console\Commands;
use App\AutoList;
use App\CurrencyQuotation;
use App\MarketHour;
use App\Setting;
use App\TransactionComplete;
use App\UsersWallet;
use Carbon\Carbon;
use Faker\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AutoOrder extends Command
{
protected $signature = "auto_order {id : id}";
protected $description = "机器人自动下单";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$id = $this->argument('id');
$faker = Factory::create();
DB::beginTransaction();
try {
while (!empty($auto = AutoList::find($id))) {
if (empty($auto->is_start)) {
DB::rollback();
return $this->error('机器人已关闭-' . Carbon::now()->toDateTimeString());
break;
} else {
$this->info('开启机器人-' . Carbon::now()->toDateTimeString());
$price_area = AutoList::getPriceArea($auto->currency_id, $auto->legal_id);
if (!empty($price_area)) {
$this->info('当前价格区间为 ' . $price_area['min'] . '-' . $price_area['max']);
$this->info('设置价格区间为 ' . $auto->min_price . '-' . $auto->max_price);
if ($auto->min_price <= $price_area['min'] && $auto->max_price >= $price_area['max']) {
$new_complete = new TransactionComplete();
$new_complete->user_id = $auto->buy_user_id;
$new_complete->from_user_id = $auto->sell_user_id;
$new_complete->price = $faker->randomFloat(2, $price_area['min'], $price_area['max']);
$new_complete->number = $faker->randomFloat(2, $auto->min_number, $auto->max_number);
$new_complete->create_time = time();
$new_complete->currency = $auto->currency_id;
$new_complete->legal = $auto->legal_id;
$new_complete->save();
$buy_wallet_legal = UsersWallet::where('user_id', $auto->buy_user_id)->where('currency', $auto->legal_id)->lockForUpdate()->first();
if (!empty($buy_wallet_legal)) {
$legal_decrement = bc_mul($new_complete->number, $new_complete->price, 5);
$buy_wallet_legal->decrement('legal_balance', $legal_decrement);
}
$buy_wallet = UsersWallet::where('user_id', $auto->buy_user_id)->where('currency', $auto->currency_id)->lockForUpdate()->first();
if (!empty($buy_wallet)) {
$buy_wallet->increment('change_balance', $new_complete->number);
}
$sell_wallet_legal = UsersWallet::where('user_id', $auto->sell_user_id)->where('currency', $auto->legal_id)->lockForUpdate()->first();
if (!empty($sell_wallet_legal)) {
$legal_increment = bc_mul($new_complete->number, $new_complete->price, 5);
$sell_wallet_legal->increment('legal_balance', $legal_increment);
}
$sell_wallet = UsersWallet::where('user_id', $auto->sell_user_id)->where('currency', $auto->currency_id)->lockForUpdate()->first();
if (!empty($sell_wallet)) {
$sell_wallet->decrement('change_balance', $new_complete->number);
}
$this->info($auto->legal_name . '/' . $auto->currency_name . ' 生成价格为 ' . $new_complete->price . ' 数量为 ' . $new_complete->number . ' 的交易记录-' . Carbon::now()->toDateTimeString());
$total = TransactionComplete::where('currency', $auto->currency_id)->where('legal', $auto->legal_id)->where('create_time', '>=', strtotime(date('Y-m-d')))->sum('number');
$data = ['legal_id' => $auto->legal_id, 'currency_id' => $auto->currency_id, 'volume' => $total, 'now_price' => $new_complete->price];
CurrencyQuotation::updateTodayPriceTable($data);
MarketHour::batchWriteMarketData($auto->currency_id, $auto->legal_id, $new_complete->number, $new_complete->price, 4);
DB::commit();
}
} else {
DB::rollback();
return $this->error('没有当前价格区间');
}
sleep($auto->need_second);
}
}
} catch (\Exception $exception) {
DB::rollback();
return $this->error($exception->getMessage());
}
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Setting;
use App\Users;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class BonusAlgorithm extends Command
{
protected $signature = "bonus_algorithm";
protected $description = "奖金算法";
protected $user_bonus = array();
protected $ecology_bonus = array();
public function handle()
{
$user_bonus = Setting::getValueByKey("user_bonus");
$ecology_bonus = Setting::getValueByKey("ecology_bonus");
if (empty($user_bonus) || empty($ecology_bonus)) {
$this->comment("后台奖金设置错误");
exit;
}
$this->user_bonus = @json_decode($user_bonus, true);
$this->ecology_bonus = @json_decode($ecology_bonus, true);
$users = Users::get();
$this->comment("奖金算法start");
foreach ($users as $u) {
if ($u->balance > 0) {
$this->setUserBonus($u);
}
}
foreach ($users as $s) {
if ($s->level == Users::USER_LEVEL_ORDINARY) {
$this->setEcologyBonus($s);
}
}
foreach ($users as $a) {
if ($a->level > Users::USER_LEVEL_ORDINARY) {
$this->setAgentReward($a);
}
}
$this->comment("奖金算法end");
}
public function setAgentReward($user)
{
if (empty($user)) {
return false;
}
DB::beginTransaction();
try {
$son = Users::where("parent_id", $user->id)->get();
$money = 0;
if (!empty($son)) {
foreach ($son as $s) {
$money_g = $this->getSonBonus($s) * $this->getProportion($user->level, $s->level);
$money = $money + $money_g;
}
}
if (!empty($money)) {
$user->sub_balance = $user->sub_balance + $money;
$user->save();
AccountLog::insertLog(array("user_id" => $user->id, "value" => $money, "type" => AccountLog::AGENT_REWARD, "info" => "代理商管理奖励"));
$this->comment($user->id . ":代理商管理奖励" . $money);
}
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
public function getProportion($self_level, $level)
{
if (empty($self_level) || empty($level)) {
return 0.05;
}
$difference = $self_level - $level;
if ($difference <= 0 || $difference > 5) {
return 0.05;
} else {
return $difference * 0.05;
}
}
public function getSonBonus($user)
{
if (empty($user)) {
return 0;
}
$son = Users::getSon($user->id);
$time = time();
$start_time = $time - 3600;
$user_arr = array();
array_push($user_arr, $user->id);
if (!empty($son)) {
foreach ($son as $s) {
array_push($user_arr, $s["user_id"]);
}
}
$user_bonus = AccountLog::where("type", AccountLog::USER_BONUS)->whereIn("user_id", $user_arr)->where("created_time", ">", $start_time)->sum("value");
$ecology_bonus = AccountLog::where("type", AccountLog::ECOLOGY_BONUS)->whereIn("user_id", $user_arr)->where("created_time", ">", $start_time)->sum("value");
return $user_bonus + $ecology_bonus;
}
public function setEcologyBonus($user)
{
if (empty($user)) {
return false;
}
DB::beginTransaction();
$son = Users::getSonId($user->id);
$time = time();
$start_time = $time - 3600;
$money = 0;
try {
if (!empty($son)) {
foreach ($son as $s) {
$log = AccountLog::where("type", AccountLog::USER_BONUS)->where("user_id", $s["user_id"])->where("created_time", ">", $start_time)->first();
if (!empty($log)) {
foreach ($this->ecology_bonus as $eb) {
if (!empty($eb["one"]) && !empty($eb["two"]) && !empty($eb["three"]) && !empty($eb["four"])) {
if ($eb["one"] <= $user->balance && $user->balance < $eb["two"]) {
$interest_rate = $s["level"] == 1 ? $eb["three"] : $eb["four"];
$interest_rate = $interest_rate / 100;
$money = $money + $log->value * $interest_rate;
break 1;
}
}
}
}
}
}
if ($money > 0) {
$user->sub_balance = $user->sub_balance + $money;
$user->save();
AccountLog::insertLog(array("user_id" => $user->id, "value" => $money, "type" => AccountLog::ECOLOGY_BONUS, "info" => "生态推广奖励增加"));
$this->comment($user->id . ":生态推广奖励增加" . $money);
}
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
public function setUserBonus($user)
{
if (empty($user)) {
return false;
}
DB::beginTransaction();
try {
foreach ($this->user_bonus as $ub) {
if (!empty($ub["one"]) && !empty($ub["two"]) && !empty($ub["three"])) {
if ($ub["one"] <= $user->balance && $user->balance < $ub["two"]) {
$money = $user->balance * ($ub["three"] / 100);
$user->sub_balance = $user->sub_balance + $money;
$user->save();
AccountLog::insertLog(array("user_id" => $user->id, "value" => $money, "type" => AccountLog::USER_BONUS, "info" => "日均收益增加"));
$this->comment($user->id . ":日均收益增加" . $money);
break 1;
}
}
}
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Console\Commands;
use App\C2cDeal;
use App\Users;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\C2cDealSend;
use App\Setting;
use App\LegalDeal;
class CancelC2ctime extends Command
{
protected $signature = "cancel:c2cdeal";
protected $description = "c2c取消订单倒计时";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$now = Carbon::now();
$this->comment('开始执行自动取消C2C交易脚本-' . $now->toDateTimeString());
$userLegalDealCancel_time = Setting::getValueByKey("userLegalDealCancel_time") * 60;
$result = LegalDeal::where("is_sure", 0)->get();
foreach ($result as $key => $value) {
$time = time();
$create_time = strtotime($value->create_time);
if ($create_time + $userLegalDealCancel_time <= $time) {
$id = $value->id;
if ($value->is_sure == 0) {
LegalDeal::cancelLegalDealById($id);
$aaaa = Users::find($value->user_id);
$aaaa->today_LegalDealCancel_num = $aaaa->today_LegalDealCancel_num + 1;
$aaaa->LegalDealCancel_num__update_time = time();
$aaaa->save();
} else {
return $this->error('该订单状态不能取消');
}
}
}
$this->comment('执行成功');
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\UsersWallet;
use App\Setting;
use App\Utils\RPC;
use App\Currency;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class CollectToken extends Command
{
protected $signature = "collect_token{currency_id : id}";
protected $description = "收集代币";
protected $contract_address = "";
protected $total_account_address = "";
protected $total_account_key = "";
protected $currency_type = "";
protected $decimal_scale = 18;
public function handle()
{
$currency_id = $this->argument('currency_id');
$currency = Currency::find($currency_id);
$contract_address = $currency->contract_address;
$total_account_address = $currency->total_account;
$total_account_key = $currency->key;
$currency_type = $currency->type;
$this->decimal_scale = $currency->decimal_scale;
if (empty($contract_address) || empty($total_account_address) || empty($total_account_key)) {
$this->comment("后台账号设置错误");
exit;
}
$this->contract_address = $contract_address;
if ($currency_type == 'erc20') {
$this->total_account_address = substr($total_account_address, 2);
} else {
$this->total_account_address = $total_account_address;
}
$this->total_account_key = $total_account_key;
$this->currency_type = $currency_type;
$datas = UsersWallet::where('currency', $currency_id)->get();
$this->comment("start");
foreach ($datas as $d) {
$this->collectToken($d);
}
$this->comment("end");
}
public function collectToken($data)
{
if ($this->currency_type == 'btc') {
return false;
}
if (empty($data->address)) {
return false;
}
$address = $data->address;
if ($this->currency_type == 'eth') {
$url = "https://api.etherscan.io/api?module=account&action=balance&address=" . $address . "&tag=latest&apikey=579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45" . rand(1, 10000);
} else {
$url = "https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=" . $this->contract_address . "&address=" . $address . "&tag=latest&apikey=579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45" . rand(1, 1000);
}
$content = RPC::apihttp($url);
if (!$content) {
return false;
}
DB::beginTransaction();
try {
$content = json_decode($content, true);
if (isset($content["message"]) && $content["message"] == "OK") {
$lessen = bc_pow(10, $this->decimal_scale);
$chain_balance = bc_div($content["result"], $lessen);
if ($chain_balance > 0) {
if ($this->currency_type == 'eth') {
$content["result"] = $content["result"] / 1000000000000000000;
$content['result'] -= 0.001;
$address_url = 'http://47.92.171.137:8999/web3/transfer?toaddress=' . $this->total_account_address . '&from_address=' . $address . '&transfer_value=' . $content["result"] . '&privates=' . decrypt($data->private);
} else {
$address_url = "http://47.92.171.137:8999/web3/transfer/oec?is_new=1&toaddress=" . $this->total_account_address . "&transfer_value=" . $content["result"] . "&contract_address=" . $this->contract_address . "&fromeaddress=" . $address . "&privates=" . decrypt($data->private) . '&decimal_scale=' . $this->decimal_scale;
}
$lian = RPC::apihttp($address_url);
$lian = @json_decode($lian, true);
if ($lian["error"] == "0") {
$data->old_balance = 0;
$data->save();
AccountLog::insertLog(array("user_id" => 99999, "value" => $content["result"], "type" => AccountLog::ETH_EXCHANGE, "info" => $data->user_id . "归拢", 'currency' => $data->currency));
$this->comment($this->total_account_address . "user_id:" . $lian["content"]);
} else {
$this->comment('请求地址:');
dump($address_url);
$this->comment('请求响应:');
dump($lian);
$this->comment("请重试" . $lian["error"]);
}
} else {
$this->comment($content["result"]);
}
} else {
$this->comment($content);
}
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Console\Commands;
use App\Currency;
use App\Setting;
use App\Users;
use App\UsersWallet;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class ExecuteCurrency extends Command
{
protected $signature = "execute_currency {id : id}";
protected $description = "上币执行脚本";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$id = $this->argument('id');
try {
$is_execute = Setting::getValueByKey('currency_' . $id, 0);
if ($is_execute == 1) {
throw new \Exception('该币上币脚本正在运行中,请不要重复执行');
}
Setting::updateValueByKey('currency_' . $id, 1);
$currency = Currency::find($id);
if (empty($currency)) {
throw new \Exception('币种不存在');
}
if (!in_array($currency->type, ['btc', 'usdt', 'eth', 'erc20', 'xrp'])) {
throw new \Exception('不支持的币种');
}
$address_url = '/v3/wallet/address';
$project_name = config('app.name');
$http_client = app('LbxChainServer');
$this->info('开始执行按币种生成钱包脚本--' . Carbon::now()->toDateTimeString());
$user_query = Users::whereNotExists(function ($query) use($id) {
$query->select(DB::raw(1))->from('users_wallet')->where('currency', $id)->whereRaw('users_wallet.user_id = users.id');
});
$count = $user_query->count();
$this->info('共有 ' . $count . ' 个用户需要添加新的钱包地址');
$i = 1;
foreach ($user_query->cursor() as $user) {
if (UsersWallet::where('user_id', $user->id)->where('currency', $id)->exists()) {
$this->error('第 ' . $i . '/' . $count . ' 个用户有此币种钱包,用户 id 为:' . $user->id);
continue 1;
}
$this->info('开始生成第 ' . $i . '/' . $count . ' 个用户的钱包地址,用户 id 为:' . $user->id);
$response = $http_client->post($address_url, ['form_params' => ['userid' => $user->id, 'projectname' => $project_name]]);
$result = json_decode($response->getBody()->getContents());
if ($result->code != 0) {
return false;
}
$walllet_data = $result->data;
if ($currency->type == 'btc') {
$address = $walllet_data->btc_address;
$private = $walllet_data->btc_private;
} elseif ($currency->type == 'usdt') {
$address = $walllet_data->usdt_address;
$private = $walllet_data->usdt_private;
} elseif ($currency->type == 'eth') {
$address = $walllet_data->eth_address;
$private = $walllet_data->eth_private;
} elseif ($currency->type == 'erc20') {
$address = $walllet_data->erc20_address;
$private = $walllet_data->erc20_private;
} elseif ($currency->type == 'xrp') {
$address = $walllet_data->xrp_address;
$private = $walllet_data->xrp_private;
} else {
$this->error('暂不支持生成该币种的钱包');
continue 1;
}
UsersWallet::unguarded(function () use($address, $private, $user, $currency) {
UsersWallet::create(['user_id' => $user->id, 'currency' => $currency->id, 'address' => $address, 'private' => $private, 'create_time' => time()]);
});
$i++;
}
Setting::updateValueByKey('currency_' . $id, 0);
$this->info('执行成功');
} catch (\Exception $exception) {
return $this->error($exception->getMessage());
}
}
}
+226
View File
@@ -0,0 +1,226 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\CurrencyMatch;
use App\UsersWallet;
use Illuminate\Console\Command;
use App\Follow;
use App\Users;
use App\LeverTransaction;
use Illuminate\Support\Facades\DB;
class FollowCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'follow';
/**
* The console command description.
*
* @var string
*/
protected $description = '处理跟单';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Follow::query()
->where('status', 1)
->chunkById(50, function ($items) {
$items->each(function ($follow) {
$this->handleFollow($follow);
});
});
}
protected function handleFollow($follow)
{
//查看跟随的用户是否为交易员
$is_trader = Users::where('id', $follow->follow_user_id)->value('is_trader');
if ($is_trader != 1) {
$this->cancelFollow($follow->id);
return false;
}
$transaction = LeverTransaction::query()
->where([
'user_id' => $follow->follow_user_id,
'status' => 1
])
->where('create_time', '>=', strtotime($follow->created_at))
->get();
foreach ($transaction as $val) {
//查询是否已存在该订单的跟单
$exists_follow_order = LeverTransaction::query()
->where('user_id', $follow->user_id)
->where('follow_order_id', $val->id)
->where('follow_user_id', $follow->follow_user_id)
->exists();
//不存在则添加
if (!$exists_follow_order) {
$this->generateFollowOrder($val, $follow);
}
}
}
/**
* 生成跟随订单
*
* @param $order
* @param $follow
* @return false|void
*/
protected function generateFollowOrder($order, $follow)
{
try {
$order = $order->getOriginal();
$currency_match = CurrencyMatch::where('legal_id', $order['legal'])
->where('currency_id', $order['currency'])
->first();
if (!$currency_match) { //指定交易对不存在
throw new \Exception("指定交易对不存在");
}
if ($currency_match->open_lever != 1) { //未开通本交易对的交易功能
throw new \Exception("未开通本交易对的交易功能");
}
$follow_order = $order;
$follow_order['order_type'] = 2;
$follow_order['follow_user_id'] = $order['user_id'];
$follow_order['follow_order_id'] = $order['id'];
$follow_order['user_id'] = $follow->user_id;
$follow_order['status'] = LeverTransaction::TRANSACTION;
if ($follow->type == 1) {//跟随类型:1固定比例跟随 2固定手数跟随
$number = bc_mul($order['number'], $follow->number, 2);
$number = $number <= 1 ? 1 : $number;
} else {
$number = $follow->number;
}
//算法参考:App\Http\Controllers\Api\LeverController->submit()
$all_money = bc_mul($order['price'], $number);
$caution_money = bc_div($all_money, $order['multiple']); //保证金
//计算手续费
$lever_trade_fee_rate = bc_div($currency_match->lever_trade_fee ?? 0, 100);
$trade_fee = bc_mul($all_money, $lever_trade_fee_rate); //手续费
$follow_order['share'] = $number;
$follow_order['number'] = $number;
$follow_order['origin_caution_money'] = $caution_money;
$follow_order['caution_money'] = $caution_money;
$follow_order['trade_fee'] = $trade_fee;
//追加用户的代理商关系
$user = Users::query()->where('id', $follow->user_id)->first(['agent_path']);
$follow_order['agent_path'] = $user->agent_path;
DB::beginTransaction();
$legal = UsersWallet::where("user_id", $follow->user_id)
->where("currency", $order['legal'])
->lockForUpdate()
->first();
if (!$legal) {
throw new \Exception("该用户对应钱包未找到");
}
$user_lever = $legal->lever_balance;
$shoud_deduct = bc_add($caution_money, $trade_fee); //保证金+手续费
if (bc_comp($user_lever, $shoud_deduct) < 0) {
throw new \Exception($currency_match->legal_name . '余额不足,不能小于:' . $shoud_deduct . '(手续费:' . $trade_fee . ')');
}
unset($follow_order['id']);
$lever_transaction = LeverTransaction::query()->create($follow_order);
//扣除保证金
$result = change_wallet_balance(
$legal,
4,
-$caution_money,
AccountLog::LEVER_TRANSACTION_DEDUCT_CAUTION,
'跟随购买 ' . $currency_match->symbol . ' 杠杆交易,价格' . $order['price'] . ',扣除保证金',
false,
0,
0,
serialize([
'trade_id' => $lever_transaction->id,
'all_money' => $all_money,
'multiple' => $order['multiple'],
])
);
if ($result !== true) {
throw new \Exception('扣除保证金失败:' . $result);
}
//扣除手续费
$result = change_wallet_balance(
$legal,
4,
-$trade_fee,
AccountLog::LEVER_TRANSACTION_TRADE_FEE,
'跟随购买 ' . $currency_match->symbol . ' 杠杆交易,扣除手续费',
false,
0,
0,
serialize([
'trade_id' => $lever_transaction->id,
'all_money' => $all_money,
'lever_trade_fee_rate' => $lever_trade_fee_rate,
])
);
if ($result !== true) {
throw new \Exception('扣除手续费失败:' . $result);
}
DB::commit();
dump("跟随订单已生成,ID{$lever_transaction->id}");
} catch (\Throwable $ex) {
DB::rollBack();
$msg = "跟随者用户id{$follow->user_id},跟随订单id{$order['id']}" . $ex->getMessage();
$this->writeLog($msg);
dump($msg);
return false;
}
}
//取消跟随
protected function cancelFollow($follow_id)
{
Follow::where('id', $follow_id)->update([
'status' => 2
]);
}
/**
* 写日志
* @param $msg
*/
protected function writeLog($msg)
{
$path = base_path() . '/storage/logs/follow/';
$filename = 'FollowCommand-' . date('Ymd') . '.log';
file_exists($path) || @mkdir($path);
error_log(date('Y-m-d H:i:s') . ' ' . $msg . PHP_EOL, 3, $path . $filename);
}
}
+220
View File
@@ -0,0 +1,220 @@
<?php
namespace App\Console\Commands;
use App\MarketHour;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCESS_KEY') or define('ACCESS_KEY', 'e480c999-bgbfh5tv3f-7a172162-43c3b'); // 你的ACCESS_KEY
class GHK extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'get_h_kline {period} {size}';
/**
* The console command description.
*
* @var string
*/
protected $description = '获取K线图数据';
private $url = 'https://api.huobi.pro';//'https://api.huobi.pro';
private $api = '';
public $api_method = '';
public $req_method = '';
public $period ;
public $size;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
global $argv;
parent::__construct();
// var_dump(ACCESS_KEY);exit;
if(!array_key_exists(2,$argv) || ! array_key_exists(3,$argv)){
return;
}
$this->period = $argv[2];
$this->size = $argv[3];
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
//拼接所有的交易对
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
// echo ("begin2");
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar_a['currency_name'] = $item['name'];
$ar_a['quote_name'] = $legal['name'];
$ar[] = $ar_a;
}
}
}
foreach ($ar as $vv) {
if (in_array($vv["name"], array("btcusdt", "ethusdt", "ltcusdt", "bchusdt", "eosusdt", "etcusdt", "xrpusdt", "htusdt", "qtumusdt", "iotausdt", "neousdt", "nasusdt", "elausdt", "sntusdt", "wiccusdt", "adausdt", "xemusdt", "ruffusdt", "zilusdt", "dtausdt",'usdcusdt','shibusdt'))) {
// if (in_array($vv["name"], array("btcusdt","ethusdt","ltcusdt"))) {
// if (in_array($vv["name"], array("btcusdt"))) {
$ar_new[] = $vv;
}
}
foreach ($ar_new as $it) {
$data = $this->get_history_kline($it['name'], $this->period, $this->size);
if ($data) {
} else {
// echo ("重新采集\n\r");
// sleep(5);
continue;
}
if ($data['status'] != 'ok') {
// echo ("begin6");
// var_dump($data);
$this->error('请求失败');
continue;
}
$list = $data['data'];
foreach($list as $value){
$data = [
'id' => $value['id'],
'period' => $this->period,
'base-currency' => strtoupper($it['currency_name']),
'quote-currency' => strtoupper($it['quote_name']),
'open' => $value['open'],
'close' => $value['close'],
'high' => $value['high'],
'low' => $value['low'],
'vol' => $value['vol'],
'amount' => $value['amount'],
];
MarketHour::setEsearchMarket($data);
}
}
}
/**对象转数组
* @param $obj
* @return mixed
*/
public function object2array($obj){
return json_decode( json_encode( $obj),true);
}
//科学计算发转字符串
public function sctonum($num, $double = 8){
if(false !== stripos($num, "e")){
$a = explode("e",strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
}else{
return $num;
}
}
// /**
// * 行情类API
// */
// // 获取K线数据
public function get_history_kline($symbol = '', $period='',$size=0) {
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = [
'symbol' => $symbol,
'period' => $period
];
if ($size) $param['size'] = $size;
$url = $this->create_sign_url($param);
// echo $url;exit;
return json_decode($this->curl($url) , TRUE);
}
// /**
// * 类库方法
// */
// // 生成验签URL
public function create_sign_url($append_param = []) {
// 验签参数
$param = [
'AccessKeyId' => '89fcab07-1hrfj6yhgg-ae50f8cf-6c7db',
'SignatureMethod' => 'HmacSHA256',
'SignatureVersion' => 2,
'Timestamp' => date('Y-m-d\TH:i:s', time())
];
if ($append_param) {
foreach($append_param as $k=>$ap) {
$param[$k] = $ap;
}
}
return $this->url.$this->api_method.'?'.$this->bind_param($param);
}
// // 组合参数
function bind_param($param) {
$u = [];
$sort_rank = [];
foreach($param as $k=>$v) {
$u[] = $k."=".urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=".urlencode($this->create_sig($u));
return implode('&', $u);
}
// // 生成签名
function create_sig($param) {
$sign_param_1 = $this->req_method."\n".$this->api."\n".$this->api_method."\n".implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, '88dd5bbe-1799f6a1-e2a33400-924b1', true);
return base64_encode($signature);
}
public function curl($url,$postdata=[]) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_TIMEOUT,60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt ($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
+243
View File
@@ -0,0 +1,243 @@
<?php
namespace App\Console\Commands;
use App\Currency;
use App\UserChat;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline extends Command
{
protected $signature = "get_kline_data";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
while (true) {
try {
echo "开始推送\r\n";
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
echo "begin2";
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
echo "开始遍历币种\r\n";
foreach ($ar as $vv) {
if (in_array($vv["name"], array("shibusdt", "goldusdt", "uncusdt", "grtcusdt", "tonusdt"))) {
$ar_new[] = $vv;
}
}
// file_put_contents("ar_new.txt", json_encode($ar_new) . PHP_EOL, FILE_APPEND);
foreach ($ar_new as $it) {
echo "遍历币种开始\r\n";
$data = array();
echo "开始请求\r\n";
$data = $this->get_history_kline($it['name'], '1min', 1);
if ($data) {
} else {
// file_put_contents("test1.txt", $it['name']. PHP_EOL, FILE_APPEND);
echo "重新采集\r\n";
continue 2;
}
echo "请求结束\r\n";
if ($data['status'] != 'ok') {
echo "begin6";
$this->error('请求失败');
continue 2;
}
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('type', 5)->where('period', '1min')->where('sign', 2)->first();
if ($insert_instance) {
echo "begin7";
$this->error('指定时间行情已存在,直接跳过');
continue 2;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 5;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '1min';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
$update_Data = [];
$update_Data['currency_id'] = $it['currency_id'];
$update_Data['legal_id'] = $it['legal_id'];
$update_Data['now_price'] = $this->sctonum($info['close']);
$update_Data['add_time'] = time();
$update_Data['volume'] = '0.00000';
$update_Data['change'] = '+0.00';
$time = strtotime(date("Y-m-d"));
$day_Data = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('period', '1day')->where('sign', 2)->where('day_time', '<=', $time)->where('end_price', '>', '0.00000')->orderby('id', 'DESC')->first();
if (!empty($day_Data)) {
$_zero_price = $day_Data->end_price;
} else {
$_zero_price = 0;
}
$update_Data['volume'] = DB::table('market_hour')->where('day_time', '>', $time)->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('period', '1min')->where('sign', 2)->sum('number');
switch (bccomp($update_Data['now_price'], $_zero_price, 5)) {
case 1:
if ($_zero_price === 0) {
$update_Data['change'] = '+0.000';
} else {
$a = bcsub($update_Data['now_price'], $_zero_price, 5);
$_pencet_num = bcdiv($a, $_zero_price, 5);
$update_Data['change'] = '+' . bcmul($_pencet_num, 100, 3);
}
break 3;
case 0:
$update_Data['change'] = '+0.000';
break 3;
case -1:
if ($_zero_price === 0) {
$update_Data['change'] = '+0.000';
} else {
$a = bcsub($_zero_price, $update_Data['now_price'], 5);
$_pencet_num = bcdiv($a, $_zero_price, 5);
$update_Data['change'] = '-' . bcmul($_pencet_num, 100, 3);
}
break 3;
default:
$update_Data['change'] = '+0.000';
}
$que_data = DB::table('currency_quotation')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->orderby('id', 'DESC')->first();
if (!empty($que_data)) {
DB::table('currency_quotation')->where('id', $que_data->id)->update($update_Data);
} else {
DB::table('currency_quotation')->insert($update_Data);
}
$currency = Currency::find($it['currency_id']);
$legal = Currency::find($it['legal_id']);
$update_Data['currency_name'] = $currency->name;
$update_Data['legal_name'] = $legal->name;
$update_Data['type'] = 'daymarket';
$update_Data['high'] = $insert_Data['highest'];
$update_Data['low'] = $this->sctonum($info['low']);
$update_Data['symbol'] = $currency->name . '/' . $legal->name;
echo "begin8";
$new_data = ['type' => 'kline', 'period' => $insert_Data['period'], 'currency_id' => $insert_Data['currency_id'], 'currency_name' => $currency->name, 'legal_id' => $insert_Data['legal_id'], 'legal_name' => $legal->name, 'symbol' => $currency->name . '/' . $legal->name, 'open' => $insert_Data['start_price'], 'close' => $insert_Data['end_price'], 'high' => $insert_Data['highest'], 'low' => $insert_Data['mminimum'], 'volume' => $insert_Data['number'], 'time' => $insert_Data['day_time'] * 1000];
echo "开始推送\r\n";
print_r($update_Data);
UserChat::sendChat($update_Data);
UserChat::sendChat($new_data);
unset($currency);
unset($legal);
echo "遍历币种结束\r\n";
}
sleep(5);
} catch (Exception $e) {
}
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
echo "获取K线数据\r\n";
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
file_put_contents("log.txt", $url . PHP_EOL, FILE_APPEND);
echo "获取K线数据结束\r\n";
return json_decode($this->curl($url), true);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
public function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
public function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
echo "curl开始\r\n";
$start = microtime(true);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if (empty($output)) {
echo "curl没有采集到\r\n";
}
echo "curl结束\r\n";
$end = microtime(true);
file_put_contents("haoshi.txt", $end - $start . PHP_EOL, FILE_APPEND);
return $output;
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline_Daily extends Command
{
protected $signature = "get_kline_data_daily";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
$kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE);
if ($kko['status'] == 'ok') {
$trade = [];
foreach ($kko['data'] as $key => $value) {
$trade[] = $value['symbol'];
}
foreach ($ar as $it) {
if (in_array($it['name'], $trade)) {
$data = array();
$data = $this->get_history_kline($it['name'], '1day', 1);
if ($data['status'] == 'ok') {
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '1day')->where('sign', 2)->where('type', 4)->first();
if (!empty($insert_instance)) {
continue 1;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 4;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '1day';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
}
}
}
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
return json_decode($this->curl($url), TRUE);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline_FifteenMin extends Command
{
protected $signature = "get_kline_data_fifteenmin";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
$kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE);
if ($kko['status'] == 'ok') {
$trade = [];
foreach ($kko['data'] as $key => $value) {
$trade[] = $value['symbol'];
}
foreach ($ar as $it) {
if (in_array($it['name'], $trade)) {
$data = array();
$data = $this->get_history_kline($it['name'], '15min', 1);
if ($data['status'] == 'ok') {
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '15min')->where('sign', 2)->where('type', 1)->first();
if (!empty($insert_instance)) {
continue 1;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 1;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '15min';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
}
}
}
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
return json_decode($this->curl($url), TRUE);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline_Hourly extends Command
{
protected $signature = "get_kline_data_hourly";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
$kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE);
if ($kko['status'] != 'ok') {
return false;
}
$trade = array_column($kko['data'], 'symbol');
foreach ($ar as $it) {
if (!in_array($it['name'], $trade)) {
continue 1;
}
$data = array();
$data = $this->get_history_kline($it['name'], '60min', 1);
if ($data['status'] != 'ok') {
continue 1;
}
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '60min')->where('sign', 2)->where('type', 2)->first();
if (!empty($insert_instance)) {
continue 1;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 2;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '60min';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
return json_decode($this->curl($url), TRUE);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
+148
View File
@@ -0,0 +1,148 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline_Monthly extends Command
{
protected $signature = "get_kline_data_monthly";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
$kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE);
if ($kko['status'] == 'ok') {
$trade = [];
foreach ($kko['data'] as $key => $value) {
$trade[] = $value['symbol'];
}
foreach ($ar as $it) {
if (in_array($it['name'], $trade)) {
$data = array();
$data = $this->get_history_kline($it['name'], '1mon', 1);
if ($data['status'] == 'ok') {
$info = $data['data'][0];
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '1mon')->where('sign', 2)->where('type', 9)->first();
if (!empty($insert_instance)) {
continue 1;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 9;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '1mon';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
}
}
}
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
return json_decode($this->curl($url), TRUE);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline_ThirtyMin extends Command
{
protected $signature = "get_kline_data_thirtymin";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
$kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE);
if ($kko['status'] == 'ok') {
$trade = [];
foreach ($kko['data'] as $key => $value) {
$trade[] = $value['symbol'];
}
foreach ($ar as $it) {
if (in_array($it['name'], $trade)) {
$data = array();
$data = $this->get_history_kline($it['name'], '30min', 1);
if ($data['status'] == 'ok') {
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '30min')->where('sign', 2)->where('type', 7)->first();
if (!empty($insert_instance)) {
continue 1;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 7;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '30min';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
}
}
}
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
return json_decode($this->curl($url), TRUE);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline_Weekly extends Command
{
protected $signature = "get_kline_data_weekly";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
$kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE);
if ($kko['status'] == 'ok') {
$trade = [];
foreach ($kko['data'] as $key => $value) {
$trade[] = $value['symbol'];
}
foreach ($ar as $it) {
if (in_array($it['name'], $trade)) {
$data = array();
$data = $this->get_history_kline($it['name'], '1week', 1);
if ($data['status'] == 'ok') {
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '1week')->where('sign', 2)->where('type', 8)->first();
if (!empty($insert_instance)) {
continue 1;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 8;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '1week';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
}
}
}
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
return json_decode($this->curl($url), TRUE);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
+146
View File
@@ -0,0 +1,146 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
defined('SECRET_KEY') || define('SECRET_KEY', '');
class GetKline_FiveMin extends Command
{
protected $signature = "get_kline_data_fivemin";
protected $description = "获取K线图数据";
private $url = "https://api.huobi.br.com";
private $api = "";
public $api_method = "";
public $req_method = "";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$all = DB::table('currency')->where('is_display', '1')->get();
$all_arr = $this->object2array($all);
$legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get();
$legal_arr = $this->object2array($legal);
$ar = [];
foreach ($legal_arr as $legal) {
foreach ($all_arr as $item) {
if ($legal['id'] != $item['id']) {
$ar_a = [];
$ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']);
$ar_a['currency_id'] = $item['id'];
$ar_a['legal_id'] = $legal['id'];
$ar[] = $ar_a;
}
}
}
$kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE);
if ($kko['status'] != 'ok') {
return false;
}
$trade = array_column($kko['data'], 'symbol');
foreach ($ar as $it) {
if (in_array($it['name'], $trade)) {
$data = array();
$data = $this->get_history_kline($it['name'], '5min', 1);
if ($data['status'] != 'ok') {
continue 1;
}
$info = $data['data'][0];
$insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '5min')->where('sign', 2)->where('type', 6)->first();
if (!empty($insert_instance)) {
continue 1;
}
$insert_Data = array();
$insert_Data['currency_id'] = $it['currency_id'];
$insert_Data['legal_id'] = $it['legal_id'];
$insert_Data['start_price'] = $this->sctonum($info['open']);
$insert_Data['end_price'] = $this->sctonum($info['close']);
$insert_Data['mminimum'] = $this->sctonum($info['low']);
$insert_Data['highest'] = $this->sctonum($info['high']);
$insert_Data['type'] = 6;
$insert_Data['sign'] = 2;
$insert_Data['day_time'] = $info['id'];
$insert_Data['period'] = '5min';
$insert_Data['number'] = bcmul($info['amount'], 1, 5);
$insert_Data['mar_id'] = $info['id'];
DB::table('market_hour')->insert($insert_Data);
echo 'five min done';
}
}
}
public function object2array($obj)
{
return json_decode(json_encode($obj), true);
}
public function sctonum($num, $double = 8)
{
if (false !== stripos($num, "e")) {
$a = explode("e", strtolower($num));
return bcmul($a[0], bcpow(10, $a[1], $double), $double);
} else {
return $num;
}
}
public function get_history_kline($symbol = '', $period = '', $size = 0)
{
$this->api_method = "/market/history/kline";
$this->req_method = 'GET';
$param = ['symbol' => $symbol, 'period' => $period];
if ($size) {
$param['size'] = $size;
}
$url = $this->create_sign_url($param);
return json_decode($this->curl($url), TRUE);
}
public function create_sign_url($append_param = [])
{
$param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())];
if ($append_param) {
foreach ($append_param as $k => $ap) {
$param[$k] = $ap;
}
}
return $this->url . $this->api_method . '?' . $this->bind_param($param);
}
function bind_param($param)
{
$u = [];
$sort_rank = [];
foreach ($param as $k => $v) {
$u[] = $k . "=" . urlencode($v);
$sort_rank[] = ord($k);
}
asort($u);
$u[] = "Signature=" . urlencode($this->create_sig($u));
return implode('&', $u);
}
function create_sig($param)
{
$sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param);
$signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true);
return base64_encode($signature);
}
public function curl($url, $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->req_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $output;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use App\Market;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class GetMarket extends Command
{
protected $signature = "get_market";
protected $description = "获取行情";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$opts = ["http" => ["method" => "GET", "header" => "Accepts: application/json\r\n" . "X-CMC_PRO_API_KEY: 8c89b9cf-8fcb-4f2a-bac1-c93295b72074\r\n"]];
$context = stream_context_create($opts);
$file = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=1,2', false, $context);
$coin_list = json_decode($file, true);
DB::beginTransaction();
try {
if (!empty($coin_list['data'])) {
foreach ($coin_list['data'] as $row) {
$market = Market::find($row['id']);
if (empty($market)) {
$market = new Market();
}
$market->id = $row['id'];
$market->name = $row['name'];
$market->symbol = $row['symbol'];
$market->rank = $row['cmc_rank'];
$market->circulating_supply = $row['circulating_supply'];
$market->total_supply = $row['total_supply'];
$market->max_supply = $row['max_supply'];
$market->quotes = serialize($row['quote']);
$market->last_updated = $row['last_updated'];
$market->save();
}
DB::commit();
echo 111;
$message = '请求接口成功,并更新数据库->' . date('Y-m-d H:i:s');
$this->info($message);
} else {
echo 222;
$message = '请求数据接口失败,无数据->' . date('Y-m-d H:i:s');
$this->info($message);
}
} catch (\Exception $exception) {
DB::rollback();
echo 333;
$message = $exception->getMessage() . '->' . date('Y-m-d H:i:s');
$this->info($message);
}
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Setting;
use App\Users;
use App\HistoricalData;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class HistoricalDatas extends Command
{
protected $signature = "historical_data";
protected $description = "历史数据";
public function handle()
{
DB::beginTransaction();
try {
$day = intval(date("d", time()));
$week = date("w");
$yesterday_start = date("Y-m-d", strtotime("-1 day"));
$yesterday_start = strtotime($yesterday_start);
$yesterday_end = $yesterday_start + 86400;
$aaa = HistoricalData::insertData($yesterday_start, $yesterday_end);
if ($week == "1") {
$week_start = date("Y-m-d", strtotime("last Monday"));
$week_start = strtotime($week_start);
HistoricalData::insertData($week_start, time(), "week");
}
if ($day == 1) {
$month_start = date("Y-m-d", strtotime("last month"));
$month_start = strtotime($month_start);
HistoricalData::insertData($month_start, time(), "month");
}
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\MarketHour;
use Elasticsearch\ClientBuilder;
use App\CurrencyMatch;
class ImportMarketFromEsearch extends Command
{
protected $signature = "market:import";
protected $description = "Command description";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$from_host = ['http://mhy.happyawn.com:9200', '39.109.113.168:9200'];
$to_host = ['45.192.181.101:9200'];
$from_host = ['host' => '39.109.113.168:9200'];
$to_host = ['host' => '45.192.181.101:9200'];
$from_client = self::getEsearchClient($from_host);
$to_client = self::getEsearchClient($to_host);
$huobi_matchs = CurrencyMatch::getHuobiMatchs();
$from = 1543593600;
$to = 1545235200;
foreach ($huobi_matchs as $key => $match) {
$base_currency = $match->currency_name;
$quote_currency = $match->legal_name;
$type = strtoupper($base_currency . '.' . $quote_currency) . '.1day';
$result = self::getEsearchMarket($from_client, $base_currency, $quote_currency, '1day', $from, $to);
$params = [];
foreach ($result as $key => $value) {
$params['body'][] = ['index' => ['_index' => 'market.kline', '_type' => $type]];
$params['body'][] = $value;
}
$result = $to_client->bulk($params);
var_dump($result);
}
}
public static function getEsearchClient($hosts)
{
$es_client = ClientBuilder::create()->setHosts($hosts)->build();
return $es_client;
}
public static function getEsearchMarket($es_client, $base_currency, $quote_currency, $peroid, $from, $to)
{
$size = 0;
$base_currency = strtoupper($base_currency);
$quote_currency = strtoupper($quote_currency);
$interval_list = ["1min" => 60, "5min" => 300, "15min" => 900, "30min" => 1800, "60min" => 3600, "1hour" => 3600, "1day" => 86400, "1week" => 604808, "1mon" => 2592000, "1year" => 31536000];
$interval = $interval_list[$peroid];
$size = intval(($to - $from) / $interval) + 100;
$type = $base_currency . '.' . $quote_currency . '.' . $peroid;
$params = ['index' => 'market.kline', 'type' => $type, 'body' => ['query' => ['bool' => ['filter' => ['range' => ['id' => ['gte' => $from, 'lte' => $to]]]]], 'sort' => ['id' => ['order' => 'asc']], 'size' => $size]];
$result = $es_client->search($params);
if (isset($result['hits'])) {
$data = array_column($result['hits']['hits'], '_source');
} else {
$data = [];
}
return $data;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\LeverTransaction;
use App\UsersWallet;
use App\AccountLog;
use App\Setting;
class Insurancemoney extends Command
{
protected $signature = "insurance_money";
protected $description = "持币生币";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$today = strtotime(date('Y-m-d'));
$count = UsersWallet::where('lock_insurance_balance', '>', 0)->count();
if ($count <= 0) {
$this->info(date('Y-m-d H:i:s') . ' 没有要执行的任务');
return;
}
$this->info(date('Y-m-d H:i:s') . ' 共' . $count . '个任务');
$insurance_money_rate = Setting::getValueByKey('insurance_money_rate', 1);
foreach (UsersWallet::where('lock_insurance_balance', '>', 0)->cursor() as $w) {
try {
DB::beginTransaction();
$lock = $w->lock_insurance_balance;
$return = bc_mul($lock, bc_div($insurance_money_rate, 100));
$res = change_wallet_balance($w, 5, $return, AccountLog::INSURANCE_MONEY, "用户持险生币", false);
if ($res !== true) {
throw new \Exception($res);
}
DB::commit();
$this->info($w->id . ':执行成功');
} catch (\Exception $e) {
DB::rollBack();
$this->comment($w->id . '失败:' . $e->getMessage());
}
}
$this->info(date('Y-m-d H:i:s') . ' 全部执行完成');
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Setting;
use App\Users;
use App\LhDepositOrder;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class LHDisptchInterest extends Command
{
protected $signature = "lhdispatch_interest";
protected $description = "锁仓派息";
protected $lock_daily_return = "";
public function handle()
{
$res = LhDepositOrder::where([
'status' => 1,
])->where('start_at','<',date("Y-m-d"))
->where('last_settle_time','<',date("Y-m-d"))
->orWhere('last_settle_time',null)
->take(500) ->get();
$this->comment("start");
foreach($res as $order){
LhDepositOrder::dispatchInterest($order->id);
}
$this->comment("end");
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Setting;
use App\Users;
use App\UsersWallet;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class Locking extends Command
{
protected $signature = "locking";
protected $description = "锁定任务";
protected $lock_daily_return = "";
public function handle()
{
$lock_daily_return = Setting::getValueByKey("lock_daily_return");
if (empty($lock_daily_return)) {
$this->comment("后台设置错误");
exit;
}
$this->lock_daily_return = $lock_daily_return;
$datas = UsersWallet::where("remain_lock_balance", ">", 0)->where("lock_balance", ">", 0)->get();
$this->comment("start");
foreach ($datas as $d) {
$this->lockingMethod($d);
}
$this->comment("end");
}
public function lockingMethod($data)
{
if (empty($data)) {
return false;
}
$user = Users::find($data->user_id);
if (empty($user)) {
return false;
}
$money = $data->lock_balance * $this->lock_daily_return / 100;
if ($money >= $data->remain_lock_balance) {
$money = $data->remain_lock_balance;
$data->remain_lock_balance = 0;
} else {
$data->remain_lock_balance = $data->remain_lock_balance - $money;
}
if ($money == 0) {
return false;
}
DB::beginTransaction();
try {
$data->balance = $data->balance + $money;
$data->save();
AccountLog::insertLog(array("user_id" => $data->user_id, "value" => $money, "type" => AccountLog::LOCK_BALANCE, "info" => "释放余额增加"));
AccountLog::insertLog(array("user_id" => $data->user_id, "value" => -1 * $money, "type" => AccountLog::LOCK_REMAIN_BALANCE, "info" => "锁仓减少"));
$this->comment("锁仓改变:" . $data->user_id);
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
}
File diff suppressed because one or more lines are too long
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Users;
use App\UsersWallet;
class MakeWallet extends Command
{
protected $signature = "make:wallet {user_id? : user_id} {--operate=single : the operation type:all,single}";
protected $description = "生成钱包";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$userId = $this->argument('user_id');
$operateName = $this->option('operate');
if ($operateName == 'all') {
$this->info("给全部用户生成钱包");
Users::chunk(1000, function ($users) {
foreach ($users as $key => $user) {
UsersWallet::makeWallet($user->id);
$this->info('用户id' . $user->id . '生成钱包完成');
}
});
} elseif ($operateName == 'single') {
$this->info("给单个用户生成钱包");
$user = Users::getById($userId);
if (empty($user)) {
$this->info("错误的用户id");
} else {
$res = UsersWallet::makeWallet($userId);
if ($res) {
$this->info("用户" . $user->id . ",生成成功!");
} else {
$this->error("用户" . $user->id . ",生成失败!");
}
}
} else {
$this->error("参数错误");
return;
}
$this->info('全部生成完成');
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Setting;
use App\Users;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class MonitorEthLog extends Command
{
protected $signature = "monitor_eth_log";
protected $description = "监听以太坊账号";
protected $rate_exchange = 0;
protected $last_hash = "";
protected $company_eth_address = "";
public function handle()
{
$this->rate_exchange = Setting::getValueByKey("rate_exchange", 10);
$this->last_hash = Setting::getValueByKey("last_hash");
$this->company_eth_address = Setting::getValueByKey("company_eth_address");
if (empty($this->company_eth_address)) {
$this->comment("公司以太坊地址为空");
exit;
}
$this->comment("start");
$this->getEthLog();
$this->comment("end");
}
public function getEthLog($page = 1)
{
$parameter = array("module" => "account", "action" => "txlist", "address" => $this->company_eth_address, "startblock" => "0", "endblock" => "99999999", "page" => $page, "offset" => "10", "sort" => "desc", "apikey" => "579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45");
$data = RPC::http_post("https://api.etherscan.io/api", $parameter);
$jsonInfo = @json_decode($data, true);
if (!empty($jsonInfo)) {
if ($jsonInfo["status"] == "1" && $jsonInfo["message"] == "OK") {
$continue = false;
if (count($jsonInfo["result"]) > 0) {
if (count($jsonInfo["result"]) == 10) {
$continue = true;
}
foreach ($jsonInfo["result"] as $j) {
if ($j["hash"] == $this->last_hash) {
$continue = false;
break 1;
} else {
if ($j["to"] == $this->company_eth_address && $j["value"] > 0) {
$user = Users::where('eth_address', $j["from"])->first();
if (!empty($user)) {
$this->updateUserBalance($user, $j);
}
}
}
}
}
if ($continue) {
$this->getEthLog($page + 1);
}
} else {
$this->comment($jsonInfo["message"]);
$this->comment($jsonInfo["result"]);
}
}
}
public function updateUserBalance($user, $info = array())
{
if (empty($user) || empty($info)) {
return false;
}
DB::beginTransaction();
try {
$balance = $info["value"] / 10000000000000 * $this->rate_exchange;
$user->balance = $user->balance + $balance;
if ($user->balance >= 5000000 && $user->level != Users::USER_LEVEL_LARGEAREA_AGENT) {
$user->level = Users::USER_LEVEL_LARGEAREA_AGENT;
} elseif ($user->balance >= 3000000 && $user->level < Users::USER_LEVEL_PROVINCIAL_AGENT) {
$user->level = Users::USER_LEVEL_PROVINCIAL_AGENT;
} elseif ($user->balance >= 2000000 && $user->level < Users::USER_LEVEL_CITY_AGENT) {
$user->level = Users::USER_LEVEL_CITY_AGENT;
} elseif ($user->balance >= 1000000 && $user->level < Users::USER_LEVEL_COUNTY_AGENT) {
$user->level = Users::USER_LEVEL_COUNTY_AGENT;
}
$user->save();
$this->updateParentLevel($user);
AccountLog::insertLog(array("user_id" => $user->id, "value" => $balance, "type" => AccountLog::ETH_EXCHANGE, "info" => $info["hash"]));
Setting::updateValueByKey("last_hash", $info["hash"]);
$this->comment($user->id . ":增加有效可用余额" . $balance);
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
public function updateParentLevel($user)
{
if (empty($user) || empty($user->parent_id)) {
return false;
}
$parent = Users::find($user->parent_id);
if (empty($parent)) {
return false;
}
if ($parent->level < Users::USER_LEVEL_LARGEAREA_AGENT) {
$min_count = 0;
$min_money = 0;
if ($parent->level == Users::USER_LEVEL_PROVINCIAL_AGENT) {
$min_count = 3;
$min_money = 100000;
} elseif ($parent->level == Users::USER_LEVEL_CITY_AGENT) {
$min_count = 4;
$min_money = 10000;
} elseif ($parent->level == Users::USER_LEVEL_COUNTY_AGENT) {
$min_count = 5;
$min_money = 10000;
} elseif ($parent->level == Users::USER_LEVEL_GROUP) {
$min_count = 6;
$min_money = 10000;
} elseif ($parent->level == Users::USER_LEVEL_ORDINARY) {
$min_count = 8;
$min_money = 5000;
}
$count = Users::where("parent_id", $parent->id)->where("level", $parent->level)->where("balance", ">=", $min_money)->count();
if ($count >= $min_count) {
$parent->level = $parent->level + 1;
$parent->save();
}
}
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\LeverTransaction;
use App\UsersWallet;
use App\AccountLog;
class OvernightFee extends Command
{
protected $signature = "lever:overnight";
protected $description = "杠杆交易隔夜费";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$today = strtotime(date('Y-m-d'));
$count = LeverTransaction::where('create_time', '<', $today)->where('status', LeverTransaction::TRANSACTION)->count();
if ($count <= 0) {
$this->info(date('Y-m-d H:i:s') . ' 没有要执行的任务');
return;
}
$this->info(date('Y-m-d H:i:s') . ' 共' . $count . '个任务');
$current = 0;
LeverTransaction::where('create_time', '<', $today)->where('status', LeverTransaction::TRANSACTION)->chunk(100, function ($lever_transactions) use(&$current) {
try {
foreach ($lever_transactions as $key => $trade) {
$current = $current + 1;
$this->info('正在执行第' . $current . '个任务');
DB::transaction(function () use($trade) {
$trade->refresh();
if ($trade->status != LeverTransaction::TRANSACTION) {
throw \Exception('交易状态异常');
}
$profit = $trade->profits;
$overnight_rate = bc_div($trade->overnight, 100);
$trade_money = bc_mul($trade->price, $trade->number);
$overnight_fee = bc_mul($trade_money, $overnight_rate);
$caution_money = $trade->caution_money;
$wallet_money = 0;
$user_wallet = UsersWallet::where('user_id', $trade->user_id)->where('currency', $trade->legal)->lockForUpdate()->first();
$user_wallet && ($wallet_money = $user_wallet->lever_balance);
$subtotal = bc_add($wallet_money, $caution_money);
if (bc_comp($subtotal, $overnight_fee) < 0) {
if (bc_comp($profit, $overnight_fee) < 0) {
}
}
if (bc_comp($trade->caution_money, $overnight_fee) >= 0) {
$caution_should_deduct = $overnight_fee;
$balance_should_deduct = 0;
} else {
$caution_should_deduct = $caution_money;
$balance_should_deduct = bc_sub($overnight_fee, $caution_should_deduct);
}
$extra_data = serialize(['trade_id' => $trade->id, 'trade_money' => $trade_money, 'overnight_rate' => $overnight_rate, 'overnight_fee' => $overnight_fee, 'caution_deduct' => $caution_should_deduct, 'balance_deduct' => $balance_should_deduct]);
$result = change_wallet_balance($user_wallet, 4, -1 * $balance_should_deduct, AccountLog::LEVER_TRANSACTION_OVERNIGHT, '杠杆交易id:' . $trade->id . ',收取隔夜费:' . $overnight_fee . '(从保证金扣除:' . $caution_should_deduct . ',从余额扣除:' . $balance_should_deduct . ')', false, 0, 0, $extra_data, true, true);
if ($result !== true) {
throw new \Exception($result);
}
$trade->caution_money = bc_sub($caution_money, $caution_should_deduct);
$trade->overnight_money = bc_add($trade->overnight_money, $overnight_fee);
$result = $trade->save();
if (!$result) {
throw new \Exception('从交易保证金扣除隔夜费失败');
}
});
}
} catch (\Exception $e) {
throw $e;
}
});
$this->info(date('Y-m-d H:i:s') . ' 全部执行完成');
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\UsersWallet;
use App\Currency;
class RegenerateWallet extends Command
{
protected $signature = "regenerate:wallet {id : id}";
protected $description = "重新生成钱包";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$id = $this->argument('id');
$currency = Currency::find($id);
if (!$currency) {
throw new \Exception('币种不存在');
}
$http_client = app('LbxChainServer');
$wallets = UsersWallet::where('currency', $id)->get();
$wallets->each(function ($item, $key) use($currency, $http_client) {
$response = $http_client->request('post', '/v3/wallet/address', ['form_params' => ['userid' => $item->user_id, 'projectname' => 'new_bvex']]);
$result = json_decode($response->getBody()->getContents());
if (isset($result->code) && $result->code != 0) {
echo '用户id:' . $item->user_id . ',请求失败' . PHP_EOL;
return;
}
$result = $result->data;
echo '用户id:' . $item->user_id . ',原地址:' . $item->address;
if ($currency->type == 'btc') {
$item->address = $result->btc_address;
$item->private = $result->btc_private;
} elseif ($currency->type == 'usdt') {
$item->address = $result->usdt_address;
$item->private = $result->usdt_private;
} elseif ($currency->type == 'eth') {
$item->address = $result->eth_address;
$item->private = $result->eth_private;
} elseif ($currency->type == 'erc20') {
$item->address = $result->erc20_address;
$item->private = $result->erc20_private;
} elseif ($currency->type == 'xrp') {
$item->address = $result->xrp_address;
$item->private = $result->xrp_private;
} else {
return;
}
$item->save();
echo ',新地址:' . $item->address . PHP_EOL;
});
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RemoveQueue extends Command
{
protected $signature = "remove_queue";
protected $description = "定期移除积压任务";
public function handle()
{
$this->comment("start1");
$redis = \Illuminate\Support\Facades\Redis::connection();
$res = $redis->keys('queues:*');
foreach ($res as $v) {
if ($redis->type($v) == 'list' && $redis->llen($v) > 3000) {
$redis->del($v);
}
}
$this->comment("end");
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class ResetDatabase extends Command
{
protected $signature = "reset_database {force}";
protected $description = "清理数据库";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$force = $this->argument('force');
if ($force === 'yes') {
$needs_delete_table_arr = ['account_log', 'address', 'agent_log', 'agent_money_log', 'c2c_deal', 'c2c_deal_send', 'candy_transfer', 'conversion', 'failed_jobs', 'false_data', 'feedback', 'flash_against', 'historical_data', 'insurance_claim_applies', 'jobs', 'legal_deal', 'legal_deal_send', 'lever_transaction', 'micro_orders', 'seller', 'transaction', 'transaction_complete', 'transaction_in', 'transaction_out', 'user_algebra', 'user_cash_info', 'user_profiles', 'user_real', 'users_insurances', 'users_transfer_to_change', 'users_wallet_out', 'wallet_log'];
$retain_table = ['agent' => ['select_field' => 'user_id', 'retain_id' => [1]], 'users' => ['select_field' => 'id', 'retain_id' => [1]], 'users_wallet' => ['select_field' => 'user_id', 'retain_id' => [1]]];
foreach ($needs_delete_table_arr as $table) {
if (\Schema::hasTable($table)) {
DB::table($table)->delete();
}
}
foreach ($retain_table as $table_name => $table) {
DB::table($table_name)->whereNotIn($table['select_field'], $table['retain_id'])->delete();
}
$this->info('清理成功!');
} else {
$this->error('命令错误!');
}
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\DAO\FactprofitsDAO;
use Illuminate\Support\Facades\DB;
class ReturnProfit extends Command
{
protected $signature = "return:profit";
protected $description = "返还杠杆交易亏损";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$aaa = new FactprofitsDAO();
$all = DB::table('lever_transaction')->select("user_id")->groupBy('user_id')->get();
foreach ($all as $key => $value) {
var_dump($value->user_id);
var_dump($aaa::Profit_loss_release($value->user_id));
}
}
}
?>
@@ -0,0 +1,56 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\MicroOrder;
use App\UsersInsurance;
use App\UsersWallet;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class ReturnServiceCharge extends Command
{
protected $signature = "return_service_charge";
protected $description = "返还交易手续费用";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->comment('=========' . date('Y-m-d H:i:s') . "开始执行返还保险交易手续费=========");
$yesterday = Carbon::today()->toDateString();
MicroOrder::whereDate('created_at', $yesterday)->where('is_insurance', '>', 0)->where('return_at', null)->chunk(1000, function ($orders) {
foreach ($orders as $order) {
$user_id = $order->user_id;
$currency_id = $order->currency_id;
$service_charge = $order->fee;
$user_insurance = UsersInsurance::where('user_id', $user_id)->whereHas('insurance_type', function ($query) use($currency_id) {
$query->where('currency_id', $currency_id);
})->where('status', 1)->where('claim_status', 0)->first();
if (!$user_insurance) {
$this->error("user_id:" . $user_id . ",未找到生效保险");
continue 1;
}
$user_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->first();
if (!$user_wallet) {
$this->error("user_id:" . $user_id . "," . $currency_id . "钱包不存在。");
continue 1;
}
try {
DB::beginTransaction();
change_wallet_balance($user_wallet, 5, $service_charge, AccountLog::RETURN_INSURANCE_TRADE_FEE, '返还保险交易手续费', false);
$order->return_at = Carbon::now();
$order->save();
DB::commit();
$this->info("user_id:" . $user_id . ",返还保险交易手续费成功");
} catch (\Exception $e) {
DB::rollBack();
$this->error("user_id:" . $user_id . ",返还保险交易手续费失败:" . $e->getMessage());
}
}
});
$this->comment('=========' . date('Y-m-d H:i:s') . "执行返还保险交易手续费成功!=========");
}
}
+316
View File
@@ -0,0 +1,316 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\TransactionComplete;
use App\Transaction;
use App\UserChat;
use App\TransactionIn;
use App\TransactionOut;
use App\Users;
use App\UsersWallet;
use Faker\Factory;
use Illuminate\Console\Command;
use App\Robot as RobotModel;
use Illuminate\Support\Facades\Log;
defined('ACCOUNT_ID') or define('ACCOUNT_ID', '50154012'); // 你的账户ID
defined('ACCESS_KEY') or define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14'); // 你的ACCESS_KEY
defined('SECRET_KEY') or define('SECRET_KEY', ''); // 你的SECRET_KEY
class Robot extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'robot {id} {--mode=}';
/**
* The console command description.
*
* @var string
*/
protected $description = '匹配交易自动挂单机器人';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('--------------------------------------------------');
$this->info('开始执行机器人:' . now()->toDateTimeString());
$id = $this->argument('id');
while (true) {
$robotList = RobotModel::where('id','>',0)->get();
foreach($robotList as $robot){
if ($robot->status == RobotModel::STOP) {
$this->info('机器人已关闭');
break;
}
$this->info('当前交易对是:' . $robot->currency_info . '/' . $robot->legal_info);
$this->info('当前数量区间:' . $robot->number_min . '-' . $robot->number_max);
try {
if ($robot->sell == RobotModel::OPEN) {
$this->info('开始卖出');
$this->sell($robot, $robot->number_max, $robot->number_min);
}
if ($robot->buy == RobotModel::OPEN) {
$this->info('开始买入');
$this->buy($robot, $robot->number_max, $robot->number_min);
}
} catch (\Exception $e) {
$this->info($e->getMessage());
}
$complete = TransactionComplete::orderBy('id', 'desc')
->where("currency", $robot->currency_id)
->where("legal", $robot->legal_id)
->take(20)
->get();
$send = array(
"type" => "deal_list",
"currency_id" => $robot->currency_id,
"legal_id" => $robot->legal_id,
"complete" => $complete,
);
echo '开始发送';
UserChat::sendChat($send);
}
$robot = RobotModel::find($id);
// if (!$robot) {
// $this->info('找不到此机器人');
// break;
// }
sleep($robot->second);
}
$this->info('机器人执行结束:' . now()->toDateTimeString());
$this->info('--------------------------------------------------');
}
protected function sell($robot, $number_max, $number_min)
{
//随机数量
$num = $this->getNumber($number_min, $number_max);
$total_number = $num;
//随机价格
$price = $this->getPrice(strtolower($robot->currency_info . $robot->legal_info), $robot->float_number_down, $robot->float_number_up);
$user = Users::find($robot->sell_user_id);
$in = TransactionIn::where("price", ">=", $price)
->where("currency", $robot->currency_id)
->where("legal", $robot->legal_id)
->where("number", ">", "0")
->orderBy('price', 'desc')
->get();
$user_currency = UsersWallet::where("user_id", $robot->sell_user_id)
->where("currency", $robot->currency_id)
->first();
$has_num = 0;
if (!empty($in)) {
foreach ($in as $i) {
if ($has_num >= $num) break;
$shengyu_num = $num - $has_num;
$this_num = $i->number > $shengyu_num ? $this_num = $shengyu_num : $this_num = $i->number;
$has_num = $has_num + $this_num;
if ($this_num > 0) {
TransactionOut::transaction($i, $this_num, $user, $user_currency, $robot->legal_id, $robot->currency_id);
}
}
// Transaction::newDealList($robot->legal_id, $robot->currency_id);
}
$num = $num;//$num - $has_num;
if ($num > 0) {
$out = new TransactionOut();
$out->user_id = $robot->sell_user_id;
$out->price = $price;
$out->number = $num;
$out->total_number = $total_number;
$out->currency = $robot->currency_id;
$out->legal = $robot->legal_id;
$out->create_time = time();
$out->save();
// $user_currency->change_balance = $user_currency->change_balance - $num;
// $user_currency->lock_change_balance = $user_currency->lock_change_balance + $num;
// $user_currency->save();
AccountLog::insertLog([
'user_id' => $robot->sell_user_id,
'value' => -$num,
'info' => "提交卖出记录扣除",
'type' => AccountLog::TRANSACTIONOUT_SUBMIT_REDUCE
]);
}
Transaction::pushNews($robot->currency_id, $robot->legal_id);
}
protected function buy($robot, $number_max, $number_min)
{
//随机数量
$num = $this->getNumber($number_min, $number_max);
$total_number = $num;
//随机价格
$price = $this->getPrice(strtolower($robot->currency_info.$robot->legal_info), $robot->float_number_down, $robot->float_number_up);
$user = Users::find($robot->buy_user_id);
$has_num = 0;
$user_legal = UsersWallet::where("user_id", $robot->buy_user_id)->where("currency", $robot->legal_id)->first();
$out = TransactionOut::where("price", "<=", $price)
->where("number", ">", "0")
->where("currency", $robot->currency_id)
->where("legal", $robot->legal_id)
->orderBy('price', 'asc')
->get();
if (!empty($out)) {
foreach ($out as $o) {
if ($has_num < $num) {
$shengyu_num = $num - $has_num;
$this_num = 0;
if ($o->number > $shengyu_num) {
$this_num = $shengyu_num;
} else {
$this_num = $o->number;
}
$has_num = $has_num + $this_num;
if ($this_num > 0) {
// echo 333;
TransactionIn::transaction($o, $this_num, $user, $robot->legal_id, $robot->currency_id);
}
} else {
break;
}
}
// Transaction::newDealList($robot->legal_id, $robot->currency_id);
}else{
echo 'empty out';
}
$num = $num ;//- $has_num;
if ($num > 0) {
$in = new TransactionIn();
$in->user_id = $robot->buy_user_id;
$in->price = $price;
$in->number = $num;
$in->currency = $robot->currency_id;
$in->legal = $robot->legal_id;
$in->total_number = $total_number;
$in->create_time = time();
$in->save();
$all_balance = $price * $num;
// $user_legal->legal_balance = $user_legal->legal_balance - $all_balance;
// $user_legal->lock_legal_balance = $user_legal->lock_legal_balance + $all_balance;
// $user_legal->save();
AccountLog::insertLog([
'user_id' => $robot->buy_user_id,
'value' => -$all_balance,
'info' => "提交卖入记录扣除",
'type' => AccountLog::TRANSACTIONIN_SUBMIT_REDUCE
]);
}
// Transaction::pushNews($robot->currency_id, $robot->legal_id);
}
/**获取火币行情价格
*
* @param $symbol
* @param $float_number_down
* @param $float_number_up
*
* @return float
*/
public function getPrice($symbol, $float_number_down, $float_number_up)
{
$url = 'https://api.huobi.br.com/market/trade?symbol=' . $symbol;
$info = $this->curl($url);
$price = $info['tick']['data'][0]['price'];
$faker = Factory::create();
$price = $faker->randomFloat(2, $price - $float_number_down, $price + $float_number_up);
unset($faker);
return $price;
}
/**获取买入卖出随机数
*
* @param $number_min
* @param $number_max
*
* @return float
*/
public function getNumber($number_min, $number_max)
{
$faker = Factory::create();
$num = $faker->randomFloat(2, $number_min, $number_max);
unset($faker);
return $num;
}
public function curl($url, $type = 'GET', $postdata = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($type == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return @json_decode($output, true);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Currency;
use App\Level;
use App\Users;
use App\UsersWallet;
use App\Setting;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class Test extends Command
{
protected $signature = "Testtest";
protected $description = "测试";
public function handle()
{
$this->comment("start");
Users::rebate(357, 357, 3, 100, 1, 2);
$this->comment("end");
}
}
?>
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\TransferEths;
use App\UsersWallet;
use App\Setting;
use App\Currency;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class TransferEth extends Command
{
protected $signature = "transfer_eth{currency_id : id}";
protected $description = "批量转eth";
protected $contract_address = "";
protected $total_account_address = "";
protected $total_account_key = "";
protected $currency_type = "";
protected $eth_transfer_value = 0.001;
public function handle()
{
$currency_id = $this->argument('currency_id');
$currency = Currency::find($currency_id);
$contract_address = $currency->contract_address;
$total_account_address = $currency->total_account;
$total_account_key = $currency->key;
$currency_type = $currency->type;
if (empty($contract_address) || empty($total_account_address) || empty($total_account_key)) {
$this->comment("后台账号设置错误");
exit;
}
$this->contract_address = $contract_address;
$this->total_account_address = $total_account_address;
$this->total_account_key = $total_account_key;
$this->currency_type = $currency_type;
$datas = UsersWallet::where('currency', $currency_id)->get();
$this->comment("start");
foreach ($datas as $d) {
$this->transferEth($d);
}
$this->comment("end");
}
public function transferEth($data)
{
if ($this->currency_type != 'btc') {
if (!empty($data->address)) {
$address = $data->address;
if ($this->currency_type != 'erc20') {
return false;
}
$url = "https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=" . $this->contract_address . "&address=" . $address . "&tag=latest&apikey=579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45" . rand(1, 1000);
$content = RPC::apihttp($url);
if ($content) {
DB::beginTransaction();
try {
$content = json_decode($content, true);
var_dump($content);
if (isset($content["message"]) && $content["message"] == "OK") {
$content["result"] = $content["result"] / 1000000000000000000;
if ($content["result"] > 0) {
$transfer_url = "http://47.92.171.137:8999/web3/transfer?from_address=" . $this->total_account_address . "&toaddress=" . $address . "&transfer_value=" . $this->eth_transfer_value . "&privates=" . $this->total_account_key;
$transfer_content = RPC::apihttp($transfer_url);
$transfer_content = @json_decode($transfer_content, true);
if ($transfer_content["error"] == "0") {
AccountLog::insertLog(array("user_id" => 9999999, "value" => 0.001, "type" => AccountLog::ETH_EXCHANGE, "info" => $data->user_id . "打入ETH成功", 'currency' => $data->currency));
$this->comment($transfer_content["content"]);
$this->comment($data->user_id . "充值成功");
$wallet = UsersWallet::find($data->id);
$wallet->old_balance = $wallet->old_balance + 0.001;
$wallet->save();
} else {
$this->comment("请重试");
}
} else {
$this->comment($data->user_id . "没有代币");
}
}
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
$this->comment($ex->getMessage());
}
}
}
}
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\UsersWallet;
use App\Jobs\UpdateBalance as UpdateBalanceJob;
class UpdateBalance extends Command
{
protected $signature = "update_balance";
protected $description = "更新用户余额";
public function handle()
{
$this->comment("开始执行");
UsersWallet::chunk(100, function ($wallets) {
$wallets->each(function ($item, $key) {
UpdateBalanceJob::dispatch($item)->onQueue('update:block:balance');
});
});
$this->comment("执行完成");
}
}
?>
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Currency;
use App\Level;
use App\Users;
use App\UsersWallet;
use App\Setting;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UpdateFund extends Command
{
protected $signature = "update_user_fund";
protected $description = "更新资产";
public function handle()
{
$this->comment("start");
$user = Users::all();
if (count($user) != 0) {
foreach ($user as $v) {
$fund = $this->fund($v->id);
$v->fund = $fund;
$v->save();
}
}
$this->comment("end");
}
public function fund($user_id)
{
$currency = Currency::where('is_micro', 1)->get();
if (empty($currency)) {
return 0;
}
$price = 0;
foreach ($currency as $v) {
$user_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $v->id)->first();
if (!empty($user_wallet)) {
$fund = $user_wallet->micro_balance * $v->price;
$price += $fund;
}
}
return $price;
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Utils\RPC;
use App\{Currency, LbxHash, UsersWallet};
use App\DAO\BlockChain;
class UpdateHashStatus extends Command
{
protected $signature = "update_hash_status";
protected $description = "更新链上哈希状态";
public function handle()
{
$datas = LbxHash::whereIn('type', [0, 2])->where("status", 0)->get();
$this->comment("开始执行");
foreach ($datas as $d) {
$this->updateHashStatus($d);
}
$this->comment("结束任务");
}
public function updateHashStatus($data)
{
if (empty($data->txid)) {
return false;
}
echo 'id:' . $data->id . ',正在检测Hash:' . $data->txid . PHP_EOL;
try {
DB::beginTransaction();
$user_wallet = UsersWallet::lockForUpdate()->find($data->wallet_id);
$currency = Currency::find($user_wallet->currency);
if (empty($currency)) {
throw new \Exception('币种不存在');
}
$currency_type = $currency->type;
if (!in_array($currency_type, ['usdt', 'btc', 'eth', 'erc20'])) {
throw new \Exception('不支持的币种');
}
$currency_type == 'erc20' && ($currency_type = 'eth');
if ($data->type == 0) {
try {
BlockChain::updateWalletBalance($user_wallet);
} catch (\Exception $ex) {
echo $ex->getMessage() . PHP_EOL;
}
} elseif ($data->type == 2) {
if ($currency->type == 'usdt') {
$currency_type = 'btc';
} elseif ($currency->type == 'erc20') {
$currency_type = 'eth';
}
}
$chain_client = app('LbxChainServer');
$uri = "/wallet/" . $currency_type . '/tx';
$response = $chain_client->request('get', $uri, ['query' => ['hash' => $data->txid]]);
$result = $response->getBody()->getContents();
$result = json_decode($result, true);
file_exists(base_path('storage/logs/blockchain/')) || @mkdir(base_path('storage/logs/blockchain/'));
Log::useDailyFiles(base_path('storage/logs/blockchain/blockchain'), 7);
Log::critical($uri, $result);
if (isset($result["code"]) && $result["code"] == 0) {
if ($data->type == 0) {
$new_balance = bc_sub($user_wallet->old_balance, $data->amount);
$user_wallet->old_balance = bc_comp($new_balance, 0) > 0 ? $new_balance : 0;
} elseif ($data->type == 2) {
}
$data->status = 1;
$user_wallet->save();
} else {
if (isset($result["code"]) && $result["code"] > 1) {
$data->status = 2;
} else {
throw new \Exception('等待链上确认中');
}
}
$data->save();
DB::commit();
} catch (\Exception $ex) {
DB::rollBack();
$this->comment($ex->getFile());
$this->comment($ex->getLine());
$this->comment($ex->getMessage());
}
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Console\Commands;
use App\Utils\RPC;
use App\Users;
use App\UsersWallet;
use App\HuobiSymbol;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
class UpdateHuobiSymbol extends Command
{
protected $signature = "update_Huobi_Symbol";
protected $description = "更新火币交易对";
public function handle()
{
$this->comment("start1");
$url = 'api.huobi.br.com/v1/common/symbols';
$N2w8E = new Client();
$cli = $N2w8E;
$content = $cli->get($url)->getBody()->getContents();
$content = json_decode($content, true);
HuobiSymbol::getSymbolsData($content['data']);
$this->comment("end");
}
}
?>
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\{LeverTransaction};
use App\Jobs\LeverClose;
class UpdateLever extends Command
{
protected $signature = "remove_task";
protected $description = "移除积压任务";
public function handle()
{
$this->comment("开始任务");
\Illuminate\Support\Facades\Redis::del('queues:lever:update');
$this->comment("结束任务");
}
}
?>
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Console\Commands;
use App\News;
use App\UserReal;
use Illuminate\Console\Command;
class UpdateNews extends Command
{
protected $signature = "update_news";
protected $description = "更新项目的新闻";
public function __construct()
{
parent::__construct();
}
protected $searches = ["cfmcoin" => "toex"];
public function handle()
{
$news_list = News::get();
foreach ($news_list as $news) {
foreach ($this->searches as $k => $v) {
$news->content = str_replace($k, $v, $news->content);
$news->title = str_replace($k, $v, $news->title);
$news->keyword = str_replace($k, $v, $news->keyword);
$news->abstract = str_replace($k, $v, $news->abstract);
$news->thumbnail = str_replace($k, $v, $news->thumbnail);
$news->cover = str_replace($k, $v, $news->cover);
}
$news->save();
}
}
}
?>
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Users;
class UpdateParent extends Command
{
protected $signature = "update:parent";
protected $description = "更新用户上级";
public function __construct()
{
parent::__construct();
}
public function handle()
{
Users::where('type', 1)->chunk(10000, function ($users) {
foreach ($users as $key => $user) {
$parent = Users::where('origin_user_id', $user->origin_parent_id)->first();
if (!$parent) {
continue 1;
}
$user->parent_id = $parent->id;
$user->save();
$this->info('更新用户' . $user->id . '的上级完成');
}
});
$this->info('全部执行完成');
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace App\Console\Commands;
use App\Users;
use App\UsersWallet;
use Illuminate\Console\Command;
class UpdatePrivate extends Command
{
protected $signature = "update_private";
protected $description = "更新私钥以及钱包地址";
public function handle()
{
$this->comment("start1");
foreach (Users::cursor() as $user) {
echo $user->id . '--';
$n = 0;
$return = $this->updateWallet($user);
while (!$return && $n < 3) {
$n++;
$return = $this->updateWallet($user);
}
}
$this->comment("end");
}
public function updateWallet($user)
{
$address_url = '/v3/wallet/address';
$project_name = config('app.name');
$http_client = app('LbxChainServer');
$response = $http_client->post($address_url, ['form_params' => ['userid' => $user->id, 'projectname' => $project_name]]);
$result = json_decode($response->getBody()->getContents());
if (!isset($result->code) || $result->code != 0) {
$this->error('请求钱包接口发生异常');
return false;
}
$address = $result->data;
$wallets = UsersWallet::where('user_id', $user->id)->get();
foreach ($wallets as $wallet) {
if (empty($wallet->currencyCoin)) {
continue 1;
}
$currency_type = $wallet->currencyCoin->type;
if ($address) {
if ($currency_type == 'btc') {
$wallet->address = $address->btc_address;
$wallet->private = $address->btc_private;
} elseif ($currency_type == 'usdt') {
$wallet->address = $address->usdt_address;
$wallet->private = $address->usdt_private;
} elseif ($currency_type == 'eth') {
$wallet->address = $address->eth_address;
$wallet->private = $address->eth_private;
} elseif ($currency_type == 'erc20') {
$wallet->address = $address->erc20_address;
$wallet->private = $address->erc20_private;
} elseif ($currency_type == 'xrp') {
$wallet->address = $address->xrp_address;
$wallet->private = $address->xrp_private;
}
$wallet->save();
$this->comment("user_id:" . $wallet->user_id . ',' . $currency_type . '钱包私钥更新成功');
}
}
$this->comment("user_id:" . $wallet->user_id . '用户私钥更新成功!');
return true;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Console\Commands;
use App\AccountLog;
use App\Currency;
use App\Level;
use App\Users;
use App\UsersWallet;
use App\Setting;
use App\Utils\RPC;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UserLevel extends Command
{
protected $signature = "update_user_level";
protected $description = "更新级别";
public function handle()
{
$this->comment("start");
$level_one = new Level();
$l = $level_one->orderBy('level', 'desc')->first();
if (!empty($l)) {
$user = Users::where('level', '<', $l->level)->get();
if (count($user) == 0) {
$this->comment('没有用户可以升级');
}
$level = Level::all();
foreach ($user as $v) {
foreach ($level as $l) {
if ($l->level <= $v->level) {
continue 1;
} else {
if ($l->fill_currency != 0) {
if ($v->fund < $l->fill_currency) {
continue 1;
}
}
$count = Users::where('parent_id', $v->id)->where(function ($query) use($l) {
if ($l->direct_drive_price != 0) {
$query->where('fund', '>=', $l->direct_drive_price);
}
})->count('id');
if ($l->direct_drive_count != 0) {
if ($l->direct_drive_count > $count) {
continue 1;
}
}
$v->level = $l->level;
$v->save();
}
}
}
}
$this->comment("end");
}
public function fund($user_id)
{
$currency = Currency::where('is_micro', 1)->get();
if (empty($currency)) {
return 0;
}
$price = 0;
foreach ($currency as $v) {
$user_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency->id)->first();
if (!empty($user_wallet)) {
$fund = $user_wallet->micro_balance * $v->price;
$price += $fund;
}
}
return $price;
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Console\Commands;
use App\UserChat;
use Illuminate\Console\Command;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Worker;
use function foo\func;
class WebSocket extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'websocket {worker_command} {--mode=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'websocket';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
// $class_name = config('websocket.client.callback_class');
// $class_name = \App\Utils\Workerman\WorkerCallback::class;
// $process_num = config('websocket.client.process_num');
//// $process_num = 1;
// $this->callback_class = new $class_name();
// $this->worker = new Worker();
// $this->worker->count = $process_num;
// $this->worker->name = 'Huobi Websocket';
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// $this->initWorker();
// $this->bindEvent();
// $this->worker->runAll();
$worker = new Worker();
$worker->count = 1;
$worker->name = 'Huobi Websocketddd';
$worker->onWorkerStart = (function () {
$server_address = 'ws://api.huobi.pro:443/ws';
AsyncTcpConnection::$defaultMaxPackageSize = 1048576000;
$connection = new AsyncTcpConnection($server_address);
$connection->transport = 'ssl';
$connection->onConnect = (function ($con) {
$sub_data = json_encode([
'sub' => 'market.btcusdt.kline.1min',
'id' => 'market.btcusdt.kline.1min',
//'freq-ms' => 5000, //推送频率,实测只能是0和5000,与官网文档不符
]);
$con->send($sub_data);
});
$connection->onMessage = (function ($con, $data) {
$data = gzdecode($data);
$data = json_decode($data, false, 512, JSON_BIGINT_AS_STRING);
// var_dump($data);
// return;
if (isset($data->ping)) {
echo "回应ping\r\n";
$con->send(json_encode(['pong' => $data->ping]));
} else {
UserChat::sendText($data);
}
});
$connection->connect();
});
$worker->runAll();
}
protected function initWorker()
{
// global $argv;
// $argv[1] = $command = $this->argument('worker_command');
// $mode = $this->option('mode');
// isset($mode) && $argv[2] = '-' . $mode;
}
protected function bindEvent()
{
// foreach ($this->events as $key => $event) {
// method_exists($this->callback_class, $event) && $this->worker->$event = [$this->callback_class, $event];
// }
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Workerman\Worker;
class WebSocketClient extends Command
{
protected $signature = "websocket:client {worker_command} {--mode=}";
protected $description = "websocket client";
protected $worker;
protected $events = ["onWorkerStart", "onConnect", "onMessage", "onClose", "onError", "onBufferFull", "onBufferDrain", "onWorkerStop", "onWorkerReload"];
protected $callback_class;
public function __construct()
{
parent::__construct();
$class_name = config('websocket.client.callback_class');
$process_num = config('websocket.client.process_num');
$this->callback_class = new $class_name();
$this->worker = new Worker();
$this->worker->count = $process_num;
$this->worker->name = 'Huobi Websocket';
}
public function handle()
{
$this->initWorker();
$this->bindEvent();
$this->worker->runAll();
}
protected function initWorker()
{
global $argv;
$command = $this->argument('worker_command');
$argv[1] = $command;
$mode = $this->option('mode');
if ((bool) isset($mode)) {
$argv[2] = '-' . $mode;
}
}
protected function bindEvent()
{
foreach ($this->events as $key => $event) {
if ((bool) method_exists($this->callback_class, $event)) {
$this->worker->{$event} = [$this->callback_class, $event];
}
}
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Workerman\Worker;
class WebSocketClient extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'websocket:client {worker_command} {--mode=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'websocket client';
protected $worker;
protected $events = [
'onWorkerStart',
'onConnect',
'onMessage',
'onClose',
'onError',
'onBufferFull',
'onBufferDrain',
'onWorkerStop',
'onWorkerReload'
];
protected $callback_class;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$class_name = config('websocket.client.callback_class');
$class_name = \App\Utils\Workerman\WorkerCallback::class;
$process_num = config('websocket.client.process_num');
// $process_num = 8;
// $process_num = 1;
$this->callback_class = new $class_name();
$this->worker = new Worker();
$this->worker->count = $process_num;
$this->worker->name = 'Huobi Websocket';
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->initWorker();
$this->bindEvent();
$this->worker->runAll();
}
protected function initWorker()
{
global $argv;
$argv[1] = $command = $this->argument('worker_command');
$mode = $this->option('mode');
isset($mode) && $argv[2] = '-' . $mode;
}
protected function bindEvent()
{
foreach ($this->events as $key => $event) {
method_exists($this->callback_class, $event) && $this->worker->$event = [$this->callback_class, $event];
}
}
}