<?php

namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use Binance;
use Lin\Ftx\Ftx;
use Lin\Okex\OkexV5;
use App\Libraries\BybitApi;
use App\Helpers\site_helper;
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');
			$strategy_mode = $this->request->getPost('strategy_mode');
			$remark = $this->request->getPost('remark');
			$strategy_type = $this->request->getPost('strategy_type');
			$risk_type = $this->request->getPost('risk_type');
			$session = \Config\Services::session();
	 		$uusersid = $session->get('uusersid');
			$condition1 = "uusersid ='".$uusersid."'";
			$user = $this->common_model->GetRow('user_strategy',$condition1);
			$member = $this->db->table('user_strategy')->where('uusersid',$uusersid)->where('pair',$id)->get()->getRow();
		//	print_r($member);
// 			exit;
			if($member=='')
			{
				
		 		$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,
					'strategy_mode' => $strategy_mode,
					'risk_type' => $risk_type,
					'remark' => $remark,
					'strategy_type' => $strategy_type,
			        "pair"	=>  $id
				);

		    $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');
// 			}
// 				throw new \CodeIgniter\Router\Exceptions\RedirectException('tradedetails/'.$id);
				
			
		}
		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,
			"sub_position_callback" =>  $sub_position_callback,
			'strategy_mode' => $strategy_mode,
			'remark' => $remark,
			'strategy_type' => $strategy_type,
			'risk_type' => $risk_type,
		    'pair' => $id,
		    'uusersid'=> $uusersid

			);
			$this->db = db_connect();
			$session = session();
        
     		$check_pair_process =$this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and pair ='".$id."' and trade_status != 2 order by id desc")->getRow();
			if($check_pair_process)
			{
				$query_status = $this->db->table('trade_process')->where('uusersid', $uusersid)->where('id', $check_pair_process->id)->update($trade_data1);
			}
			else
			{
			    $check_pair_process =$this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' and pair ='".$id."' order by id desc")->getRow();
			    if($check_pair_process)
			    {
			        $query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->where('pair',$id)->update($trade_data1);
			    }
			    else
			    {
			        $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');
// 			}
// 			throw new \CodeIgniter\Router\Exceptions\RedirectException('tradedetails/'.$id);

		}


       
		if($this->request->getPost('strategy') === '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');
            $member = $this->db->table('user_strategy')->where('uusersid',$uusersid)->where('pair',$id)->get()->getRow();

			$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,
		        'pair'=>$id
			);
			
		

			$this->db = db_connect();
			
				if($member=='')
		     	{
		     	    $query_status = $this->db->table('user_strategy')->insert($trade_data);
		     	}
		     	else
		     	{ 
		     	  $query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->where('pair',$id)->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();
		if($this->session->get('exchange')){
			$exchange = $this->session->get('exchange');
		}else{
			$exchange = 1;
		}

	
		if($exchange == 1) /*binance */
			$bind_api =$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='1'")->getRow();
		else if($exchange == 7) /*kucoin*/
			$bind_api =$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='7'")->getRow();
		else if($exchange == 5) /*bybit*/
			$bind_api =$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='5'")->getRow();
		else if($exchange == 6) /*okex*/
			$bind_api =$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='6'")->getRow();
		else if($exchange == 4) /*okex*/
			$bind_api =$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='4'")->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 exchange ='".$exchange."'  and trade_status != 2 order by id desc limit 1")->getRow();
        
        if(empty($trade_process))
        {
            
           
           $trade_process =$this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' and pair='".$id."' order by id desc")->getRow();
           if($trade_process)
           {
               
            $trade_process =$this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' and pair='".$id."' order by id desc")->getRow();
               
           }
           else
           {
              
                $trade_process =$this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' and pair='0' order by id desc")->getRow();
           }
		   
        }
        
        
        
        
        $this->data['trade_process'] = $trade_process;

	

    echo view('user/tadedetail',$this->data);
}

public function trade_change($id)
{
        $this->db = db_connect();
		$session = \Config\Services::session();
		$uusersid=$session->get('uusersid');
		$condition = "uusersid ='".$uusersid."'";
        $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,
		    "sub_position_callback" =>  $sub_position_callback,
			'strategy_mode' => $strategy_mode,
			'remark' => $remark,
			'strategy_type' => $strategy_type
			// "sync_strategy_status"	=>  0

			);
			
        
     		$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');
			}
			
			print_r($trade_data1);
			exit;
			
			throw new \CodeIgniter\Router\Exceptions\RedirectException('tradedetails/'.$id);	

    
    
}

public function trades()
{
	$this->common_model = model('CommonModel');
	$session = \Config\Services::session();
	$uusersid = $session->get('uusersid');
	if($this->session->get('exchange'))
	{
		$exchange = $session->get('exchange');
	}
	else
	{
		$exchange = 1;
	}
	$segments = $this->request->uri->getSegments();
	$symbol=$segments[1];
	
	
	$get_records=$this->db->table('api_trade_history')->where('uuserid',$uusersid)->where('pair',$symbol)->where('exchange',$exchange)->orderBy('time','desc')->limit(10)->get()->getResult();

	$get_count=$this->db->query("select * from api_trade_history where uuserid='".$uusersid."' and pair='".$symbol."' and exchange='".$exchange."'")->getNumRows();
	

	
	$this->data['records']=$get_records;
	$this->data['count']=$get_count;
	$this->data['count']=$get_count;
	$this->data['symbol']=$symbol;
	echo view('user/trades_list',$this->data);
	


}





public function trade_records()
{

	$this->common_model = model('CommonModel');
	$session = \Config\Services::session();
	$exchange= $this->request->getPost('exchange');
	$userid = $this->request->getPost('uusersid');
	$pair = $this->request->getPost('pair');
	$page = $this->request->getPost('page');
	$itemsPerPage = $this->request->getPost('itemsPerPage');
	$offset = ($page - 1) * $itemsPerPage;
	$start_date = $this->request->getPost('start_date');
	$end_date = $this->request->getPost('end_date');

	$ordermode= $this->request->getPost('ordermode');
	$sta_mode=$this->request->getPost('stamode');


	
	$condi="uuserid='".$userid."' and exchange='".$exchange."'";
    if($start_date!='' && $end_date!='')
	{
		$condi.=" and date between '".$start_date."' and '".$end_date."'";
	}
	if($pair!='')
	{
		$condi.=" and pair='".$pair."'";
	}
	if($sta_mode!='')
	{
		$condi.=" and strategy_mode='".$sta_mode."'";
	}

	if($ordermode!='')
	{
		if($ordermode=='1' || $ordermode=='2')
			$condi.=" and type='".$ordermode."' and description not like '%manual%'";
		else if($ordermode=='3')
			$condi.=" and type='1' and description like '%manual_buy%' ";
		else if($ordermode=='4')
			$condi.=" and type='2' and description like '%manual_sell%' ";	
	}



	$totalItems =$this->db->query("select * from api_trade_history where $condi")->getNumRows();
	$get_records =$this->db->query("select * from api_trade_history where  $condi order by id desc limit $offset,$itemsPerPage")->getResult();


	
    /*if($start_date!='' && $end_date!='')
	{
		$totalItems =$this->db->query("select * from api_trade_history where date between '".$start_date."' and '".$end_date."' and  uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."'")->getNumRows();
		$get_records =$this->db->query("select * from api_trade_history where date between '".$start_date."' and '".$end_date."' and uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."' order by id desc limit $offset,$itemsPerPage")->getResult();
	}
	else
	{
		$totalItems =$this->db->query("select * from api_trade_history where uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."'")->getNumRows();
		$get_records =$this->db->query("select * from api_trade_history where uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."' order by id desc limit $offset,$itemsPerPage")->getResult();
	}*/
	$totalPages = ceil($totalItems / $itemsPerPage);
	

	
	$items = array();
	if($get_records)
	{
		foreach($get_records as $row)
		{
			$get_mode=$this->db->query("select * from trade_process where id='".$row->trade_process_id."'")->getRow();
            //$mode=$get_mode->strategy_type;
            $mode=$row->strategy_type;
			if($row->type=='1')
			{   
				$turnover='-';
				$label="<label class='btn btn-success'>Buy</label>";
				$profit='';
				$fuel='';
				$percentage='';
			}
			else
			{
			   	 if($row->description=='')
			        $desc='Sell';
			    else
			       $desc=$row->description;
			      
			     $desc=str_replace('_',' ',$desc);
			     $desc=ucwords($desc);
				$turnover=$row->quantity;
				$label="<label class='btn btn-danger'>".$desc."</label>";
				$profit=$row->comm_price;
				$percentage=$row->profit_percentage;
				$description = "fuel fee deduction for order no ".$row->order_id;
				
				
				$get_fuel=$this->db->query("select * from history where uusersid='".$userid."' and description like '%$description%'")->getRow();
				if($get_fuel)
				{
				    $fuel=$get_fuel->amount;
				}
				else
				{
				    $fuel='0.00';
				}
			}

			$order_time=date("Y-m-d H:i:s",$row->time/1000);
            $base = substr($row->pair, 0, -4);
            
            $base = substr($row->pair, 0, -4);
            $pair_disp=$base.'/USDT';


			if($row->strategy_mode=='1')
				$sta_modes='Warehouse Mode';
			else if($row->strategy_mode=='2')
				$sta_modes='Subbin Mode';
			else 
				$sta_modes='Subbin Realtime';


			if($row->type=='1' && $row->description!='manual_buy')
			{
				$order_mode='Auto Buy';
			}
			else if($row->type=='1' && $row->description=='manual_buy')
			{
				$order_mode='Manual Buy';
			}

			
			else if($row->type=='2' && $row->description!='manual_sell')
			{
				$order_mode='Auto Sell';
			}
			else
			{
				$order_mode='Manual Sell';
			}

			$items[] = [
				'id' => $row->id,
				'image' =>'styles/images/tradingpair_images/'.$row->pair.'.png',
				'pair' => $pair_disp,
				'mode' => $mode,
				'type' => $label,
				'method' => $row->type,
				'profit' => $profit,
				'percentage' => $percentage,
				'fuel' => $fuel,
				'turnover' => $turnover,
				'orderTime' => $order_time,
				'sta_mode' => $sta_modes,
				'order_mode' => $order_mode,
				'orderNo' => $row->order_id,
				'averagePrice' => $row->live_price,
				'filledQuantity' => $row->received_amount,
				'filledAmount' => $row->quantity,
				'tradingPair' => $base,
				'currency' => 'USDT'
			];

		}
	}
	echo json_encode([
		'items' => $items,
		'hasPrev' => $page > 1,
		'hasNext' => $page < $totalPages,
		'totalPages' => $totalPages,
		'totalitems' => $totalItems
	]);
	
}

