<?php

namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use Binance;

class TradeDetail extends BaseController
{
	public function __construct(){
		// $CommonModel = new CommonModel();
		$CommonModel = model('CommonModel');
			$validation =  \Config\Services::validation();

	$this->db = db_connect();
    $this->session = session();
	}
   public function index($id) {
   	$session = \Config\Services::session();
		if(!$session->get('user_login')){
			return redirect()->to(site_url('user/login'));
		}
		$this->indexpage($id);
    }
	
	public function indexpage($id) {


		$this->db = db_connect();
		$session = \Config\Services::session();
		if(!$session->get('user_login')){
			return redirect()->to(site_url('user/login'));
		}
        $CommonModel = model('CommonModel');
        $this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
	    $this->userdash_model = model('userdash_model');
	    $session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		//$this->db->query("SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");


		// $languageid = ($this->session->get('user_langid')) ? $this->session->get('user_langid'): '1';
		$condition = "payment_key in('logo','status')";
		$payment_data_list = $CommonModel->GetPaymentsName($condition);
		$site_data = $CommonModel->GetSettingall('infobox');
		if($site_data) {
			foreach ($site_data as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}

		} else {
			$site_data_default = $CommonModel->defaultlangSettingall('infobox');
			foreach ($site_data_default as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}
		}

		$site_lang_data = $CommonModel->GetSiteSettings('site');
		
		if($site_lang_data){	
			$site_data = array_merge($site_data, $site_lang_data);
		}

		foreach ($site_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}
		$session= \Config\Services::session();
	 	$uusersid=$session->get('uusersid');
		$condition = "uusersid ='".$uusersid."'";
		$this->data['user'] = $this->common_model->GetRow('user_strategy',$condition);


		if(!empty($this->request->getPost()))
		{			
			$margin_column_limit =$this->request->getPost('replenishment_time');
			$first_buy_amount=$this->request->getPost('first_buy_amount');
			$open_position_doubled=$this->request->getPost('open_position_doubled');
			$whole_profit_ratio=$this->request->getPost('whole_profit_ratio');
			$whole_profit_callback=$this->request->getPost('whole_profit_callback');
			$buyin_callback=$this->request->getPost('buyin_callback');
			$sub_position_callback=$this->request->getPost('sub_position_callback');
			
			$num=$margin_column_limit;
			for($i=0; $i < $num; $i++) 
			{					
				$trade1[$i]=$_POST["call_time".$i.""];
				$buyin_ratio_times[$i]=$_POST["order_time".$i.""];
			}
				
			if($num >= 5)
			{
				$j=0;
				for ($i=4; $i < $num; $i++) 
				{  
					$sub_positon[$i]=$_POST["rep_time".$j.""];
					$buyin_ratio_times[$i]=$_POST["order_time".$i.""];
					$j++;
					
				}

				$trade2 =array(implode(',',$buyin_ratio_times));		
				$trade3 =array(implode(',',$sub_positon));						
			}
			else
			{							
				$trade2 = $buyin_ratio_times;	
			}




			$tade1=implode(',',$trade1);
			$tade2=implode(',',$trade2);
			
			if($trade3)
			{
			 $tade3=implode(',',$trade3);
			}
			else
			{
			$tade3=0;
			}

			$session= \Config\Services::session();
	 		$uusersid=$session->get('uusersid');


			$condition1 = "uusersid ='".$uusersid."'";
			$user = $this->common_model->GetRow('user_strategy',$condition1);




			if($user=='')
			{
		 		$trade_data1=array(
		 			"uusersid"				=> $uusersid,
					"first_buy_amount" 		=>  $first_buy_amount,
			        "open_position_doubled" =>  $open_position_doubled,
			        "margin_column_limit" 	=>  $margin_column_limit,
			        "whole_profit_ratio"	=>  $whole_profit_ratio,
			        "whole_profit_callback" =>  $whole_profit_callback,
			        "buyin_callback" 		=>  $buyin_callback,
			        "margincall_drop"		=> 	$tade1,
			        "buyin_ratio_times"		=>	$tade2,
			        "sub_position"           => $tade3,
			        "sub_position_callback" =>  $sub_position_callback,
			        // "sync_strategy_status"	=>  0
				);

		    $this->db = db_connect();
			$session = session();
			$query_status = $this->db->table('user_strategy')->insert($trade_data1);
			if($query_status)
			{
				$session = \Config\Services::session();
				$session->setFlashData('success_message', 'Trader Settings Updated Successfully');
				
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', 'Trader Settings Updation Failed');
			}
			
		}
		else
		{
			$trade_data1=array(
			"first_buy_amount" 		=>  $first_buy_amount,
			"open_position_doubled" =>  $open_position_doubled,
			"margin_column_limit" 	=>  $margin_column_limit,
			"whole_profit_ratio"	=>  $whole_profit_ratio,
			"whole_profit_callback" =>  $whole_profit_callback,
			"buyin_callback" 		=>  $buyin_callback,
			"margincall_drop"		=> 	$tade1,
			"buyin_ratio_times"		=>	$tade2,
		    "sub_position"           => $tade3,
			"sub_position_callback" =>  $sub_position_callback,
			// "sync_strategy_status"	=>  0

			);


			$this->db = db_connect();
			$session = session();
        
      $check_pair_process =$this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and pair ='".$id."' order by id desc")->getRow();


	if($check_pair_process)
	{
	$query_status = $this->db->table('trade_process')->where('uusersid', $uusersid)->where('pair', $id)->update($trade_data1);
	}
	$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data1);

			if($query_status)
			{
				$session = \Config\Services::session();
				$session->setFlashData('success_message', 'Trader Settings Updated Successfully');
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', 'Trader Settings Updation Failed');
			}




		}
		}

