<!doctype html>
<html lang="en" translate="no" class="w-[640px] mx-auto md:w-full">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Trade Request</title>
      <?php echo view('user/layout/head');?>
      <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/styles/web_style/css/jquery.dataTables.min.css" />
      <style>
      table.dataTable thead { 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%); color:#fff; 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;
      }
      .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;
}

   </style>
      <?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://revotechbot.com/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' => 'linear', '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];
    
    
    $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;
}
        
        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'];


}

  
?>

<style>
.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;
}
td{ padding:10px !important;font-size:13px;font-weight:bold;}
.label {font-size:13px;margin-top:10px;}
.section {padding:10px;}
.value { color:orange;}
      </style>
   </head>
   <body class="reg-overflow">
      <section class="dash-banner-bg banner-bg">
         <div class="container">
         <!---header start---->
         <?php echo view('user/layout/header');?>
         <!---header end---->
         <!---banner start---->
         <div class="row">
            <div class="col-12">
               <div class="dash-wrap">
                  <div class="title text-center py-2">
                     <h2 class="text-primary">Trade 
                      <a href="<?php echo base_url();?>/trades/<?php echo $id;?>"><span style="float:right;margin-right:20px;color:orange;"><i class="fa fa-calendar-days" title="Trading Records"></i></span> </a></h2>
                     
                  </div>
                  
                  <?php 
                   $base = substr($id, 0, -4);
                   $pair_disp=$base.'/USDT';
                   
                   
                   
                   
                   if(!empty($pair->strategy_mode))
                    {
                      $strategy_mode_disp=$pair->strategy_mode;
                      $risk_mode=$trade_process->risk_type;
                    }
                    else
                    {
                      $strategy_mode_disp=$user->strategy_mode;
                      $risk_mode=$user->risk_type;
                    }
                   
                
                     if($strategy_mode_disp=='1')
                     {
                      $s_mode =  "Whole warehouse mode";
                     }
                     else if($strategy_mode_disp=='2')
                     {
                      $s_mode =  "Sub-bin";
                     }
                     else
                     {
                      $s_mode =  "Sub-bin Realtime";
                     }
                     
                 
                 if($risk_mode==1)
                 {
                  $risk_display =  "Steady";
                 }
                  if($risk_mode==2)
                 {
                  $risk_display =  "Conservative";
                 }
                  if($risk_mode==3)
                 {
                  $risk_display =  "Radical";
                 }
                     
                     
                  ?>
                  <div class="trade-sec-one" style="width:100%;background:#121212;">
                     <div class="trade-sec-content">
                        <h4 class="text-white mb-0"><?php echo $pair_disp;?></h4>
                        <br>
                        <small class="text-white" id="crypto-strategy">cycle</small> &nbsp;| &nbsp;
                        <span class="text-white ms-2" id="crypto-strategy_mode"><?php echo $s_mode;?></span> &nbsp;| &nbsp;
                         <span class="text-white ms-2" id="risk_mode"><?php echo $risk_display;?></span>
                     </div>
                    
                     
                     <div class="row">
                        <div class="col-lg-4">
                            <div class="section">
                                <div class="label text-white">Hold Amount</div>
                                <div class="value" id="trade_position_amount" ><?php if(!empty($tradeupdate['trade_position_amount'])) { echo $tradeupdate['trade_position_amount']; } else echo 0;?></div>
                            </div>
                        </div>
                      <div class="col-lg-4">
                          <div class="section">
                              <div class="label text-white">Average Position</div>
                              <div class="value" id="trade_avg_position"><?php if(!empty($tradeupdate['trade_avg_position'])) { echo number_format($tradeupdate['trade_avg_position'],8); } else { echo 0; };?></div>
                          </div>
                      </div>
                    
                      <div class="col-lg-4">
                          <div class="section">
                              <div class="label text-white">Position Quantity</div>
                              <div class="value" id="trade_position_quantity"><?php if(!empty($tradeupdate['trade_position_quantity'])) { echo $tradeupdate['trade_position_quantity']; } else { echo 0;}?></div>
                          </div>
                      </div>
                    </div>
                    
                    <?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;
                     }
                    ?>
                    
                    <div class="row">
                        <div class="col-lg-4">
                            <div class="section">
                                <div class="label text-white">Current Price</div>
                                <div class="value all_list_price"> <?php 
                            if(intval($output['price']) > 99) 
                              echo number_format($output['price'],5);
                            else
                              echo number_format($output['price'],8);
                            ?></div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="section">
                                <div class="label text-white">Coverage Price</div>
                                <div class="value"><span id="down_price"><?php if(!empty($tradeupdate['down_price'])) { echo $tradeupdate['down_price'] ;} else { echo "< 0.0";}?></span></div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="section">
                                <div class="label text-white">Liquidation Price</div>
                                <div class="value"><span id="take_profit_trigger"><?php if(!empty($tradeupdate['take_profit_trigger'])) { echo $tradeupdate['take_profit_trigger'];} else { echo "> 0.0";}?></span></div>
                            </div>
                        </div>
                        
                         <div class="row">
                             
                          <div class="col-lg-4">
                          <div class="section">
                              <div class="label text-white">No. Of calls</div>
                              <div class="value" id="trade_number_of_call"><?php echo $last_margin;?></div>
                          </div>
                      </div>
                        <div class="col-lg-4">
                            <div class="section">
                                <div class="label text-white">Rate of Return</div>
                                <div class="value" id="trade_rate_percentage12"><?php if(!empty($tradeupdate['trade_rate_percentage'])) { echo $tradeupdate['trade_rate_percentage'];} else { echo 0;}?></div>
                            </div>
                        </div>
                        </div>
                    </div>
                    


                  </div>
                  <ul class=" list-unstyled static mt-4 mb-0 trade-menu text-center">
                     

                  <li id="Cstartegy" style="cursor: pointer;" >
                     <iconify-icon icon="gg:menu-boxed"></iconify-icon>
                        <h6 class="text-white-50"  id="Cstartegy_Name">Cycle</h6>
                  </li>

                  <li id="Ostartegy"  style="display: none;cursor: pointer;">
                     <iconify-icon icon="gg:menu-boxed"></iconify-icon>
                     <h6 class="text-white-50" id="Ostartegy_Name">Single</h6>
                  </li>


                     <li style="cursor: pointer;">
                     <?php 
                     if(!empty($pair) && $pair->trade_status != 2)
                     {
                     ?>
                     <a href="" id="sell_popup" data-bs-toggle="modal" data-bs-target="#SellModal" data-bs-whatever="@fat">
                     <iconify-icon icon="iconoir:upload-square"></iconify-icon>
                     <h6 class="text-white-50">Sell</h6>
                     </a>
                     <?php
                     }
                     else
                     {
                     ?>
                     <a id="sellModels" data-bs-whatever="@fat">
                     <iconify-icon icon="iconoir:upload-square"></iconify-icon>
                     <h6 class="text-white-50">Sell</h6>
                     </a>
                     <?php
                     }
                     ?>
                     </li>


                     <li style="cursor: pointer;"> 

                     <?php 
                     if(!empty($pair) &&  $pair->trade_status != 2)
                     {
                     ?>
                     <a href="" id="buy_popup" data-bs-toggle="modal" data-bs-target="#BuyModal" data-bs-whatever="@fat">
                     <iconify-icon icon="icons8:buy"></iconify-icon>
                     <h6 class="text-white-50">Buy</h6>
                   
                     </a>
                     <?php
                     }
                     else
                     {
                     ?>
                     <a id="buyModels">
                     <iconify-icon icon="icons8:buy"></iconify-icon>
                     <h6 class="text-white-50">Buy</h6>
                     </a>
                     <?php
                     }
                     ?>
                     </li>

                      <li>
                        <a id="Margin_Clk" class="text-decoration-none">
                           <iconify-icon icon="carbon:pause-future"></iconify-icon>
                           <h6 class="text-white-50" id="mc">Stop margin call</h6>
                        </a>
                     </li>
                     <li>
                        <a href="" data-bs-toggle="modal" data-bs-target="#staticBackdrop1" data-bs-whatever="@fat" class="text-decoration-none">
                           <iconify-icon icon="bxs:cube"></iconify-icon>
                           <h6 class="text-white-50">Strategy mode</h6>
                        </a>
                     </li>
                  </ul>
                  <div style="clear:both;"><br></div>
                  
                  
                      <div class="trade-button text-center">
                    <!--<a href="" data-bs-toggle="modal" data-bs-target="#staticBackdrop" class="btn btn-primary">First Start Price</a>-->
                   <a href="<?php echo base_url();?>/tradesettings/<?php echo $id;?>" class="btn btn-primary">Transaction settings </a>
                    
                  

            <?php 
            if($activation) 
            { 
              if(!empty($pair)) 
              {
                if($pair->trade_status == 0) 
                { 
              ?>
             <a type="button" id="resume_button" class="btn btn-success">Resume</a>
              <?php 
                } 
              else if($pair->trade_status == 1) 
              { 
                ?>
              <a id="pause_button" class="btn btn-outline-primary">Pause</a>
            <?php 
            } 
          else if($pair->trade_status == 2) 
          {
             ?>
          <a  id="start_button" class="btn btn-primary">Start</a>
        <?php 
        } 
       if($pair->trade_status == 0 || $pair->trade_status == 1) { ?>
       <a  id="stop_button" class="btn btn-danger">Stop</a>
      <?php }   

      }
         else { ?>
            <a id="start_button" class="btn btn-primary" >Start</a>
      <?php } } else {  ?>
            <a id="start_button_block" class="btn btn-primary" >Start</a>
      <?php }  ?>