public function orders()
{
	$this->common_model = model('CommonModel');
	$session = \Config\Services::session();
	$uusersid = $session->get('uusersid');
	if($this->session->get('exchange'))
	{
		$exchange = $this->session->get('exchange');
	}
	else
	{
		$exchange = 1;
	}
	$symbol='';
	$get_records=$this->db->table('api_trade_history')->where('uuserid',$uusersid)->where('exchange',$exchange)->orderBy('time','desc')->limit(10)->get()->getResult();
	$get_count=$this->db->query("select * from api_trade_history where uuserid='".$uusersid."' and exchange='".$exchange."'")->getNumRows();
	
	$this->data['records']=$get_records;
	$this->data['count']=$get_count;
	$this->data['count']=$get_count;
	$this->data['symbol']=$symbol;
	echo view('user/orders_list',$this->data);
	


}

public function order_records()
{

	$this->common_model = model('CommonModel');
	$session = \Config\Services::session();
	$exchange= $this->request->getPost('exchange');
	$userid = $this->request->getPost('uusersid');
	$pair = $this->request->getPost('pair');
	$page = $this->request->getPost('page');
	$itemsPerPage = $this->request->getPost('itemsPerPage');
	$offset = ($page - 1) * $itemsPerPage;
	$start_date = $this->request->getPost('start_date');
	$end_date = $this->request->getPost('end_date');
	$ordermode= $this->request->getPost('ordermode');
	$sta_mode=$this->request->getPost('stamode');

	
	$condi="uuserid='".$userid."' and exchange='".$exchange."'";
    if($start_date!='' && $end_date!='')
	{
		$condi.=" and date between '".$start_date."' and '".$end_date."'";
	}
	if($pair!='')
	{
		$condi.=" and pair='".$pair."'";
	}
	if($sta_mode!='')
	{
		$condi.=" and strategy_mode='".$sta_mode."'";
	}

	if($ordermode!='')
	{
		if($ordermode=='1' || $ordermode=='2')
			$condi.=" and type='".$ordermode."' and description not like '%manual%'";
		else if($ordermode=='3')
			$condi.=" and type='1' and description like '%manual_buy%' ";
		else if($ordermode=='4')
			$condi.=" and type='2' and description like '%manual_sell%' ";	
	}



	$totalItems =$this->db->query("select * from api_trade_history where $condi")->getNumRows();
	$get_records =$this->db->query("select * from api_trade_history where  $condi order by id desc limit $offset,$itemsPerPage")->getResult();

		

    /*if($start_date!='' && $end_date!='')
	{
		
		if($pair=='')
		{
			$totalItems =$this->db->query("select * from api_trade_history where date between '".$start_date."' and '".$end_date."' and  uuserid='".$userid."' and exchange='".$exchange."'")->getNumRows();
			$get_records =$this->db->query("select * from api_trade_history where date between '".$start_date."' and '".$end_date."' and uuserid='".$userid."' and exchange='".$exchange."' order by id desc limit $offset,$itemsPerPage")->getResult();
		}
		else
		{
			$totalItems =$this->db->query("select * from api_trade_history where date between '".$start_date."' and '".$end_date."' and  uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."'")->getNumRows();
			$get_records =$this->db->query("select * from api_trade_history where date between '".$start_date."' and '".$end_date."' and uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."' order by id desc limit $offset,$itemsPerPage")->getResult();
		}
	}
	else
	{
		if($pair!='')
		{
			$totalItems =$this->db->query("select * from api_trade_history where uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."'")->getNumRows();
			$get_records =$this->db->query("select * from api_trade_history where uuserid='".$userid."' and exchange='".$exchange."' and pair='".$pair."' order by id desc limit $offset,$itemsPerPage")->getResult();
		}
		else
		{
			$totalItems =$this->db->query("select * from api_trade_history where uuserid='".$userid."' and exchange='".$exchange."'")->getNumRows();
			$get_records =$this->db->query("select * from api_trade_history where uuserid='".$userid."' and exchange='".$exchange."' order by id desc limit $offset,$itemsPerPage")->getResult();
		}
	}*/
	$totalPages = ceil($totalItems / $itemsPerPage);
	

	
	$items = array();
	if($get_records)
	{
		foreach($get_records as $row)
		{
			$get_mode=$this->db->query("select * from trade_process where id='".$row->trade_process_id."'")->getRow();
            //$mode=$get_mode->strategy_type;
            $mode=$row->strategy_type;
			if($row->type=='1')
			{   
				$turnover='-';
				$label="<label class='btn btn-success'>Buy</label>";
				$profit='';
				$fuel='';
				$percentage='';
			}
			else
			{
				$turnover=$row->quantity;
				
				 if($row->description=='')
			        $desc='Sell';
			    else
			       $desc=$row->description;
			      
			     $desc=str_replace('_',' ',$desc);
			     $desc=ucwords($desc);
				$label="<label class='btn btn-danger'>".$desc."</label>";
				$profit=$row->comm_price;
				$percentage=$row->profit_percentage;
				$description = "fuel fee deduction for order no ".$row->order_id;
				$get_fuel=$this->db->query("select * from history where uusersid='".$userid."' and description like '%$description%'")->getRow();
				if($get_fuel)
				{
				    $fuel=$get_fuel->amount;
				}
				else
				{
				    $fuel='0.00';
				}
			}

			$order_time=date("Y-m-d H:i:s",$row->time/1000);
            $base = substr($row->pair, 0, -4);
            $base = substr($row->pair, 0, -4);
            $pair_disp=$base.'/USDT';

			$pair_descr=str_replace("_",'',$row->description);
			$pair_desc=ucwords($pair_descr);

			if($row->strategy_mode=='1')
				$sta_modes='Warehouse Mode';
			else if($row->strategy_mode=='2')
				$sta_modes='Subbin Mode';
			else 
				$sta_modes='Subbin Realtime';


			if($row->type=='1' && $row->description!='manual_buy')
			{
				$order_mode='Auto Buy';
			}
			else if($row->type=='1' && $row->description=='manual_buy')
			{
				$order_mode='Manual Buy';
			}

			
			else if($row->type=='2' && $row->description!='manual_sell')
			{
				$order_mode='Auto Sell';
			}
			else
			{
				$order_mode='Manual Sell';
			}


			
			$items[] = [
				'id' => $row->id,
				'image' =>'styles/images/tradingpair_images/'.$row->pair.'.png',
				'pair' => $pair_disp,
				'mode' => $mode,
				'type' => $label,
				'method' => $row->type,
				'profit' => $profit,
				'percentage' => $percentage,
				'fuel' => $fuel,
				'turnover' => $turnover,
				'description' => $pair_desc,
				'sta_mode' => $sta_modes,
				'order_mode' => $order_mode,
				'orderTime' => $order_time,
				'orderNo' => $row->order_id,
				'averagePrice' => $row->live_price,
				'filledQuantity' => $row->received_amount,
				'filledAmount' => $row->quantity,
				'tradingPair' => $base,
				'currency' => 'USDT'
			];

		}
	}

	echo json_encode([
		'items' => $items,
		'hasPrev' => $page > 1,
		'hasNext' => $page < $totalPages,
		'totalPages' => $totalPages,
		'totalitems' => $totalItems
	]);
	
}

public function margin_update()
{
	$this->common_model = model('CommonModel');
	$session = \Config\Services::session();

	if($this->session->get('exchange'))
	{
		$exchange = $this->session->get('exchange');
	}
	else
	{
		$exchange = 1;
	}

	$num= $this->request->getPost('magin_col_limit');
	$id= $this->request->getPost('pair');
	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(!empty($trade3))
			{
			 $tade3=implode(',',$trade3);
			}
			else
			{
			$tade3 = 0;
			}


			$session = \Config\Services::session();
				$this->db = db_connect();
	 		$uusersid = $session->get('uusersid');
			$condition1 = "uusersid ='".$uusersid."'";
			$user = $this->common_model->GetRow('user_strategy',$condition1);
			$member = $this->db->table('user_strategy')->where('uusersid',$uusersid)->where('pair',$id)->get()->getRow();
// 			print_r($member);
// 			exit;
			if($member=='')
			{
				
		 		$trade_data1=array(
		 		
			        "margincall_drop"		=> 	$tade1,
			        "buyin_ratio_times"		=>	$tade2,
			        "sub_position"           => $tade3,
					"margin_column_limit" 	=>  $num,
		
				);

		    $this->db = db_connect();
			$session = session();
			
			$uusersid=$session->get('uusersid');
			
		
		    
		 
			$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(
		
			"margincall_drop"		=> 	$tade1,
			"buyin_ratio_times"		=>	$tade2,
		    "sub_position"           => $tade3,
			"margin_column_limit" 	=>  $num,
			

			);

		
			$session = session();
        	$check_pair_process =$this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and pair ='".$id."' and exchange='".$exchange."' order by id desc")->getRow();
			if($check_pair_process)
			{
				$query_status = $this->db->table('trade_process')->where('uusersid', $uusersid)->where('pair', $id)->where('exchange',$exchange)->update($trade_data1);
			}
			
			$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->where('pair', $id)->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');
			}
		}

		return redirect()->to('tradesettings/'.$id);

}