		if(!empty($this->request->getPost('strategy')))
		{

			$qury = $this->db->query("SELECT * FROM suggested_strategy WHERE id='1' ")->getResult();
		    $qry=$qury[0];
			$margin_column_limit =$qry->margin_column_limit;
			$first_buy_amount=$qry->first_buy_amount;
			$open_position_doubled=$qry->open_position_doubled;
			$whole_profit_ratio=$qry->whole_profit_ratio;
			$whole_profit_callback=$qry->whole_profit_callback;
			$buyin_callback=$qry->buyin_callback;
			$sub_position_callback	= $qry->sub_position_callback;
			
			$tade1=$qry->margincall_drop ;
			$tade2=$qry->buyin_ratio_times;

			
			$session= \Config\Services::session();
	 		$uusersid=$session->get('uusersid');


			$trade_data = array(
				"first_buy_amount" 		=>  $first_buy_amount,
		        "open_position_doubled" =>  $open_position_doubled,
		        "margin_column_limit" 	=>  $margin_column_limit,
		        "whole_profit_ratio"	=>  $whole_profit_ratio,
		        "whole_profit_callback" =>  $whole_profit_callback,
		        "buyin_callback" 		=>  $buyin_callback,
		        "margincall_drop"		=> 	$tade1,
		        "buyin_ratio_times"		=>	$tade2,
		        "sub_position_callback" =>  $sub_position_callback,
		        // "sync_strategy_status"	=> 	0
			);

			$this->db = db_connect();

			$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data);
			if($query_status)
			{
				$session=\Config\Services::session();
				$session->setFlashData('success_message', 'Suggested Strategy Successfully Applied');
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', 'Failed to apply Suggested Strategy');
			}
			
		}
		$this->data['id'] = $id;

        $activation =  $this->db->query("SELECT * FROM history WHERE type='activation' and uusersid='".$uusersid."' AND status='1' ")->getRow();

      
        $bind_api =$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."'")->getRow();

        if(!empty($bind_api))
        	$this->data['bind_api'] = true;
        else
        	$this->data['bind_api'] = "";


        if($activation)
        {
		$this->data['activation'] = true;
        }
        else
        {
         $this->data['activation'] = false;
        }
          // get trading settings
    $tradSets = $this->common_model->GetResults('adminsettings','');
    $this->data['tradSet'] = $tradSets[0];

  $this->data['fuel_amount1'] = $this->db->query("SELECT SUM(amount)as amt from history where type IN('fuel','bonus') AND  status='1' and uusersid ='".$session->get('uusersid')."'")->getRow();

  $this->data['fuel_amount2'] = $this->db->query("SELECT SUM(amount)as amt from history where type = ('penalty') AND  status='1' and uusersid ='".$session->get('uusersid')."'")->getRow();

        $trade_process =$this->db->query("SELECT * FROM trade_process WHERE pair='".$id."' and uusersid='".$uusersid."'  and trade_status != 2")->getRow();

        if(!$trade_process){
           $trade_process =$this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."'")->getRow();
        }

        $this->data['trade_process'] = $trade_process;

    echo view('user/tadedetail',$this->data);
}
// start the trade
public function tradingprocess(){
	$this->session = session();

	$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$this->session->get('uusersid')."'")->getResultArray();
		    $qry=$qury[0];
	if(empty($qry)){
		$qury = $this->db->query("SELECT * FROM suggested_strategy WHERE id='1' ")->getResultArray();
		    $qry=$qury[0];
	}
	if($this->request->getPost('pair') != "")
		$qry['pair'] = $this->request->getPost('pair');
	else
		$qry['pair'] = $this->request->getPost('uri');
	$trade_query = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$this->session->get('uusersid')."' and pair='".$this->request->getPost('id')."' and trade_status != 2 order by id desc")->getRowArray();
	if(empty($trade_query)){
		$qry['trade_status'] = 1;
		unset($qry['id']);
		if(!isset($qry['uusersid']) || $qry['uusersid'] == ""){
			$qry['uusersid'] = $this->session->get('uusersid');
		}
		$qry['margin_call'] = 1;
		$qry['created_time'] = time();

	
		
        $query_status = $this->db->table('trade_process')->insert($qry);
         $last_id = $this->db->insertID();
         echo"<pre>";
         print_r($last_id);
         echo"</pre>";
       if($last_id){
       	$qry_new = $this->db->query("SELECT * FROM trade_process WHERE id='".$last_id."'")->getRowArray();
       	echo"<pre>";
       	print_r($qry_new);
       	echo"</pre>";
       		if($qry_new['open_position_doubled'] != 'on' || $qry_new['open_position_doubled'] == '')
        	    $quantity = 1;
            else
            	$quantity = 2;
            $price = $qry_new['first_buy_amount'] * $quantity;
            // return $this->marketbuy($qry_new['uusersid'],$qry_new['id'],$price,$qry_new['pair']);
            		$flags['isQuoteOrder'] = true;
				// $order = $api->buy("BNBUSDT", "10",0,"MARKET",$flags);
				// $order = $api->marketQuoteSell("BNBUSDT", "100",$flags);
            	
        $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$qry_new['uusersid']."'");

        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
        $api = new Binance\API($key,$secret);

        if($price <= 11){
        	$price = 11;
        }
		$order = $api->marketQuoteBuy($qry_new['pair'], $price,$flags);

		echo"<pre>";
		print_r($qry_new['pair']);
		print_r($price);
		print_r($flags);
		echo"</pre>";

		

		echo"<pre>";
		print_r($order);
		echo"</pre>";

		$order_history = array(
			'pair' => $order['symbol'],
			'order_id' => $order['orderId'],
			'trade_process_id' => $qry_new['id'],
			'uuserid' => $qry_new['uusersid'],
			'type' => '1',
			'strategy_mode' => $qry_new['strategy_mode'],
			'quantity' => $order['cummulativeQuoteQty'],
			'original_quantity' => $price,
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'date' => date('Y-m-d',time()),
			'description'=>'first_buy',
			'live_price' => $order['fills'][0]['price'],
			'status' => 0
		);
		echo"<pre>";
		print_r($order_history);
		echo"</pre>";
		$this->db = db_connect();
		$this->db->table('api_trade_history')->insert($order_history);

	}
}else {
		$query_status = $this->db->query("UPDATE trade_process SET trade_status=1, updated_time='".time()."' WHERE uusersid='".$this->session->get('uusersid')."' and pair='".$this->request->getPost('id')."' and trade_status = 0 order by id desc ");
	}

}


// pause the current trade
public function tradingprocess1(){
	$this->db = db_connect();
	if($this->request->getPost('pair') != "")
		$qry['pair'] = $this->request->getPost('pair');
	else
		$qry['pair'] = $this->request->getPost('uri');
	$trade_query = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$this->session->get('uusersid')."' and pair='".$this->request->getPost('id')."' and trade_status = 1 ")->getRowArray();
	if(!empty($trade_query)){
		$qry['trade_status'] = 0;
		$query_status = $this->db->query("UPDATE trade_process SET trade_status=0, updated_time='".time()."' WHERE uusersid='".$this->session->get('uusersid')."' and pair='".$this->request->getPost('id')."' and trade_status = 1 ");
		if($query_status)
			echo "success";
		else 
			echo 'fail';
	}
    
}


