<?php


/**
	* 
	* Start 
	* Create Date: 17 Jun, 2016
	* This module file using for commmonly used method in all controller.
	* Created saravana kumar.
	* @see no link
	* Last Updated: 23 Jun, 2016
	* End
	* 
**/
	namespace App\Models;
	use CodeIgniter\Model;
	use Binance;
	// $api = new Binance\API($key,$secret,true);
	Class Strategy extends Model {
		public function __construct() {
			$this->db = \Config\Database::connect();
            $this->session = session();
			$this->common_model = model('CommonModel');
		}
		public function index(){

		}
  public function manual_strategy(){
            $strategy_users = $this->db->table('api_manual_trade')->select('uuserid')->distinct()->where('status','1')->get()->getResult();
				$ia=0;
				foreach ($strategy_users as $key => $value) {
				$userid[$ia] = $value->uuserid;
				$ia++;
				}
            // $userid[0] = 131;

				for ($i=0; $i < count($userid); $i++) { 
                     $userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid[$i])->get()->getRow();
				     $trade_process_array = $this->db->table('trade_process')->where('uusersid',$userid[$i])->where('trade_status','1')->get()->getResult();

				     for ($j=0; $j < count($trade_process_array); $j++) {
                           $trade_process = $trade_process_array[$j];
				           $manual_buy = $this->db->table('api_manual_trade')->where('trade_process_id',$trade_process->id)->where('type',1)->where('status','1')->get()->getRow();
				           $manual_sell = $this->db->table('api_manual_trade')->where('trade_process_id',$trade_process->id)->where('type',2)->where('status','1')->get()->getRow();
				           	$key = $userid_bind_process->api_key;
						$secret = $userid_bind_process->secret_key;
						$api = new Binance\API($key,$secret);

				           $ticker = $api->prices($trade_process->pair);
                           $live_price =  $ticker[$trade_process->pair];
                         echo"<pre>";
                         print_r("live_price ".$live_price);
                         print_r("manual buy trigger ".$manual_buy->trigger_price);
                         print_r("manual sell trigger ".$manual_sell->trigger_price);
                         echo"</pre>";
                         
				           
                           if($manual_buy){
                           
                           	   if($manual_buy->trigger_price >= $live_price){ 
                                $quantity = $manual_buy->amount;
                                $description = "manual_buy";

                           	    $ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
								$balances = $api->balances($ticker);
								$total_asset = $balances['USDT']['available'];
								$k = "";

									if($quantity >= 11 && $total_asset > $quantity)
										$buy_result = $this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair,$description);
									if($buy_result)
										$buy_record_update = $this->db->table('api_manual_trade')->set('status','2')->where("id",$manual_buy->id)->update();


								}	

                           }

                               if($manual_sell){
                           
                           	   if($manual_sell->trigger_price <= $live_price){
										$trade_where = array(
									'uuserid' => $userid[$i],
									'type' => '1',
									'status' => 0,
									'trade_process_id' => $trade_process->id,
									);

									$buy_records = $this->db->table('api_trade_history')->selectAvg('live_price')->where($trade_where)->orderBy('id','DESC')->get()->getRow();
 
                                $quantity = $manual_sell->amount;
                                $description = "manual_sell";
                                $price = "";

                           	    $ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
								$balances = $api->balances($ticker);
								$total_asset = $balances['USDT']['available'];
								$k = "";

									if($quantity >= 11 && $total_asset > $quantity)
										$result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records,$description);
									if($buy_result)
										$buy_record_update = $this->db->table('api_manual_trade')->set('status','2')->where("id",$manual_sell->id)->update();

								}	

                           }

				       }
			    }		

		}


		public function first_strategy(){

			$first_strategy_users = $this->db->table('trade_process')->select('uusersid')->where('strategy_mode','1')->distinct()->where('trade_status','1')->get()->getResult();
			$ia=0;
			foreach ($first_strategy_users as $key => $value) {
			$userid[$ia] = $value->uusersid;
			$ia++;
			}
            $db = db_connect();
			$admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
			$fuel_fee_percent = $admin_settings->min_fuel_fee;

			// $userid[0] = 131;
         
			

			for ($i=0; $i < count($userid); $i++) { 

				$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid[$i])->get()->getRow();
				$trade_process_array = $this->db->table('trade_process')->where('uusersid',$userid[$i])->where('trade_status','1')->where('strategy_mode','1')->get()->getResult();

				for ($j=0; $j < count($trade_process_array); $j++) {

					$trade_process = $trade_process_array[$j];

					if ($userid_bind_process && $trade_process && $trade_process->trade_status == '1') {
						
						
						$key = $userid_bind_process->api_key;
						$secret = $userid_bind_process->secret_key;
						$api = new Binance\API($key,$secret);

					$ticker = $api->prices($trade_process->pair); // Make sure you have an updated ticker object for this to work
					
					$trade_where = array(
						'uuserid' => $userid[$i],
						// 'type' => '1',
						'trade_process_id' => $trade_process->id,
					);

					$last_buy = $this->db->table('api_trade_history')->where($trade_where)->orderBy('id','DESC')->get()->getRow();

					$last_buy_live_price = $last_buy->live_price;

					$this->session->set('cron_pair',strtolower($trade_process->pair));

					$live_price =  $ticker[$trade_process->pair];

					


// echo '<script type="text/javascript">acted()</script>';
// echo '<script type="text/javascript">acted1()</script>';

echo"<pre>";
print_r($_SESSION['high_price']);
echo "<br>";
print_r($_SESSION['live_price']);
echo "<br>";
print_r($_SESSION['previous_high_price']);
echo"</pre>";


// echo "<pre>";
// print_r("high price ".$this->session->get('high_price'));
// print_r("live price ".$this->session->get('live_price'));
// print_r("previous_high_price ".$this->session->get('previous_high_price'));
// echo "</pre>";

     //                if(!$this->session->get('live_price') && $this->session->get('live_price') == "")
					//      $live_price =  $ticker[$trade_process->pair];
     //                else
					// $live_price = $this->session->get('live_price');
					// $high_price = $this->session->get('high_price');
					// if(!$this->session->get('previous_high_price') && $this->session->get('previous_high_price') == ""){

					     // $live_price =  $ticker[$trade_process->pair];
                          $ticks = $api->candlesticks($trade_process->pair, "15m");
                           $res = end($ticks);
                           $previous_high_price = $res['close'];


					// }else{
					// $previous_high_price = $this->session->get('previous_high_price');
			  //     	}     

					// $live_price = 0.254;
					print_r("Last Buy Price ".$last_buy_live_price);
					echo "<br>";
					print_r("cron_pair ".$_SESSION['cron_pair']);
					echo "<br>";
					// print_r("high_price ".$_SESSION['high_price']);
					// echo "<br>";
					print_r("previous_high_price ".$previous_high_price);
					echo "<br>";
					print_r("Live Price ".$live_price);
					// exit();

					if ($last_buy_live_price > $live_price) {

						// normal margin call drop buy function
                        if($last_buy->type == 1)  {  
                        	$trade_where_new = array(
						'uuserid' => $userid[$i],
						'type' => '1',
						'status' => 0,
						'trade_process_id' => $trade_process->id,
					);

      $last_buy_recheck = $this->db->table('api_trade_history')->where($trade_where_new)->orderBy('margin_call_drops','DESC')->get()->getRow();
       $last_margin_call_drop = $last_buy_recheck->margin_call_drops;
       if($last_margin_call_drop == 0){
       	 $number_of_margincall = 0;
       }else{
       	$number_of_margincall = $last_margin_call_drop;
       }
						$margin_call_drop = $trade_process->margincall_drop;
						$explode_margin_call_drop = explode(',', $margin_call_drop);
						$exploded = array_combine(range(1, count($explode_margin_call_drop)), $explode_margin_call_drop);
						$old_price = '';

					
         
						for ($k=$number_of_margincall; $k<=count($exploded); $k++) {

							
					        $last_buy = $this->db->table('api_trade_history')->where($trade_where)->orderBy('id','DESC')->get()->getRow();
							if ($old_price == '') {
								$old_price = $last_buy->live_price;
							}

							
                           

							$call_drop_where = array(
								'trade_process_id' => $trade_process->id,
								'uuserid' => $userid[$i],
								'margin_call_drops' => $k,
								'type' => 1,
								'status' => 0
							);


							$call_drop = $this->db->table('api_trade_history')->where($call_drop_where)->get()->getRow();
							// echo"<pre>";
							// print_r($call_drop);
							// echo"</pre>";
                 			if (!$call_drop) {
								$check_percentage = ($old_price - $live_price) / $old_price * 100;
								echo"<pre>";
								print_r("Old price".$old_price);
								print_r("Current Down".$check_percentage);
								print_r("Next call percentage".$k." :".$exploded[$k]);
								echo"</pre>";

								if ($check_percentage >= $exploded[$k]) {

									$explode_buyin_ratio_times = explode(',', $trade_process->buyin_ratio_times);
									$exploded_buy_ratio = array_combine(range(1, count($explode_buyin_ratio_times)), $explode_buyin_ratio_times);

									if($trade_process->open_position_doubled != 'on' || $trade_process->open_position_doubled == '')
										$quantity = 1;
									else
										$quantity = 2;
									$price = $trade_process->first_buy_amount * $quantity;
									$description = "";

									$quantity = $price * $exploded_buy_ratio[$k];

									if ($trade_process->margin_call == '1' ) {
										$buy_done = $this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair,$description);
										$call_drop_where1 = array(
										'trade_process_id' => $trade_process->id,
										'uuserid' => $userid[$i],
										// 'margin_call_drops' => $k
										);
								
								$call_drop = $this->db->table('api_trade_history')->where($call_drop_where1)->orderBy('id','DESC')->get()->getRow();

								$old_price = $call_drop->live_price;
					
									}
								}
                            break;
							}else{

								$call_drop_where1 = array(
									'trade_process_id' => $trade_process->id,
									'uuserid' => $userid[$i],
									// 'margin_call_drops' => $k
								);
								
								$call_drop = $this->db->table('api_trade_history')->where($call_drop_where1)->orderBy('id','DESC')->get()->getRow();

								$old_price = $call_drop->live_price;
							}
						if($buy_done)
						break;
						}
					}
			else if($last_buy->type == 2){
				   $trade = $this->db->table('trade_process')->where("id",$trade_process->id)->get()->getRow();
				   if($previous_high_price < $live_price && $trade->flag_buy != 1){
	                $sell_record_update = $this->db->table('trade_process')->set('flag_buy','1')->where("id",$trade_process->id)->update();
                  	$buy_in_callback_temp = $live_price * $trade_process->buyin_callback / 100;
					$buy_in_callback_temp = $buy_in_callback_temp + $live_price;
					$sell_record_update1 = $this->db->table('trade_process')->set('buy_limit',$buy_in_callback_temp)->where("id",$trade_process->id)->update();
				   }
			       else if($previous_high_price < $live_price && $trade->flag_buy == 1 && $live_price < $trade->buy_limit){
                  	$sell_record_update = $this->db->table('trade_process')->set('flag_buy','1')->where("id",$trade_process->id)->update();
                  	$buy_in_callback_temp = $live_price * $trade_process->buyin_callback / 100;
					$buy_in_callback_temp = $buy_in_callback_temp + $live_price;
					$sell_record_update1 = $this->db->table('trade_process')->set('buy_limit',$buy_in_callback_temp)->where("id",$trade_process->id)->update();
                  	}
					$trade = $this->db->table('trade_process')->where("id",$trade_process->id)->get()->getRow();
                  	 
                  	  echo"<pre>";
                  	  print_r($trade);
                  	  echo"</pre>";
                  	  // exit();

                  	if($trade->flag_buy == 1) {

                  	$buy_in_callback_temp = $trade->buy_limit;

					echo"<pre>";
					print_r("buy in call back price".$buy_in_callback_temp);
					echo"</pre>";

					if($buy_in_callback_temp <= $live_price){

						if($trade_process->open_position_doubled != 'on' || $trade_process->open_position_doubled == ''){
								$quantity = 1;
						}
						else
						{
								$quantity = 2;
						}
								$price = $trade_process->first_buy_amount * $quantity;
								$quantity = $price ;

								echo"<pre>";
								print_r($exploded_buy_ratio[$k]);
								echo "\n";
								print_r($quantity);
								echo "\n";
								print_r($trade_process->margin_call);
								echo"</pre>";
								// exit();

								$ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
								$balances = $api->balances($ticker);
								$total_asset = $balances['USDT']['available'];
								$k = "";
								$description = "";

										if($quantity >= 11 && $total_asset > $quantity)
										$buy_result = $this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair,$description);
										$call_drop_where1 = array(
										'trade_process_id' => $trade_process->id,
										'uuserid' => $userid[$i],
										// 'margin_call_drops' => $k
										);
								
								$call_drop = $this->db->table('api_trade_history')->where($call_drop_where1)->orderBy('id','DESC')->get()->getRow();

								$old_price = $call_drop->live_price;
								
					            }
                  	}
				}
			}else{

				if($last_buy->type == 2){  //after take profit call market up buyincallback call

		            $buy_record_update1 = $this->db->table('trade_process')->set('flag_buy','0')->where("id",$trade_process_id)->update();
                    $buy_record_update2 = $this->db->table('trade_process')->set('buy_limit','')->where("id",$trade_process_id)->update();

					$buy_in_callback_temp = $last_buy->live_price * $trade_process->buyin_callback / 100;
					$buy_in_callback_temp = $buy_in_callback_temp + $last_buy->live_price;

					echo"<pre>";
					print_r("sell ".$buy_in_callback_temp);
					print_r("live_price ".$live_price);
					echo"</pre>";

					if($buy_in_callback_temp <= $live_price){

						if($trade_process->open_position_doubled != 'on' || $trade_process->open_position_doubled == '')
								$quantity = 1;
						else
								$quantity = 2;
								$price = $trade_process->first_buy_amount * $quantity;
								$quantity = $price ;

								echo"<pre>";
								print_r($exploded_buy_ratio[$k]);
								echo "\n";
								print_r($quantity);
								echo "\n";
								print_r($trade_process->margin_call);
								echo"</pre>";
								// exit();

								$ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
								$balances = $api->balances($ticker);
								$total_asset = $balances['USDT']['available'];

								echo"<pre>";
								print_r("profit buy");
								echo"</pre>";

								$k = "";
								$description = "";
								

										if($quantity >= 11 && $total_asset > $quantity)
										$buy_result = $this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair,$description);
										$call_drop_where1 = array(
										'trade_process_id' => $trade_process->id,
										'uuserid' => $userid[$i],
										// 'margin_call_drops' => $k
										);
								
								$call_drop = $this->db->table('api_trade_history')->where($call_drop_where1)->orderBy('id','DESC')->get()->getRow();

								$old_price = $call_drop->live_price;
								
								
					            }

				}
				else { 

					

					

					

						$trade_where = array(
							'uuserid' => $userid[$i],
							'type' => '1',
							'status' => 0,
							'trade_process_id' => $trade_process->id,
						);
					  $buy_records = $this->db->table('api_trade_history')->selectAvg('live_price')->where($trade_where)->get()->getRow();
                      $buy_records1 = $this->db->table('api_trade_history')->selectSum('quantity')->where($trade_where)->get()->getRow();
					  $buy_records2 = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where)->get()->getRow();




                        if(!empty($buy_records1->quantity) && !empty($buy_records2->received_amount)){
						    $buy_records = $buy_records1->quantity / $buy_records2->received_amount;
                        }
					    else
					    	$buy_records = 0;

						// $check_percentage = ($live_price - $buy_records) / $buy_records * 100 ;

						

						// $buy_records= 418.2;

						if ($buy_records > 0 && $buy_records != '') {

							$avg_price = round($buy_records,8) * $trade_process->whole_profit_ratio / 100;

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

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

							$max_down_price = $max_increase_price - $max_down_percentage;

							$max_down_price = round($max_down_price,8);

						

								echo"<pre>";
								print_r("MAX ".$max_increase_price);
								print_r("LIVE PRICE ".$live_price);
								print_r("MAX DOWN  ".$max_down_price);
								echo"</pre>";
								// exit();

								// $max_increase_price = 417.5;
								// $max_down_price = 417.5;

                        $trade = $this->db->table('trade_process')->where("id",$trade_process->id)->get()->getRow();

                            
                            if ($live_price >= $max_increase_price && $trade->flag != 1) {
                            	$sell_record_update = $this->db->table('trade_process')->set('flag','1')->where("id",$trade_process->id)->update();
                            	$sell_record_update1 = $this->db->table('trade_process')->set('sell_limit',$max_down_price)->where("id",$trade_process->id)->update();
                            }

                        $trade = $this->db->table('trade_process')->where("id",$trade_process->id)->get()->getRow();


                        echo"<pre>";
                        print_r($trade);
                        echo"</pre>";
                        // die;

                     

							if ($trade->flag == 1) {

								$trade_where = array(
									'uuserid' => $userid[$i],
									'type' => '1',
									'status' => 0,
									'trade_process_id' => $trade_process->id,
								);


		$buyed_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where)->orderBy('id','DESC')->get()->getRow();

								
								
								$quantity = number_format($buyed_quantity->received_amount,8);
								$price = $max_increase_price; // Try to sell it for 0.5 btc
								$stopPrice = $trade->sell_limit; // Sell immediately if price goes below 0.4 btc
								// $quantity = 0.07;

								echo"<pre>";
								print_r("MAX ".$max_increase_price);
								print_r("LIVE PRICE ".$live_price);
								print_r("MAX DOWN  ".$max_down_price);
								echo"</pre>";
								// exit();
								$ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
								$balances = $api->balances($ticker);
								$total_asset = $balances[substr($trade->pair,0,-4)]['available'];

								
							
								
								if($trade->sell_limit == $live_price){
									if(!empty($quantity) && $total_asset >= $quantity)
								           $result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records1);
								    else
								    	$result = 0;
								} else if($live_price > $avg_price && $trade->sell_limit >= $live_price){
									if(!empty($quantity) && $total_asset >= $quantity)
                                        $result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records1);
                                    else
                                    	$result = 0;
					  } else if(!empty($trade_process->oneshot_limit) && $trade_process->oneshot_limit != 0){   // one shot hit new feature
                                    if($trade_process->oneshot_limit >= $live_price){
									if(!empty($quantity) && $total_asset >= $quantity)
								           $result_oneshothit = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records1);
								    else
								    	$result_oneshothit = 0;

								   if($result_oneshothit){
								    	$buy_record_update = $this->db->table('api_trade_history')->set('status','1')->where($trade_where)->update();
								      $this->db->table('trade_process')->set('trade_status','2')->where('id',$trade_process->id)->update();
								      break;
								    }
								}
                        }else{

                        	if($live_price > $trade_process->sell_limit && $previous_high_price > $live_price){
                                 if(!empty($quantity) && $total_asset >= $quantity)
								           $result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records1);
								    else
								    	$result = 0;
                        	}

                        }

							
							

							if($result)
									$buy_record_update = $this->db->table('api_trade_history')->set('status','1')->where($trade_where)->update();

							if ($trade_process->strategy_type != 'Cycle Strategy' && $result) {
									$this->db->table('trade_process')->set('trade_status','2')->where('id',$trade_process->id)->update();
								}

								$margin_call_drop = $trade_process->margincall_drop;

								$explode_margin_call_drop = explode(',', $margin_call_drop);
								$exploded = array_combine(range(1, count($explode_margin_call_drop)), $explode_margin_call_drop);

								$last_call_drop = array_key_last($exploded);

								$call_drop_where = array(
									'trade_process_id' => $trade_process->id,
									'uuserid' => $userid[$i],
									'margin_call_drops' => $last_call_drop
								);

								$call_drop_check = $this->db->table('api_trade_history')->where($call_drop_where)->get()->getRow();


								if ($call_drop_check != '') {
									$this->db->table('trade_process')->set('trade_status','2')->where('id',$trade_process->id)->update();
								}
								

								// return true;
							}
						}
					}
				}

				}
				$this->session->remove('live_price');
				$this->session->remove('cron_pair');
					$this->session->remove('high_price');
					$this->session->remove('previous_high_price');
			}
		}

	}




	public function marketbuy($userid,$trade_process_id,$quantity,$margin_call_drops,$api,$pair,$description=""){
        print_r("buy pair".$pair);
		print_r("buy amount".$quantity);
		// print_r($api);
		// exit();
		$flags['isQuoteOrder'] = true;

		if($quantity < 11){
			$quantity = 11;
		}
		$quantity = str_replace(',', '', $quantity);
				// $order = $api->buy("BNBUSDT", "10",0,"MARKET",$flags);
				// $order = $api->marketQuoteSell("BNBUSDT", "100",$flags);
		$order = $api->marketQuoteBuy($pair, $quantity,$flags);
		echo"<pre>";
		print_r($order);
		echo"</pre>";

		if($order) { 
	      if(!empty($description) || $description == ""){
        $buy_record_update = $this->db->table('trade_process')->set('flag','0')->where("id",$trade_process_id)->update();
         $buy_record_update1 = $this->db->table('trade_process')->set('flag_buy','0')->where("id",$trade_process_id)->update();
         $buy_record_update2 = $this->db->table('trade_process')->set('buy_limit','')->where("id",$trade_process_id)->update();
           }


		$trade_process = $this->db->table('trade_process')->where('uusersid',$userid)->where('trade_status','1')->where('id',$trade_process_id)->get()->getRow();

		$order_history = array(
			'pair' => $order['symbol'],
			'order_id' => $order['orderId'],
			'trade_process_id' => $trade_process_id,
			'uuserid' => $userid,
			'type' => '1',
			'quantity' => $order['cummulativeQuoteQty'],
			' original_quantity' => $quantity,
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'live_price' => $order['fills'][0]['price'],
			'margin_call_drops' => $margin_call_drops,
			'description' => $description,
			'date' => date('Y-m-d',time()),
			'strategy_mode' => $trade_process->strategy_mode,
			'status' => 0,
		);

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

		$this->db->table('api_trade_history')->insert($order_history);

		return true;
	}else{
		$duplicate_check = $this->db->table('notification_table')->where('uusersid',$userid)->like('message','Binance '.$pair)->like('created_date',date('Y-m-d'))->get()->getRow();
	    if(!$duplicate_check) { 
		$notification = array(
						'uusersid' => $userid, 
						'message'  => 'Binance '.$pair.' failed to cover short position due to insufficient exchange balance and has stopped opening short position. if you need to reopen short position, please go to the strategy details page of Open margin call',
						'created_date' => date('Y-m-d H:i:s')
		);
		$this->db->table('notification_table')->insert($notification);
	   } 
	   return false;
	}
	}

	public function marketsell($userid,$trade_process_id,$quantity,$margin_call_drops,$api,$pair){

		$flags['isQuoteOrder'] = true;
		$order = $api->marketQuoteSell($trade_process->pair,$quantity);
		$order_history = array(
			'pair' => $order['symbol'],
			'order_id' => $order['orderId'],
			'trade_process_id' => $trade_process_id,
			'uuserid' => $userid,
			'type' => '2',
			'quantity' => $order['cummulativeQuoteQty'],
			' original_quantity' => $quantity,
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'live_price' => $order['fills'][0]['price'],
			'margin_call_drops' => $margin_call_drops
		);
		$this->db->table('api_trade_history')->insert($order_history);
		$buy_record_update = $this->db->table('trade_process')->set('flag','0')->where("id",$trade_process_id)->update();
		return true;

	}

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

		print_r("sell pair".$pair);
		print_r("sell amount".$quantity);

	    $quantity = str_replace(',', '', $quantity);

	    echo"<pre>";
	    print_r("Quantity ".$quantity);
	    echo"</pre>";
	    

		$exchange_info = $api->exchangeInfo();

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

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

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

		echo"<pre>";
		print_r("stepsize");
		echo "<br>";
		print_r($current);
		echo "<br>";
		print_r($quantity);
		echo"</pre>";
	
 
		// $order = $api->marketQuoteSell($pair,$quantity);
		$quantity = str_replace(',', '', $quantity);

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

		// $order = $api->marketQuoteSell($pair,$quantity);

		$order = $api->sell($pair,$quantity,0,"MARKET");
		echo"<pre>";
		print_r($order);
		echo"</pre>";
		

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

	     $db = db_connect();
		 $admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
		 $fuel_fee_percent = $admin_settings->min_fuel_fee;

	    $avg_price1 = $order['cummulativeQuoteQty'] - $avg_price->quantity; 
	    $reverse_percent = 100 - $fuel_fee_percent;
	    $avg_price = $avg_price1 * ($reverse_percent / 100);
	    $comm_price = $avg_price1 * ($fuel_fee_percent / 100);

	    $profit1 = $avg_price / $order['cummulativeQuoteQty'];
	    $profit = $profit1 * 100;

		$order_history = array(
			'pair' => $pair,
			'order_id' => $order['orderId'],
			'trade_process_id' => $trade_process_id,
			'uuserid' => $userid,
			'type' => '2',
			'quantity' => $order['cummulativeQuoteQty'],
			' original_quantity' => $order['cummulativeQuoteQty'],
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'live_price' => $stopPrice,
			'avg_price' => $avg_price1,
			'comm_price' => $comm_price,
			'profit_percentage' => $profit,
			'description' => $description,
			'margin_call_drops' => '',
			'date' => date('Y-m-d',time()),
			'strategy_mode' => $trade_process->strategy_mode,
			'status' => 0,
		);
	    echo"<pre>";
	    print_r($order_history);
	    echo"</pre>";
		$this->db->table('api_trade_history')->insert($order_history);
        $deposit_data = array(           // fuel fee deduction
        'uusersid' => $userid,
        'amount'  => $comm_price,
        'depositid' => $this->db->InsertID(),
        'type'  => 'fuel', 
        'description'  => 'fuel fee deduction for order no '.$order['orderId'],
        'date'  => date('Y-m-d H:i:s'),
        'currency' => 1,
        'transactionid' => $trade_process_id
        );
		$this->db->table('history')->insert($deposit_data); 
		$return = true;
	}else{
		$duplicate_check = $this->db->table('notification_table')->where('uusersid',$userid)->like('message','Binance '.$pair)->like('created_date',date('Y-m-d'))->get()->getRow();
			if(!$duplicate_check) { 
			$notification = array(
			'uusersid' => $userid, 
			'message'  => 'Binance '.$pair.' failed to cover short position due to insufficient exchange balance and has stopped opening short position. if you need to reopen short position, please go to the strategy details page of Open margin call',
			'created_date' => date('Y-m-d H:i:s')
			);
			$this->db->table('notification_table')->insert($notification);
			}
		$return = false;
	}
		return $return;
	}

}
?>
<!-- <script type="text/javascript" src="<?php echo base_url();?>/assets/js/bundle.js"></script> -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- 
<script type="text/javascript">

  function acted(){ 
  const ws = new WebSocket('wss://stream.binance.com:9443/ws/<?php echo $_SESSION['cron_pair'];?>@miniTicker');

  console.log(ws);
ws.onmessage = function (event) {
    var data = JSON.parse(event.data);
    <?php $h_p = "<script>document.write(data['h'])</script>"?> 
    <?php $l_p = "<script>document.write(data['c'])</script>"?> 
    console.log("live price "+data['c']);
    console.log("high price "+data['h']);
     $.ajax({
      'method': 'POST',
      'url': '<?php echo base_url("/update_live_price");?>',
      data:{'price':data['c'],'high_price':data['h']},
      success:function(msg)
      {
        console.log(msg);
      }
      });
}

}

 function acted1(){
  const ws = new WebSocket('wss://stream.binance.com:9443/ws/<?php echo $_SESSION['cron_pair'];?>@kline_5m');

  console.log(ws);
ws.onmessage = function (event) {
    var data = JSON.parse(event.data);
    console.log("previous_high_price "+data['k']['h']);
        <?php $p_h_p = "<script>document.write(data['k']['h'])</script>"?> 
    // console.log(data['c']);
     $.ajax({
      'method': 'POST',
      'url': '<?php echo base_url("/update_live_price");?>',
      data:{'previous_high_price':data['k']['h']},
      success:function(msg)
      {
      	console.log(msg);
      }
      });
}

}
setInterval(acted,120000);
setInterval(acted1,120000);
</script> -->