public function order_ftx($orderid,$ftx){
	$result = $ftx->orders()->get([
        'order_id'=>$orderid,
    ]);
    if($result['result']['status'] != "new")
    return $result;
    else
    	$this->order_ftx($orderid,$ftx);
}
// start the trade
public function tradingprocess(){
	$session= \Config\Services::session();
	
	if(!empty($session->get('uusersid')))
	    $uusersid=$session->get('uusersid');
	else
	    $uusersid=$this->request->getPost('uusersid');

	$exchange= $this->session->get('exchange');
	
	if($exchange=='')
	    $exchange='1';
	
	$this->db = db_connect();
	/*$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."'")->getResultArray();
	$qry=$qury[0];
	if(empty($qry)){
		$qury = $this->db->query("SELECT * FROM suggested_strategy WHERE id='1' ")->getResultArray();
		    $qry=$qury[0];
	}*/
	

	
	
	$qry='';
    $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$this->session->get('uusersid')."' And pair='".$this->request->getPost('id')."'")->getResultArray();
    if(!empty($qury[0]))
    {
        $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$this->session->get('uusersid')."' And pair='".$this->request->getPost('id')."'")->getResultArray();
        $qry=$qury[0];
    }
    else
    {
        //echo '2';
        $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$this->session->get('uusersid')."' And pair='0'")->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 and exchange= '".$this->request->getPost('exchange')."' order by id desc")->getRowArray();
	if(empty($trade_query))
	{
	   
		$qry['trade_status'] = 1;
		unset($qry['sync_strategy_status']);
		unset($qry['no_strategies']);
		unset($qry['currency_block_list']);
		unset($qry['id']);
		if(!isset($qry['uusersid']) || $qry['uusersid'] == ""){
			$qry['uusersid'] = $this->session->get('uusersid');
		}
		$qry['margin_call'] = 1;
		$qry['created_time'] = time();
		$qry['sync_strategy_status'] = 0;
		$qry['strategy_id'] = 0;
		$qry['exchange'] = $exchange;

		$total_asset=0;
        if($exchange == 1)/*Binance Balance*/ 
		{ 
			$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$qry['uusersid']."' and type='1'");
			$ref=$referral1->getRow();
			$key = $ref->api_key;
			$secret = $ref->secret_key;
			$total_asset=0;
			$balances=binance_balance($key,$secret);
			if($balances)
			{
			    $total_asset=$balances;
			}
        }
		else if($exchange == 2) /*Huobi*/
		{
			

		}
		else if($exchange == 3)/*Indodax*/ 
		{
			
		}
		else if($exchange == 4)/*Kraken*/ 
		{
			
		}
		else if($exchange == 5)/*ByBit*/
		{
			$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$qry['uusersid']."' and type='5'");
			$ref=$referral1->getRow();
			$key = $ref->api_key;
			$secret = $ref->secret_key;
			$account = $ref->account;
		    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
			$bybitApi = new BybitApi($key, $secret);
			$total_asset = $bybitApi->getBalance('USDT',$acc_type);
			
		}
		else if($exchange == 7)/*Kucoin Balance*/
		{
			$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$qry['uusersid']."' and type='7'");
			$ref=$referral1->getRow();
			$key = $ref->api_key;
			$secret = $ref->secret_key;
			$pass_phrase = $ref->pass_phrase;
			$total_asset=accountbalance($key,$secret,$pass_phrase);
		}
		else if($exchange == 6) /*Okex Balance*/
		{
				$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$qry['uusersid']."' and type='6'");
				$ref=$referral1->getRow();
				$key = $ref->api_key;
				$secret = $ref->secret_key;
				$passphrase = $ref->pass_phrase;
				$api = new OkexV5($key,$secret,$passphrase);
				$result_pre =$api->account()->getBalance([
				]);
   				 $result = $result_pre['data'][0]['details'];
        		if(!empty($result)) 
				{ 
        			foreach ($result as $key => $value) 
					{
        				if($value['ccy'] == "USDT")
						{
							$total_asset = $value['availBal'];
							break;
        				}
						else
        					$total_asset = 0;
        				}
        			}
					else
					{
        				$total_asset = 0;
        			}
        }
		else
		{
				$referral1=$this->db->query("SELECT * FROM ftx_bind_process WHERE uusersid='".$qry['uusersid']."'");
				$ref = $referral1->getRow();
				$key = $ref->api_key;
				$secret = $ref->secret_key;
				$ftx = new Ftx($key,$secret);
				$ftx->setOptions([
					//Set the request timeout to 60 seconds by default
					'timeout'=>10,
					//If you are developing locally and need an agent, you can set this
					//'proxy'=>true,
					//More flexible Settings
					/* 'proxy'=>[
					'http'  => 'http://127.0.0.1:12333',
					'https' => 'http://127.0.0.1:12333',
					'no'    =>  ['.cn']
					], */
					//Close the certificate
					//'verify'=>false,
					//Set Demo Trading
				]);   
				$fet=$ftx->wallet()->getBalances();   // No test feature in FTX
				if(!empty($fet['result'])) 
				{ 
					foreach ($fet['result'] as $key => $value) 
					{
						if($value['coin'] == "USDT")
						{
							$total_asset = $value['total'];
							break;
						}
						else
						$total_asset = 0;
					}
				}
				else
				{
					$total_asset = 0;
				}
        }

		$total_asset=str_replace(",",'',$total_asset);
	

		if($total_asset >= $qry['first_buy_amount'])
		{
		    
		    $query_status = $this->db->table('trade_process')->insert($qry);
         	$last_id = $this->db->insertId();
         	
		}
		else
		{
		    echo 2;
		    exit;
		}
		
	
  
       if($last_id)
	   {
	       
       	  $qry_new = $this->db->query("SELECT * FROM trade_process WHERE id='".$last_id."'")->getRowArray();
       	    if($qry_new['open_position_doubled'] != 'on' || $qry_new['open_position_doubled'] == '')
        	    $quantity = 1;
            else
            	$quantity = 2;
            $price = $qry_new['first_buy_amount'] * $quantity;
           
			if($exchange == 1) 
			{     
				$flags['isQuoteOrder'] = true;	
			     $order=binance_order($key,$secret,"BUY", $qry_new['pair'], $price, 0,"MARKET",$flags);
			     if($order['orderId'])
			     {
    			    
    			  
    				$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'],
    				'strategy_type' =>$qry_new['strategy_type'],
    				'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'],
    				'exchange'  => $exchange,
    				'status' => 0
    				);
		           $this->db = db_connect();
				    $this->db->table('api_trade_history')->insert($order_history);
				    return true;
			     }
			     else
			     {
			         $this->db->query("delete from trade_process where id='".$last_id."'");
			         return $order['msg'];
			         
			     }
                
			}
			else if($exchange == 7) /* Kucoin */
			{
				$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$qry['uusersid']."' and type='7'");
				$ref=$referral1->getRow();
				$key = $ref->api_key;
				$secret = $ref->secret_key;
				$order = buyorder($qry_new['pair'], $price,$key,$secret);
				if($order)
				{
					$response=explode("&&",$order);
					$message=$response[0];
					$order=$response[1];
					
					if($message=="Success")
					{

						$orderDetails = fetchOrderDetails($order);
						if($orderDetails)
						{

						$order_history = array(
							'pair' => $qry_new['pair'],
							'order_id' => $order,
							'trade_process_id' => $qry_new['id'],
							'uuserid' => $qry_new['uusersid'],
							'type' => '1',
							'strategy_mode' => $qry_new['strategy_mode'],
							'strategy_type' =>$qry_new['strategy_type'],
							'quantity' => $price,
							'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'],
							'exchange'  => $exchange,
							'status' => 0
							);
					
							$this->db = db_connect();
							$this->db->table('api_trade_history')->insert($order_history);
							return true;
						}
						else
						{

							$message="Order Details Not retrived ID ".$order." record ";
							$notification = array(
								'uusersid' => $qry['uusersid'], 
								'message'  => $message.' for pair:'.$qry_new['pair'],
								'created_date' => date('Y-m-d H:i:s')
							);
							$this->db->table('notification_table')->insert($notification);

						}

					}
					else
					{
						
						$notification = array(
							'uusersid' => $qry['uusersid'], 
							'message'  => $message.' for pair:'.$qry_new['pair'],
							'created_date' => date('Y-m-d H:i:s')
						);
						$this->db->table('notification_table')->insert($notification);

					}

				}

			}
			else if($exchange == 5) /* ByBit */
			{
			    
				$minOrderValue = $price; 
				$tickers = $bybitApi->ticker(['category' => 'linear', 'symbol' => $qry_new['pair']]);
				$currentPrice = $tickers['lastPrice']; 
				$qty = ceil($minOrderValue / $currentPrice);
				$orderlinkid = "ByBit_".rand(11111111,99999999);
				$other = ['orderLinkId' => $orderlinkid]; // User customised order ID. A max of 36 characters. Combinations of numbers, letters (upper and lower cases), dashes, and underscores are supported. it will be returned .
				$order = $bybitApi->order('linear',$qry_new['pair'],'Buy','Market',"$qty","0",$other);
			
				$orderid = isset($order['result']['orderId']) ? $order['result']['orderId'] : false;

				

				if($orderid)
				{

					return $orderid.'&&'.$qry_new['id'].'&&'.$price;
					//$order_det = $bybitApi->GetOrders(['category' => 'linear','orderId' => $orderid]);

					//echo '<pre>';
					//print_r($order_det);
					//echo '</pre>';

					/*if(isset($order_det['result']['list']) && !empty($order_det['result']['list']))
					{
						$history = $order_det['result']['list'][0];
						$order_history = array(
							'pair' => $qry_new['pair'],
							'order_id' => $orderid,
							'trade_process_id' => $qry_new['id'],
							'uuserid' => $qry_new['uusersid'],
							'type' => '1',
							'strategy_mode' => $qry_new['strategy_mode'],
							'strategy_type' => $qry_new['strategy_type'],
							'quantity' => $history['cumExecValue'],
							'original_quantity' => $price,
							'time' => $history['createdTime'],
							'received_amount' => $history['cumExecQty'],
							'date' => date('Y-m-d',time()),
							'description'=>'first_buy',
							'live_price' => $history['lastPriceOnCreated'],
							'exchange'  => $exchange,
							'status' => 0
						);

										
						$this->db = db_connect();
						$this->db->table('api_trade_history')->insert($order_history);
						return true;
					}*/
				}
			}
			else if($exchange == 6) /* OKEX */
			{
				$new = substr_replace( $qry_new['pair'], '-', -4, 0 );
				$order_check=$api->trade()->postOrder([
				'instId'=> $new,
				'tdMode'=>'cash',
				'side'=>'buy',
				'ordType'=>'market',
				'sz'=> $price
				]);
				$res_okex_orderid = $order_check['data'][0]['ordId'];
				
				$order = $api->trade()->getOrder([
				'instId'=> $new,
				'ordId'=> $res_okex_orderid
				]);

				
	
					$order = $order['data'][0];
						echo"<pre>";
					print_r($order);
					echo"</pre>";
					$order_history = array(
						'pair' => str_replace('-', '', $order['instId']),
						'order_id' => $order['ordId'],
						'trade_process_id' => $qry_new['id'],
						'uuserid' => $qry_new['uusersid'],
						'type' => '1',
						'strategy_mode' => $qry_new['strategy_mode'],
						'strategy_type' =>$qry_new['strategy_type'],
						'quantity' => $order['sz'],
						'original_quantity' => $price,
						'time' => $order['fillTime'],
						'received_amount' => $order['fillSz'] - $order['fee'],
						'date' => date('Y-m-d',time()),
						'description'=>'first_buy',
						'live_price' => $order['fillPx'],
						'exchange'  => $exchange,
						'status' => 0
					);
						$this->db = db_connect();
					$this->db->table('api_trade_history')->insert($order_history);
					return true;
			}
			else
			{
					$new = substr_replace($qry_new['pair'], '/', -4, 0 );
					$exchange_asset = substr($qry_new['pair'],0,-4);
					$getfilecompare = file_get_contents("https://min-api.cryptocompare.com/data/price?fsym=USDT&tsyms=".strtoupper($exchange_asset)."");
					$getval  = json_decode($getfilecompare,TRUE);
					$calbtc  = $getval[$exchange_asset];
					$position_quantity = $calbtc * $price;
					echo "<pre>";
					print_r($position_quantity);
					echo "</pre>";
					$result_ft = $ftx->markets()->get([
						'market_name'=> $new, // BTC/USD   BTC-PERP  BTC-0626
						// 'depth'=>'10'
					]);
					echo "<pre>";
					print_r($result_ft);
					echo "</pre>";
					$stepsize =  $result_ft['result']['sizeIncrement'];
					$stepsize1 = fmod($stepsize, 1);
					$total_no = str_replace('.', '', $stepsize1);
					$count = strlen($total_no);
					if($stepsize == 1.00000000)
						$current = 0;
					else
						$current = $count - 1;

					$pos_qty = number_format($position_quantity,$current);
					echo "<pre>";
					print_r($pos_qty);
					echo "</pre>";
					$order_pre1 = $ftx->orders()->post([
						'market' => $new,
						'side' => 'buy',
						'type' => 'market',
						'size' => $pos_qty,
						'price' => NULL
					]);
					$fsym = explode('/', $order['market'])[1];
					$tsyms = explode('/', $order['market'])[0];

					$getfilecompare = file_get_contents("https://min-api.cryptocompare.com/data/price?fsym=".strtoupper($fsym)."&tsyms=".strtoupper($tsyms)."");
					$getval  = json_decode($getfilecompare,TRUE);
					$calbtc  = $getval[$tsyms];
					$position_quantity = $calbtc * $price ;                        
					$order_pre = $order_pre1['result'];
					echo "<pre>";
					print_r($order_pre);
					echo "</pre>";

					if($order_pre)
					{
						if($order_pre['status'] == 'new')
						{
							$order = $this->order_ftx($order_pre['id'],$ftx);
		    			}
						else
						{
		    				$order = $order_pre;
		    			}
		    		} 
   					 $order = $order['result'];
					if($order) 
					{ 
						$order_history = array(
						'pair' => str_replace('/', '', $order['market']),
						'order_id' => $order['id'],
						'trade_process_id' => $qry_new['id'],
						'uuserid' => $qry_new['uusersid'],
						'type' => '1',
						'strategy_mode' => $qry_new['strategy_mode'],
						'quantity' => $order['size'] * $order['avgFillPrice'],
						'original_quantity' => $order['size'] * $order['avgFillPrice'],
						'time' => strtotime($order['createdAt']),
						'received_amount' => $order['size'],
						'date' => date('Y-m-d',time()),
						'description'=>'first_buy',
						'live_price' => $order['avgFillPrice'],
						'exchange'  => $exchange,
						'status' => 0
						);
						$this->db = db_connect();
						$this->db->table('api_trade_history')->insert($order_history);
						return true;
					}
			}
	

		}
		else
	     return false;
		}
		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 ");
			return false;
		}

}