// stop the current trade
public function tradingprocess2(){
	$this->db = db_connect();
	      $trade_query = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$this->request->getPost('uusersid')."' and pair='".$this->request->getPost('id')."' and id='".$this->request->getPost('pair')."'")->getRow();

	      if($trade_query){

	      		$api_trade_data = array(
					'trade_process_id' => $trade_query->id,
					'uuserid' => $this->request->getPost('uusersid'),
					'type' => '1',
					'status' => 0
				);

			$trade_where = array(
							'uuserid' => $this->request->getPost('uusersid'),
							'type' => '1',
							'status' => 0,
							'trade_process_id' => $trade_query->id,
						);
$total_position_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
$buy_records = $this->db->table('api_trade_history')->selectAvg('live_price')->where($trade_where)->orderBy('id','DESC')->get()->getRow();


	    $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
          $api = new Binance\API($key,$secret);
          $ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
          $balances = $api->balances($ticker);
          $total_asset = $balances[substr($this->request->getPost('id'),0,-4)]['available'];
          $price = "";
          $live_price = $ticker[$this->request->getPost('id')];
          $sell_amount = number_format($total_position_quantity->received_amount,8);
          if(!empty($total_asset) && $total_asset != 0 && $sell_amount > 0){
          if($sell_amount <= $total_asset){
              $result = $this->take_profit($this->request->getPost('uusersid'),$trade_query->id,$sell_amount,$price,$live_price,$api,$trade_query->pair,$buy_records->live_price);
                      $query_status = $this->db->query("UPDATE trade_process SET trade_status=2, updated_time='".time()."' WHERE uusersid='".$this->request->getPost('uusersid')."' and pair='".$this->request->getPost('id')."'");
          }
      }else{
      	$query_status = $this->db->query("UPDATE trade_process SET trade_status=2, updated_time='".time()."' WHERE uusersid='".$this->request->getPost('uusersid')."' and pair='".$this->request->getPost('id')."'");
      }
      $query_status = $this->db->query("UPDATE trade_process SET trade_status=2, updated_time='".time()."' WHERE uusersid='".$this->request->getPost('uusersid')."' and pair='".$this->request->getPost('id')."'");
        if($query_status)
			echo "success";
		else 
			echo 'fail';
	      }
		
		
	}


	public function orderDetails(){
		$this->db = db_connect();
		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
          $api = new Binance\API($key,$secret);
          $this->data['id'] = $this->request->getPost('pair');
		$this->data['orderstatus'] = $api->orderStatus($this->request->getPost('pair'), $this->request->getPost('id'));
		$orderstatus = $this->data['orderstatus'];
		$order_info =$this->db->query("SELECT * FROM api_trade_history WHERE order_id='".$orderstatus['orderId']."'")->getRow();
		$this->data['order_info'] = $order_info;

        // if(!empty($order_info) && $order_info->type == 2 && $order_info->subsell_status == 1) {
        //     $order_buy_info =$this->db->query("SELECT * FROM api_trade_history WHERE type=1 and trade_process_id = '".$order_info->trade_process_id."'  and margin_call_drops='".$order_info->margin_call_drops."' order by id desc")->getRow();
        //     $this->data['order_buy_info'] = $order_buy_info;
        //     if(!empty($order_buy_info)) { 
        //     $avg_price1 = $order_info->quantity - $order_buy_info->quantity;
        //      $avg_price = $avg_price1 * 80/100;
        //     $this->data['avg_price'] = $avg_price;
        //     $avg_percentage1 = $avg_price / $order_info->quantity;
        //     $avg_percentage2 = $avg_percentage1 * 100;
        //     $avg_percentage = $avg_percentage2 * 80/100;
        //     $this->data['avg_percentage'] = $avg_percentage;
        //     }
        // }else if(!empty($order_info) && $order_info->type == 2 && $order_info->subsell_status != 1){
            $this->data['avg_price'] = $order_info->avg_price - $order_info->comm_price;
            $this->data['avg_percentage'] = $order_info->profit_percentage;
        // }
		echo view('user/order_details_model',$this->data);
	}

	public function update_live_price(){
		if($this->request->getPost('price'))
		$this->session->set('live_price',$this->request->getPost('price'));
	    if($this->request->getPost('high_price'))
		$this->session->set('high_price',$this->request->getPost('high_price'));
	    if($this->request->getPost('previous_high_price'))
		$this->session->set('previous_high_price',$this->request->getPost('previous_high_price'));
		echo "success";
	}

	public function cancel_order()
	{
		$segments = $this->request->getPost('id');
		$buy_record_update = $this->db->table('api_manual_trade')->set('status','2')->where("id",$segments)->update();
		echo "success";
	}



public function take_profit($userid,$trade_process_id,$quantity,$price,$stopPrice,$api,$pair,$avg_price){

		// $flags['isQuoteOrder'] = true;

  $exchange_info = $api->exchangeInfo();

  foreach ($exchange_info['symbols'] as $key => $value) {
      if( strcasecmp( $value['symbol'], $pair ) == 0){
        $stepsize = $value['filters'][2]['stepSize'];
      break;
      }
    }



$stepsize = fmod($stepsize, 1);
$total_no = str_replace('.', '', $stepsize);
$count = strlen($total_no) - 1;

// $stepsize = explode('.', $stepsize)[1];
 if($stepsize == 1.00000000)
 	$current = 0;
 else
    $current = $count+1;


$quantity = number_format($quantity,$current);


		// $order = $api->marketQuoteSell($pair,$quantity);
		$order = $api->sell($pair,$quantity,0,"MARKET");

		echo"<pre>";
		print_r($order);
		echo"</pre>";

		// $order = $api->sell($pair, $quantity, $price, "TAKE_PROFIT_LIMIT", ["stopPrice"=>$stopPrice]);
		
        if($order) { 
        	$buy_record_update = $this->db->table('trade_process')->set('flag','0')->where("id",$trade_process_id)->update();
		$trade_process = $this->db->table('trade_process')->where('uusersid',$userid)->where('trade_status','1')->where('id',$trade_process_id)->get()->getRow();

		$order_history = array(
			'pair' => $pair,
			'order_id' => $order['orderId'],
			'trade_process_id' => $trade_process_id,
			'uuserid' => $userid,
			'type' => '2',
			'quantity' => $order['cummulativeQuoteQty'],
			' original_quantity' => $order['cummulativeQuoteQty'],
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'live_price' => $stopPrice,
			'avg_price' => $avg_price,
			'description' => "close_trade",
			'margin_call_drops' => '',
			'strategy_mode' => $trade_process->strategy_mode,
			'status' => 0,
		);
        $this->db = db_connect();
		$this->db->table('api_trade_history')->insert($order_history);
		echo"<pre>";
		print_r($this->db->insertID());
		echo"</pre>";
		$return = true;
	}else{
		$return = false;
	}

		return $return;
	}

