<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/rowreorder/1.2.8/css/rowReorder.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css"> -->
<style type="text/css">
  .heart0
  {
  font-size: 25px;
  color:red;
  }
  .heart1
  {
  font-size: 25px;
  color:red;
  }
  .heart {
  font-size: 25px;
  color:red;
  }

.btn-primary{
  background: rgb(32, 60, 157) !important;
  color: white !important;
}
</style>

<div class="trading-table">
<div class="table-responsive">
<table class="table-striped display nowrap" id="table_example">
<thead>
<tr>
<td> List </td>
<td class="text-center">Quantity </td>
<td class="text-center"> Floating Loss </td>
<td class="text-center"> Price </td>
<td class="text-center"> Change% </td>
<td class="text-center"> Rate of Return </td>

</tr>
</thead><tbody>
<?php 
$this->session = session();
$uusersid = $this->session->get('uusersid');
$this->db = db_connect();
    $operation =$this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and trade_status != 2 order by id desc")->getResult();
    $i=0;
    foreach ($operation as $key => $value) {
      $required_pairs[$i] = substr($value->pair, 0, -4);
      $i++;
    }
$validation =  \Config\Services::validation();
$this->db = db_connect();
$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."'")->getResult();
$ref=$referral1[0];
$key = $ref->api_key;
$secret = $ref->secret_key;

if(empty($ref)){
  $key = "sFlTSc2Y56NQpdTBcjFw2vxESWXyeWBozax5gP3CoRQx8n70XgPw960G2pQWUeFg";
  $secret = "BZZswPqHBAYkY9Oz8YQIe9afnqEmY6VxfJLF44TI8rNDDaB6EuyWa6cN3Hy32pQG";
  $api = new Binance\API($key,$secret);
}else{
   $api = new Binance\API($key,$secret);
   $account = $api->accountStatus();
   if($account['sapi']['code'] == "-2008" || $account['sapi']['code'] == "-1022" || $account['sapi']['code'] == "-2015")
    {
        $key = "tJuR6dN9AZp9KiAn41avxq64KsyDxa8FIaRjxTf0k1qplZIv1MRnHrS3zQIqHuzZ";
        $secret = "GlRLQS2VGYfa1sOUaS3NIgGmszJOAuxu7Xk0anY1r4ifRmGYVYxoG25LOBnESE67";
        $api = new Binance\API($key,$secret);
    }
 }


$marketpair = $api->prevDay();

$ticker = $api->prices(); // Make sure you have an updated ticker object for this to work

$balances = $api->balances($ticker);