public function tradingprocess_resume() 
{
	$session= \Config\Services::session();
	
	if(!empty($session->get('uusersid')))
	$uusersid=$session->get('uusersid');
	else
	$uusersid=$this->request->getPost('uusersid');
	
	$trade_query = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and pair='".$this->request->getPost('id')."' and trade_status != 2 and exchange= '".$this->request->getPost('exchange')."' order by id desc")->getRowArray();
	if(!empty($trade_query))
	{
	    $query_status = $this->db->query("UPDATE trade_process SET trade_status=1, updated_time='".time()."' WHERE uusersid='".$uusersid."' and pair='".$this->request->getPost('id')."' and trade_status = 0 order by id desc ");
	}
	
}

public function bybit_order()
{

	$session= \Config\Services::session();
	$this->db = db_connect();

	$uusersid=$this->request->getPost('uusersid');
	$exchange=$this->request->getPost('exchange');
	$orderid=$this->request->getPost('orderid');
	$tradeid=$this->request->getpost('tradeid');
	$price=$this->request->getpost('price');
	
	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='5'");
	$ref=$referral1->getRow();
	$key = $ref->api_key;
	$secret = $ref->secret_key;
	$account = $ref->account;
	$acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
	$bybitApi = new BybitApi($key, $secret);
	$order_det = $bybitApi->GetOrders(['category' => 'linear','orderId' => $orderid]);
	echo '<pre>';
	print_r($order_det);
	echo '</pre>';

	$qry_new = $this->db->query("SELECT * FROM trade_process WHERE id='".$tradeid."'")->getRowArray();
	if(isset($order_det['result']['list']) && !empty($order_det['result']['list']))
	{
			$history = $order_det['result']['list'][0];
			$order_history = array(
				'pair' => $qry_new['pair'],
				'order_id' => $orderid,
				'trade_process_id' => $qry_new['id'],
				'uuserid' => $qry_new['uusersid'],
				'type' => '1',
				'strategy_mode' => $qry_new['strategy_mode'],
				'strategy_type' => $qry_new['strategy_type'],
				'quantity' => $history['cumExecValue'],
				'original_quantity' => $price,
				'time' => $history['createdTime'],
				'received_amount' => $history['cumExecQty'],
				'date' => date('Y-m-d',time()),
				'description'=>'first_buy',
				'live_price' => $history['lastPriceOnCreated'],
				'exchange'  => $exchange,
				'status' => 0
			);
		$this->db = db_connect();
		$this->db->table('api_trade_history')->insert($order_history);
		return true;
	}


}


// pause the current trade
public function tradingprocess1(){
	$session= \Config\Services::session();
	$this->db = db_connect();
	if($this->request->getPost('pair') != "")
		$qry['pair'] = $this->request->getPost('pair');
	else
		$qry['pair'] = $this->request->getPost('uri');

		if(!empty($session->get('uusersid')))
			$uusersid=$session->get('uusersid');
		else
			$uusersid=$this->request->getPost('uusersid');

	$trade_query = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$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='".$uusersid."' and pair='".$this->request->getPost('id')."' and trade_status = 1 ");
		if($query_status)
			echo "success";
		else 
			echo 'fail';
	} 
}