public function tradingbuy()
{
	$validation =  \Config\Services::validation();
	$this->db = db_connect();
    $this->session = session();
    $uusersid = $this->session->get('uusersid');
    $CommonModel = model('CommonModel');
	$num = $this->request->getPost('num');
	$val= $this->request->getPost('val');
	$id= $this->request->getPost('id');
    $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;

   

    // $key = "wcYWabBn1sHWzvVmYjwQrF8JMbh8ngCUW3oA1IbEJrghBgqmB1U9BMMQUGmU42hv";
    // $secret = "1cSiCLlNnfKhcaX0wyIhXB1QLFtckdzKxR7Lqq2TlB0CQB31xdNoeGbwx39NjDra";
        $api = new Binance\API($key,$secret);
        $marketpair = $api->prevDay($id);
        $output['symbol'] = $marketpair['symbol']; 
        $quantity = $num;
        $price = $val;
        $flags['isQuoteOrder'] = true;
        if($price != "" || $price != 0){
        $order_history = array(
			'trade_process_id' => $this->request->getPost('trade_process_id'),
			'uuserid' => $uusersid,
			'type' => '1',
			'amount' => $quantity,
			'trigger_price' => $price,
			'created_date' => time(),
			'status' => 1
		);
		$manual_buy = $this->db->table('api_manual_trade')->where('trade_process_id',$this->request->getPost('trade_process_id'))->where('type',1)->where('status','1')->get()->getRow();
        if($manual_buy) {
        	echo "fail";
        	exit();
        }else{ 
		$result = $this->db->table('api_manual_trade')->insert($order_history);
		if($result)
			echo "success";
		else
			echo "failure";
	    }
        }
        else{
        	$num = str_replace(',', '', $num);
        $order = $api->marketQuoteBuy($output['symbol'], $num,$flags);

    $trade_process =$this->db->query("SELECT * FROM trade_process WHERE pair='".$id."' and uusersid='".$this->request->getPost('uusersid')."' and trade_status != 2 order by id desc")->getRow();
    if($order){

    	// if($order['status'] == "NEW")
    	// 	$status = 0;
    	// else 
    	// 	$status = 1;
        $order_history = array(
			'pair' => $order['symbol'],
			'order_id' => $order['orderId'],
			'trade_process_id' => $trade_process->id,
			'uuserid' => $trade_process->uusersid,
			'type' => '1',
			'strategy_mode' => $trade_process->strategy_mode,
			'quantity' => $order['cummulativeQuoteQty'],
			'original_quantity' => $price,
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'description'=>'manual_buy',
			'date' => date('Y-m-d',time()),
			'live_price' => $order['fills'][0]['price'],
			'status' => 0
		);
		$this->db->table('api_trade_history')->insert($order_history);

		echo"<pre>";
		print_r($this->db->getLastQuery());
		echo"</pre>";
		echo"<pre>";
		print_r($order_history);
		echo"</pre>";
        echo "success";
        }
        else{
        echo "failure"; 
        }  
    }
        // if($order==true)
        // {
        // 	$data=array(
        // 	'userid'=>$_SESSION["uusersid"],
        // 	'orderid'=>$order['orderId'],
        // 	'orderlistid'=>$order['orderListId'],
        // 	'symbol'=>$order['symbol'],
        // 	'price'=>$order['price'],
        // 	'type'=>$order['side'],
        // 	'commission'=>$order['commission'],
        // 	'commission_asset'=>$order['commissionAsset'],
        // 	'quantity'=>$order['executedQty'],
        // 	'transaction_on'=>date('Y-m-d H:i:s')
        // );
        // 	$this->db = db_connect();
        // 	$query_status=$this->db->table('exchange2')->insert($data);
        // 	$msg='success';
        // }
        // else
        // {
        // 	$msg='';
        // }

        // echo $msg;

       // print_r($order);
        //	exit();

      //Array ( [symbol] => BNBUSDT [orderId] => 3191725 [orderListId] => -1 [clientOrderId] => iABJfgBXMtEHjnkj1QV3qI [transactTime] => 1642666663773 [price] => 800.00000000 [origQty] => 1.00000000 [executedQty] => 1.00000000 [cummulativeQuoteQty] => 476.89500000 [status] => FILLED [timeInForce] => GTC [type] => LIMIT [side] => BUY [fills] => Array ( [0] => Array ( [price] => 476.80000000 [qty] => 0.05000000 [commission] => 0.00000000 [commissionAsset] => BNB [tradeId] => 233131 ) [1] => Array ( [price] => 476.90000000 [qty] => 0.95000000 [commission] => 0.00000000 [commissionAsset] => BNB [tradeId] => 233132 ) ) ) 
       
}



public function tradingsell()
{
	$validation =  \Config\Services::validation();
	$this->db = db_connect();
    $this->session = session();
	$CommonModel = model('CommonModel');

	  $num = $this->request->getPost('num');
	  $val= $this->request->getPost('val');
	  $id= $this->request->getPost('id');

	 $uusersid =$this->session->get("uusersid");
     $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;

       
        $api = new Binance\API($key,$secret);

        $marketpair = $api->prevDay($id);
        $output['symbol'] = $marketpair['symbol'];

        $quantity = $num;
        $price = $val;
        $symbol = $output['symbol'];

    if($price != "" || $price > 0){
		$order_history = array(
		'trade_process_id' => $this->request->getPost('trade_process_id'),
		'uuserid' => $uusersid,
		'type' => '2',
		'amount' => $quantity,
		'trigger_price' => $price,
		'created_date' => time(),
		'status' => 1
		);
		$manual_sell = $this->db->table('api_manual_trade')->where('trade_process_id',$this->request->getPost('trade_process_id'))->where('type',2)->where('status','1')->get()->getRow();
		if($manual_sell){
			echo "fail";
			exit();
		}
		else { 
		$result = $this->db->table('api_manual_trade')->insert($order_history);
		if($result)
			echo "success";
		else
			echo "failure";
	}
    }
        else{
			try {
				$quantity = str_replace(',', '', $quantity);
				$exchange_info = $api->exchangeInfo();

  foreach ($exchange_info['symbols'] as $key => $value) {
      if( strcasecmp( $value['symbol'], $output['symbol'] ) == 0){
        $stepsize = $value['filters'][2]['stepSize'];
      break;
      }
    }
// $stepsize = explode('.', $stepsize)[1];
if($stepsize == 1.00000000)
 	$current = 0;
 else
    $current = log(1.00000000, $stepsize);
        if($current != 0)
		$quantity = number_format($quantity,$current);
$quantity = str_replace(',', '', $quantity);
	$order = $api->sell($output['symbol'], $quantity,0,"MARKET");
			} catch (Exception $e) {
			echo 'failure';
			exit();
			}
  


      $trade_process =$this->db->query("SELECT * FROM trade_process WHERE pair='".$id."' and uusersid='".$this->request->getPost('uusersid')."' and trade_status != 2 order by id desc")->getRow();
    if($order){
    	// if($order['status'] == "NEW")
    	// 	$status = 0;
    	// else 
    	// 	$status = 1;
        $order_history = array(
			'pair' => $order['symbol'],
			'order_id' => $order['orderId'],
			'trade_process_id' => $trade_process->id,
			'uuserid' => $trade_process->uusersid,
			'type' => '2',
			'strategy_mode' => $trade_process->strategy_mode,
			'quantity' => $order['cummulativeQuoteQty'],
			'original_quantity' => $price,
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'description'=>'manual_sell',
			'date' => date('Y-m-d',time()),
			'live_price' => $order['fills'][0]['price'],
			'status' => 0
		);
		$this->db->table('api_trade_history')->insert($order_history);

		echo"<pre>";
		print_r($this->db->getLastQuery());
		echo"</pre>";
		echo"<pre>";
		print_r($order_history);
		echo"</pre>";
        echo "success";
        }
        else{
        echo "failure"; 
        }  

          }

       //print_r($order);


       //Array ( [symbol] => BNBUSDT [orderId] => 3193152 [orderListId] => -1 [clientOrderId] => Gkvu5fYeMmFY8vIt9j7msT [transactTime] => 1642667099578 [price] => 200.00000000 [origQty] => 1.00000000 [executedQty] => 1.00000000 [cummulativeQuoteQty] => 470.74700000 [status] => FILLED [timeInForce] => GTC [type] => LIMIT [side] => SELL [fills] => Array ( [0] => Array ( [price] => 470.86000000 [qty] => 0.95000000 [commission] => 0.00000000 [commissionAsset] => USDT [tradeId] => 233247 ) [1] => Array ( [price] => 468.60000000 [qty] => 0.05000000 [commission] => 0.00000000 [commissionAsset] => USDT [tradeId] => 233248 ) ) ) 


}