if(!empty($required_pairs)) { 
$i=0;
foreach ($marketpair as $key => $value) {
  if(substr($value['symbol'], -4) == "USDT"){
    if(in_array(substr_replace($value['symbol'] ,"",-4), $required_pairs)){
      $output[$i]['symbol'] = $value['symbol'];
      $output[$i]['price'] = $value['lastPrice'];
      $output[$i]['change'] = $value['priceChangePercent'];
    }
      $i++;
  }
}
$k = 0;
foreach ($output as $key => $value) {
  $output[$k] = $value;
  $k++;
}
$output =  array_unique($output,SORT_REGULAR);
}else {
  $output = "";
}
$this->session = session();
$uusersid = $this->session->get('uusersid');
 

              if($output){
  foreach ($output as $key => $value) {

   
    $pair =  $value['symbol'];
      
      // return $session;

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

      $trade_record =  $this->db->table('trade_process')->where($where_)->orderBy('id','DESC')->get()->getRow();
     


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

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

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

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

      

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


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

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

            if ($total_position_quantity->received_amount > 0) {

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

          }else{

          $tradeupdate['trade_position_quantity'] = 0.00;

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

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



      

       $ticker = $api->prices($value['symbol']); 
          $live_price =  $ticker[$value['symbol']];

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

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


          // $tradeupdate['trade_avg_position'] = $first_buy->live_price;

            $tradeupdate['trade_avg_position'] = str_replace(',', '', $tradeupdate['trade_avg_position']);
          $tradeupdate['trade_position_amount'] = str_replace(',', '', $tradeupdate['trade_position_amount']);


          if($avg_position_amount == 0 &&  $tradeupdate['trade_position_amount'] == 0){
            $check_percentage = '0';
            $tradeupdate['floating_loss'] = 0;
          }
          else if ($avg_position_amount > $live_price) {
            
            // echo "first_buy = ".$avg_position_amount.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";
            // echo "decrease";

            // $tradeupdate['floating_loss'] = '-'.$avg_position_amount - $live_price;
            
            $check_percentage = ($avg_position_amount - $live_price) / $avg_position_amount * 100 ;
            $check_percentage = '-'.$check_percentage;
            $floating_loss = $total_position_amount->quantity * $check_percentage / 100;
            $tradeupdate['floating_loss'] = number_format($floating_loss,5);
          }elseif ($avg_position_amount == $live_price) {
            
            // echo "first_buy = ".$avg_position_amount.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";

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

            // echo "increase";
            $check_percentage = ($live_price - $avg_position_amount) / $live_price * 100 ;
            $floating_loss = $total_position_amount->quantity * $check_percentage / 100;
            $tradeupdate['floating_loss'] = number_format($floating_loss,5);

            // $tradeupdate['floating_loss'] = '+'.$live_price - $tradeupdate['trade_avg_position'];

          }

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


        

 

      }else{
        $tradeupdate['trade_position_amount'] = "";
        $tradeupdate['floating_loss'] = "";
        $tradeupdate['trade_rate_percentage'] = "";
      }

    if($value['change'] > 0){
      $class = "up";
      $change = '+'.$value['change'];
    }else{
      $class = 'down';
      $change = $value['change'];
    }


    if($tradeupdate['trade_rate_percentage'] == 0){
        $default_style = "dark";
    }else if($tradeupdate['trade_rate_percentage'] > 0){
        $default_style = "primary";
    }else{
        $default_style = "danger";
    }

    if($trade_record != "") { 
    
?>
            <tr>
                <td class="get" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><img src="<?php echo base_url('styles/images/tradingpair_images/'.$value['symbol'].'.png');?>"  class="img-fluid me-1" height="50px" width="50px;"><?php echo $value['symbol'];?> </td>
                <td class="text-center get" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $tradeupdate['trade_position_amount'] ? $tradeupdate['trade_position_amount'] : "0.000000" ;?></td>
                <td class="text-center get" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $tradeupdate['floating_loss'] ? $tradeupdate['floating_loss'] : "0" ;?></td>
                <td class="text-center get" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $value['price'];?></td>
                <td class="text-center get" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><span class="<?php echo $class;?>"><?php echo $change;?></span></td>
                <td class="text-center get" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><button class="btn btn-<?php echo $default_style; ?>"><?php echo $tradeupdate['trade_rate_percentage'] ? $tradeupdate['trade_rate_percentage'] : "0%" ;?></button></td>
              </tr>
              <?php 
            }else{ ?>
              <tr>
              <td colspan="6">No Active Pairs Found</td>
            </tr>
           <?php }
            }
               } 
      ?>
             
            </tbody>
          </table>
  
</div>
</div>
<script src="<?php echo base_url('styles/new_style/js/jquery-2.1.4.min.js');?>"></script>
<script src="<?php echo base_url('styles/new_style/js/bootstrap.min.js');?>"></script>
<script src="<?php echo base_url('/assets/js/plugins/notifications/jquery.quicksearch.js');?>"></script>
<!-- <script type="text/javascript" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/rowreorder/1.2.8/js/dataTables.rowReorder.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script> -->
<script type="text/javascript">
  $(document).ready(function() {
//     var table = $('#table_example').DataTable( {
//         rowReorder: {
//             selector: 'td:nth-child(2)'
//         },
//         responsive: true
//     } );
// } );

$('input#id_search').quicksearch('table#table_example tbody tr');

   $('.get').click(function(){
        window.location = $(this).data('href');
        return false;
    });
 });
</script>