// resume the current trade
public function tradingprocess3(){
	$session= \Config\Services::session();
	$this->db = db_connect();
	if($this->request->getPost('pair') != "")
		$qry['pair'] = $this->request->getPost('pair');
	else
		$qry['pair'] = $this->request->getPost('uri');

		if(!empty($session->get('uusersid')))
	$uusersid=$session->get('uusersid');
	else
	$uusersid=$this->request->getPost('uusersid');

	$trade_query = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and pair='".$this->request->getPost('id')."' and trade_status = 0 ")->getRowArray();
	if(!empty($trade_query)){
		$qry['trade_status'] = 1;
		$query_status = $this->db->query("UPDATE trade_process SET trade_status=1, updated_time='".time()."' WHERE uusersid='".$uusersid."' and pair='".$this->request->getPost('id')."' and trade_status = 0 ");
		if($query_status)
			echo "success";
		else 
			echo 'fail';
	} 
}





	public function orderDetails(){
		$this->db = db_connect();
		$exchange = $this->request->getPost('exchange');
		if($exchange == 1)
		    $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
	    else if($exchange == 2)
	        $referral1=$this->db->query("SELECT * FROM okex_bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
	    else
	    	$referral1=$this->db->query("SELECT * FROM ftx_bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
        if($exchange == 2)
        	$passphrase = $ref->pass_phrase;

        $this->data['id'] = $this->request->getPost('pair');
        if($exchange == 1){
          $api = new Binance\API($key,$secret);
          $this->data['orderstatus'] = $api->orderStatus($this->request->getPost('pair'), $this->request->getPost('id'));
           $orderid = $this->data['orderstatus']['orderId'];
        }
        else if($exchange == 2){
          $api = new OkexV5($key,$secret,$passphrase);
			// $api->setOptions([
			// 		'headers'=>['x-simulated-trading'=>1]
			// ]);
			$this->data['orderstatus'] = $api->trade()->getOrder([
				'instId'=> substr_replace($this->request->getPost('pair'), '-', -4, 0),
				'ordId'=> $this->request->getPost('id')
			]);
			$orderid = $this->data['orderstatus']['data'][0]['ordId'];
        }
        else{
          $api = new Ftx($key,$secret);
          $this->data['orderstatus'] = $api->orders()->get([
	        'order_id'=>$this->request->getPost('id')
	    ]);
           $orderid = $this->data['orderstatus']['result']['id'];
        }
        
   
		
		$orderstatus = $this->data['orderstatus'];
	
		$order_info = $this->db->query("SELECT * FROM api_trade_history WHERE order_id='".$this->request->getPost('id')."'")->getRow();
		$this->data['order_info'] = $order_info;
		$this->data['exchange'] = $exchange;
		$this->data['orderid'] = $orderid;
         $this->data['pos_qty'] = $order_info->quantity;
          $this->data['res_qty'] = $order_info->received_amount;
		  if($exchange == 1){
          $this->data['time_order'] = date('Y-m-d h:i:s',substr($orderstatus['updateTime'],0,-3));
          $this->data['ordersymbol'] = substr($orderstatus['symbol'], 0,-4);
          $this->data['orderprice'] = $orderstatus['price'];
    
          }else if($exchange == 2){
          $this->data['time_order'] = date('Y-m-d h:i:s',substr($orderstatus['data'][0]['fillTime'],0,-3));
	      
	      $this->data['symbol_ok']   = $order_info->pair;
          $this->data['ordersymbol'] = substr($symbol_ok, 0,-4);
          $this->data['orderprice'] = $orderstatus['data'][0]['price'];
          }else{
          $this->data['time_order'] = date('Y-m-d h:i:s',strtotime($orderstatus['result']['createdAt']));
	      $symbol_ft  = str_replace('/', '', $orderstatus['result']['market']);
          $this->data['ordersymbol'] = substr($symbol_ft, 0,-4);
          $this->data['orderprice'] = $orderstatus['result']['avgFillPrice'];
          }

        // 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_price'] = $order_info->avg_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";
	}

// 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 exchange='".$this->request->getPost('exchange')."' order by id desc")->getRow();
    if($trade_query)
    {
            $api_trade_data = array(
					'trade_process_id' => $trade_query->id,
					'uuserid' => $this->request->getPost('uusersid'),
					'type' => '1',
					'trade_close' => 0,
					'exchange' => $this->request->getPost('exchange')
				);

            $total_position_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
            $total_position_amount=$total_position_quantity->received_amount;
            $quantity = number_format($total_position_amount,8);
            $exchange = $this->request->getPost('exchange');
            if($exchange == 1) 
            { 
                $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type= '1'");
                $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=$quantity;
                $sell_amount = str_replace(',', '', $sell_amount);
                if($total_asset < $sell_amount)
                {
                    if($trade_process->pair == "BNBUSDT")
                        $quantity_fee = $sell_amount * ( 0.65 / 100 );
                    else
                        $quantity_fee = $sell_amount * ( 0.1 / 100 );
                    
                    $sell_amount = $sell_amount - $quantity_fee;
                } 
                if($total_asset < $sell_amount)
                {
            	    $sell_amount = $total_asset;
                }

            }
            else if ($exchange == 2)
            {   // OKEX
                $this->db = db_connect();
                $referral1=$this->db->query("SELECT * FROM okex_bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
                $ref=$referral1->getRow();
                $key = $ref->api_key;
                $secret = $ref->secret_key;
                $passphrase = $ref->pass_phrase;
                $api = new OkexV5($key,$secret,$passphrase);
               //        $api->setOptions([
               //      'headers'=>['x-simulated-trading'=>1]
               // ]);
                $coin = strtolower(substr($this->request->getPost('id'),0,-4));
                $result_pre =$api->account()->getBalance([
                ]);
                $result = $result_pre['data'][0]['details'];
                if(!empty($result))
                { 
                    foreach($result as $key => $value)
                    {
                        if($value['ccy'] == strtoupper($coin))
                        {
                            $total_asset = $value['availBal'];
                            break;
                        }
                        else
                        $total_asset = 0;
                    }   
                }
                else
                {
                    $total_asset = 0;
                }
                $new = substr_replace( $this->request->getPost('id'), '-', -4, 0 );
                $new_symbol = $new.'-SWAP';     
                $ticker = $api->market()->getTicker([
                'instId'=> $new_symbol,
                ]);
               if(empty($ticker['data']) || $ticker['code'] == 51001){
                $result_okex=$api->market()->getTickers([
                'instType'=>'SPOT',
                ]);
                if($result_okex['data']){
                  foreach ($result_okex['data'] as $key => $value) {
                    if($value['instId'] == $new){
                      $ticker = $value;
                      break;
                    }
                  }
                $live_price = $ticker['last'];
                }
             }
              else
              {
                $live_price = $ticker['data'][0]['last'];
         
              }
      
            }
            else 
            { // FTX
                $referral1=$this->db->query("SELECT * FROM ftx_bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
                $ref=$referral1->getRow();
                $key = $ref->api_key;
                $secret = $ref->secret_key;
                $api = new Ftx($key,$secret);
                $fet=$api->wallet()->getBalances();
                $coin = substr($this->request->getPost('id'),0,-4);
                if(!empty($fet['result'])) 
                { 
                    foreach ($fet['result'] as $key => $value) 
                    {
                        if($value['coin'] == $coin)
                        {
                            $total_asset = $value['total'];
                            break;
                        }
                        else
                            $total_asset = 0;
                    }
                }
                else
                {
    	            $total_asset = 0;
                }
    
                $new = substr_replace( $this->request->getPost('id'), '/', -4, 0 );    
    
                    $result_ftt=$api->markets()->get([
                    'market_name'=> $new,// BTC/USD   BTC-PERP  BTC-0626
                    //'depth'=>'10'
                ]);
              $live_price =  $result_ftt['result']['last'];
            }

        
        
       

         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,$total_usdt->quantity,$exchange);
                if($result)
                { 
			        $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 1;
		}
		else 
		{
		 
			echo 0;
		}
	      }
		
		
	}


public function truncate_number( $number, $precision = "") {
    // Zero causes issues, and no need to truncate
    // if ( 0 == (int)$number ) {
    //     return $number;
    // }
    // Are we negative?
    $negative = $number / abs($number);
    // Cast the number to a positive to solve rounding
    $number = abs($number);
    // Calculate precision number for dividing / multiplying
    $precision = pow(10, $precision);
    // Run the math, re-applying the negative value to ensure returns correctly negative / positive
    return floor( $number * $precision ) / $precision * $negative;
}


public function take_profit($userid,$trade_process_id,$quantity,$price,$stopPrice,$api,$pair,$avg_price,$exchange)
{
        $db = db_connect();
        $quantity = str_replace(',', '', $quantity);
	    $trade_process = $this->db->table('trade_process')->where('uusersid',$userid)->where('trade_status','1')->where('id',$trade_process_id)->get()->getRow();
	    if($trade_process->exchange == 1) 
		{ 
		    $userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid)->get()->getRow();
			$api_key = $userid_bind_process->api_key;	
    		$api_secret = $userid_bind_process->secret_key;	
    		$exchange_info=binance_exchangeinfo($api_key);
		    $filters='';
    		foreach($exchange_info as $key => $value) 
    		{
    		    if($value['symbol']==$pair)
    			{
					 $filters=$value['filters'];
					    break;
    			}
    		}
				
    		$lotSizeFilter = null;
            foreach ($filters as $filter)
            {
                if($filter['filterType'] === 'LOT_SIZE') 
                {
                    $lotSizeFilter = $filter;
                    break;
                }
            }
            $minQty = $lotSizeFilter['minQty'];
            $maxQty = $lotSizeFilter['maxQty'];
            $stepsize = $lotSizeFilter['stepSize'];
            $stepsize1 = fmod($stepsize, 1);
			$total_no = str_replace('.', '', $stepsize1);
			$count = strlen($total_no);
            // $stepsize = explode('.', $stepsize)[1];
			if($stepsize == 1.00000000)
				$current = 0;
			else
			    $current = $count - 1;
                      
            $order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
			    	
			if(empty($order['orderId'])) 
			{
			    $quantity = $this->truncate_number($quantity,$current); 
				$quantity = str_replace(',', '', $quantity);
				$order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
			}
		}
			
			if($order) 
    		{ 
    			if(!empty($description) || $description == "") 
    			{
    			    $buy_record_update = $this->db->table('trade_process')->set('flag','0')->where("id",$trade_process_id)->update();
    			    $buy_record_update1 = $this->db->table('trade_process')->set('flag_buy','0')->where("id",$trade_process_id)->update();
    			    $buy_record_update2 = $this->db->table('trade_process')->set('sell_limit','')->where("id",$trade_process_id)->update();
    			}
    		    $db = db_connect();
    		    $admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
    		    $fuel_fee_percent = $admin_settings->min_fuel_fee;
    		    $total_avg_price = $avg_price->quantity;
    
    		    if($trade_process->exchange == 1)
    		    { 
    	             if($subsell_status != 1)
    		            $avg_price1 = $order['cummulativeQuoteQty'] - $avg_price; 
    		        else
    		            $avg_price1 = $order['cummulativeQuoteQty'] - $avg_price;
    
        			$orderid = $order['orderId'];
        			$pos_qty = $order['cummulativeQuoteQty'];
        			$time_order = $order['transactTime'];
        			$res_qty = $order['executedQty'];
    
    
    	        }
        	     else if($trade_process->exchange == 2)
        	     {
                     if($subsell_status != 1)
        		     $avg_price1 = $position_quantity - $avg_price; 
        		     else
        		     $avg_price1 = $position_quantity - $avg_price; 
        
        			 $orderid = $order['ordId'];
        			 $pos_qty = $position_quantity;
        			 $time_order = $order['fillTime'];
        			 $res_qty = $order['sz'];
        	     }
        	     else
        	     {
                     if($subsell_status != 1)
        		     $avg_price1 = $position_quantity - $avg_price; 
        		     else
        		     $avg_price1 = $position_quantity - $avg_price; 
        
        			$orderid = $order['id'];
        			$pos_qty = $position_quantity;
        			$time_order = strtotime($order['createdAt']);
        			$res_qty = $order['size'];
        	     } 
    	    
        		$total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process_id)->where("trade_close",'0')->orderBy('id','DESC')->get()->getRow();
            
                $total_position_amount=$total_position_amount1->quantity;
            
                echo "total_position_amount  =>" .$total_position_amount;
            
    		    $sell_quantity=$pos_qty;
    		    echo "Sell Quantity =>" .$sell_quantity;
    
        		if($sell_quantity > $total_position_amount)
        		{
        			$profit=$sell_quantity-$total_position_amount;
        		}
        		else
        		{
        			$profit=$sell_quantity- $total_position_amount;
        		}
        
        		$profit_percentage=($profit/$total_position_amount)*100;
        
        		$fuel_fee = $profit * ($fuel_fee_percent / 100);
    
           
            	if($orderid > 0)
            	{
        		    $order_history = array(
        			'pair' => $pair,
        			'order_id' => $orderid,
        			'trade_process_id' => $trade_process_id,
        			'uuserid' => $userid,
        			'type' => '2',
        			'quantity' => $pos_qty,
        			' original_quantity' => $pos_qty,
        			'time' => $time_order,
        			'received_amount' => $res_qty,
        			'live_price' => $stopPrice,
        			'avg_price' => $avg_price1,
        			'comm_price' => $profit,
        			'profit_percentage' => $profit_percentage,
        			'description' => $description,
        			'margin_call_drops' => '',
        			'date' => date('Y-m-d',time()),
        			'strategy_mode' => $trade_process->strategy_mode,
        			'strategy_type' => $trade_process->strategy_type,
        			'description' => "close_trade",
        			'flag' => $flag ? $flag : 0,
        			'status' => 0,
        			'exchange' => $trade_process->exchange
        		);
            	$this->db->table('api_trade_history')->insert($order_history);
            	
            	
            	    if($fuel_fee > 0)
            	    {
                        $deposit_data = array(           // fuel fee deduction
                        'uusersid' => $userid,
                        'amount'  => $fuel_fee,
                        'depositid' => $this->db->InsertID(),
                        'type'  => 'deducted_gaswallet', 
                        'description'  => 'fuel fee deduction for order no '.$orderid,
                        'date'  => date('Y-m-d H:i:s'),
                        'currency' => 1,
                        'transactionid' => $trade_process_id
                        );
                		$this->db->table('history')->insert($deposit_data); 
            	   }
            	$sell_record_update = $this->db->table('api_trade_history')->set('trade_close','1')->where('trade_close','0')->where("trade_process_id",$trade_process_id)->update();
            	}
    		$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');
	$exchange= $this->request->getPost('exchange');
	if($exchange == 1)
	{
    	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type='1'");
        $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;
        $flags['isQuoteOrder'] = true;
    }
	else if($exchange == 5)
	{

	}
	else if($exchange == 6)
	{
    	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type='6'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
        $passphrase = $ref->pass_phrase;
        $okex = new OkexV5($key,$secret,$passphrase);
		$quantity = $num;
    }
	else if($exchange == 7)
	{
    	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type='7'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
        $passphrase = $ref->pass_phrase;
        $okex = new OkexV5($key,$secret,$passphrase);
		$quantity = $num;
    }
	else
	{
        $referral1=$this->db->query("SELECT * FROM ftx_bind_process WHERE uusersid='".$this->request->getPost('uusersid')."'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
    	$ftx = new Ftx($key,$secret);
		$ftx->setOptions([
			//Set the request timeout to 60 seconds by default
			'timeout'=>10,
			//If you are developing locally and need an agent, you can set this
			//'proxy'=>true,
			//More flexible Settings
			/* 'proxy'=>[
			'http'  => 'http://127.0.0.1:12333',
			'https' => 'http://127.0.0.1:12333',
			'no'    =>  ['.cn']
			], */
			//Close the certificate
			//'verify'=>false,
			//Set Demo Trading
		]);
		$quantity = $num;
    }
        $price = $val;

        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,
			'exchange' => $exchange
		);
		$manual_buy = $this->db->table('api_manual_trade')->where('trade_process_id',$this->request->getPost('trade_process_id'))->where('type',1)->where('status','1')->where('exchange',$exchange)->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{

        	if($exchange == 1) { 
        	$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 and exchange = 1 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'],
			'exchange' => $exchange,
			'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"; 
        }
        }else if($exchange == 2){
        	$num = str_replace(',', '', $num);
        	$new = substr_replace( $id, '-', -4, 0 );
	$order_check=$okex->trade()->postOrder([
        'instId'=> $new,
        'tdMode'=>'cash',
        'side'=>'buy',
        'ordType'=>'market',
        'sz'=> $num
    ]);

		$res_okex_orderid = $order_check['data'][0]['ordId'];
		
		$order = $okex->trade()->getOrder([
        'instId'=> $new,
        'ordId'=> $res_okex_orderid
        ]);

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

		

		echo"<pre>";
		print_r($order);
		echo"</pre>";
        $order = $order['data'][0];
         $trade_process =$this->db->query("SELECT * FROM trade_process WHERE pair='".$id."' and uusersid='".$this->request->getPost('uusersid')."' and trade_status != 2 and exchange = 2 order by id desc")->getRow();
         if($order) {
		$order_history = array(
			'pair' => str_replace('-', '', $order['instId']),
			'order_id' => $order['ordId'],
			'trade_process_id' => $trade_process->id,
			'uuserid' => $trade_process->uusersid,
			'type' => '1',
			'strategy_mode' => $trade_process->strategy_mode,
			'quantity' => $order['sz'],
			'original_quantity' => $price,
			'time' => $order['fillTime'],
			'received_amount' => $order['fillSz'] - $order['fee'],
			'date' => date('Y-m-d',time()),
			'description'=>'manual_buy',
			'live_price' => $order['fillPx'],
			'exchange'  => $exchange,
			'status' => 0
		);
		$this->db->table('api_trade_history')->insert($order_history);
		echo "success";
	}else{
		echo "failure";
        }  
	}else{
            $num = str_replace(',', '', $num);

        		$new = substr_replace( $id, '/', -4, 0 );
 	$exchange_asset = substr($id,0,-4);
	$getfilecompare = file_get_contents("https://min-api.cryptocompare.com/data/price?fsym=USDT&tsyms=".strtoupper($exchange_asset)."");
    $getval  = json_decode($getfilecompare,TRUE);
    $calbtc  = $getval[$exchange_asset];
    $position_quantity = $calbtc * $num ;
    $result_ft = $ftx->markets()->get([
        'market_name'=> $new, // BTC/USD   BTC-PERP  BTC-0626
        // 'depth'=>'10'
    ]);
    $stepsize =  $result_ft['result']['sizeIncrement'];
    $stepsize1 = fmod($stepsize, 1);
$total_no = str_replace('.', '', $stepsize1);
$count = strlen($total_no);
	 if($stepsize == 1.00000000)
	 	$current = 0;
	 else
	    $current = $count - 1;

    $pos_qty = number_format($position_quantity,$current);
    $order_pre = $ftx->orders()->post([
        'market' => $new,
        'side' => 'buy',
        'type' => 'market',
        'size' => $pos_qty,
        'price' => NULL
    ]);


    $fsym = explode('/', $order['market'])[1];
    $tsyms = explode('/', $order['market'])[0];

    $getfilecompare = file_get_contents("https://min-api.cryptocompare.com/data/price?fsym=".strtoupper($fsym)."&tsyms=".strtoupper($tsyms)."");
    $getval  = json_decode($getfilecompare,TRUE);
    $calbtc  = $getval[$tsyms];
    $position_quantity = $calbtc * $price ;                        
    $order_pre = $order_pre['result'];

		    if($order_pre){
		    	if($order_pre['status'] == 'new'){
                   $order = $this->order_ftx($order_pre['id'],$ftx);
		    	}else{
		    		$order = $order_pre;
		    	}
		    } 
    $order = $order['result'];


		echo"<pre>";
		print_r($order);
		echo"</pre>";
         $trade_process =$this->db->query("SELECT * FROM trade_process WHERE pair='".$id."' and uusersid='".$this->request->getPost('uusersid')."' and trade_status != 2 and exchange = 3 order by id desc")->getRow();
         if($order) {
    $fsym = explode('/', $order['market'])[1];
    $tsyms = explode('/', $order['market'])[0];
    $getfilecompare = file_get_contents("https://min-api.cryptocompare.com/data/price?fsym=".strtoupper($fsym)."&tsyms=".strtoupper($tsyms)."");
    $getval  = json_decode($getfilecompare,TRUE);
    $calbtc  = $getval[$tsyms];
    $position_quantity = $calbtc * $num;
		$order_history = array(
			'pair' => str_replace('/', '', $order['market']),
			'order_id' => $order['id'],
			'trade_process_id' => $trade_process->id,
			'uuserid' => $trade_process->uusersid,
			'type' => '1',
			'strategy_mode' => $trade_process->strategy_mode,
			'quantity' => $order['size'] * $order['avgFillPrice'],
			'original_quantity' => $order['size'] * $order['avgFillPrice'],
			'time' => strtotime($order['createdAt']),
			'received_amount' => $order['size'],
			'date' => date('Y-m-d H:i:s',strtotime($order['createdAt'])),
			'description'=>'manual_buy',
			'live_price' => $order['avgFillPrice'],
			'exchange'  => $exchange,
			'status' => 0
		);
		echo "<pre>";
		print_r($order_history);
		echo "</pre>";
		$this->db->table('api_trade_history')->insert($order_history);
		echo "success";
	}else{
		echo "failure";
        }  
	}
    }  
}