public function sell_calculate(){
	$quantity = $this->request->getPost('quantity');
	$price = $this->request->getPost('price');
	$id = $this->request->getPost('id');
			$ch = curl_init();

          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
         curl_setopt($ch, CURLOPT_URL,"https://api.nomics.com/v1/currencies/ticker?key=7349cd0bf1561564e2afbe46f3d2805ee96b6092&ids=USDT&interval=1d&convert=".substr($id, 0,-4)."&per-page=100&page=1");
          curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
          $result=curl_exec ($ch);
          $getresponse = json_decode($result);

          $quantz =  $quantity/$getresponse[0]->price;

          $result = $price - $quantz;

          echo number_format($result,5);
}

public function profit_calculation(){
	$quantity = $this->request->getPost('quantity');
	$id = $this->request->getPost('symbol');
		  $ch = curl_init();
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
          curl_setopt($ch, CURLOPT_URL,"https://api.nomics.com/v1/currencies/ticker?key=7349cd0bf1561564e2afbe46f3d2805ee96b6092&ids=TRX&interval=1d&convert=".substr($id, 0,-4)."&per-page=100&page=1");
          curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
          $result=curl_exec ($ch);
          $getresponse = json_decode($result);
          $quantz =  $quantity * $getresponse[0]->price;
          $result = $price - $quantz;
          echo number_format($result,5);
}

public function logModal()
{
    $this->db = db_connect();
	$session= \Config\Services::session();
	$uusersid=$session->get('uusersid');
	//GET today records only use date(date)=date(now());
    $this->data['logs'] = $this->db->query("SELECT * FROM `log_records` WHERE  DATE(date) = DATE(NOW()) AND uusersid ='".$uusersid."' order by id desc ")->getResult();
	echo view('user/logmodal',$this->data);
}


public function replenishment_time()
	{
		$session= \Config\Services::session();
		$id =$session->get('uusersid');
		$num = service('request')->getPost('number');	
		$pair = service('request')->getPost('pair');	

		$this->db = db_connect();

		$qury = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$id."' AND pair='".$pair."' ")->GetResult();
		$qry=$qury[0];		

		if(!$qry)
		{
		$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$id."'")->GetResult();
		$qry=$qury[0];
        }
	
					
		// $num=$qry->margin_column_limit;			
		$lmt=$qry->sub_position;
		$margin=explode(',',$lmt);
		$margn=array_slice($margin,-$num);

		if($num >= 5)
		{
			$j=0;
			for ($i=4; $i < $num; $i++) 
			{ 
				$c=$i+1;				
				echo   "<div class='modal-form mb-4'>";
				echo    "<label class=''>The ".$c."th sub-position</label>";
				echo   "<div class='input-group'>";
				echo    "<input type='text' class='form-control mt-1'  name='rep_time".$j."' required  value=".$margn[$j].">";
				echo    "<span class='input-group-text mt-1'>% </span> </div>";
				echo   "</div>";

				$j++;
			}
        }
	   else
	   {
		 echo "";
	   }

	}
	


	public function replenishment_time1()
	{
		$session= \Config\Services::session();
		$id =$session->get('uusersid');
		$num = service('request')->getPost('number1');
	    $pair = service('request')->getPost('pair');	

		$this->db = db_connect();
	

      $qury = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$id."' AND pair='".$pair."' ")->GetResult();
		$qry=$qury[0];		

		if(!$qry)
		{
		$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$id."'")->GetResult();
		$qry=$qury[0];
        }


		$marg=$qry->margincall_drop;
		$margin=explode(',',$marg);

		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;	
			echo   "<div class='modal-form mb-4'>";
			echo    "<label class=''>The ".$c."nd call</label>";
			echo   "<div class='input-group'>";
			echo    "<input type='text' class='form-control mt-1' required name='call_time".$i."' value=".$margin[$i].">";
			echo    "<span class='input-group-text mt-1'>% </span> </div>";
			echo   "</div>";
		}
	}

	public function replenishment_time2()
	{
		$session= \Config\Services::session();
		$id =$session->get('uusersid');
		$num = service('request')->getPost('number2');
	    $pair = service('request')->getPost('pair');	

		$this->db = db_connect();


		$qury = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$id."' AND pair='".$pair."' ")->GetResult();
		$qry=$qury[0];		

		if(!$qry)
		{
		$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$id."'")->GetResult();
		$qry=$qury[0];
        }



		$buy=$qry->buyin_ratio_times;
		$buyin=explode(',',$buy);
		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;
			echo   "<div class='modal-form mb-4'>";
			echo    "<label class=''>The ".$c."th order amount</label>";
			echo   "<div class='input-group'>";
			echo    "<input type='text' class='form-control mt-1' required  name='order_time".$i."' value=".$buyin[$i].">";
			echo    "<span class='input-group-text mt-1'>Times</span> </div>";
			echo   "</div>";
	   }


	}
public function first_preset_price()
{
	$uusersid = service('request')->getPost('uusersid');
	$first_preset_price = service('request')->getPost('first_preset_price');
	
	$trade_data=array(
		"first_preset_price" 		=>  $first_preset_price,
	);

	$this->db = db_connect();

	$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data);	

}

public function strategy_mode()
{
	$uusersid = service('request')->getPost('uusersid');
	$strategy_mode = service('request')->getPost('strategy_mode');
	
	$trade_data=array(
		"strategy_mode" 		=>  $strategy_mode,
	);

	$this->db = db_connect();

	$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data);

}
public function strategy_type()
{
	$uusersid = service('request')->getPost('uusersid');
	$strategy_type = service('request')->getPost('strategy_type');
	
	$trade_data=array(
		"strategy_type" 		=>  $strategy_type
	);
	$this->db = db_connect();

	$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data);

}


public function call_margin()
{

		    $session = session();
	 	    $uusersid= $session->get('uusersid');
			$this->db = db_connect();
           
            $pair = service('request')->getPost('pair');
            $pair_id = service('request')->getPost('margin_id');
            $url = service('request')->getPost('url');

            if($pair !=="" && $pair_id !="")
            {
            $trade_datas=array(
			"margin_call" 		=>  $pair_id,
			);


$select_user_pair = $this->db->query("SELECT * from trade_process where pair='".$pair."' AND trade_status='0' or trade_status='1' and uusersid='".$uusersid."' ")->getRow();

if($select_user_pair !="")
	{
     $query_status = $this->db->table('trade_process')->where('pair', $pair)->update($trade_datas);
     echo "success";

		
		if($pair_id==0)
		{
		$name = "Stop margin call";
		}
		if($pair_id==1)
		{
		$name = "Initiate margin call";
		}


		    if($url!="" && !is_numeric( $url ))
            {


		$trade_datas_1=array(
		"menu" 		=>  $url ." Switch to ".$name,
		"uusersid"  =>  $uusersid,
		"date"      => date('Y-m-d H:i:s'),
		);

		$query_status1 = $this->db->table('log_records')->insert($trade_datas_1);

	        }

	}


}
}


