<!doctype html>
<html lang="en"  class="w-[640px]">
   <head>
      <?php echo view('user/layout/head');?>
   </head>
   <style>
      .news {
      background:linear-gradient(180deg, rgba(179,137,34,1) 0%, rgba(140,98,10,1) 50%, rgba(179,137,34,1) 100%, rgba(14,72,62,1) 100%);
      border-radius: 5px;
      padding: 7px 5px;
      }
      .swal2-popup {
      font-size: 12px !important;
      font-weight:bold;
      }
      #BuyModal h6
      {
      font-size: 14px;
      }
      #BuyModal .modal-content {
      position: relative;
      display: flex;
      flex-direction: column;
      width: 95%;
      pointer-events: auto;
      background-color: #fff;
      background-clip: padding-box;
      border: 1px solid rgba(0,0,0,.2);
      border-radius: .3rem;
      outline: 0;
      padding: 16px;
      }
      #SellModal h6
      {
      font-size: 14px;
      }
      #SellModal .modal-content {
      position: relative;
      display: flex;
      flex-direction: column;
      width: 95%;
      pointer-events: auto;
      background-color: #fff;
      background-clip: padding-box;
      border: 1px solid rgba(0,0,0,.2);
      border-radius: .3rem;
      outline: 0;
      padding: 16px;
      }
      .btn-danger
      {
      margin-bottom:20px;
      }
      .notify {
      position: fixed;
      top: 10px;
      left: 10px;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
      width: 350px;
      font-size: 14px;
      text-align: center;
      }
      /* Positions
      ========================================================================== */
      .notify-top-right,
      .notify-bottom-right {
      left: auto;
      right: 10px;
      }
      .notify-top-center,
      .notify-bottom-center {
      left: 50%;
      margin-left: -175px;
      }
      .notify-bottom-left,
      .notify-bottom-right,
      .notify-bottom-center {
      top: auto;
      bottom: 10px;
      }
      .notify button {
      -webkit-appearance: none;
      padding: 0;
      cursor: pointer;
      background: 0 0;
      border: 0;
      display: none;
      }
      /* Responsiveness
      ========================================================================== */
      /* Phones portrait and smaller */
      @media (max-width: 479px) {
      /*
      * Fit in small screen
      */
      .notify {
      left: 10px;
      right: 10px;
      width: auto;
      margin: 0;
      }
      }
      /* Sub-object: `notify-message`
      ========================================================================== */
      .notify-message {
      position: relative;
      cursor: pointer;
      }
      .notify .alert-default {
      background: #fff;
      border: 1px solid #e5e5e5;
      }
      .table
      {
        --bs-table-bg : linear-gradient(153deg, rgb(8, 73, 123) 0%, rgb(5, 104, 181) 48%) !important;
        --bs-table-color: #fff !important;
      }
      table.dataTable thead { background:linear-gradient(153deg, rgb(8, 73, 123) 0%, rgb(5, 104, 181) 48%) !important; color:#fff !important; font-size:13px;}
      table.dataTable tbody tr { background:transparent; color:#fff;}
      .table-striped > tbody > tr:nth-of-type(2n+1) > *{ color:#fff;}
      .change-success{ background:green;color:#fff;font-size:12px;padding:5px;}
      .change-danger{ background:red;color:#fff;font-size:12px;padding:5px;}
      .dataTables_length {display:none;}
      .dataTables_paginate {display:none;}
      .dataTables_info {display:none;}
      .dataTables_filter { margin-bottom:10px;}
      table.dataTable tbody td {font-size: 13px;}
      label {
      display: inline-block;
      color: #fff !important;
      margin-top: 10px;
      }
      .dataTables_wrapper .dataTables_filter input {
      margin-left: 0.5em;
      border: 1px solid #ddd;
      height: 30px;
      border-radius: 10px;
      }
          @media only screen and (max-width: 320px) {
  .trade-wrap {
    height: 65vh !important;
  }
}
      /* element {
	width: 121.867px;
	background: linear-gradient(153deg, rgb(8, 73, 123) 0%, rgb(5, 104, 181) 48%);
	color: white;
} */
   </style>
   <body class="section-overflow">
      <!--banner start -->
      <?php 
               use App\Helpers\site_helper;
               $validation =  \Config\Services::validation();
               $this->db = db_connect();
               $this->session = session();
               $uusersid = $this->session->get('uusersid');
               $exchange_id = $this->session->get('exchange');
              
               
               helper('kucoin_helper');
               $uri = service('uri');
               $this->common_model = model('CommonModel');
               $this->session->set('pair',$id);
               $base_curr = substr($this->session->get('pair'), 0,-4);
               
               $buy_bal=gas_wallet_bal($uusersid);
               
               
               
               if($exchange_id=='1')
               {
                   $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='1'");
                   $ref=$referral1->getRow();
                   $usdt_balance='0';
                   if(empty($ref))
                   {
                     $usdt_balance='0';
                   }
                   else
                   {
                     $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$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'];
                     $output['price'] =  $marketpair['lastPrice'];
                     $output['change'] = $marketpair['priceChangePercent'];*/
                     
                     $balances=binance_balance($key,$secret);
                     if($balances)
                     {
                         $usdt_balance=$balances;
                     }
                     else
                     {
                         $usdt_balance='0';
                     }
                         
                   }
                 
                 $update_symbol=$id;
               
                 //$get_data=candleprice($key,$secret,$update_symbol);
               
               
                $i=0;
                 $data_binance = json_decode(file_get_contents('https://aqua-x.co/trading_pairs.json'), true);
                 if($data_binance)
                 {
                     foreach ($data_binance as $marketpair) 
                     {
                         if ($marketpair['symbol'] === $update_symbol) 
                         {
                              $output[$i]['symbol'] = $update_symbol;
                             $output[$i]['price'] = isset($marketpair['lastPrice']) ? $marketpair['lastPrice'] : null;
                             $output[$i]['change'] = isset($marketpair['priceChangePercent']) ? $marketpair['priceChangePercent'] : null;
                              $i++;
                         }
                     }
                     $output=$output[0];
                     
                  }
                 
                 }
               elseif($exchange_id=='7')
               {
                   $usdt_balance='0';
                   $get_api_bind=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='7'")->getRow();
                   if($get_api_bind)
                   {
                     $key = $get_api_bind->api_key;
                     $secret = $get_api_bind->secret_key;
                     $pass_phrase = $get_api_bind->pass_phrase;
                     $usdt_balance=accountbalance($key,$secret,$pass_phrase);
                     
                   }
               
                   $pair_value=substr($id,0,-4);
                   $required_pairs = [$pair_value];
                   
                   $marketpair=get_pair($required_pairs);
                   
                   $symbol=str_replace("-","",$marketpair['symbol']);
                   $output['symbol'] = $symbol;
                   $output['price'] =  $marketpair['price'];
                   $output['change'] = $marketpair['change'];
               
               }
               
               elseif($exchange_id == 5)
               {
                  $usdt_balance=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 App\Libraries\BybitApi($key, $secret);
                     $usdt_balance = $bybitApi->getBalance('USDT',$acc_type);
                     $tickers = $bybitApi->ticker(['category' => 'spot', 'symbol' => $id]); 
                   }
                    
                  
                   $output['symbol'] = $tickers['symbol'];
                   $output['price'] = $tickers['lastPrice'];
                   $output['change'] = $tickers['price24hPcnt'];
               }
               
               
               $usdt_balance=str_replace(',',"",$usdt_balance);
               $live_price = $output['price'];
               
               $tradSets = $this->common_model->GetResults('adminsettings','');
               $tradSet = $tradSets[0];
               
               $check_strategy = $this->db->table('user_strategy')->where('uusersid',$uusersid)->where('pair',$id)->get()->getRow();
               
               $pair =$this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and pair ='".$id."' and trade_status != 2 and exchange='".$exchange_id."' order by id desc")->getRow();
               
               
               if(!empty($pair))
               {
               $sync_strategy_status = $pair->sync_strategy_status ? $pair->sync_strategy_status : 0;
               $manual_buy = $this->db->table('api_manual_trade')->where('trade_process_id',$pair->id)->where('type',1)->where('status','1')->get()->getRow();
               $manual_sell = $this->db->table('api_manual_trade')->where('trade_process_id',$pair->id)->where('type',2)->where('status','1')->get()->getRow();
               $pair_trade_status=$pair->trade_status;
               }
               else
               {
               $sync_strategy_status='0';
               $pair_trade_status='';
               }
               
               
               
               
               if(isset($this->data) && !empty($this->data)) 
               {
                   
                 $activation =  $this->db->query("SELECT * FROM history WHERE type='activation' and uusersid='".$uusersid."'")->getRow();
                
                 if($activation)
                 {
                     $date2 = date('Y-m-d H:m:s');
                     if(strtotime($date2) > strtotime($activation->expiry_date))
                     {
                       $this->db->table('history')->where('uusersid',$uusersid)->where('historyid',$activation->historyid)->where('type','activation')->update(array('status' => '0'));
                     }
                     else
                     {
                        $this->db->table('history')->where('uusersid',$uusersid)->where('historyid',$activation->historyid)->where('type','activation')->update(array('status' => '1'));
                     }
                                          
                 }
                 $activation =  $this->db->query("SELECT * FROM history WHERE type='activation' and uusersid='".$uusersid."' and status='1'")->getRow();
                 $bind_api =$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."'")->getRow();
                 if(!empty($bind_api))
                   $bind_api = true;
                 else
                   $bind_api = false;
               
                   if($activation)
                   {
                       $activation = true;
                   }
                   else
                   {
                       
                     $activation = false;
                   }
                       // get trading settings
               }
               
               
               
               $qury = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' AND  pair = '".$id."' and trade_status != 2  and exchange='".$exchange_id."' order by id desc limit 1")->getResult();
               
               if(!empty($qury))
               {
               $qry=$qury[0];
               //$qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."'")->getResult();
               //$qry=$qury[0];
               $first_buy_amount=$qry->first_buy_amount;
               
               $open_position_doubled=$qry->open_position_doubled;
               $margin_column_limit=$qry->margin_column_limit;
               $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;
               $strategy_mode=$qry->strategy_mode;
               
               
               }
               else
               {
               
               
               
               $qry='';
               $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' And pair='".$id."'")->getResult();
               if(!empty($qury[0]))
               {
                 
                 $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."' And pair='".$id."'")->getResult();
                 $qry=$qury[0];
               }
               else
               {
                
                 $qury = $this->db->query("SELECT * FROM user_strategy WHERE uusersid='".$uusersid."'")->getResult();
                 $qry=$qury[0];
               }
               $first_buy_amount=$qry->first_buy_amount;
               
               $open_position_doubled=$qry->open_position_doubled;
               $margin_column_limit=$qry->margin_column_limit;
               $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;
               $strategy_mode=$qry->strategy_mode;
               
               
               }
               
               
               if(!empty($pair)) 
               { 
               
                 /*$api_trade_data = array(
                   'trade_process_id' => $pair->id,
                   'uuserid' => $uusersid,
                   'type' => '1',
                   'trade_close' => 0,
                   'exchange' => $exchange_id 
                 );*/
                 
                 
                 $api_trade_data = array(
                   'pair' => $pair->pair,
                   'uuserid' => $uusersid,
                   'type' => '1',
                   'trade_close' => 0,
                   'exchange' => $exchange_id 
                 );
                 
                     
                 $api_trade_data_margin= array(
                   'pair' => $pair->pair,
                   'uuserid' => $uusersid,
                   'type' => '1',
                   'exchange' => $exchange_id 
                 );
                 
                 
               
                 $last_call_drop_data = array(
                   'trade_process_id' => $pair->id,
                   'uuserid' => $uusersid,
                   'exchange' => $exchange_id
                 );
               
                 $api_trade_data1 = array(
                   'trade_process_id' => $pair->id,
                   'uuserid' => $uusersid,
                   'type' => '2',
                   'description' => 'manual_sell',
                   'trade_close' => 0,
                   'exchange' => $exchange_id
                 );
               
                 $api_trade_data2 = array(
                   'trade_process_id' => $pair->id,
                   'uuserid' => $uusersid,
                   'type' => '1',
                   'trade_close' => 0,
                   'margin_call_drops = ' => 0,
                   'exchange' => $exchange_id
                 );
               
               
                  $profit_where = array(
                     'uuserid' => $uusersid,
                     'type' => '3',
                     'trade_process_id' => $pair->id,
                     'trade_close' => 0,
                     'exchange' => $exchange_id
                 );
               
               
               if($pair->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($pair->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) * $pair->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 * $pair->whole_profit_callback / 100;
               $max_down_price = $max_increase_price - $max_down_percentage;
               $max_down_price = round($max_down_price,8);
               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(!empty($last_call_drop))
               {
               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' => $pair->id,
               );
               
               $last_buy_recheck = $this->db->table('api_trade_history')->where($trade_where_new)->orderBy('margin_call_drops','DESC')->get()->getRow();
               if(!empty($last_buy_recheck)){
               $last_margin_call_drop = $last_buy_recheck->margin_call_drops ? $last_buy_recheck->margin_call_drops : 0;
               }
               else
               {
               $last_margin_call_drop='0';
               }
               $call_perc = explode(',', $pair->margincall_drop)[$last_margin_call_drop];
               $tradeupdate['margin_call_drops'] = $call_perc;
               
               if(!empty($last_call_drop))
               {
               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;
               
               $down_price = $last_call_drop->live_price - $price_down;
               
               $last_quantity =$last_call_drop->quantity;
               }
               else
               {
               $down_price='0';
               $last_quantity='';
               }
               
               
               $tradeupdate['down_price']  = "< ".number_format($down_price,9);
               
               /*$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'] = $last_quantity;
               $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;
               }*/
               
               
               
               $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process->id)->where("trade_close",'0')->where('type','1')->orderBy('id','DESC')->get()->getRow();
	$total_position_amount1=$total_position_amount1->quantity;
	
	
	$total_position_amount2 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process->id)->where("description",'manual_sell')->where('type','2')->orderBy('id','DESC')->get()->getRow();
	$total_position_amount2=$total_position_amount2->quantity;
	
	$total_position_amount= $total_position_amount1-$total_position_amount2;

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



	$total_position_qty = $this->db->table('api_trade_history')->selectSum('received_amount')->where("trade_process_id",$trade_process->id)->where("trade_close",'0')->where('type','1')->orderBy('id','DESC')->get()->getRow();
	$total_position_qty1=$total_position_qty->received_amount;
	
	
      $total_position_qty2 = $this->db->table('api_trade_history')->selectSum('received_amount')->where("trade_process_id",$trade_process->id)->where("description",'manual_sell')->where('type','2')->orderBy('id','DESC')->get()->getRow();
      $total_position_qty2=$total_position_qty2->received_amount;

      $total_position_quantity= $total_position_qty1-$total_position_qty2;

      if ($total_position_quantity  > 0) {
      $tradeupdate['trade_position_quantity'] = number_format($total_position_quantity,5);
      }else{
         $tradeupdate['trade_position_quantity'] = 0.00;
      }
                 
                 if ($avg_position_amount > 0) {
                   $tradeupdate['trade_avg_position'] = $avg_position_amount;
                 }else{
                   $tradeupdate['trade_avg_position'] = 0.00;
                 }
                 
               
               
                 $call_drop = $this->db->table('api_trade_history')->where($api_trade_data_margin)->where('margin_call_drops !=',0)->orderBy('id','DESC')->get()->getRow();
                
                 if(!empty($call_drop))
                 {
                     
                   if($call_drop->margin_call_drops == $trade_process->margin_column_limit){
                       $tradeupdate['down_price'] = "Limit Reached";
                       $tradeupdate['margin_call_drops'] = "0";
                   }
               }
               
               
                 
               if(!empty($call_drop)){
                  
                 if ($call_drop->margin_call_drops != '' || $call_drop->margin_call_drops != '0') 
                 {
                   $tradeupdate['trade_number_of_call'] = $call_drop->margin_call_drops;
                 }else{
                   $tradeupdate['trade_number_of_call'] = '0';
                 }
               }
               else
               {
                 $tradeupdate['trade_number_of_call'] = '0';
               }
               
                     $api_trade_data = array(
                     'trade_process_id' => $pair->id,
                     'uuserid' => $uusersid,
                     'type' => '1',
                   );
               
                   $tradeupdate['live_price'] = $live_price;
                   // $first_buy =  $this->db->table('api_trade_history')->where($api_trade_data)->like('description','first_buy')->get()->getRow();
               
               
                   // $first_buy_live_price = $first_buy->live_price;
                   $check_percentage=0;
                   if($avg_position_amount == 0 &&  $tradeupdate['trade_position_amount'] == 0){
                     $check_percentage = '0';
                   }
               
                   else if ($avg_position_amount > $live_price) {
                     
                     // echo "first_buy = ".$first_buy_live_price.'  -  ';
                     // echo "live_price  = ".$live_price;
                     // echo "<br>";
                     // echo "decrease";
                     
                     $check_percentage = ($avg_position_amount - $live_price);
                     $check_percentage = $check_percentage  / $avg_position_amount;
                     $check_percentage = $check_percentage  * 100 ;
                     $check_percentage = '-'.number_format($check_percentage,2);
                   }elseif ($avg_position_amount == $live_price) {
                     
                     // echo "first_buy = ".$avg_position_amount.'  -  ';
                     // echo "live_price  = ".$live_price;
                     // echo "<br>";
               
                     // echo "same";
                     $check_percentage = '0';
                   }else{
                     
                     // echo "first_buy = ".$avg_position_amount.'  -  ';
                     // echo "live_price  = ".$live_price;
                     // echo "<br>";
               
                     // echo "increase";
                     $check_percentage = $live_price - $avg_position_amount;
                     $check_percentage = $check_percentage  / $live_price;
                     $check_percentage = $check_percentage  * 100 ;
                   }
               
               
                   $tradeupdate['trade_rate_percentage'] = $check_percentage;
               
               
               
                   if ($avg_position_amount > $live_price) {
                     
                     // echo "first_buy = ".$avg_position_amount.'  -  ';
                     // echo "live_price  = ".$live_price;
                     // echo "<br>";
                     // echo "decrease";
                     
                   $check_percentage1 = ($avg_position_amount - $live_price) / $avg_position_amount;
                   $check_percentage1 = $check_percentage1  * 100 ;
                         $check_percentage1 = '-'.number_format($check_percentage1,2);
                   }elseif ($avg_position_amount == $live_price) {
                     
                     // echo "first_buy = ".$avg_position_amount.'  -  ';
                     // echo "live_price  = ".$live_price;
                     // echo "<br>";
               
                     // echo "same";
                     $check_percentage1 = '0.00';
                   }else{
                     // echo "first_buy = ".$avg_position_amount.'  -  ';
                     // echo "live_price  = ".$live_price;
                     // echo "<br>";
               
                     // echo "increase";
                     $check_percentage1 = ($live_price - $avg_position_amount) / $live_price;
                     $check_percentage1 = $check_percentage1  * 100 ;
                   }
               
               
               $tradeupdate['trade_estimate_price'] = $check_percentage1;
                   
               
               $total_sell_amount = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data1)->get()->getRowArray();
               
               $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->get()->getRowArray();
               
               $total_position_amount = $total_position_amount1['quantity'] - $total_sell_amount['quantity'];
               $total_position_amount = number_format($total_position_amount,4);
               
               $tradeupdate['trade_remain_amount'] = $tradeupdate['trade_position_amount'];
               
            //   $base = substr($id, 0, -4);
            //                 $pair_disp=$base.'/USDT';
               
               
               }
               
             $base = substr($id, 0, -4);
             $pair_disp=$base.'/USDT';
               
               
               
               ?>
      <section class="banner-bg overall-bg ">
         <div class="container">
         <header class="pt-3 pb-3">
               <div class="row">
                  <div class="col-1">
                     <div class="back-arrow">
                        <a href="<?php echo base_url();?>/user/quantify">
                           <iconify-icon icon="bi:arrow-left-circle-fill"></iconify-icon>
                        </a>
                     </div>
                  </div>
                  <div class="col-8">
                     <div class="title title-top py-2">
                        <h2 class="text-primary aleo"><?php echo $pair_disp;?></h2>
                     </div>
                  </div>
                  <div class="col-3">
                     <div class="common-icon d-flex align-items-center justify-content-end">
                        <div class="wallet-icon header-icon me-2">
                           <a href="<?php echo base_url();?>/trades/<?php echo $id;?>" class="text-decoration-none ">
                           <i class="fa fa-calendar-days" title="Trading Records"></i>
                           </a>
                        </div>
                        <div class="header-icon">
                           <a href="<?php echo base_url();?>/news" class="text-decoration-none">
                              <iconify-icon icon="mdi:notifications-none"></iconify-icon>
                           </a>
                        </div>
                     </div>
                  </div>
               </div>
            </header>
         </div>
         <section class="dash-wrap trade-wrap">
          
            <div class="container">
               <div class="row">
                  <div class="col-12">
                     <div class="trade-sec-header ">
                        <div class="trade d-flex align-items-center text-white">
                           <div class="trade-icon">
                              <img src="<?php echo base_url('styles/images/tradingpair_images/'.$output['symbol'].'.png');?>" style="width:64px;height:64px;">
                           </div>
                           <div class="trade-content ms-4">
                              <h6 class="text-white fw-semibold aleo d-flex mb-3 align-items-center">
                                 <?php echo $pair_disp;?>
                                 <iconify-icon icon="mdi:tick-decagram" class="ms-2"></iconify-icon>
                              </h6>
                              <div class="added-trade-btn text-start">
                                 <?php
                                    if(!empty($pair)) 
                                    {
                                      if($pair->trade_status == 0) 
                                      { 
                                    ?>
                                 <a id="pause_button"  class="btn btn-outline-primary">Pause</a>
                                 <?php 
                                    } 
                                    else if($pair->trade_status == 1) 
                                    { 
                                    ?>
                                 <a id="pause_button"  class="btn btn-outline-primary">Pause</a>
                                 <?php 
                                    } 
                                    }
                                    ?>
                                 <a  id="crypto-strategy" class="btn btn-outline-primary">cycle</a>
                              </div>
                           </div>
                        </div>
                     </div>
                     
                     <ul class="trade-menu-link mb-0 list-unstyled">
                           
                        <li id="Ostartegy" style="display: none;cursor: pointer;">
                           <div class="trade-menu-icon">
                              <img src="<?php echo base_url();?>/assets/images/single-icon.png" alt="">
                           </div>
                           <div class="trade-menu-content">
                              <h6 id="Ostartegy_Name" class="mb-0 mt-2 text-white aleo fw-semibold">Single</h6>
                           </div>
                        </li>
                        <li id="Cstartegy" style="cursor: pointer;">
                           <div class="trade-menu-icon">
                              <img src="<?php echo base_url();?>/assets/images/single-icon.png" alt="">
                           </div>
                           <div class="trade-menu-content">
                              <h6 id="Cstartegy_Name" class="mb-0 mt-2 text-white aleo fw-semibold">Cycle</h6>
                           </div>
                        </li>
                        <?php 
                           if(!empty($pair) && $pair->trade_status != 2)
                           {
                           ?>
                        <li id="sell_popup" data-bs-toggle="modal" data-bs-target="#SellModal" data-bs-whatever="@fat">
                           <div class="trade-menu-icon">
                              <img src="<?php echo base_url();?>/assets/images/sell-icon.png" alt="">
                           </div>
                           <div class="trade-menu-content">
                              <h6 class="mb-0 mt-2 text-white aleo fw-semibold">Sell</h6>
                           </div>
                        </li>
                        <?php
                           }
                           else
                           {
                           ?>
                        <li id="sellModels" data-bs-whatever="@fat">
                           <div class="trade-menu-icon">
                              <img src="<?php echo base_url();?>/assets/images/sell-icon.png" alt="">
                           </div>
                           <div class="trade-menu-content">
                              <h6 class="mb-0 mt-2 text-white aleo fw-semibold">Sell</h6>
                           </div>
                        </li>
                        <?php
                           }
                           ?>
                        <?php 
                           if(!empty($pair) &&  $pair->trade_status != 2)
                           {
                           ?>
                        <!--<li id="buy_popup" data-bs-toggle="modal" data-bs-target="#BuyModal" data-bs-whatever="@fat">
                           <div class="trade-menu-icon">
                              <img src="<?php echo base_url();?>/assets/images/buy-icon.png" alt="">
                           </div>
                           <div class="trade-menu-content">
                              <h6 class="mb-0 mt-2 text-white aleo fw-semibold">Buy</h6>
                           </div>
                        </li>-->
                        <?php
                           }
                           else
                           {
                           ?>
                        <!--<li id="buyModels">
                           <div class="trade-menu-icon">
                              <img src="<?php echo base_url();?>/assets/images/buy-icon.png" alt="">
                           </div>
                           <div class="trade-menu-content">
                              <h6 class="mb-0 mt-2 text-white aleo fw-semibold">Buy</h6>
                           </div>
                        </li>-->
                        <?php } ?>
                     </ul>
                     <div class="trade-button text-center mb-3 d-flex align-items-center justify-content-center">
                        <a href="<?php echo base_url();?>/tradesettings/<?php echo $id;?>" class="btn btn-outline-primary me-1 d-flex align-items-center justify-content-center">
                           <iconify-icon icon="ant-design:setting-filled" class="me-2"></iconify-icon>
                           setting
                        </a>
                        <?php 
                           if($activation) 
                           { 
                             if(!empty($pair)) 
                             {
                               if($pair->trade_status == 0) 
                               { 
                             ?>
                        <a id="resume_button"  class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">
                           <iconify-icon icon="wpf:repeat" class="me-2" ></iconify-icon>
                           Resume 
                        </a>
                        <?php 
                           } 
                           
                           else if($pair->trade_status == 2) 
                           {
                           ?>
                        <a id="start_button" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Start </a>
                        <?php 
                           } 
                           if($pair->trade_status == 1) { ?>
                        <a id="stop_button" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Stop </a>
                        <?php }   
                           }
                              else { ?>
                        <a id="start_button" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Start </a>
                        <?php } } else {  ?>
                        <a id="start_button_block" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Start </a>
                        <?php }  ?>
                     </div>
                     <div class="trade-value-title">
                        <h6 class="text-white aleo mb-0 fw-normal p-3">Average Price (USDT) <span class="fw-bold" id="trade_avg_position"><?php if(!empty($tradeupdate['trade_avg_position'])) { echo number_format($tradeupdate['trade_avg_position'],8); } else { echo 0; };?></span></h6>
                     </div>
                     <div class="trade-added-value">
                        <ul class=" trade-sec-list-one trade-sec-list list-unstyled text-center ">
                           <li>
                              <small class="text-white-50">Hold Amount</small>
                              <h5 class="text-white mb-0" id="trade_position_amount"><?php if(!empty($tradeupdate['trade_position_amount'])) { echo $tradeupdate['trade_position_amount']; } else echo 0;?> USDT</h5>
                           </li>
                           <li>
                              <small class="text-white-50">Hold Volume</small>
                              <h5 class="text-white mb-0" id="trade_position_quantity"><?php if(!empty($tradeupdate['trade_position_quantity'])) { echo $tradeupdate['trade_position_quantity']; } else { echo 0;}?></h5>
                           </li>
                           <?php 
                              $get_last_trade=$this->db->query("select * from api_trade_history where trade_process_id='".$id."' order by id desc limit 1")->getRow();
                              if($get_last_trade)
                              {
                                  $last_margin=$get_last_trade->margin_call_drops;
                              }
                              else
                              {
                                  $last_margin=0;
                              }
                              ?>
                           <li>
                              <small class="text-white-50">No.of Calls</small>
                              <h5 class="text-white mb-0" id="trade_number_of_call"><?php echo $last_margin;?></h5>
                           </li>
                        </ul>
                        <ul class="mb-0 trade-sec-list-two trade-sec-list list-unstyled text-center">
                           <li>
                              <small class="text-white-50">Current Price</small>
                              <h5 class="text-white mb-0 value all_list_price"> <?php 
                                 if(intval($output['price']) > 99) 
                                   echo number_format($output['price'],5);
                                 else
                                   echo number_format($output['price'],8);
                                 ?></h5>
                           </li>
                           <li>
                              <small class="text-white-50">Coveage Price</small>
                              <h5 class="text-white mb-0" id="down_price"><?php if(!empty($tradeupdate['down_price'])) { echo $tradeupdate['down_price'] ;} else { echo "< 0.0";}?></h5>
                           </li>
                           <li>
                              <small class="text-white-50">Liquid Price</small>
                              <h5 class="text-white mb-0" id="take_profit_trigger"><?php if(!empty($tradeupdate['take_profit_trigger'])) { echo $tradeupdate['take_profit_trigger'];} else { echo "> 0.0";}?></h5>
                           </li>
                            <li>
                              <small class="text-white-50">Rate of Return</small>
                              <h5 class="text-white mb-0" id="trade_rate_percentage12"><?php if(!empty($tradeupdate['trade_rate_percentage'])) { echo $tradeupdate['trade_rate_percentage'];} else { echo 0;}?>%</h5>
                           </li>
                        </ul>
                     </div>
                     <div class="trade-value-time mt-3">
                        <h6 class="text-white aleo mb-0 fw-normal p-3">First Time Order <span class="fw-bold">&nbsp;&nbsp;<?php echo $trade_process->first_buy_amount ? $trade_process->first_buy_amount : 0;?> </span></h6>
                     </div>
                     <ul class="mb-0 trade-time-content my-3 list-unstyled ">
                        <li>
                           <h6 class="text-white-50 mb-0">Multiple Invest Limit <span class="text-white">&nbsp;&nbsp;<?php echo $trade_process->margin_column_limit ? $trade_process->margin_column_limit : 0;?></span></h6>
                        </li>
                        <li>
                           <h6 class="text-white-50 mb-0">Take Profit Ratio <span class="text-white">&nbsp;&nbsp;<?php echo $trade_process->whole_profit_ratio ? $trade_process->whole_profit_ratio."%" : "0%";?></span></h6>
                        </li>
                        <li>
                           <h6 class="text-white-50 mb-0">Earning Call Back<span class="text-white">&nbsp;&nbsp;<?php echo $trade_process->whole_profit_callback ? $trade_process->whole_profit_callback."%" : "0%";?></span></h6>
                        </li>
                        <li>
                           <h6 class="text-white-50 mb-0">Call Back for Margin Call <span class="text-white">&nbsp;&nbsp;<?php  if(!empty($trade_process->buyin_callback)) { echo $trade_process->buyin_callback."%" ;} else { echo "0%";}?></span></h6>
                        </li>
                     </ul>
                     <?php 
                        if(!empty($trade_process->buyin_ratio_times))
                        {
                        ?>
                     <div class="trade-value-time mt-3">
                        <h6 class="text-white aleo mb-0 fw-normal p-3">Open Position <span class="fw-bold"> <?php  if(!empty($trade_process->buyin_ratio_times)) { echo "X ".$trade_process->buyin_ratio_times ;} else { echo "";}?> </span></h6>
                     </div>
                    
                     <div class="table-responsive trans position-relative">
                        <table id="example1" class="table table-striped">
                           <thead>
                              <tr>
                                 <th> No.Of Call </th>
                                 <th> Call For Drop Position </th>
                                 <th> Call Up Multiples </th>
                              </tr>
                           </thead>
                           <tbody>
                              <?php 
                                 $call_limit=$trade_process->margin_column_limit;
                                 
                                 
                                 
                                 for($i=0;$i<$call_limit;$i++)
                                 {
                                     $j=$i+1;
                                      if($j=='1')
                                         $call="1st";
                                       else if($j=='2')
                                         $call="2nd";
                                       else if($j=='3')
                                         $call="3rd";
                                       else
                                         $call=$j."th";
                                         
                                         $margin_call=explode(",",$trade_process->margincall_drop);
                                         $position_amt=explode(",",$trade_process->buyin_ratio_times);
                                         
                                        
                                        
                                         if(!empty($margin_call[$i]))
                                           $margin_value=$margin_call[$i];
                                         else
                                           $margin_value='0';
                                 
                                         
                                          if(!empty($position_amt[$i]))
                                             $position_value=$position_amt[$i];
                                          else
                                            $position_value='0';
                                 
                                         
                                           if($margin_value!='0')
                                           {
                                     ?>
                              <tr>
                                 <td><?php echo $call;?> Call</td>
                                 <td><?php echo $margin_value;?>%</td>
                                 <td><?php echo $position_value;?></td>
                              </tr>
                              <?php 
                                 }
                                 }
                                 ?>
                           </tbody>
                        </table>
                     </div>
                     <?php 
                        }
                        ?>
                     <div class="operation-content my-3">
                        <h5 class="text-primary py-1 aleo text-uppercase">Operation Reminder</h5>
                        <p class="text-white">When the Trade Pilot intelligent system is in operation, please refrain from manually managing your currency account, fixed deposit, or activating the freezing function. This precaution is necessary to prevent any potential anomalies in the system, which could impact your profitability. </p>
                     </div>
                     <!-- <div class="file-preset py-2"> 
                        <a href="#" class="menu-list d-flex align-items-center justify-content-between text-decoration-none">
                          <div class="menu-content">
                                    <span class="ms-2">Fist preset start price</span>
                                
                                </div>
                                <div class="menu-list-arrow">
                                  <i class="fa-solid fa-greater-than"></i>
                              </div>
                              </a>
                              
                                </div> -->
                     <!--<div class="trade-button text-center mb-3 d-flex align-items-center justify-content-center">
                        <a href="<?php echo base_url();?>/tradesettings/<?php echo $id;?>" class="btn btn-outline-primary me-1 d-flex align-items-center justify-content-center">
                           <iconify-icon icon="ant-design:setting-filled" class="me-2"></iconify-icon>
                           setting
                        </a>
                        <?php 
                           if($activation) 
                           { 
                             if(!empty($pair)) 
                             {
                               if($pair->trade_status == 0) 
                               { 
                             ?>
                        <a id="resume_button"  class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">
                           <iconify-icon icon="wpf:repeat" class="me-2" ></iconify-icon>
                           Resume 
                        </a>
                        <?php 
                           } 
                           
                           else if($pair->trade_status == 2) 
                           {
                           ?>
                        <a id="start_button" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Start </a>
                        <?php 
                           } 
                           if($pair->trade_status == 1) { ?>
                        <a id="stop_button" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Stop </a>
                        <?php }   
                           }
                              else { ?>
                        <a id="start_button" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Start </a>
                        <?php } } else {  ?>
                        <a id="start_button_block" class="btn btn-outline-primary ms-1 d-flex align-items-center justify-content-center ">Start </a>
                        <?php }  ?>
                     </div>-->
                     <!---banner end---->
                  </div>
               </div>
            </div>
         </section>
         <!-- Buy Modal -->
         <div class="modal fade" id="BuyModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="BuyModal" style="display: none;" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
               <div class="modal-content" style="border-radius:30px;padding: 11px;" >
                  <div class="modal-header">
                     <h5 class="modal-title" id="exampleModalLabel">BUY</h5>
                     <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                  </div>
                  <div class="modal-body">
                     <div class="row">
                        <div class="col-lg-12">
                           <input type="hidden" id="pair" value="<?php echo $id;?>">
                           <div class="row" style="display:none;">
                              <div class="col-lg-6">
                                 <h6> Position amount </h6>
                              </div>
                              <div class="col-lg-6" >
                                 <span id="trade_position_amount1"><?php if(!empty($tradeupdate['total_position_amount'])) { echo $tradeupdate['trade_position_amount']; } else { echo "0"; }?></span> USDT
                              </div>
                           </div>
                           <div class="row mt-2">
                              <div class="col-lg-6">
                                 <h6>Average position price</h6>
                              </div>
                              <div class="col-lg-6">
                                 <span id="trade_avg_position1"><?php if(!empty($tradeupdate['trade_avg_position'])){ echo number_format($tradeupdate['trade_avg_position'],8);} else {  "0" ; }?></span> USDT
                              </div>
                           </div>
                           <div class="row mt-2">
                              <div class="col-lg-6">
                                 <h6> Position quantity</h6>
                              </div>
                              <div class="col-lg-6">
                                 <span id="trade_position_quantity"><?php if(!empty($tradeupdate['trade_position_quantity'])) { echo $tradeupdate['trade_position_quantity']; } else { "0";} ?></span>&nbsp;&nbsp;<?php echo substr($id, 0,-4);?>
                              </div>
                           </div>
                           <div class="row mt-2">
                              <div class="col-lg-6">
                                 <h6>Current price</h6>
                              </div>
                              <div class="col-lg-6 all_list_price">
                                 <?php 
                                    if($output['price'])
                                     echo $output['price'];
                                     else
                                      echo '0.00';?>
                              </div>
                           </div>
                           <div class="row mt-2">
                              <div class="col-lg-6">
                                 <h6>Rate of return</h6>
                              </div>
                              <div class="col-lg-6">
                                 <span id="trade_rate_percentage2"><?php if(!empty($tradeupdate['trade_rate_percentage'])) { echo $tradeupdate['trade_rate_percentage'] ; } else { echo "0%" ; }?> %</span>
                              </div>
                           </div>
                           <hr>
                           <div class="row mt-2" style="display:none;">
                              <div class="col-lg-6">
                                 <h6>Estimated average position price</h6>
                              </div>
                              <div class="col-lg-6 all_list_price1">
                                 <?php if(!empty($tradeupdate['trade_avg_position'])) { echo $tradeupdate['trade_avg_position'];} else { echo "0"; } ?>
                              </div>
                           </div>
                           <div class="row mt-2" style="display:none;" >
                              <div class="col-lg-6">
                                 <h6>Estimated holding profit and loss</h6>
                              </div>
                              <div class="col-lg-6" id="trade_estimate_price2">
                                 -
                              </div>
                           </div>
                           <div class="col-lg-6" >
                              <h6>Trigger Price</h6>
                           </div>
                           <div class="row mt-2">
                              <div class="col-lg-12">
                                 <div class="input-group mb-4">
                                    <input type="text" class="form-control" id='limit_clk' placeholder="Enter Trigger's price" aria-label="Recipient's username" aria-describedby="basic-addon2">
                                    <div class="input-group-append">
                                       <button class="btn btn-primary" id="market_clk" type="button" style="height:80%;">Market Price</button>
                                    </div>
                                 </div>
                              </div>
                           </div>
                           <div class="row mt-2">
                              <div class="col-lg-6">
                                 <h6>Purchase Amount</h6>
                              </div>
                           </div>
                           <div class="row mt-2">
                              <div class="col-lg-12">
                                 <div class="form-block mb-3 position-relative">
                                    <input name="code1" class="form-control"   type="text" id="code1" required="" placeholder="Please Enter Purchase Amount" value="" />
                                    <div id="pur_err" style="color:red;font-size:12px;"></div>
                                 </div>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <div class="modal-footer" style="padding: 0px;">
                     <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                     <button type="button" id="buy" class="btn btn-primary" style="width:20% !important">Buy</button>
                  </div>
               </div>
            </div>
         </div>
         <!-- Sell Modal -->
         <div class="modal fade" id="SellModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="SellModal" style="display: none;" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
               <div class="modal-content" style="border-radius:30px;padding: 11px;" >
                  <div class="modal-header">
                     <h5 class="modal-title" id="exampleModalLabel">Sell</h5>
                     <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                  </div>
                  <div class="modal-body">
                     <div class="modal-body">
                        <div class="row">
                           <div class="col-lg-12">
                              <input type="hidden" id="pair1" value="<?php echo $id;?>">
                              <div class="row">
                                 <div class="col-lg-6">
                                    <h6> Position amount </h6>
                                 </div>
                                 <div class="col-lg-6">
                                    <span class="trade_position_amount"><?php if(!empty($tradeupdate['trade_position_amount'])) { echo $tradeupdate['trade_position_amount'];} else { echo '0';}?></span> USDT
                                 </div>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-6">
                                    <h6>Average position price</h6>
                                 </div>
                                 <div class="col-lg-6">
                                    <span class="trade_avg_position"><?php if(!empty($tradeupdate['trade_avg_position'])) { echo $tradeupdate['trade_avg_position'];} else { echo '0'; } ?></span>USDT
                                 </div>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-6">
                                    <h6>Position quantity</h6>
                                 </div>
                                 <div class="col-lg-6">
                                    <span class="trade_position_quantity"><?php if(!empty($tradeupdate['trade_position_quantity'])) { echo $tradeupdate['trade_position_quantity'];} else { echo '0'; }?></span>&nbsp;&nbsp;<?php echo substr($id, 0,-4);?>
                                 </div>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-6">
                                    <h6>Current price</h6>
                                 </div>
                                 <div class="col-lg-6 all_list_price">
                                    <?php 
                                       if($output['price'])
                                        echo $output['price'];
                                        else
                                         echo '0.00';?>
                                 </div>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-6">
                                    <h6>Position profit and loss</h6>
                                 </div>
                                 <div class="col-lg-6" id="trade_estimate_price">
                                    <?php if(!empty($tradeupdate['trade_estimate_price'])) { echo $tradeupdate['trade_estimate_price'] ; } else { echo "0%"; }?>
                                 </div>
                              </div>
                              <hr>
                              <div class="row mt-2">
                                 <div class="col-lg-12">
                                    <h6>Estimated selling profit</h6>
                                 </div>
                                 <div class="col-lg-12 estimate_sell"></div>
                              </div>
                              <div class="col-lg-12">
                                 <h6>Trigger Price (Sell at market price after reaching the trigger price)</h6>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-12">
                                    <div class="input-group mb-4">
                                       <input type="text" class="form-control" id='limit_clk1' placeholder="Enter Trigger's Price" style="background:#000;color:#fff;" aria-label="Recipient's username" aria-describedby="basic-addon2">
                                       <div class="input-group-append">
                                          <button class="btn btn-primary" id="market_clk1" type="button" style="height:50px;font-size:19px;">Market Price</button>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-12">
                                    <h6>Clearance Quantity</h6>
                                 </div>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-12">
                                    <div class="form-block mb-3 position-relative">
                                       <input name="code1" class="form-control clearance"   type="text" id="clearance" required="" placeholder="Please Enter Clearance Quantity in  <?php echo substr($id,0,-4);?>" value="" style="background:#000;color:#fff;" />
                                    </div>
                                 </div>
                              </div>
                              <div class="row mt-2">
                                 <div class="col-lg-12">
                                    <button class="btn btn-danger" id="quarter" type="button">25%</button>
                                    <button class="btn btn-danger" id="half" type="button">50%</button>
                                    <button class="btn btn-danger" id="onebuythree" type="button">75%</button>
                                    <!--<button class="btn btn-danger" id="full" type="button">100%</button>-->
                                 </div>
                              </div>
                              <br/>
                              <div class="row mt-2">
                                 <div class="col-lg-6">
                                    <h6>Remaining Position Amount</h6>
                                 </div>
                                 <div class="col-lg-6">
                                    <span id="remaining_amount"><?php if(!empty($tradeupdate['trade_remain_amount'])) { echo $tradeupdate['trade_remain_amount']; } else { echo '0'; }?></span> USDT
                                 </div>
                                 <span id="err" style="color: red;"></span>
                              </div>
                           </div>
                        </div>
                     </div>
                     <input type="hidden" name="manual_sell" id="manual_sell" value="">
                     <div class="modal-footer" style="padding: 0px;">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" id="sell"  class="btn btn-primary " style="width:20% !important">Sell</button>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <?php 
            if(!empty($pair))
            {
                $sta_mode=$pair->strategy_type;
            }
            else
            {
                $sta_mode=$user->strategy_type;
            }
            
            if($sta_mode=='Cycle Strategy')
            {
                $sta_mode='Cycle';
            }
            else
            {
                $sta_mode='Single';
            }
            ?>
         <input type="hidden" value="<?php echo $sta_mode;?>" id="find_mode">
         <input type="hidden" value="<?php if(!empty($pair->strategy_mode)) { echo $pair->strategy_mode; } else { echo $user->strategy_mode; }?>" id="modes">
         <input type="hidden" value="" id="all_list_price" name="all_list_price" value="<?php if($output['price']) { echo $output['price'];} else { '0.0' ;} ?>">
         <!--footer start -->
         <?php echo view('user/layout/footer');?>
         <!--footer end -->
      </section>
  
      <?php echo view('user/layout/footer-script');?>
      <script>
         AOS.init({
         });
      </script>
      <script src="<?php echo base_url();?>/styles/new_style/js/notify.js"></script>
      <script src="<?php echo base_url();?>/styles/web_style/js/jquery.dataTables.min.js"></script>
      <script type="text/javascript">
         $('#market_clk').on('click',function()
         {
          
           var limit_price= $("#all_list_price").val();
           
          
           if($('#limit_clk').is(':disabled'))
           {
             $("#limit_clk").attr('disabled', false);
             $("#limit_clk").val('');
             
           }
           else
           {
             $("#limit_clk").attr('disabled', true);
             $("#limit_clk").val(limit_price);
           }
         });
         $('#market_clk1').on('click',function()
         {
              var limit_price= $("#all_list_price").val();
           if($('#limit_clk1').is(':disabled'))
           {
         
             $("#limit_clk1").attr('disabled', false);
             $("#limit_clk1").val('');
           }
           else
             {
               $("#limit_clk1").attr('disabled', true);
               $("#limit_clk1").val(limit_price);
             }
         
         });
         
         $('#buy_popup').on('click', function()
         {
           $('.all_list_price1').html($('#trade_avg_position1').html()+" USDT");
          $('#trade_estimate_price2').html($('#trade_rate_percentage2').html());
         });
         
         $('#quarter').on('click',function()
         {
           
            $('#manual_sell').val(this.id);
            $('.estimate_sell').html("");
           var price = <?php if(!empty($tradeupdate['trade_remain_amount'])) { echo str_replace(',', '', $tradeupdate['trade_remain_amount']); } else { echo 0;}?>;
           var quantity = <?php if(!empty($tradeupdate['trade_position_quantity'])) { echo str_replace(',', '', $tradeupdate['trade_position_quantity']); } else { echo 0;}?>;
           var quantity_quarter = +quantity * 25 / 100;
           quantity_quarter = quantity_quarter.toString().replace(/\,/g,"");
           var quarter = +price * 25 / 100;
           var remain = +price - +quarter;
           $('#clearance').val(quantity_quarter);
           $('#remaining_amount').html(remain);
           var profit_loss = $('#trade_estimate_price').html();
           var position_perc = profit_loss.substring(0, profit_loss.length - 1);
           var live_price = $('.all_list_price').html();
           var est_sell_pre = quantity_quarter * live_price;
                  var estimate_sell1 =  +parseFloat(price) * +parseFloat(profit_loss) / 100;
           var estimate_sell = estimate_sell1 * 1/4;
            $('.estimate_sell').html(estimate_sell.toPrecision(5));
         
         });
         
         
         $('#half').on('click',function()
         {
            $('#manual_sell').val(this.id);
            $('.estimate_sell').html("");
           var price =<?php if(!empty($tradeupdate['trade_remain_amount'])) { echo str_replace(',', '', $tradeupdate['trade_remain_amount']);} else {echo "0"; }?>;
           var quantity = <?php if(!empty($tradeupdate['trade_position_quantity'])) { echo str_replace(',', '', $tradeupdate['trade_position_quantity']) ; } else { echo 0 ;}?>;
           var quantity_quarter = +quantity * 50 / 100;
           quantity_quarter = quantity_quarter.toString().replace(/\,/g,"");
           var quarter = +price * 50 / 100;
           var remain = price - quarter;
           $('#clearance').val(quantity_quarter);
           $('#remaining_amount').html(remain);
           var profit_loss = $('#trade_estimate_price').html();
           var position_perc = profit_loss.substring(0, profit_loss.length - 1);
           var live_price = $('.all_list_price').html();
            var estimate_sell1 =  +parseFloat(price) * +parseFloat(profit_loss) / 100;
           var estimate_sell = estimate_sell1 * 1/2;
            $('.estimate_sell').html(estimate_sell.toPrecision(5));
         
         });
         
         
         $('#onebuythree').on('click',function()
         {
            $('#manual_sell').val(this.id);
            $('.estimate_sell').html("");
           var price = <?php if(!empty($tradeupdate['trade_remain_amount'])) { echo str_replace(',', '', $tradeupdate['trade_remain_amount']); } else { echo "0";}?>;
           var quantity = <?php if(!empty($tradeupdate['trade_position_quantity'])) { echo str_replace(',', '', $tradeupdate['trade_position_quantity']); } else { echo "0";}?>;
           var quantity_quarter = +quantity * 75 / 100;
           quantity_quarter = quantity_quarter.toString().replace(/\,/g,"");
           var quarter = +price * 75 / 100;
           var remain = price - quarter;
           $('#clearance').val(quantity_quarter);
           $('#remaining_amount').html(remain);
           var profit_loss = $('#trade_estimate_price').html();
           var position_perc = profit_loss.substring(0, profit_loss.length - 1);
           var live_price = $('.all_list_price').html();
           var est_sell_pre = quantity_quarter * live_price;
           var estimate_sell1 =  +parseFloat(price) * +parseFloat(profit_loss) / 100;
           var estimate_sell = estimate_sell1 * 3/4;
           $('.estimate_sell').html(estimate_sell.toPrecision(5));
         
         });
         
         
         $('#full').on('click',function()
         {
           $('#manual_sell').val(this.id);
           $('.estimate_sell').html("");
           var price = <?php if(!empty($tradeupdate['trade_remain_amount'])){ echo str_replace(',', '', $tradeupdate['trade_remain_amount']);} else { echo "0";}?>;
           $('#clearance').val(<?php if(!empty($tradeupdate['trade_position_quantity'])) { echo str_replace(',', '', $tradeupdate['trade_position_quantity']);} else { echo 0 ;}?>);
           $('#remaining_amount').html(0);
           var profit_loss = $('#trade_estimate_price').html();
           var position_perc = profit_loss.substring(0, profit_loss.length - 1);
           var live_price = $('.all_list_price').html();
           var est_sell_pre = <?php if(!empty($tradeupdate['trade_position_quantity'])) { echo str_replace(",","",$tradeupdate['trade_position_quantity']) ;}else{ echo 0; }?> * live_price;
           var estimate_sell = +parseFloat(price) * +parseFloat(profit_loss) / 100;
           $('.estimate_sell').html(estimate_sell.toPrecision(5));
           
         });
         
         $('#clearance').on('change',function()
         {
           var price =  $('#clearance').val();
           var id=$('#pair1').val();
           var old_price =  <?php if(!empty($tradeupdate['trade_remain_amount'])){ echo str_replace(',', '', $tradeupdate['trade_remain_amount']);} else { echo 0; }?>;
           var total_quantz =  <?php if(!empty($tradeupdate['total_position_amount'])){str_replace(',', '', $tradeupdate['total_position_amount']); } else { echo 0;} ?>;
           
           if(price <= total_quantz)
           {
             $('#err').html();
             var live_price = $('.all_list_price').html();
             var total_price = live_price * price ;
             total_price = total_price.toString().replace(/\,/g,"");
             var msg = old_price - total_price;
             $('#remaining_amount').html(msg);
             var profit_loss = $('#trade_estimate_price').html();
             var position_perc = profit_loss.substring(0, profit_loss.length - 1);
             var live_price = $('.all_list_price').html();
             var est_sell_pre = price * live_price;
             var estimate_sell1 = +parseFloat(est_sell_pre) * +parseFloat(position_perc) / 100;
             var estimate_sell = estimate_sell1 * 80/100;
           if(position_perc > 0)
             $('.estimate_sell').html(estimate_sell.toPrecision(5));
           else
             $('.estimate_sell').html("-"+estimate_sell.toPrecision(5));
             
            }
            else
            {
             $('#err').html('Your Clearance Amount is not greater than available position quantity');        
            }
            });
         
         
            
         $('#sell').on('click',function() 
         {
           if($('#limit_clk1').is(':disabled'))
             var val= "";
           else
             var val = $('#limit_clk1').val();
           var status = $('#manual_sell').val();
           if(status == 'full')
             status = 1;
           else
             status = 0;
           var num=  $('#clearance').val();
           var id=$('#pair1').val();
           var uusersid=<?php echo $this->session->get('uusersid');?>;
           var exchange=<?php echo $this->session->get('exchange');?>;
           var percentage=$('#manual_sell').val();
           var est_profit=$('.estimate_sell').html();
           
           var avg_price=$('.trade_avg_position').html();
           var trade_process_id = <?php if(!empty($pair)) { echo $pair->id ;} else { echo  '0'; } ?>;
           $.ajax({
             'method': 'POST',
             'url': '<?php echo base_url("/tradingsell");?>',
              data:{'val':val,'num':num,'id':id,'uusersid':uusersid,'trade_process_id':trade_process_id,'status': status,'exchange':exchange,'avg_price':avg_price,'percentage':percentage,'est_profit':est_profit},
             
             success:function(msg)
             { 
                 var msg=msg.split('&&');
              
              if(msg[0]!='success')
                 $.notify(' <i class="fas fa-exclamation-triangle"></i>&nbsp;&nbsp;'+msg[1], 'danger');
               else
               {
                   $.notify('<i class="fas fa-check"></i>&nbsp;&nbsp; Maual sell executed successfully... ', 'success');
                 //window.location.reload();
               }
             },
             error: function (request, message, error) {
              let  err =  handleException(request, message, error);
                 if(err)
                   $.notify(' <i class="fas fa-exclamation-triangle"></i>&nbsp;&nbsp; Sell process failed. Please try again... ', 'danger');
             }
           })
         });
         
         
         
           $('#sync_modal').on('click',function(){
             $.notify('<i class="fas fa-exclamation-triangle"></i>Transaction settings are restricted for sync mode. Use first preset start price to change the first buy amount', 'danger');
           });
         
             $('#sync_mode').on('click',function(){
            $.notify('<i class="fas fa-exclamation-triangle"></i>Strategy mode changes are restricted for sync mode.', 'danger');
           });
         
         
      </script>
      <script type="text/javascript">
         $('#exampleModal1_clr').on('click', function() {
         
         var num = <?php echo $trade_process->margin_column_limit;?>;
         if(num == "")
         num = 7;
         
         $.ajax({
         type: 'post',
         dataType:'html',
         url : '<?php echo base_url("/replenishment_time1");?>',
         data : {'number1':num,'pair':'<?php echo $output['symbol']?>'},
         headers: {'X-Requested-With': 'XMLHttpRequest'},
         success : function(msg)
         {
         if(msg)
         {
         $('#ex_demo1').html(msg);
         }
         }
         });
         
         $.ajax({
         type: 'post',
         dataType:'html',
         url : '<?php echo base_url("/replenishment_time2");?>',
         data : {'number2':num,'pair':'<?php echo $output['symbol']?>'},
         headers: {'X-Requested-With': 'XMLHttpRequest'},
         success : function(msg)
         {
         if(msg)
         {
         $('#ex_demo2').html(msg);
         }
         }
         });
         
         $.ajax({
         type: 'post',
         dataType:'html',
         url : '<?php echo base_url("/replenishment_time");?>',
         data : {'number':num,'pair':'<?php echo $output['symbol']?>'},
         headers: {'X-Requested-With': 'XMLHttpRequest'},
         success : function(msg)
         {
         if(msg)
         {
         $('#ex_demo').html(msg);
         }
         }
         });
         
         });
         
         
         $('#replenishment_time').keyup(function(){
         
         var num = $('#replenishment_time').val();
         
         if(num>=5)
         {
                 $.ajax({
                 type: 'post',
                 dataType:'html',
                 url : '<?php echo base_url("/replenishment_time");?>',
                 data : {'number':num,'pair':'<?php echo $output['symbol']?>'},
                 headers: {'X-Requested-With': 'XMLHttpRequest'},
                 success : function(msg)
                 {
                   if(msg)
                   {
                   $('#ex_demo').html(msg);
                   }
                 }
                 });
         
                  $('#subposition').css('display', 'block');
         
         }
         else
         {
         $('#ex_demo').html("");
         $('#subposition').css('display', 'none');
         }
         });
         
         
         $('#replenishment_time').keyup(function(){
         
         var num = $('#replenishment_time').val();
         
         if(num>0)
         {
                 $.ajax({
                 type: 'post',
                 dataType:'html',
                 url : '<?php echo base_url("/replenishment_time1");?>',
                 data : {'number1':num,'pair':'<?php echo $output['symbol']?>'},
                 headers: {'X-Requested-With': 'XMLHttpRequest'},
                 success : function(msg)
                 {
                   if(msg)
                   {
                   $('#ex_demo1').html(msg);
                   }
                 }
                 });
         
         }
         });
         
         $('#replenishment_time').keyup(function(){
         var num = $('#replenishment_time').val();
         if(num>0)
         {
                 $.ajax({
                 type: 'post',
                 dataType:'html',
                 url : '<?php echo base_url("/replenishment_time2");?>',
                 data : {'number2':num,'pair':'<?php echo $output['symbol']?>'},
                 headers: {'X-Requested-With': 'XMLHttpRequest'},
                 success : function(msg)
                 {
                   if(msg)
                   {
                   $('#ex_demo2').html(msg);
                   }
                 }
                 });
         
         }
         });
         
         $('#submit_button').click(function(){
         var first_buy_amount =  $("[name=first_buy_amount]").val();
         var whole_profit_ratio =  $("[name=whole_profit_ratio]").val();
         var whole_profit_callback =  $("[name=whole_profit_callback]").val();
         var sub_position_callback = $("[name=sub_position_callback]").val();
         var limit = $("[name=replenishment_time]").val();
         var buyin_callback =  $("[name=buyin_callback]").val();
         var flag = 1;
         if(!(whole_profit_ratio > 0)){
             $.notify(' <i class="fas fa-exclamation-triangle"></i> Please enter a value greater than 1', 'danger');
             flag = 0;
         }
           if(limit >= 5){
           var j=0;
           var i;
              for(i=5; limit >= i; i++){
               var var_name = "rep_time"+j;
               if($("[name="+var_name+"]").val() < sub_position_callback && flag == 1){
               $.notify(' <i class="fas fa-exclamation-triangle"></i> Subbin Take profit ratio will be greater than subbin take profit callback', 'danger');
               flag = 0;
               }
               j++;
              }
           }
         
         
         if(whole_profit_ratio < whole_profit_callback && flag == 1){
             $.notify(' <i class="fas fa-exclamation-triangle"></i> Take profit ratio will be greater than take profit callback', 'danger');
             flag = 0;
           }
           if(!(buyin_callback >= 0) && flag == 1){
             $.notify(' <i class="fas fa-exclamation-triangle"></i> Please enter a positive value', 'danger');
             flag = 0;
           }
           if(!(first_buy_amount >= 11 && flag == 1)){
             $.notify(' <i class="fas fa-exclamation-triangle"></i> Minimum first buy amount is 11 USDT', 'danger');
             flag = 0;
         }
         
         var empty = true;
         
         $('#exampleModal1 input[type="text"]').each(function() {
         if($(this).val() == ''){
         $flag = 0;
         empty = false;
         }
         });
         
         if(empty == false){
         $.notify(' <i class="fas fa-exclamation-triangle"></i> Some fields are empty', 'danger');
         }
         
           if(flag == 1 && empty == true){
             $('#exampleModal1').submit();
             $.notify('<i class="fas fa-check"></i>  Set Successfully', 'success');
           }
             
         });  
         
         $('#subposition').css('display', 'none');
         
           var num = $('#replenishment_time').val();
         
         if(num >= 5)
           {
             $('#subposition').css('display', 'block');
           }
           else
           {
             $('#subposition').css('display', 'none');
           }
           $('#sure_price').click(function(){
         var uusersid = <?php echo $uusersid ? $uusersid : '';?>;
         var first_preset_drop = $('#first_preset_price').val();
         var flag=0;
         $("#first_err").html("");
         
         if(first_preset_drop=='')
         {
         $("#first_err").html("Please Enter Amount");
         flag=1;
         }
         else
         {
          var reg= /^[0-9.]+$/;
          if(!reg.test(first_preset_drop))
          {
            $("#first_err").html("Please Enter Only Numbers");
            flag=1;
          }
         
         }
         if(flag!='1')
         {
         
         var pair = '<?php echo $output['symbol'];?>';
         $.ajax({
         type: 'post',
         url : '<?php echo base_url("/dashboard/first_preset_drop");?>',
         data : {'first_preset_drop':first_preset_drop,'uusersid':uusersid,'pair':'<?php echo $output['symbol'];?>'},
         headers: {'X-Requested-With': 'XMLHttpRequest'},
         success : function(msg)
         {
         if(msg)
         {
            $.notify('<i class="fas fa-check-circle"></i> Presend Amount Successfully Updated', 'success');
            window.location.reload();
         }
         }
         });
         }
         });
         
         
         $('#sure_limit').click(function(){
         var uusersid = $('#uusersid').val();
         var oneshot_limit = $('#oneshot_limit').val();
         $.ajax({
         type: 'post',
         url : '<?php echo base_url("/dashboard/oneshot_limit");?>',
         data : {'oneshot_limit':oneshot_limit,'uusersid':uusersid,'pair':'<?php echo $output['symbol'];?>'},
         headers: {'X-Requested-With': 'XMLHttpRequest'},
         success : function(msg)
         {
         if(msg)
         {
          window.location.reload();
         }
         }
         });
         });
      </script>
      <script type="text/javascript">
         $(document).ready(function() {
             
                $('#example1').DataTable();
               
           <?php if(!empty($activation) && !empty($id)) 
           { 
               ?>
           
           var trade_update = async function(){
         
            var  live_price = $('.all_list_price').html();
             $.ajax({
               type: 'post',
               url : '<?php echo base_url('trade_update');?>',
               data : {pair:'<?php echo $id; ?>','uusersid': '<?php echo $this->session->get('uusersid');?>','exchange': '1','live_price': live_price},
               success : function(msg) { 
         console.log(msg);
                 var myArray = JSON.parse(msg);
         
                 var total_amount = myArray['trade_position_amount'];
                 var trade_position_quantity = myArray['trade_position_quantity'];
                 var avg_position =  myArray['trade_avg_position'];
                 var calls =  myArray['trade_number_of_call'];
                 var rate_percentage =  myArray['trade_rate_percentage'];
                 var live_price =  myArray['live_price'];
                 var status =  myArray['status'];
                 var take_profit_trigger =  myArray['take_profit_trigger'];
                 var down_price =  myArray['down_price'];
                 var current_position_amount =  myArray['current_position_amount'];
                 var trade_estimate_price =  myArray['trade_estimate_price'];
                 trade_details(total_amount,avg_position,calls,rate_percentage,live_price,status,take_profit_trigger,down_price,current_position_amount,trade_estimate_price,trade_position_quantity); 
               }
             });
           };
           var interval = setInterval(trade_update, 6000); 
         
         
             
         <?php } ?>
         
         
         
         
         
         
           function trade_details(total_amount,avg_position,calls,rate_percentage,live_price,status,take_profit_trigger,down_price,current_position_amount,trade_estimate_price,trade_position_quantity){
             $('#trade_rate_percentage12').text(rate_percentage+" %");
             $('#trade_position_amount').text(total_amount);
             $('#trade_position_amount1').text(total_amount);
             $('#trade_position_amount2').text(total_amount);
             $('.trade_position_amount').text(total_amount);
             $('#trade_avg_position').text(avg_position);
             $('#trade_avg_position1').text(avg_position);  
             $('.trade_avg_position').text(avg_position);
             $('#trade_number_of_call').text(calls);
             $('#trade_rate_percentage1').text(rate_percentage);
             $('#trade_rate_percentage2').text(rate_percentage+" %");
             $('#take_profit_trigger').text(take_profit_trigger);
             $('#trade_estimate_price').text(trade_estimate_price);
             $('#trade_estimate_price1').text(trade_estimate_price);
             $('#trade_position_quantity').text(trade_position_quantity);
             $('.trade_position_quantity').text(trade_position_quantity);
             $('#down_price').text(down_price);
             $('.all_list_price').text(live_price);
             $('.current_position_amount').text(current_position_amount+" USDT");
             if(status == 1)
             $('#margin_status').text("Waiting For Trigger");
             else if(status == "")
             $('#margin_status').text(" ");
             else
             $('#margin_status').text("Stop Margin Call");
           }
         });
      </script>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10.6.0/dist/sweetalert2.min.css">
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.6.0/dist/sweetalert2.all.min.js"></script>
      <script type="text/javascript">
         $(document).ready(function(){
         
           if($('#Ostartegy').is(':hidden')){
             $('#oneshot_limit_section').css('display','inline-block');
           }
           
           
         
         
         $('#Cstartegy_Name').on('click',function(){
         
         
         
               Swal.fire({
                         title: 'Order Mode',
                         text: "Are You sure you want to change it single?",
                         icon: 'warning',
                         showCancelButton: true,
                         confirmButtonColor: '#3085d6',
                         cancelButtonColor: '#d33',
                         confirmButtonText: 'Yes, confirm it!'
                             }).then((result) => {
                                 // Check if user confirmed
                                 if (result.isConfirmed) {
                                     // If confirmed, show a success message
         
                                     var num="Cycle Strategy";
                                     var pairs = "<?php if(!empty($pair->trade_status)) { echo $pair->trade_status;};?>";
                                     var pair_id  = "<?php echo $output['symbol']?>";
         
                                     $.ajax({
                                     type: 'post',
                                     dataType:'html',
                                     url : '<?php echo base_url("/Cstartegy");?>',
                                     data : {'number2':num,'pair':pairs,'pair_id':pair_id,'url':'<?php echo $uri->getSegment(2); ?>'},
                                     headers: {'X-Requested-With': 'XMLHttpRequest'},
                                     success : function(msg)
                                     {
                                     if(msg)
                                     {
                                       $.notify('<i class="fas fa-check"></i>  Trade Mode Single changed Successfully', 'success');
                                       $('#Cstartegy').css('display','none');
                                         $('#Ostartegy').css('display','inline-block');
                                         $('#oneshot_limit_section').css('display','none');
                                         var a = $('#Ostartegy_Name').text();
                                         $('#crypto-strategy').html(a);
                                     }
                                     }
                                     });
                         }
                     });  
         
         
         });
         
         
         $('#Cstartegy').on('click',function(){
         
         
         
               Swal.fire({
                         title: 'Order Mode',
                         text: "Are You sure you want to change it single?",
                         icon: 'warning',
                         showCancelButton: true,
                         confirmButtonColor: '#3085d6',
                         cancelButtonColor: '#d33',
                         confirmButtonText: 'Yes, confirm it!'
                             }).then((result) => {
                                 // Check if user confirmed
                                 if (result.isConfirmed) {
                                     // If confirmed, show a success message
         
                                     var num="Cycle Strategy";
                                     var pairs = "<?php if(!empty($pair->trade_status)) { echo $pair->trade_status;};?>";
                                     var pair_id  = "<?php echo $output['symbol']?>";
         
                                     $.ajax({
                                     type: 'post',
                                     dataType:'html',
                                     url : '<?php echo base_url("/Cstartegy");?>',
                                     data : {'number2':num,'pair':pairs,'pair_id':pair_id,'url':'<?php echo $uri->getSegment(2); ?>'},
                                     headers: {'X-Requested-With': 'XMLHttpRequest'},
                                     success : function(msg)
                                     {
                                     if(msg)
                                     {
                                       $.notify('<i class="fas fa-check"></i>  Trade Mode Single changed Successfully', 'success');
                                       $('#Cstartegy').css('display','none');
                                         $('#Ostartegy').css('display','inline-block');
                                         $('#oneshot_limit_section').css('display','none');
                                         var a = $('#Ostartegy_Name').text();
                                         $('#crypto-strategy').html(a);
                                     }
                                     }
                                     });
                         }
                     });  
         
         
         });
         
         
         
         $('#Margin_Clk').on('click',function()
         {
         
           
           var pairs = "<?php if(!empty($pair->trade_status)) { echo $pair->trade_status;};?>";
         
          if(pairs)
          {
         
           var mci = $('.smc').html();
         
          if(mci == "Stop margin call")
          {
              $('#mc').html("Initiate margin call");
              var value = 1;
          }
          if(mci != "Stop margin call")
          {
             $('#mc').html("Stop margin call");
             var value = 0;
          }
         
         
         var pairs  = "<?php echo $output['symbol']?>";
         
         $.ajax({
         type: 'post',
         dataType:'html',
         url : '<?php echo base_url("/call_margin");?>',
         data : {'margin_id':value,'pair':pairs,'url':'<?php echo $uri->getSegment(2); ?>'},
         headers: {'X-Requested-With': 'XMLHttpRequest'},
         success : function(msg)
         {
         if(msg)
         {
            $.notify('<i class="fas fa-check-circle"></i>  Set Successfully', 'success');
         }
         }
         });
         
          if(value != 1)
               $('#margin_status').text('Waiting For Trigger');
          else
               $('#margin_status').text("Stop Margin Call");  
         
         }
         else
         {
         $.notify('<i class="fas fa-times-circle"></i> No position temporarily', 'danger');
         }
         });
         
         $('#sure_mode').on('click',function(){
         
         var num = $('input[name="strategy_mode"]:checked').val();
         
         var pairs = "<?php if(!empty($pair->trade_status)) { echo $pair->trade_status;};?>";
         var pair_id  = "<?php echo $output['symbol']?>";
         
         $.ajax({
         type: 'post',
         dataType:'html',
         url : '<?php echo base_url("/Cstartegy_mode");?>',
         data : {'number2':num,'pair':pairs,'pair_id':pair_id,'url':'<?php echo $uri->getSegment(2); ?>'},
         headers: {'X-Requested-With': 'XMLHttpRequest'},
         success : function(msg)
         {
           console.log(msg);
         if(msg == 1)
         {
           $.notify('<i class="fas fa-check"></i>  Set Successfully', 'success');
            window.location.reload();
         }else if(msg == 0){
           $.notify(' <i class="fas fa-exclamation-triangle"></i> &nbsp;&nbsp; Strictly restricted after 5th trade', 'danger');
         }
         }
         });
         
         });
         
         
         $('#Ostartegy').on('click',function(){
         
         
         
         
           Swal.fire({
                         title: 'Order Mode',
                         text: "Are You sure you want to change it Cyle?",
                         icon: 'warning',
                         showCancelButton: true,
                         confirmButtonColor: '#3085d6',
                         cancelButtonColor: '#d33',
                         confirmButtonText: 'Yes, confirm it!'
                             }).then((result) => {
                                 // Check if user confirmed
                                 if (result.isConfirmed) {
                                     // If confirmed, show a success message
         
                                     var num="Ostartegy";
         
                                 var pairs = "<?php if(!empty($pair->trade_status)) { echo $pair->trade_status;};?>";
                                 var pair_id  = "<?php echo $output['symbol']?>";
         
                                 $.ajax({
                                 type: 'post',
                                 dataType:'html',
                                 url : '<?php echo base_url("/Ostartegy");?>',
                                 data : {'number2':num,'pair':pairs,'pair_id':pair_id,'url':'<?php echo $uri->getSegment(2); ?>'},
                                 headers: {'X-Requested-With': 'XMLHttpRequest'},
                                 success : function(msg)
                                 {
                                 if(msg)
                                 {
                                   $.notify('<i class="fas fa-check"></i>  Trade Mode Cyle Startegy Setup Successfully', 'success');
                                   $('#Cstartegy').css('display','inline-block');
                                     $('#Ostartegy').css('display','none');
                                     $('#oneshot_limit_section').css('display','inline-block');
                                     var b = $('#Cstartegy_Name').text();
                                     $('#crypto-strategy').html(b);
                                 }
                                 }
                                 });
                         }
                     });  
          });
           
         
           $('#sellModels').on('click',function(){         
               $.notify(' <i class="fas fa-exclamation-triangle"></i>  No position temporarily ', 'danger');
           });
           $('#buyModels').on('click',function(){         
               $.notify(' <i class="fas fa-exclamation-triangle"></i> Please start the strategy first', 'danger');
           });
         
         
         
             <?php $uri = service('uri');?>
         
         $('#pause_button').on('click',function()
         {
           var uusersid='<?php echo $this->session->get('uusersid');?>';
         
           $.ajax({
             'method': 'POST',
             'url': '<?php echo base_url("/tradingprocess1");?>',
              data:{'id':"<?php echo $id;?>",'uusersid':uusersid,'uri':"<?php echo $uri->getSegment(2);?>" },
             success:function(msg)
             {
               $.notify(' <i class="fas fa-check-circle"></i>  Trade paused successfully', 'success'); 
                window.location.reload();
             }
           })
         });
         
         $('#stop_button').on('click',function()
         {
              var pair_id="<?php if(!empty($pair)){ echo $pair->id;}?>";
             var uusersid='<?php echo $this->session->get('uusersid');?>';
             var exchange='<?php echo $this->session->get('exchange');?>';
           
             Swal.fire({
                                 title: 'Trade close',
                                 text: "Are You sure you want to Close current trade!. Please once verify with live price higher or not for negivative profit deduction purpose",
                                 icon: 'warning',
                                 showCancelButton: true,
                                 confirmButtonColor: '#3085d6',
                                 cancelButtonColor: '#d33',
                                 confirmButtonText: 'Yes, confirm it!'
                             }).then((result) => {
                                 // Check if user confirmed
                                 if (result.isConfirmed) {
                       
                           $.ajax({
                             'method': 'POST',
                             'url': '<?php echo base_url("/tradingprocess2");?>',
                              data:{'id':"<?php echo $id;?>",'uusersid':uusersid,'uri':"<?php echo $uri->getSegment(2);?>",'pair':pair_id,'uusersid':"<?php echo $this->session->get('uusersid');?>",'exchange': exchange },
                             success:function(msg)
                             {
                                  var msg=msg.split('&&');
                                    if(msg[0]=='error')
                                    {
                                        $.notify(' <i class="fas fa-exclamation-triangle"></i> &nbsp;&nbsp'+msg[1], 'danger');   
                                    }
                                    else
                                    {
                                           /*$.notify(' <i class="fas fa-check"></i>&nbsp;&nbsp; Please wait trade progressing... ', 'success');
                                           var orderid=msg[1];
                                           var order=msg[2];
                                           var trade_id=msg[3];
                                           //order_close(orderid,order,trade_id,exchange);
                                           
                                           setTimeout(order_close(orderid,order,trade_id,exchange), 5000);*/
                                           $.notify(' <i class="fas fa-check-circle"></i>  Trade closed successfully', 'success'); 
                                           //if(exchange=='5')
                                           window.location.reload();
                                        
                                    }
                               
                             }
                           })
                   
                     }
             });  
         });
         
          
         
         var margin_call = '<?php if(!empty($user->margin_call)){ echo $user->margin_call;}?>';
          
         if(margin_call==1)
          {
               $('#mc').html("Stop margin call");
          }
          else
          {
             $('#mc').html("Initiate margin call");
          }
         
         var output_symbol = '<?php echo $id;?>';
         var uusersid='<?php echo $this->session->get('uusersid');?>';
         var exchange='<?php echo $this->session->get('exchange');?>';
         
         setInterval(function(){
         $.ajax({
         type:'post',
         method: 'POST',
         url: '<?php echo base_url("/autoLoadPrice");?>',
         dataType:"html",
         data:{
         'symbol':output_symbol,
         'uusersid':uusersid,
         'exchange':exchange
         },
         success: function (data) {
         $('.all_list_price').html(data);
         $("#all_list_price").val(data);
         }
         });
         
         }, 4000);
         
         var find_mode = $('#find_mode').val();
          var mode = $('#modes').val();
          if(mode==1)
          {
           mode =  "Whole warehouse";
          }
           if(mode==2)
          {
           mode =  "Sub-bin";
          }
           if(mode==3)
          {
           mode =  "Sub-bin Realtime";
          }
         
          if(find_mode=="Single strategy" || find_mode=='Single')
          {
             $('#crypto-strategy').html("Single");
             $('#crypto-strategy_mode').html(mode);
             $('#Cstartegy').css('display','none');
             $('#Ostartegy').css('display','inline-block');
             $('#oneshot_limit_section').css('display','none');
          }
          else
          {
             $('#crypto-strategy').html(find_mode);
             $('#crypto-strategy_mode').html(mode);
             $('#Cstartegy').css('display','inline-block');
             $('#Ostartegy').css('display','none');
             $('#oneshot_limit_section').css('display','inline-block');
         
          }
         
         
           $('.main-table table').dataTable({
               "language": { search: "" },
               "Info": false
         });
         
         
         function doalert(obj) {
             $('#Cstartegy').css('display','none');
             $('#Ostartegy').css('display','inline-block');
             $('#oneshot_limit_section').css('display','none');
             var a = $('#Ostartegy_Name').text();
             $('#crypto-strategy').html(a);
         }
         
          function Ooalert(obj) {
             $('#Cstartegy').css('display','inline-block');
             $('#Ostartegy').css('display','none');
             $('#oneshot_limit_section').css('display','inline-block');
             var b = $('#Cstartegy_Name').text();
             $('#crypto-strategy').html(b);
         }
         });
         
         
      </script>
      <script type="text/javascript">
         $('#start_button_block').on('click',function(){  
             $.notify(' <i class="fas fa-exclamation-triangle"></i>  Please activate the robot first ', 'danger');
           });
         
           $('#start_button').on('click',function(){ 
             var check_strategy = '<?php echo $check_strategy ? 1 : 0;?>';
             var avaialabe_fuel_fee     =  '<?php echo $buy_bal ? $buy_bal : 0;?>';
             var fuel_fee               = '<?php echo $tradSet->min_fuel_fee ? $tradSet->min_fuel_fee : 0 ;?>';
             
             var fuel_gas               = '<?php echo $tradSet->min_fuel ? $tradSet->min_fuel : 10 ;?>';
             var activate               = '<?php echo $activation ? $activation : 0; ?>';
             var usdt_balance = '<?php echo $usdt_balance ? $usdt_balance : 0 ;?>';
          
             var uusersid='<?php echo $this->session->get('uusersid');?>';
             var exchange ='<?php echo $this->session->get('exchange');?>';
             
             //var calculated_fuel=parseFloat(11) * parseFloat(fuel_fee)/100;
             var first_buy_amount='<?php echo $first_buy_amount ? $first_buy_amount : 0 ;?>';
         
             var pair_id  = "<?php echo $id;?>";
            // console.log('available fuel '+avaialabe_fuel_fee.replace(',',''));
              //console.log('fuel fee '+fuel_gas);
              
            if(check_strategy == '1')
            
             {
            if(activate)
            {
         
               if(parseFloat(avaialabe_fuel_fee.replace(',',''))>=parseFloat(fuel_gas) && parseFloat(usdt_balance) >= parseFloat(first_buy_amount))
               {
                  if(<?php echo $bind_api ? $bind_api : 0;?>)
                  {
                            Swal.fire({
                                  title: 'Are you sure?',
                                  text: "Here is your selected Pair :"+pair_id,
                                  icon: 'warning',
                                  showCancelButton: true,
                                  confirmButtonColor: '#3085d6',
                                  cancelButtonColor: '#d33',
                                  confirmButtonText: 'Yes, confirm it!'
                              }).then((result) => {
                                  // Check if user confirmed
                                  if (result.isConfirmed) {
                                      // If confirmed, show a success message
                  
                                      $.notify(' <i class="fas fa-check-circle"></i>  Please wait trade requested....', 'success'); 
                                $.ajax({
                                  'method': 'POST',
                                  'url': '<?php echo base_url("/tradingprocess");?>',
                                  data:{'id':"<?php echo $id;?>",'uusersid':uusersid,'uri':"<?php echo $uri->getSegment(2);?>",'exchange':exchange,'pair':"<?php echo $output['symbol']?>" },
                                  success:function(msg)
                                  {
                                      if(exchange=='1')
                                       {
                                           
                                            if(msg=='1' || msg=='')
                                            {
                                                $.notify(' <i class="fas fa-check-circle"></i>  Trade started successfully', 'success'); 
                                                window.location.reload();
                                            }
                                            else
                                            {
                                                var msg=msg.trim();
                                                if(msg=='2')
                                                {
                                                    $.notify(' <i class="fas fa-exclamation-triangle"></i> &nbsp;&nbsp: Please check API Balance..', 'danger'); 
                                                    
                                                }
                                                else
                                                {    if(msg!='')
                                                     {
                                                        $.notify(' <i class="fas fa-exclamation-triangle"></i> &nbsp;&nbsp'+msg, 'danger');    
                                                     }
                                                }
                                                
                                            }
                                  
                                        }
                                       else if(exchange=='5')
                                       {
                                               
                                          
                                          var msg=msg.split("&&");
                                        
                                          if(msg[0]=='success')
                                          {
                                                $.notify(' <i class="fas fa-check-circle"></i>  Trade Placement Progressing', 'success'); 
                                                var orderid=msg[1];
                                                var trade_id=msg[2];
                                                var price = msg[3];
                                              //  setTimeout(bybit_order(orderid,trade_id,price), 5000);
                                                //window.location.reload();
                                                window.location="<?php echo base_url();?>/tradedetails/<?php echo $id;?>";
                                           }
                                      
                                          else
                                          {
                                            $.notify(' <i class="fas fa-exclamation-triangle"></i> &nbsp;&nbsp'+msg[1], 'danger');   
                                            //window.location.reload();
                                          }
                                          
                                       }
                                     
                              }
                            })
                          }
                       });     
          
                    
                      }
                      else
                      {
                        $.notify(' <i class="fas fa-exclamation-triangle"></i>  Please bind your api to start the trade. ', 'danger');
                      }
         
                 }
                 else
                 {
                     
                      if(parseFloat(fuel_gas)> parseFloat(avaialabe_fuel_fee.replace(',','')))
                      {
                         // $.notify(' <i class="fas fa-exclamation-triangle"></i>  Please recharge Gas wallet Min Needed for :\n'+fuel_gas+' USDT', 'danger');
                         
                         
                          Swal.fire({
                            title: "Gas wallet fuel Low",
                            text: "Please recharge Gas wallet Min Needed for :\n"+fuel_gas+" USDT",
                            icon: "question"
                          });
                      }
                      else
                      {
                      
                        //$.notify(' <i class="fas fa-exclamation-triangle"></i>  Please recharge binance usdt balance. ', 'danger');
                        
                        Swal.fire({
                            title: "API USDT Balance Low",
                            text: "Please recharge API wallet Min Needed for first order :\n"+first_buy_amount+" USDT",
                            icon: "question"
                          });
                        
                      }
                      
                 }
          }
           else
           {
              $.notify(' <i class="fas fa-exclamation-triangle"></i>  Please activate the robot first ', 'danger');
           }
           }
           else
           {
                $.notify(' <i class="fas fa-exclamation-triangle"></i>  Please set the strategy first ', 'danger');
           }
            
           });
         
          function bybit_order(orderid,tradeid,price)
          {
         
            var uusersid='<?php echo $this->session->get('uusersid');?>';
            var exchange='<?php echo $this->session->get('exchange');?>';
            $.ajax({
                  'method': 'POST',
                  'url': '<?php echo base_url("/bybit_order");?>',
                  data:{'orderid':orderid,'tradeid':tradeid,'price':price,'uusersid':uusersid,'exchange':exchange },
                  success:function(msg)
                  {
                    $.notify(' <i class="fas fa-check-circle"></i>  Trade Placed successfully', 'success'); 
                  window.location.reload();
                  }
                })
         
         
          }
           
           
           
          $('#resume_button').on('click',function()
          { 
             var avaialabe_fuel_fee     =  '<?php echo $buy_bal ? $buy_bal : 0;?>';
             var fuel_fee               = '<?php echo $tradSet->min_fuel_fee ? $tradSet->min_fuel_fee : 0 ;?>';
             var activate               = '<?php echo $activation ? $activation : 0; ?>';
             var usdt_balance = '<?php echo $usdt_balance ? $usdt_balance : 0 ;?>';
             var uusersid='<?php echo $this->session->get('uusersid');?>';
             var exchange ='<?php echo $this->session->get('exchange');?>';
             
             var first_buy_amount='<?php echo $first_buy_amount ? $first_buy_amount : 0 ;?>'
         
             var pair_id  = "<?php echo $output['symbol']?>";
         
            if(activate)
            {
         
              
         
                if(<?php echo $bind_api ? $bind_api : 0;?>)
                {
         
                $.ajax({
                  'method': 'POST',
                  'url': '<?php echo base_url("/traderesume");?>',
                  data:{'id':"<?php echo $id;?>",'uusersid':uusersid,'exchange':exchange,'uri':"<?php echo $uri->getSegment(2);?>",'pair':"<?php echo $output['symbol']?>" },
                  success:function(msg)
                  {
                      $.notify(' <i class="fas fa-check-circle"></i>  Trade started successfully', 'success'); 
                      window.location.reload();
                  }
                })
                 
              }
              else
              {
                $.notify(' <i class="fas fa-exclamation-triangle"></i>  Please bind your api to start the trade. ', 'danger');
              }
         
           }
           else
           {
              $.notify(' <i class="fas fa-exclamation-triangle"></i>  Please activate the robot first ', 'danger');
           } 
            
           });
         
          $('#logModal').on('click',function(){
         
          var num="Ostartegy";
          var pairs = "<?php if(!empty($pair->trade_status)) { echo $pair->trade_status;};?>";
          var pair_id  = "<?php echo $output['symbol']?>";
         
          $.ajax({
          type: 'post',
          dataType:'html',
          url : '<?php echo base_url("/logModal");?>',
          data : {'number2':num,'pair':pairs,'pair_id':pair_id,'url':'<?php echo $uri->getSegment(2); ?>'},
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success : function(msg)
          {
          if(msg)
          {
          $('#logModals').html(msg)
          }
          }
          });
         
          });
         
          $('#buy').on('click',function()
          {
            
            $('#pur_err').html('');
            if($('#limit_clk').is(':disabled'))
              var val= "";
            else
              var val = $('#limit_clk').val();
            var num=  $('#code1').val();
         
            var id=$('#pair').val();
            var uusersid = <?php echo $uusersid ? $uusersid : 0;?>;
            var exchange = '<?php echo $this->session->get('exchange');?>';
         
            var trade_process_id = '<?php if(!empty($pair)) { echo $pair->id;} else { echo "0";} ?>';
             
            if(num=='')
            {
              $('#pur_err').html('Please Enter Purchase Amount');
            }
            else
            {
                $.ajax({
                'method': 'POST',
                'url': '<?php echo base_url("/tradingbuy");?>',
                data:{'val':val, 'num':num, 'id':id ,'uusersid':uusersid,'trade_process_id':trade_process_id,'exchange':exchange},
                
         
                success:function(msg)
                {
                  // console.log(msg);
                  if(msg == 'failure')
                    $.notify(' <i class="fas fa-exclamation-triangle"></i> &nbsp;&nbsp; Buy process failed. Please try again... ', 'danger');
                  else if(msg == 'fail')
                    $.notify(' <i class="fas fa-exclamation-triangle"></i> &nbsp;&nbsp; Trigger buy order already exist... ', 'danger');
                  else
                  window.location.reload();
                },
                error: function (request, message, error) {
                let  err =  handleException(request, message, error);
                    if(err)
                      $.notify(' <i class="fas fa-exclamation-triangle"></i>&nbsp;&nbsp; Buy process failed. Please try again... ', 'danger');
                }
              })
            }
          });
         
         
         
         
          function cancel(id)
          {
            $.ajax({
              'method': 'POST',
              'url': '<?php echo base_url("/cancel_order");?>',
               data:{'id':id},
              success:function(msg)
              {
                console.log(msg);
                 window.location.reload();
              }
            })
          }
         
         
         
         
         
         
         function handleException(request, message, error) {
          var msg = "";
          msg += "Code: " + request.status + "\n";
          msg += "Text: " + request.statusText + "\n";
          if (request.responseJSON != null) {
              msg += "Message: " +
              request.responseJSON.Message + "\n";
          }
          return msg;
         }
         
         
         $('#limit_clk').on('change',function(){
          if($('#code1').val() == "" || $('#code1').val() == 0){
            var avg_price = $('#trade_avg_position').html();
            var live_price = $('#limit_clk').val();
            live_price.replace(',','');
            var ror = 0.00;
         
          console.log("avg price " + avg_price);
          console.log("live price "+live_price);
         
          if(avg_price > live_price){
             ror1 = avg_price - live_price ;
             ror2 = ror1 / avg_price ;
             ror = ror2 * 100;
             ror = Number((ror).toFixed(2));
             ror = '-'+ror;
          }
          else if(avg_price < live_price) {
             ror1 = live_price - avg_price ;
             ror2 = ror1 / live_price ;
             ror = ror2 * 100;
             ror = Number((ror).toFixed(2));
              }
          $('.all_list_price1').html($('#trade_avg_position1').html()+" USDT");
          $('#trade_estimate_price2').html(ror+"%");
          }else{
            var prev_amount = $('#trade_position_amount').html();
          var prev_quantity = $('#trade_position_quantity').html();
          var amount = $('#code1').val();
          if($('#limit_clk').is(':disabled')){
          var live_price = $('.all_list_price').html();
          }else{
          if($('#limit_clk').val() == "" || $('#limit_clk').val() == 0)
          var live_price = $('.all_list_price').html();
          else
          var live_price = $('#limit_clk').val();
          }
          live_price = parseFloat(live_price.replace(/,/g, ''));
         
          console.log("prev amount " +prev_amount);
          console.log("prev quantity " +prev_quantity);
          console.log("amount " +amount);
          console.log("live price " +live_price);
         
          var quantity = amount / live_price ;
          var total_usdt = +prev_amount + +amount;
          var total_quantity = +prev_quantity + +quantity;
          console.log("quantity "+quantity);
          console.log("total usdt "+total_usdt);
          console.log("total quantity "+total_quantity);
          var avg_price = total_usdt / total_quantity;
          avg_price = Number((avg_price).toFixed(5));
         
         
          var ror = 0.00;
         
          console.log("avg price " + avg_price);
          console.log("live price "+live_price);
         
          if(avg_price > live_price){
             ror1 = avg_price - live_price ;
             ror2 = ror1 / avg_price ;
             ror = ror2 * 100;
             ror = Number((ror).toFixed(2));
             ror = '-'+ror;
          }
          else if(avg_price < live_price) {
             ror1 = live_price - avg_price ;
             ror2 = ror1 / live_price ;
             ror = ror2 * 100;
             ror = Number((ror).toFixed(2));
              }
         
          console.log(ror);
          $('.all_list_price1').html(avg_price+" USDT");
          $('#trade_estimate_price2').html(ror+"%");
         
          }
         
          });
         
          $('#code1').on('change',function(){
          var prev_amount = $('#trade_position_amount').html();
          var prev_quantity = $('#trade_position_quantity').html();
          var amount = $('#code1').val();
          if($('#limit_clk').is(':disabled')){
          var live_price = $('.all_list_price').html();
          }else{
          if($('#limit_clk').val() == "" || $('#limit_clk').val() == 0)
          var live_price = $('.all_list_price').html();
          else
          var live_price = $('#limit_clk').val();
          }
         
         
         live_price = parseFloat(live_price.replace(/,/g, ''));
         
          console.log("prev amount " +prev_amount);
          console.log("prev quantity " +prev_quantity);
          console.log("amount " +amount);
          console.log("live price " +live_price);
         
          var quantity = amount / live_price ;
          var total_usdt = +prev_amount + +amount;
          var total_quantity = +prev_quantity + +quantity;
          console.log("quantity "+quantity);
          console.log("total usdt "+total_usdt);
          console.log("total quantity "+total_quantity);
          var avg_price = total_usdt / total_quantity;
          avg_price = Number((avg_price).toFixed(5));
         
         
          var ror = 0.00;
         
          console.log("avg price " + avg_price);
          console.log("live price "+live_price);
         
          if(avg_price > live_price){
             ror1 = avg_price - live_price ;
             ror2 = ror1 / avg_price ;
             ror = ror2 * 100;
             ror = Number((ror).toFixed(2));
             ror = '-'+ror;
          }
          else if(avg_price < live_price) {
             ror1 = live_price - avg_price ;
             ror2 = ror1 / live_price ;
             ror = ror2 * 100;
             ror = Number((ror).toFixed(2));
          }
          console.log(ror);
          $('.all_list_price1').html(avg_price+" USDT");
          $('#trade_estimate_price2').html(ror+"%");
         });
         $(document).ready(function(){
          var num = $('#replenishment_time').val();
          $.ajax({
          type: 'post',
          dataType:'html',
          url : '<?php echo base_url("/replenishment_time1");?>',
          data : {'number1':num,'pair':'<?php echo $output['symbol']?>'},
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success : function(msg)
          {
          if(msg)
          {
          $('#ex_demo1').html(msg);
          }
          }
          });
         
          $.ajax({
          type: 'post',
          dataType:'html',
          url : '<?php echo base_url("/replenishment_time2");?>',
          data : {'number2':num,'pair':'<?php echo $output['symbol']?>'},
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success : function(msg)
          {
          if(msg)
          {
          $('#ex_demo2').html(msg);
          }
          }
          });
         
          $.ajax({
          type: 'post',
          dataType:'html',
          url : '<?php echo base_url("/replenishment_time");?>',
          data : {'number':num,'pair':'<?php echo $output['symbol']?>'},
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success : function(msg)
          {
          if(msg)
          {
          $('#ex_demo').html(msg);
          }
          }
          });
         });
      </script>
   </body>
</html>