/*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');
    $status = $this->request->getPost('status');
    $exchange = $this->request->getPost('exchange');
	 
   $uusersid =$this->session->get("uusersid");
      
	if($exchange == 1)
	{
    	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type='1'");
        $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']; 
        $symbol = $output['symbol'];
        $quantity = $num;
    }
	else if($exchange == 2)
	{
    	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type='2'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
        $passphrase = $ref->pass_phrase;
         $okex = new OkexV5($key,$secret,$passphrase);
		$quantity = $num;
    }

        $price = $val;


    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,
		'flag' => $status,
		'created_date' => time(),
		'status' => 1,
		'exchange' => $exchange
		);
   $manual_sell = $this->db->table('api_manual_trade')->where('trade_process_id',$this->request->getPost('trade_process_id'))->where('type',2)->where('exchange',$exchange)->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
	{
    	if($exchange == 1)
		{
			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;
      }
    }

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

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


    	$ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
		$balances = $api->balances($ticker);
		$total_asset = $balances[substr($output['symbol'],0,-4)]['available'];
	if($total_asset < $quantity){
	  if($trade_process->pair == "BNBUSDT")
	    $quantity_fee = $quantity * ( 0.65 / 100 );
	    else
	    $quantity_fee = $quantity * ( 0.1 / 100 );
	$quantity = $quantity - $quantity_fee;
	}

	if($total_asset < $quantity){
	$quantity = $total_asset;
	}
	$order = $api->sell($output['symbol'], $quantity,0,"MARKET");
	if(!$order || $order == ""){
	$quantity = $this->truncate_number($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 and exchange = 1 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()),
			'flag' => $status,
			'live_price' => $order['fills'][0]['price'],
			'exchange' => $exchange,
			'status' => 0
		);
		$this->db->table('api_trade_history')->insert($order_history);

		if($status == 1){
		$trade_where = array(
		'uuserid' => $uusersid,
		'type' => '1',
		'status' => 0,
		'trade_process_id' => $trade_process->id,
		);
	    $buy_record_update = $this->db->table('api_trade_history')->set('status','1')->where($trade_where)->update();
		}
		echo"<pre>";
		print_r($this->db->getLastQuery());
		echo"</pre>";
		echo"<pre>";
		print_r($order_history);
		echo"</pre>";
        echo "success";
        }
        else{
        echo "failure"; 
        }  
        }else if($exchange == 2){ // OKEX

        	$quantity = str_replace(',', '', $quantity);
        	$new = substr_replace( $id, '-', -4, 0 );
			$order_check=$okex->trade()->postOrder([
		        'instId'=> $new,
		        'tdMode'=>'cash',
		        'side'=>'sell',
		        'ordType'=>'market',
		        'sz'=> $quantity
		    ]);



		$res_okex_orderid = $order_check['data'][0]['ordId'];
		
		$order = $okex->trade()->getOrder([
        'instId'=> $new,
        'ordId'=> $res_okex_orderid
        ]);

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

		

		echo"<pre>";
		print_r($order);
		echo"</pre>";
        $order = $order['data'][0];


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

    if($order){
    	$ticker =  $okex->market()->getTicker([
			'instId'=> $order['instId'].'-SWAP',
		]);
		 if(empty($ticker['data']) || $ticker['code'] == 51001){
		$result_okex=$okex->market()->getTickers([
			'instType'=>'SPOT',
		]);
        if($result_okex['data']){
          foreach ($result_okex['data'] as $key => $value) {
            if($value['instId'] == $new){
              $ticker = $value;
              break;
            }
          }
      $live_price = $ticker['last'];
        }
      }else{
      $live_price = $ticker['data'][0]['last'];
      }

		$position_quantity_pre = $order['sz'] * $live_price;
		$position_quantity = $position_quantity_pre - $order['fee'];
    	// if($order['status'] == "NEW")
    	// 	$status = 0;
    	// else 
    	// 	$status = 1;
        $order_history = array(
            'pair' => str_replace('-', '', $order['instId']),
			'order_id' => $order['ordId'],
			'trade_process_id' => $trade_process->id,
			'uuserid' => $trade_process->uusersid,
			'type' => '2',
			'strategy_mode' => $trade_process->strategy_mode,
			'quantity' => $position_quantity,
			'original_quantity' => $position_quantity,
			'time' => $order['fillTime'],
			'received_amount' => $order['sz'],
			'date' => date('Y-m-d',time()),
			'description'=>'manual_sell',
			'live_price' => $order['fillPx'],
			'exchange'  => $exchange,
			'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"; 
        }  


        }else{  //FTX


        	 $quantity = str_replace(',', '', $quantity);
        		$new = substr_replace( $id, '/', -4, 0 );

			$result_ft = $ftx->markets()->get([
				'market_name'=> $new, // BTC/USD   BTC-PERP  BTC-0626
				// 'depth'=>'10'
			]);
    $stepsize =  $result_ft['result']['sizeIncrement'];
    $stepsize1 = fmod($stepsize, 1);
    $total_no = str_replace('.', '', $stepsize1);
    $count = strlen($total_no);
	 if($stepsize == 1.00000000)
	 	$current = 0;
	 else
	    $current = $count - 1;

    $pos_qty1 = number_format($quantity,$current);
    $order_pre = $ftx->orders()->post([
        'market'=>$new,
        'side'=>'sell',
        'type'=>'market',
        'size'=>$pos_qty1,
        'price' => NULL
    ]);
    $order_pre = $order_pre['result'];
      if($order_pre){
		    	if($order_pre['status'] == 'new'){
                   $order = $this->order_ftx($order_pre['id'],$ftx);
		    	}else{
		    		$order = $order_pre;
		    	}
		    } 
    $order = $order['result'];


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

    if($order){

    	$result=$ftx->markets()->get([
        'market_name'=>$order['market'],// BTC/USD   BTC-PERP  BTC-0626
        //'depth'=>'10'
    ]);
        	$live_price =  $result['result']['last'];
        	$position_quantity = $order['size'] * $live_price ;
    	// if($order['status'] == "NEW")
    	// 	$status = 0;
    	// else 
    	// 	$status = 1;
        $order_history = array(
			'pair' => str_replace('/', '', $order['market']),
			'order_id' => $order['id'],
			'trade_process_id' => $trade_process->id,
			'uuserid' => $trade_process->uusersid,
			'type' => '2',
			'strategy_mode' => $trade_process->strategy_mode,
			'quantity' => $order['size'] * $order['avgFillPrice'],
			'original_quantity' => $order['size'] * $order['avgFillPrice'],
			'time' => strtotime($order['createdAt']),
			'received_amount' => $order['size'],
			'description'=>'manual_sell',
			'date' => date('Y-m-d',time()),
			'flag' => $status,
			'exchange' => $exchange,
			'live_price' => $order['avgFillPrice'],
			'status' => 0
		);
		echo "<pre>";
		print_r($order_history);
		echo "</pre>";
		$this->db->table('api_trade_history')->insert($order_history);

		if($status == 1){
			$trade_where = array(
							'uuserid' => $uusersid,
							'type' => '1',
							'status' => 0,
							'trade_process_id' => $trade_process->id,
			);
			$buy_record_update = $this->db->table('api_trade_history')->set('status','1')->where($trade_where)->update();
		}

		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 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');
    $status = $this->request->getPost('status');
    $exchange = $this->request->getPost('exchange');
    
    helper('site_helper');

	 
   $uusersid =$this->session->get("uusersid");
   

	if($exchange == 1)
	{
    	$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type='1'");
        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
	
        $quantity = $num;
    }
    $price = $val;



    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,
		'flag' => $status,
		'created_date' => time(),
		'status' => 1,
		'exchange' => $exchange
		);
        $manual_sell = $this->db->table('api_manual_trade')->where('trade_process_id',$this->request->getPost('trade_process_id'))->where('type',2)->where('exchange',$exchange)->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
	{
	  
    	if($exchange==1)
		{
			    
			   $pair=$id;
			    $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('uusersid')."' and type='1'");
                $ref=$referral1->getRow();
              
                $api_key = $ref->api_key;
                $api_secret = $ref->secret_key;
                
                $quantity = str_replace(',', '', $quantity);
                
                
               
               
                $send_pair=substr($pair,0,-4);
				$total_asset='0';
				$balances=binance_balance1($key,$secret,$send_pair);
				
				$balances=str_replace(",",'',$balances);
				if($balances >=$quantity)
				{
				    
			
				
									
			    $exchange_info=binance_exchangeinfo($api_key);
		
			   
			  
                $filters='';
				foreach($exchange_info as $key => $value) 
				{
				   
					if($value['symbol']==$pair)
					{
						 $filters=$value['filters'];
						    break;
					}
				}
				
				$lotSizeFilter = null;
                foreach ($filters as $filter) {
                  //  print_r($filter);
                    if ($filter['filterType'] === 'LOT_SIZE') {
                        $lotSizeFilter = $filter;
                        break;
                    }
                }
                    
                
                $minQty = $lotSizeFilter['minQty'];
                $maxQty = $lotSizeFilter['maxQty'];
                $stepsize = $lotSizeFilter['stepSize'];
                $stepsize1 = fmod($stepsize, 1);
				$total_no = str_replace('.', '', $stepsize1);
				$count = strlen($total_no);
                // $stepsize = explode('.', $stepsize)[1];
				if($stepsize == 1.00000000)
					$current = 0;
				else
				    $current = $count - 1;
				
				$order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
				
			 
				
				if(empty($order['orderId']))
				{
						$quantity = $this->truncate_number($quantity,$current); 
						
						$quantity = str_replace(',', '', $quantity);
						$order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
						
				}
				
				$db = db_connect();
		        $admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
		        $fuel_fee_percent = $admin_settings->min_fuel_fee;
		 
                $trade_process = $this->db->query("SELECT * FROM trade_process WHERE pair='".$id."' and uusersid='".$this->request->getPost('uusersid')."' and trade_status != 2 and exchange = 1 order by id desc")->getRow();
                if(!empty($order['orderId']))
                {
                    
                    $pos_qty = $order['cummulativeQuoteQty'];
			        $res_qty = $order['executedQty'];
                    $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process->id)->where("trade_close",'0')->orderBy('id','DESC')->get()->getRow();
                    $total_position_amount=$total_position_amount1->quantity;
                    $sell_quantity=$pos_qty;
                    
                    if($sell_quantity > $total_position_amount)
            		{
            			$profit=$sell_quantity-$total_position_amount;
            		}
            		else
            		{
            			$profit=$sell_quantity- $total_position_amount;
            		}
            
            		$profit_percentage=($profit/$total_position_amount)*100;
            
            		$fuel_fee = $profit * ($fuel_fee_percent / 100);
        
    	
                    $order_history = array(
        		    'pair' => $order['symbol'],
        			'order_id' => $order['orderId'],
        			'trade_process_id' => $trade_process->id,
        			'uuserid' => $trade_process->uusersid,
        			'type' => '2',
        			'quantity' => $order['cummulativeQuoteQty'],
        			'original_quantity' => $order['cummulativeQuoteQty'],
        			'time' => $order['transactTime'],
        			'received_amount' => $order['executedQty'],
        			'description'=>'manual_sell',
        			'date' => date('Y-m-d',time()),
        			'flag' => $status,
        			'live_price' => $order['fills'][0]['price'],
        			'comm_price' => $profit,
			        'profit_percentage' => $profit_percentage,
        			'strategy_mode' => $trade_process->strategy_mode,
			        'strategy_type' => $trade_process->strategy_type,
        			'exchange' => $exchange,
        			'status' => 0
		        );
		        $this->db->table('api_trade_history')->insert($order_history);
		        
		        
		        	if(!empty($order['orderId']) > 0)
                	{
                        $deposit_data = array(           // fuel fee deduction
                        'uusersid' => $trade_process->uusersid,
                        'amount'  => $fuel_fee,
                        'depositid' => $this->db->InsertID(),
                        'type'  => 'deducted_gaswallet', 
                        'description'  => 'fuel fee deduction for order no '.$order['orderId'],
                        'date'  => date('Y-m-d H:i:s'),
                        'currency' => 1,
                        'transactionid' => $trade_process->id
                        );
                		$this->db->table('history')->insert($deposit_data); 
                    	$sell_record_update = $this->db->table('api_trade_history')->set('trade_close','1')->where('trade_close','0')->where("trade_process_id",$trade_process->id)->update();
                	}
            		if($status == 1)
            		{
                		$trade_where = array(
                		'uuserid' => $uusersid,
                		'type' => '1',
                		'status' => 0,
                		'trade_process_id' => $trade_process->id,
                		);
                	    $buy_record_update = $this->db->table('api_trade_history')->set('status','1')->where($trade_where)->update();
                	}
		
		            echo "success";
                }
                else
                {
                    echo $order['msg'];
                }  
                
				}
				else
				{
				    echo "Insufficent Balance For sell: only Available:".$balances."".$send_pair;
				}
		
		    
		}
    }

}




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 trade_settings()
{
	$this->db = db_connect();
	$session= \Config\Services::session();
	$this->common_model= model('CommonModel');
	$uusersid=$session->get('uusersid');

	$condition = "uusersid ='".$uusersid."'";
	$this->data['user'] = $this->common_model->GetRow('user_strategy',$condition);

	$segments = $this->request->uri->getSegments();
	$symbol=$segments[1];
	$this->data['symbol']=$symbol;
	$this->data['userid']=$uusersid;
	if($this->session->get('exchange'.$this->session->get('uusersid'))){
        $exchange = $this->session->get('exchange'.$this->session->get('uusersid'));
    }else{
    	$exchange = 1;
    }
	$trade_process =$this->db->query("SELECT * FROM trade_process WHERE pair='".$symbol."' and uusersid='".$uusersid."' and exchange ='".$exchange."'  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/trade_settings',$this->data);

}

public function margin_pass()
{
	$this->db = db_connect();
	$session= \Config\Services::session();
	// $this->common_model= model('CommonModel');
	// $uusersid=$session->get('uusersid');

	$segments = $this->request->uri->getSegments();
	$symbol=$segments[1];
	$this->data['symbol']=$symbol;
	$num = $segments[2];
	$this->data['num'] = $num;

	// if($this->session->get('exchange'.$uusersid)){
    //     $exchange = $this->session->get('exchange'.$uusersid);
    // }else{
    // 	$exchange = 1;
    // }
	// $trade_process =$this->db->query("SELECT * FROM trade_process WHERE pair='".$symbol."' and uusersid='".$uusersid."' and exchange ='".$exchange."'  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/margin_configure',$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();
		
		if(empty($qury))
		{
		    
			/*$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$id."'")->GetResult();
			$qry=$qury[0];*/
			
			$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' And pair='".$pair."'")->getResult();
            if(!empty($qury[0]))
            {
                $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' And pair='".$pair."'")->getResult();
                $qry=$qury[0];
            }
            else
            {
                $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' and pair='0'")->getResult();
                $qry=$qury[0];
            }
        }
		else
		{
			$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;	
				
				if($c=='1')
    			{
    			    $disp=$c."st";
    			}
    			else if($c=='2')
    			{
    			    $disp=$c."nd";
    			}
    			else if($c=='3')
    			{
    			    $disp=$c."rd";
    			}
    			else
    			{
    			    $disp=$c."th";    
    			}
			
				echo   "<div class='form-block position-relative login-ico'>";
				echo    "<label class=''>The ".$disp." sub-position</label>";
				echo   "<div class='form-ico password-toggle-icon2'><i class='fa fa-percent'></i></div>";
				echo    "<input type='text' class='form-control mt-1'  name='rep_time".$j."' required  value=".$margn[$j].">";
				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();
			

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


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

		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;
			if($c=='1')
			{
			    $disp=$c."st";
			}
			else if($c=='2')
			{
			    $disp=$c."nd";
			}
			else if($c=='3')
			{
			    $disp=$c."rd";
			}
			else
			{
			    $disp=$c."th";    
			}
			echo   "<div class='form-block position-relative login-ico'>";
			echo    "<label class=''>The ".$disp." call</label>";
			echo   "<div class='form-ico password-toggle-icon2'><i class='fa fa-percent'></i></div>";
			echo    "<input type='text' class='form-control mt-1' required name='call_time".$i."' value=".$margin[$i].">";
			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();
			

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



		$buy=$qry->buyin_ratio_times;
		$buyin=explode(',',$buy);
		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;
			
			if($c=='1')
			{
			    $disp=$c."st";
			}
			else if($c=='2')
			{
			    $disp=$c."nd";
			}
			else if($c=='3')
			{
			    $disp=$c."rd";
			}
			else
			{
			    $disp=$c."th";    
			}
			
			echo   "<div class='form-block position-relative login-ico'>";
			echo    "<label class=''>The ".$disp." order amount (Multiple)</label>";
			echo   "<div class='form-ico password-toggle-icon2'><i class='fa fa-times' title='multiple times'></i></div>";
			echo    "<input type='text' class='form-control mt-1' required  name='order_time".$i."' value=".$buyin[$i].">";
			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);

	}else{
		$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."' and trade_status != 2 order by id desc ")->getRow();

		if($select_user_pair)
			$pair_condition = $this->db->query("SELECT * from api_trade_history where trade_process_id='".$select_user_pair->id."' and margin_call_drops = 5 ")->getRow();
		else
			$pair_condition='';
		
		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_datas);

		}
		else
		{
			$query_status_new = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_datas);
			echo 1;
			exit;
		}
		
	}


				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 1;
			}else{
				echo 0;
			}    
}

			public function switch_update(){

			}


	        public function trade_update(){
	            
	       $this->db = db_connect();
			$pair =  $this->request->getPost('pair');
			// $pair = 'BNBUSDT';
			$uusersid = $this->request->getPost('uusersid');
			$live_price = $this->request->getPost('live_price');
			$exchange = $this->request->getPost('exchange');
			
			//$pair='BONKUSDT';
			//$uusersid='3';
		//	$exchange='1';

			// return $session;

			$where_ = array(
				'pair' => $pair,
				'uusersid' => $uusersid,
				'trade_status != ' => '2',
				'exchange' => $exchange
			);
			
			$trade_record =  $this->db->table('trade_process')->where($where_)->orderBy('id','DESC')->get()->getRow();
		    
		   

			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,*/
					'pair' => $pair,
					'uuserid' => $uusersid,
					'type' => '1',
					'trade_close' => 0,
					'exchange' => $exchange
				);

				$last_call_drop_data = array(
					'trade_process_id' => $trade_record->id,
					'uuserid' => $uusersid,
					'exchange' => $exchange
				);


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

	


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

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

		$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;
            }
        }
      
      

                $last_call_drop = $this->db->table('api_trade_history')->where($last_call_drop_data)->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);

				$max_increase_price = sprintf('%.8f', floatval($max_increase_price));

                $max_down_price = sprintf('%.8f', floatval($max_down_price));

                if(intval($max_increase_price) > 999)
            		$max_increase_price = number_format($max_increase_price,2);
            	else
            	    $max_increase_price = number_format($max_increase_price,8);

    
                if($last_call_drop->type == 2)
                  $max_increase_price = $last_call_drop->live_price + $price_down;
		            $tradeupdate['take_profit_trigger'] = $max_increase_price ? "> ".$max_increase_price : "";

			
        		
                  $trade_where_new = array(
                    'uuserid' => $uusersid,
                    'type' => '1',
                    'status' => 0,
                    'trade_process_id' => $trade_record->id,
                    'exchange' => $exchange
                  );
        
               $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 ? $last_buy_recheck->margin_call_drops : 0;
                
            
              
       

        $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;

    if(intval($down_price) > 999)
		$down_price = number_format($down_price,2);
	else
	    $down_price = number_format($down_price,9);

	    if($last_call_drop->type == 1)
           $price_down = $last_call_drop->live_price * $call_perc / 100;
        else
           $price_down = $last_call_drop->live_price * $pair->buyin_callback / 100;



        $tradeupdate['down_price']  = "< ".$down_price;

    $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;
	}

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

	$call_drop = $this->db->table('api_trade_history')->where($api_trade_data)->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',
					);

					
						$exchange = $this->request->getPost('exchange');
						if($exchange == 1) { 
						$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;
					
                        
                        $data_binance = json_decode(file_get_contents('https://revotechbot.com/trading_pairs.json'), true);
    					$live_price='';
                        foreach ($data_binance as $datas) 
                        {
                                if ($datas['symbol'] == $pair) 
                                {
                                    $live_price=$datas['lastPrice'];
                                   break;   
                                }
                                
                        }
                        
                    }
                   
		  $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) {
          
            
            $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) {
            
           
            $check_percentage = '0.00';
          }else{
            
           
            $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) {
						
					
					$check_percentage1 = ($avg_position_amount - $live_price) / $avg_position_amount * 100 ;
						    $check_percentage1 = '-'.number_format($check_percentage1,2).'%';
					}elseif ($avg_position_amount == $live_price) {
					
						$check_percentage1 = '0.00';
					}else{
					
						$check_percentage1 = ($live_price - $avg_position_amount) / $live_price * 100 ;
					}

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

				
                //print_r($tradeupdate);

				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(){
	    if(!$this->session->get('uusersid'))
			throw new \CodeIgniter\Router\Exceptions\RedirectException('login');
	    	echo view('user/order_message');
	    }

	        public function system_information(){
	    if(!$this->session->get('uusersid'))
			throw new \CodeIgniter\Router\Exceptions\RedirectException('login');
	    	echo view('user/system_information');
	    }


	    public function setExchange(){
	    	$this->session = session();
	    	$uusersid = $this->request->getPost('id');
	    	if(empty($uusersid) || $uusersid == ""){
	    		$uusersid = $this->session->get('uusersid');
	    	}
	    	$class = $this->request->getPost('class');
	    	if($class == "get"){
	    		$exchange = 1;
	    	}else if($class == "getok"){
	    		$exchange = 2;
	    	}else{
	    		$exchange = 3;
	    	}
	    	$this->session->set('exchange'.$uusersid,$exchange);
	    	echo true;
	    }