public function Cstartegy()
{

		    $session = session();
	 	    $uusersid= $session->get('uusersid');
			$this->db = db_connect();

            $pair = service('request')->getPost('pair');
            $pair_id = service('request')->getPost('pair_id');
            $url = service('request')->getPost('url');

            if($pair !=="" && $pair_id !="")
            {

            $trade_datas=array(
			"strategy_type" 		=>  "One-shot strategy",
			"uusersid"              =>  $uusersid,
			);

	$select_user_pair = $this->db->query("SELECT * from trade_process where pair='".$pair_id."'  and uusersid='".$uusersid."' ")->getRow();

	if($select_user_pair!="")
	{
      $query_status = $this->db->table('trade_process')->where('pair', $pair_id)->update($trade_datas);
      $query_status_new = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_datas);

	}

}
            if($url=="")
            {
            	$url = $pair_id;
            }

            if($url!="" && !is_numeric( $url ))
            {

            $trade_datas_1=array(
			"menu" 		=>       $url ." Modify transaction settings",
			"uusersid"  =>  $uusersid,
			"date"      => date('Y-m-d H:i:s'),
			);

           $query_status1 = $this->db->table('log_records')->insert($trade_datas_1);
           
           }

	       $trade_data1  =  array(
			"strategy_type" 		=>  "One-shot strategy",
			"uusersid"              =>  $uusersid
			);
		    

			$select_user = $this->db->query("SELECT * from user_strategy where uusersid='".$uusersid."'")->getRow();

			if($select_user)
			{
			$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data1);
		    }
		    else
		    {
		    	$query_status = $this->db->table('user_strategy')->insert($trade_data1);
		    }

		    echo "success_message";

}



public function Ostartegy()
{

		$session = session();
		$uusersid=$session->get('uusersid');
		$this->db = db_connect();

		$pair = service('request')->getPost('pair');
		$pair_id = service('request')->getPost('pair_id');
		$url = service('request')->getPost('url');


		if($pair !=="" && $pair_id !="")
		{

		$trade_datas=array(
		"strategy_type" 		=>  "Cycle Strategy",
		"uusersid"              =>  $uusersid,
		);

		$select_user_pair = $this->db->query("SELECT * from trade_process where pair='".$pair_id."' and uusersid='".$uusersid."' ")->getRow();


		if($select_user_pair !="")
		{
		$query_status = $this->db->table('trade_process')->where('pair', $pair_id)->update($trade_datas);
		$query_status_new = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_datas);
		}
		}
         
          if($url=="")
            {
            	$url = $pair_id;
            }

            if($url!="" && !is_numeric( $url ))
            {
		
			$trade_datas_1=array(
			"menu" 		=>  $url ." Modify transaction settings",
			"uusersid"  =>  $uusersid,
			"date"      => date('Y-m-d H:i:s'),
			);
			$query_status1 = $this->db->table('log_records')->insert($trade_datas_1);
            }


		$trade_data1=array(
		"strategy_type" 		=>  "Cycle Strategy",
		"uusersid"              =>  $uusersid
		);

		$select_user = $this->db->query("SELECT * from user_strategy where uusersid='".$uusersid."'")->getRow();

		if($select_user)
		{
		$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data1);
		}
		else
		{
		$query_status = $this->db->table('user_strategy')->insert($trade_data1);
		}

		echo "success_message";

}