</div>
                  
                    <ul class=" list-unstyled static mt-4 mb-0 trade-menu text-center">
                      <div class="table-responsive">
            <table class="table table-striped" style="border:none;border-collapse:collapse;">
              <tbody>
                <tr>
                  <td style="text-align:left;color:#fff;"> First order amount </td>
                  <td style="text-align:left;color:#fff;"> <?php echo $trade_process->first_buy_amount ? $trade_process->first_buy_amount : 0;?> </td>
                </tr>
                <tr>
                <td style="text-align:left;color:#fff;"> Margin call limit </td>
                <td style="text-align:left;color:#fff;"> <?php echo $trade_process->margin_column_limit ? $trade_process->margin_column_limit : 0;?> </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Take profit ratio </td>
                  <td style="text-align:left;color:#fff;"> <?php echo $trade_process->whole_profit_ratio ? $trade_process->whole_profit_ratio."%" : "0%";?> </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Take profit Callback </td>
                  <td style="text-align:left;color:#fff;"> <?php echo $trade_process->whole_profit_callback ? $trade_process->whole_profit_callback."%" : "0%";?>  </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Margin call drop </td>
                   <td style="text-align:left;color:#fff;"><?php if(!empty($tradeupdate['margin_call_drops'])) { echo $tradeupdate['margin_call_drops']."%" ;}  else { echo "0%"; }?>  </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Sub Position Call back </td>
                  <td style="text-align:left;color:#fff;"><?php echo $trade_process->sub_position_callback ? $trade_process->sub_position_callback."%" : "0%";?> </td>
                </tr>
                 <tr>
                  <td style="text-align:left;color:#fff;"> Status </td>
                  <td style="text-align:left;color:#fff;"><span id="margin_status"><?php if(!empty($trade_process->margin_call)) { echo "Waiting For Trigger"; } else { echo "Stop Margin Call"; } ?></span></td>
                  </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Buy In Call Back</td>
                  <td style="text-align:left;color:#fff;"><?php  if(!empty($trade_process->buyin_callback)) { echo $trade_process->buyin_callback."%" ;} else { echo "0%";}?></td>
                </tr>
     
              </tbody>
            </table>
          </div>
                    </ul>
                  
                
                <?php 
                 if(!empty($trade_process->buyin_ratio_times))
                 {
                ?>
                 <div class="operation-content">
                 <h3 class="text-primary py-1">Open Position <?php  if(!empty($trade_process->buyin_ratio_times)) { echo "X ".$trade_process->buyin_ratio_times ;} else { echo "";}?></h3>
                 </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">
                     <h3 class="text-primary py-1">Operation Reminder</h3>
                     <p class="text-white-50">When the tradingbot intelligent robot is operating, please do not operate the currency account by yourself, and check whether there are related settings such as fixed deposit, freezing, etc., so as to avoid abnormal judgments caused by the system and affect your rights and interests.</p>
                  </div>
                
                 <br>
            <div class="table-responsive" style="display:none;">
            <table class="table table-striped" style="border:1px solid #ddd;border-collapse:collapse;">
              <tbody>
                <tr>
                  <td style="text-align:left;color:#fff;"> First order amount </td>
                  <td style="text-align:left;color:#fff;"> <?php echo $trade_process->first_buy_amount ? $trade_process->first_buy_amount : 0;?> </td>
                </tr>
                <tr>
                <td style="text-align:left;color:#fff;"> Margin call limit </td>
                <td style="text-align:left;color:#fff;"> <?php echo $trade_process->margin_column_limit ? $trade_process->margin_column_limit : 0;?> </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Take profit ratio </td>
                  <td style="text-align:left;color:#fff;"> <?php echo $trade_process->whole_profit_ratio ? $trade_process->whole_profit_ratio."%" : "0%";?> </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Take profit Callback </td>
                  <td style="text-align:left;color:#fff;"> <?php echo $trade_process->whole_profit_callback ? $trade_process->whole_profit_callback."%" : "0%";?>  </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Margin call drop </td>
                   <td style="text-align:left;color:#fff;"><?php if(!empty($tradeupdate['margin_call_drops'])) { echo $tradeupdate['margin_call_drops']."%" ;}  else { echo "0%"; }?>  </td>
                </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Sub Position Call back </td>
                  <td style="text-align:left;color:#fff;"><?php echo $trade_process->sub_position_callback ? $trade_process->sub_position_callback."%" : "0%";?> </td>
                </tr>
                  <tr>
                  <td style="text-align:left;color:#fff;"> Call Margin Trigger Price </td>
                  <td style="text-align:left;color:#fff;"><span id="down_price"><?php if(!empty($tradeupdate['down_price'])) { echo $tradeupdate['down_price'] ;} else { echo " ";}?></span></td>
                </tr>

                <tr>
                  <td style="text-align:left;color:#fff;"> Take Profit Trigger Price </td>
                  <td style="text-align:left;color:#fff;"><span id="take_profit_trigger"><?php if(!empty($tradeupdate['take_profit_trigger'])) { echo $tradeupdate['take_profit_trigger'];} else { echo "";}?></span></td>
                </tr>
                
                <tr>
                  <td style="text-align:left;color:#fff;"> Status </td>
                  <td style="text-align:left;color:#fff;"><span id="margin_status"><?php if(!empty($trade_process->margin_call)) { echo "Waiting For Trigger"; } else { echo "Stop Margin Call"; } ?></span></td>
                  </tr>
                <tr>
                  <td style="text-align:left;color:#fff;"> Buy In Call Back</td>
                  <td style="text-align:left;color:#fff;"><?php  if(!empty($trade_process->buyin_callback)) { echo $trade_process->buyin_callback."%" ;} else { echo "0%";}?></td>
                </tr>
     
              </tbody>
            </table>
          </div>
              
      
                    <div style="clear:both;height:30px;"></div>
            </div>
         </div>
      </section>
      <!--statergy Modal -->
      <div class="modal fade" id="staticBackdrop1" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" 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" style="border-bottom: 0px;padding-top: 11px;margin-bottom:-15px;">
<p class="modal-title" id="staticBackdropLabel" style="padding-left:170px;"><b>Strategy mode</b></p>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>

<div class="modal-body">
<center>
<span class="span" style="border-bottom: 1px;">Please select a strategy mode</span>
</center>
<hr>
<?php 

if(!empty($pair->strategy_mode))
{
  $strategy_mode_disp=$pair->strategy_mode;
}
else{
  $strategy_mode_disp=$user->strategy_mode;
}
?>
<div class="row col-lg-12 mt-3">
<div class="form-check form-check-right mb-3" style="font-size: 14px;">
<input type="radio" class="form-check-label" name="strategy_mode" id="strategy_mode" value="1" <?php if($strategy_mode_disp=='1'){ echo 'checked="checked"'; } ?>> Whole warehouse mode<br><br>
<!--<input type="radio" class="form-check-label" name="strategy_mode" id="strategy_mode" value="2" <?php if($strategy_mode_disp=='2'){ echo 'checked="checked"'; } ?>> Sub-bin mode<br><br>-->
<input type="radio" class="form-check-label" name="strategy_mode" id="strategy_mode" value="3" <?php if($strategy_mode_disp=='3'){ echo 'checked="checked"'; } ?>> Sub-bin mode-real-time settlement
</div>
</div>

</div>
<div class="modal-footer" style="padding: 0px;">
  <table style="margin-bottom: -2px;">
    <tr>
      <button data-bs-dismiss="modal" class="btn btn-primary" style="border-right: 1px solid #dee2e6;text-align: center;">Cancel</button>
      <button style="text-align: center;" class="btn btn-secondary"  data-bs-dismiss="modal" name="sure_mode" id="sure_mode">Sure</button>
    </tr>
  </table>
</div>
</div>
</div>
</div>


<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">Buy</button>
</div>


</div>
</div>
</div>


<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" 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;">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="" />
</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">Sell</button>
</div>

</div>
</div>
</div>
</div>
<!--first preset -->
<div class="modal" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" class="col-lg-12" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" style="border-radius:30px;padding: 5px;position: absolute;width: 100%; " >
<div class="modal-header"style="border-bottom: 0px;border-bottom: 1px solid #dee2e6 !important;">
<center><b><p class="modal-title" id="staticBackdropLabel" style="border-bottom: 0px;font-size:15px;line-height: 24px;">First Preset Start Price</p></b></center>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" style="border-bottom: 1px solid #dee2e6;font-size:15px;line-height: 24px;">
<span style="color:#dee2e6;font-size: 13px;"><input class="form-control"  type="text" name="first_preset_price" id="first_preset_price" placeholder="Please Enter First Pre send Start Price USDT" value="<?php if(!empty($pair->first_buy_amount)) { echo $pair->first_buy_amount;} else { echo $first_buy_amount;} ?>"></span><p style="font-size:14px;"><p>
<div class="help-block" style="color:red;font-size:12px;" id="first_err"></div>
</div>
<div class="modal-footer">
  <table style="margin-bottom: -2px;">
    <tr>
      <button data-bs-dismiss="modal" class="btn btn-primary">Cancel</button>
      <button  type="button" class="btn btn-secondary" name="sure_price"  id="sure_price">Sure</button>
    </tr>
  </table>
</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' ;} ?>">


<!--first preset -->
      <?php echo view('user/layout/footer');?> 
      <?php echo view('user/layout/footer-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 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},
        
        success:function(msg)
        { 
            
         
         if(msg!= 'success')
            $.notify(' <i class="fas fa-exclamation-triangle"></i>&nbsp;&nbsp;'+msg, '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($pair)) { ?>
  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': '<?php echo $this->session->get('exchange');?>','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); 


    /*var xhr3;
    var fn3 = function(){
    if(xhr3 && xhr3.readyState != 4){
    xhr3.abort();
    }
    xhr3 = $.ajax({
    type: 'post',
    url: "<?php echo base_url("cron_third");?>",
    success: function(data) {
    console.log(data);
    }
    });
    };
    var interval = setInterval(fn3, 10000);
      var xhr1;
    var fn1 = function(){
        if(xhr1 && xhr1.readyState != 4){
            xhr1.abort();
        }
        xhr1 = $.ajax({
            type: 'post',
            url: "<?php echo base_url("cron_first");?>",
            success: function(data) {

                console.log(data);
            }
        });
    };
    var interval = setInterval(fn1, 10000);

    var xhr2;
    var fn2 = function(){
    if(xhr2 && xhr2.readyState != 4){
    xhr2.abort();
    }
    xhr2 = $.ajax({
    type: 'post',
    url: "<?php echo base_url("cron_second");?>",
    success: function(data) {

    console.log(data);

    }
    });
    };
    var interval = setInterval(fn2, 10000);*/
<?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');?>';
      
        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': 1 },
                        success:function(msg)
                        {
                          $.notify(' <i class="fas fa-check-circle"></i>  Trade stopped successfully', 'success'); 
                          // console.log(msg);
                           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")
     {
        $('#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 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(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')
                               {
                                  if(msg)
                                  {
                                      var msg1=msg.split("&&");
                                      var orderid=msg1[0];
                                      var trade_id=msg1[1];
                                      var price = msg[2];
                                      bybit_order(orderid,trade_id,price);
                                  }
                                  else
                                  {
                                    $.notify(' <i class="fas fa-times-circle"></i> Bybit Exchange Trade execution failed. Please try again', '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');
     } 
      
     });

    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>