public function autoLoadPrice()
{

	if($this->request->isAJAX()) 
	{
		 $symbol = service('request')->getPost('symbol');
		 $trim_symbol = str_replace('USDT','', $symbol);
         $exchange = $this->request->getPost('exchange');
    	$this->session = session();
        $uusersid = $this->session->get('uusersid');
        if($uusersid == "")
        	$uusersid = $this->request->getPost('uusersid');
    	$validation =  \Config\Services::validation();
    	$this->db = db_connect();

	
        if($exchange == 1) 
        { 
            $price=0;
            $data_binance = json_decode(file_get_contents('https://revotechbot.com/trading_pairs.json'), true);
            
            if($data_binance)
            {
                $markepair=$marketpair[0];
                foreach ($data_binance as $marketpair) 
                {   
                    
                    if ($marketpair['symbol'] ==$symbol) 
                    {
                         $price=number_format($marketpair['lastPrice'],9);
                         echo $price;
                         
                         
                    }
                }
                
            }	
            
	    }

	    else if($exchange == 2)
	    {
			$referral1=$this->db->query("SELECT * FROM okex_bind_process WHERE uusersid='".$uusersid."'")->getResult();
			$ref=$referral1[0];
			$key = $ref->api_key;
			$secret = $ref->secret_key;
			$passphrase = $ref->pass_phrase;

		if(empty($ref))
		{
			$key = 'd5c2840d-af58-4d3b-b2f6-949314f6c1b8';
			$secret = '9B24E5B3E49CB6F501EA53BDA93FB8BC';
			$passphrase = 'Yanceyker89@';
				$okex=new OkexV5($key,$secret,$passphrase);
				$okex->setOptions([
					'headers'=>['x-simulated-trading'=>1]
				]);
		}
		else
		{
			$okex=new OkexV5($key,$secret,$passphrase);
				// $okex->setOptions([
				//    'headers'=>['x-simulated-trading'=>1]
				//  ]);
		}

			$new = substr_replace( $symbol, '-', -4, 0 );
			$new_symbol = $new.'-SWAP';     
				$ticker = $okex->market()->getTicker([
					'instId'=> $new_symbol,
				]);
				if(empty($ticker['data']) || $ticker['code'] == 51001){
					$result_okex=$okex->market()->getTickers([
					'instType'=>'SPOT',
				]);
					if($result_okex['data']){
					foreach ($result_okex['data'] as $key => $value) {
						if($value['instId'] == $new){
						$ticker = $value;
						break;
						}
					}
				$price = $ticker['last'];
					}
      }
	  else
	  {
      $price = $ticker['data'][0]['last'];
 
      }

	if(intval($price) > 99)
		echo number_format($price,5);
	else
	    echo number_format($price,8);


}

elseif($exchange == 5)
{
	$live_price = 0;
	$get_api_bind=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='5'")->getRow();
	if($get_api_bind)
	{
		

	$key = $get_api_bind->api_key;
	$secret = $get_api_bind->secret_key;
	$account = $get_api_bind->account;
	$acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
	$bybitApi = new BybitApi($key, $secret);
	$total_asset = $bybitApi->getBalance('USDT',$acc_type);
	$tickers = $bybitApi->ticker(['category' => 'linear', 'symbol' => $symbol]); 

		$live_price = $tickers['lastPrice'];
	}

	if(intval($live_price) > 99)
		echo number_format($live_price,5);
	else
	    echo number_format($live_price,8);

}

else
{
	$referral1=$this->db->query("SELECT * FROM ftx_bind_process WHERE uusersid='".$uusersid."'")->getResult();
	$ref=$referral1[0];
	$key = $ref->api_key;
	$secret = $ref->secret_key;

	if(empty($ref)){
	$key = "lUsmd83bvErGkf4q0ctifaK8kaT1-uf2ZATn4uaH";
	$secret = "W8tKzcC420jUJPX_6Bl6MeNv5Dyg266X0rtIF33q";
	$ftx=new Ftx($key,$secret);
	}else{
	$ftx=new Ftx($key,$secret);
	}

			$new = substr_replace( $symbol, '/', -4, 0 );    

		$result=$ftx->markets()->get([
			'market_name'=> $new,  // BTC/USD   BTC-PERP  BTC-0626  //'depth'=>'10'
		]);
			$live_price =  $result['result']['last'];


		if(intval($live_price) > 99)
			echo number_format($live_price,5);
		else
			echo number_format($live_price,8);

}

}

}



}