public function Cstartegy_mode()
{

	    $session = session();
 	    $uusersid= $session->get('uusersid');
 	    $num = service('request')->getPost('number2');
		$this->db = db_connect();



		$pair = service('request')->getPost('pair');
		$pair_id = service('request')->getPost('pair_id');
	    $url = service('request')->getPost('url');

		if($pair !=="" && $pair_id !="")
		{

		$trade_datas=array(
		"strategy_mode" =>  $num
		);


		$select_user_pair = $this->db->query("SELECT * from trade_process where pair='".$pair_id."' and uusersid='".$uusersid."' ")->getRow();

		$pair_condition = $this->db->query("SELECT * from api_trade_history where trade_process_id='".$pair_id."' and margin_call_drops = 5 ")->getRow();

		if($select_user_pair !="" && !$pair_condition)
		{
		$query_status = $this->db->table('trade_process')->where('pair', $pair_id)->update($trade_datas);
		$query_status_new = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data);

		}

		}

				if($num==1)
				{ 
				$name = "Whole warehouse mode";
				}
				if($num==2)
				{
				$name = "Sub-bin mode";
				}
				if($num==3)
				{
				$name = "Sub-bin mode-real-time settlement";
				}

				if($url!="" && !is_numeric( $url ))
				{


				$trade_datas_1=array(
				"menu" 		=>  $url ." Switch to ".$name,
				"uusersid"  =>  $uusersid,
				"date"      => date('Y-m-d H:i:s'),
				);

				$query_status1 = $this->db->table('log_records')->insert($trade_datas_1);

				}


	       $trade_data1=array(
			"strategy_mode" 		=>  $num,
			"uusersid"              =>  $uusersid
			);
		    
			$select_user = $this->db->query("SELECT * from user_strategy where uusersid='".$uusersid."'")->getRow();

			if($select_user)
			{
			$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data1);
		    }
		    else
		    {
		    	$query_status = $this->db->table('user_strategy')->insert($trade_data1);
		    }
	        if($select_user_pair !="" && !$pair_condition)
			{
			    echo "success_message";
			}else{
				echo 0;
			}    


}

			public function switch_update(){

			}


	        public function trade_update(){
			$pair =  $this->request->getPost('pair');
			// $pair = 'BNBUSDT';
			$uusersid = $this->request->getPost('uusersid');
			$live_price = $this->request->getPost('live_price');
			// return $session;

			$where_ = array(
				'pair' => $pair,
				'uusersid' => $uusersid,
				'trade_status != ' => '2',
			);

			$trade_record =  $this->db->table('trade_process')->where($where_)->orderBy('id','DESC')->get()->getRow();
			echo"<pre>";
			print_r($trade_record);
			echo"</pre>";

			
         	
   //       	$query = $this->db->getLastQuery();
			// echo (string)$query;
			if($trade_record){
               $tradeupdate['status'] = $trade_record->margin_call;
			}
            else{
            	$tradeupdate['status'] = "";
            }


			if ($trade_record) {
				$api_trade_data = array(
					'trade_process_id' => $trade_record->id,
					'uuserid' => $uusersid,
					'type' => '1',
					'status' => 0
				);

				$api_trade_data2 = array(
					'trade_process_id' => $trade_record->id,
					'uuserid' => $uusersid,
					'type' => '1',
					'margin_call_drops != ' => 0
				);


				$api_trade_data1 = array(
					'trade_process_id' => $trade_record->id,
					'uuserid' => $uusersid,
					'type' => '2',
					'description' => 'manual_sell'
				);

				$profit_where = array(
					'uuserid' => $uusersid,
					'type' => '3',
					'trade_process_id' => $trade_record->id,
					'status' => 0
				);
      

		$total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
        $total_usdt = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->get()->getRow();
		if($trade_record->strategy_mode == 1){
        $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
        $total_usdt  = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->get()->getRow();
        if($total_contract->received_amount && $total_usdt->quantity)
          $avg_position_amount = $total_usdt->quantity / $total_contract->received_amount;
        else
          $avg_position_amount = 0;
      }else{
        if($trade_record->strategy_mode == 3) {
        $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        $total_usdt = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        if($total_contract->received_amount && $total_usdt->quantity)
          $avg_position_amount = $total_usdt->quantity / $total_contract->received_amount;
        else
          $avg_position_amount = 0;
      }else{
          $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        $total_usdt = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        $total_contract2 = $this->db->table('api_trade_history')->selectSum('received_amount')->where($profit_where)->get()->getRow();
        $total_contract = $total_contract->received_amount + $total_contract2->received_amount;
        $total_usdt2 = $this->db->table('api_trade_history')->selectSum('quantity')->where($profit_where)->get()->getRow();
        $total_usdt = $total_usdt->quantity + $total_usdt2->quantity;
        if($total_contract && $total_usdt)
          $avg_position_amount = $total_usdt / $total_contract;
        else
          $avg_position_amount = 0;
      }
      }
      




        if($trade_record->strategy_mode == 1){
        $last_call_drop = $this->db->table('api_trade_history')->where($api_trade_data)->orderBy('id','DESC')->get()->getRow();
        $last_average = $avg_position_amount;
        }
        else{
        $last_call_drop = $this->db->table('api_trade_history')->where($api_trade_data2)->where('margin_call_drops <=',4)->orderBy('id','DESC')->get()->getRow();
        if(empty($last_call_drop) || $last_call_drop == 0)
        $last_call_drop = $this->db->table('api_trade_history')->where($api_trade_data)->where('description','first_buy')->orderBy('id','DESC')->get()->getRow();
        $last_average = $avg_position_amount;
        }

				$avg_price = round($last_average,8) * $trade_record->whole_profit_ratio / 100;

							$max_increase_price = $last_average + $avg_price;
							
							$max_increase_price = round($max_increase_price,8);

							$max_down_percentage = $max_increase_price * $trade_record->whole_profit_callback / 100;

							$max_down_price = $max_increase_price - $max_down_percentage;

							$max_down_price = round($max_down_price,8);

							$tradeupdate['take_profit_trigger'] = "> ".number_format($max_increase_price,5);

			
		// if($last_call_drop->margin_call_drops == "")
		//    $next_call = 0;
		// else
		//    $next_call = $last_call_drop->margin_call_drops;  
                  $trade_where_new = array(
            'uuserid' => $uusersid,
            'type' => '1',
            'status' => 0,
            'trade_process_id' => $trade_record->id,
          );

                    $last_buy_recheck = $this->db->table('api_trade_history')->where($trade_where_new)->orderBy('margin_call_drops','DESC')->get()->getRow();
       $last_margin_call_drop = $last_buy_recheck->margin_call_drops;

       

        $call_perc = explode(',', $trade_record->margincall_drop)[$last_margin_call_drop];

        $tradeupdate['margin_call_drops'] = $call_perc;

        $price_down = $last_call_drop->live_price * $call_perc / 100;

        $down_price = $last_call_drop->live_price - $price_down;

        $tradeupdate['down_price']  = "< ".number_format($down_price,5);

				$total_position_amount = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->get()->getRow();
				$total_sell_amount = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data1)->get()->getRow();

			

				$total_position_amount->quantity = $total_position_amount->quantity - $total_sell_amount->quantity;


				$tradeupdate['current_position_amount'] = number_format($last_call_drop->quantity,5);
				      $total_position_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
        $total_sell_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data1)->get()->getRow();
        $total_position_quantity->received_amount = $total_position_quantity->received_amount - $total_sell_quantity->received_amount;

				if ($total_position_amount->quantity > 0) {
					
					$tradeupdate['trade_position_amount'] = number_format($total_position_amount->quantity,5);	

				}else{
					$tradeupdate['trade_position_amount'] = 0.00;
				}

		        if ($total_position_quantity->received_amount > 0) {

				$tradeupdate['trade_position_quantity'] = number_format($total_position_quantity->received_amount,5);

			    }else{

					$tradeupdate['trade_position_quantity'] = 0.00;

				}

		
				
				 // // $avg_position_amount = $this->db->table('api_trade_history')->selectAvg('live_price')->where($api_trade_data)->get()->getRow();

     //    $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
     //    $total_usdt = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->get()->getRow();

     //  //   $current_buy = $this->db->table('api_trade_history')->where($api_trade_data)->get()->getResult();
     //  //           $total_amount_bought = 0;

     //  //   if(!empty($current_buy)){        
     //  //   foreach ($current_buy as $key => $value) {
     //  //         $total_amount_bought1 = $value->received_amount * $value->quantity;
     //  //         $total_amount_bought = $total_amount_bought + $total_amount_bought1;
     //  //   }
     //  // }

        
     //    $avg_position_amount = $total_usdt->quantity / $total_contract->received_amount;


		
				if ($avg_position_amount > 0) {
					$tradeupdate['trade_avg_position'] = number_format($avg_position_amount,5);
				}else{
					$tradeupdate['trade_avg_position'] = 0.00;
				}

				$call_drop = $this->db->table('api_trade_history')->where($api_trade_data2)->where('margin_call_drops !=',0)->orderBy('id','DESC')->get()->getRow();

		if($call_drop->margin_call_drops == $trade_record->margin_column_limit){
            $tradeupdate['down_price'] = "Limit Reached";
            $tradeupdate['margin_call_drops'] = "0";
        }


		if (!empty($call_drop)) {
			$tradeupdate['trade_number_of_call'] = $call_drop->margin_call_drops;
		}else{
			$tradeupdate['trade_number_of_call'] = '0';
		}

			

				$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$uusersid)->get()->getRow();

					$api_trade_data = array(
						'trade_process_id' => $trade_record->id,
						'uuserid' => $uusersid,
						'type' => '1',
					);

					if(empty($live_price)){
						$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$uusersid)->get()->getRow();
                         $key = $userid_bind_process->api_key;
						$secret = $userid_bind_process->secret_key;
						$api = new Binance\API($key,$secret);
						$ticker = $api->prices($pair);
                        $live_price =  $ticker[$pair];
					}
					

					$tradeupdate['live_price'] = $live_price;
					// $first_buy =  $this->db->table('api_trade_history')->where($api_trade_data)->like('description','first_buy')->get()->getRow();


					// $first_buy_live_price = $first_buy->live_price;

					$avg_position_amount = str_replace(',', '', $avg_position_amount);
                    $live_price = str_replace(',', '', $live_price);
          if($avg_position_amount == 0 &&  $tradeupdate['trade_position_amount'] == 0){
            $check_percentage = '0';
          }       

		  else if ($avg_position_amount > $live_price) {
            
            // echo "first_buy = ".$first_buy_live_price.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";
            // echo "decrease";
            
            $check_percentage = ($avg_position_amount - $live_price);
            $check_percentage = $check_percentage  / $avg_position_amount;
            $check_percentage = $check_percentage  * 100 ;
            $check_percentage = '-'.number_format($check_percentage,2).'%';
          }elseif ($avg_position_amount == $live_price) {
            
            // echo "first_buy = ".$avg_position_amount.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";

            // echo "same";
            $check_percentage = '0.00';
          }else{
            
            // echo "first_buy = ".$avg_position_amount.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";

            // echo "increase";
            $check_percentage = $live_price - $avg_position_amount;
            $check_percentage = $check_percentage  / $live_price;
            $check_percentage = $check_percentage  * 100 ;
          }

          $tradeupdate['trade_rate_percentage'] = number_format($check_percentage,2).'%';





					if ($avg_position_amount > $live_price) {
						
						// echo "first_buy = ".$avg_position_amount.'  -  ';
						// echo "live_price  = ".$live_price;
						// echo "<br>";
						// echo "decrease";
						
					$check_percentage1 = ($avg_position_amount - $live_price) / $avg_position_amount * 100 ;
						    $check_percentage1 = '-'.number_format($check_percentage1,2).'%';
					}elseif ($avg_position_amount == $live_price) {
						
						// echo "first_buy = ".$avg_position_amount.'  -  ';
						// echo "live_price  = ".$live_price;
						// echo "<br>";

						// echo "same";
						$check_percentage1 = '0.00';
					}else{
						// echo "first_buy = ".$avg_position_amount.'  -  ';
						// echo "live_price  = ".$live_price;
						// echo "<br>";
						// echo "increase";
						$check_percentage1 = ($live_price - $avg_position_amount) / $live_price * 100 ;
					}

					$tradeupdate['trade_estimate_price'] = number_format($check_percentage1,2).'%';

				
				

				return json_encode($tradeupdate);

			}

	}


	public function buy_calculate(){

		$pair = $this->request->getPost('pair');
		$uusersid = $this->request->getPost('uusersid');
		$where_ = array(
				'pair' => $pair,
				'uusersid' => $uusersid,
				'trade_status != ' => '2',
			);
		$trade_record =  $this->db->table('trade_process')->where($where_)->orderBy('id','DESC')->get()->getRow();
		$api_trade_data = array(
					'trade_process_id' => $trade_record->id,
					'uuserid' => $uusersid,
					'type' => '1',
					'status' => 0
		);
        $total_bought = $this->request->getPost('buy_amount');
	    $live_price   = $this->request->getPost('live_price');
	    $total_contract1 = $total_bought * $live_price;
	    $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
        $total_contract = $total_contract->received_amount + $total_contract1;
        $current_buy = $this->db->table('api_trade_history')->where($api_trade_data)->get()->getResult();




        $total_amount_bought = 0;

        if(!empty($current_buy)){        
        foreach ($current_buy as $key => $value) {
              $total_amount_bought1 = $value->received_amount * $value->quantity;
              $total_amount_bought = $total_amount_bought + $total_amount_bought1;
        }
      }

	

      $total_amount_bought_new = $total_bought * $total_contract1;

      $total_amount_bought = $total_amount_bought + $total_amount_bought_new;


        
        $avg_position_amount = $total_amount_bought / $total_contract ;




		
				if ($avg_position_amount > 0) {
					$tradeupdate['trade_avg_position'] = number_format($avg_position_amount,5);
				}else{
					$tradeupdate['trade_avg_position'] = 0.00;
				}

					if ($tradeupdate['trade_avg_position'] > $live_price) {
						
						// echo "first_buy = ".$first_buy_live_price.'  -  ';
						// echo "live_price  = ".$live_price;
						// echo "<br>";
						// echo "decrease";
						
					$check_percentage = ($tradeupdate['trade_avg_position'] - $live_price) / $tradeupdate['trade_avg_position'] * 100;
						$check_percentage = '-'.number_format($check_percentage,2).'%';
					}elseif ($tradeupdate['trade_avg_position'] == $live_price) {
						
						// echo "first_buy = ".$tradeupdate['trade_avg_position'].'  -  ';
						// echo "live_price  = ".$live_price;
						// echo "<br>";

						// echo "same";
						$check_percentage = '0.00';
					}else{
						
						// echo "first_buy = ".$tradeupdate['trade_avg_position'].'  -  ';
						// echo "live_price  = ".$live_price;
						// echo "<br>";

						// echo "increase";
						$check_percentage = ($live_price - $tradeupdate['trade_avg_position']) / $live_price * 100 ;
					}

						$tradeupdate['trade_rate_percentage'] = number_format($check_percentage,2).'%';
                        return json_encode($tradeupdate);

	    }

	    public function order_message(){
	    	echo view('user/order_message');
	    }

	        public function system_information(){
	    	echo view('user/system_information');
	    }


public function autoLoadPrice()
{

	if ($this->request->isAJAX()) {

     $symbol = service('request')->getPost('symbol');

     $trim_symbol = str_replace('USDT','', $symbol);

	$this->session = session();
    $uusersid = $this->session->get('uusersid');
	$validation =  \Config\Services::validation();
	$this->db = db_connect();
	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."'")->getResult();
	$ref=$referral1[0];
	$key = $ref->api_key;
	$secret = $ref->secret_key;

if(empty($ref)){
  $key = "wcYWabBn1sHWzvVmYjwQrF8JMbh8ngCUW3oA1IbEJrghBgqmB1U9BMMQUGmU42hv";
$secret = "1cSiCLlNnfKhcaX0wyIhXB1QLFtckdzKxR7Lqq2TlB0CQB31xdNoeGbwx39NjDra";
$api = new Binance\API($key,$secret,true);
}else
   $api = new Binance\API($key,$secret);

	$marketpair = $api->prevDay();


	$i=0;
	$required_pairs = [$trim_symbol];
	foreach ($marketpair as $key => $value) {

if($value['symbol']==$symbol)
{

	if(substr($value['symbol'], -4) == "USDT"){
	if(in_array(substr_replace($value['symbol'] ,"",-4), $required_pairs)){
	$output[$i]['symbol'] = $value['symbol'];
	$output[$i]['price'] = $value['lastPrice'];
	$output[$i]['change'] = $value['priceChangePercent'];
	}
	$i++;
	}

if($output){
foreach ($output as $key => $value) {
	echo number_format($value['price'],4);
}
}
}
}

}

}


}
