<?php
    namespace App\Models;
	use CodeIgniter\Model;
	use Binance;
	use Lin\Okex\OkexV5;
    use Lin\Ftx\Ftx;
	use App\Helpers\site_helper;
	use App\Libraries\BybitApi;
	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 first_strategy()
		{

			$first_strategy_users = $this->db->table('trade_process')->select('uusersid')->where('strategy_mode','1')->distinct()->where('trade_status','1')->get()->getResult();
			
			
			$userid = array();
			$ia=0;
			if(!empty($first_strategy_users)) 
			{ 
			    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;
				if(empty($userid)) return false;

			$tradSets = $this->common_model->GetResults('adminsettings','');
			$tradSet = $tradSets[0];
			$min_gas_required =$tradSet->min_fuel;
			$min_gas_fee= $tradSet->min_fuel_fee;
			//$data_binance = json_decode(@file_get_contents('https://revotechbot.com/trading_pairs.json'), true);
			$data_binance=getpairs(1);
	
			for ($i=0; $i < count($userid); $i++) 
			{ 
                // $trade_process_array = $this->db->table('trade_process')->where('uusersid',$userid[$i])->where('trade_status','1')->where('strategy_mode','1')->get()->getResult();
				/*$trade_process_array = $this->db->query("Select * From trade_process t1 where created_time = (select max(created_time) from trade_process where t1.pair =trade_process.pair) AND uusersid = $userid[$i] AND trade_status = 1 AND strategy_mode = 1 order by created_time desc")->getResult();*/
				$trade_process_array = $this->db->query("Select * from trade_process where uusersid = $userid[$i] AND trade_status = 1 AND strategy_mode = 1  order by created_time desc")->getResult();
				for($j=0; $j < count($trade_process_array); $j++) 
                {
                    $trade_process = $trade_process_array[$j];
                    if($trade_process && $trade_process->trade_status == '1') 
					{

    					if($trade_process->exchange == 1)
    					{
    						$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid[$i])->where('type','1')->get()->getRow();
    				    }
    				
    					else if($trade_process->exchange=='5')
    					{
    						$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid[$i])->where('type','5')->get()->getRow();
    						$check_sells=$this->bybit_sells($userid[$i]);
    				    }
                        

    					$key = $userid_bind_process->api_key;	
    					$secret = $userid_bind_process->secret_key;	
					    if($trade_process->exchange == 2)
					    {
							$passphrase = $userid_bind_process->pass_phrase;
					    }
					    
					    if($trade_process->exchange == 1)
					    {
					        $live_price=getliveprice($trade_process->pair);
                            $live_price=number_format($live_price,9);
                            $live_price=str_replace(',','',$live_price);
    					    $previous_high_price=candleprice($key,$secret,$trade_process->pair);
    					}
    					else if($trade_process->exchange ==5)
    					{
    					    $account = $userid_bind_process->account;
                    	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                    	    $bybitApi = new BybitApi($key, $secret);
                    	    $tickers = $bybitApi->ticker(['category' => 'spot', 'symbol' => $trade_process->pair]); 
                            $live_price = $tickers['lastPrice'];
    					    
    					}
    					
				        $trade_where = array(
						    'uuserid' => $userid[$i],
						    '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));

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


    					print_r("Last Buy Price ".$last_buy_live_price);
    					echo "<br>";
    					print_r("cron_pair ".$_SESSION['cron_pair']);
    					echo "<br>";
	
    					print_r("previous_high_price ".$previous_high_price);
    					echo "<br>";
    					print_r("Live Price ".$live_price);
	
            
					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',
					         'trade_process_id' => $trade_process->id,
						);

						$last_buy_recheck = $this->db->table('api_trade_history')->where($trade_where_new)->where('margin_call_drops !=', '0')->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;
						}
						echo 'Total Executed calls:'. $number_of_margincall;
					
						$margin_call_drop = $trade_process->margincall_drop;
						$margin_call_limit=$trade_process->margin_column_limit;
						
						$explode_margin_call_drop = explode(',', $margin_call_drop);
						$exploded = array_combine(range(1, count($explode_margin_call_drop)), $explode_margin_call_drop);
						
					
				    	$old_price = '';
						$call_value=0;
						for($k=$number_of_margincall; $k<=count($exploded); $k++) 
						{
						    
						    
						    echo "<Br>";
							$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,
								'trade_close' => 0
								);
							$call_drop = $this->db->table('api_trade_history')->where($call_drop_where)->get()->getRow();
							if(empty($call_drop)) 
							{
							    $call_value=1;
								$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>";
                                echo $check_percentage.'-'. $exploded[$k];
                                
                                if($check_percentage >= $exploded[$k]) 
								{
                                    
                                    if($exploded[$k]!='0')
                                    {
    									$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;
    										
    										$quantity='1';
    										
    									$price = $trade_process->first_buy_amount * $quantity;
    									
    									$description = "";
          
									
    									if($exploded_buy_ratio[$k] > 0)
    									{
    									    
    									    $price = $trade_process->first_buy_amount;
                                            $quantity = $price * $exploded_buy_ratio[$k];
    									}
                                        else
                                        {
                                            $price = $trade_process->first_buy_amount * $quantity;
                                            $quantity=$price;
                                        }

    							        if($trade_process->exchange == 1) 
        								{ 
        									  $ticker = ''; 
        									  $total_asset='0';
        									  $balances=binance_balance($key,$secret);
                                              if($balances)
                                              {
                                                    $total_asset=$balances;
                                              }
        								}
        								
        								else if($trade_process->exchange=='5')
        							    {
        							        $send_pair=substr($trade->pair,0,-4);
        							        $account = $userid_bind_process->account;
                                    	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                                    	    $bybitApi = new BybitApi($key, $secret);
                                    	    $total_asset = $bybitApi->getBalance('USDT',$acc_type);
                                    	}
        								
        								$total_asset = str_replace(",",'',$total_asset);
        								echo "<br>";
        								echo $total_asset;
        								echo "<br>";
        								echo $userid[$i].'-'.$quantity;
                                        
                                        if($trade_process->margin_call == '1' && $total_asset >= $quantity) 
        								{
    										$gas_balance = gas_wallet_bal($userid[$i]);
    									    if($gas_balance>=$min_gas_required)
    										{
    											$buy_done = $this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair,$description);
    										}
    										else
    										{
    											$message="Gas wallet fuel insufficent for order buy";
    										     $this->notify1($userid[$i],$trade_process->id,$message);
    
    										}
    											$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
    								    {
    								        //$api_trade_data_update = array('trade_log' => '3','trade_status' => '0');
    								        //$this->db->table('trade_process')->set($api_trade_datas)->where("id",$trade_process->id)->update();
                                            //$message="Insufficent USDT Balance low on quantity buy for quantity:".$quantity."asset only balance for".$total_asset;
    										$message="Margin call stopped on order execution..";
    										$this->notify($userid[$i],$trade_process->id,$message);
    								    }
                                    }
							    }
							    else
							    {
							        echo 'exit';
							    }
                           
							}
							else
							{
							    //echo 'w';

								    $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;
								echo $old_price;
							}
								//if($buy_done)
						}
						if($call_value=='0')
						{
						   // echo 'call limit execeeded';
						   
						   
						   		$trade_where = array(
								'uuserid' => $userid[$i],
								'type' => '1',
								'trade_close' => 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;
					    	
					    
					    	/*buy records*/
					    	
					       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);
							    $max_increase_price = sprintf('%.8f', floatval($max_increase_price));
                                $max_down_price = sprintf('%.8f', floatval($max_down_price));
						        echo"<pre>";
    							print_r("MAX ".$max_increase_price);
    							print_r("LIVE PRICE ".$live_price);
    							print_r("MAX DOWN  ".$max_down_price);
    							echo"</pre>";
							    $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_increase_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>";
                                if($trade->flag == 1) 
                                {
                                    $trade_where = array(
									'uuserid' => $userid[$i],
									'type' => '1',
									'trade_close' => 0,
									'trade_process_id' => $trade_process->id,
								    );
							
    								$trade_where2 = array(
    									'trade_process_id' => $trade_process->id,
    									'uuserid' => $userid[$i],
    									'type' => '2',
    									'description' => 'manual_sell',
    									'status' => 0
    								);

                               	    $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where)->orderBy('id','DESC')->get()->getRow();
								    $total_sell_amount = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where2)->get()->getRow();
								    if($total_sell_amount->received_amount == "")
									    $total_sell_amount->received_amount = 0;
                                    //$total_position_amount = $total_position_amount1->received_amount - $total_sell_amount->received_amount;
								    $total_position_amount=$total_position_amount1->received_amount;
								    
								    $CQuantity = $total_position_amount * 0.1/100;
                                    $total_position_amount = $total_position_amount - $CQuantity;
                                    
                        
								    $quantity = number_format($total_position_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
								    echo"<pre>";
    								print_r("MAX ".$max_increase_price);
    								print_r("LIVE PRICE ".$live_price);
    								print_r("MAX DOWN  ".$max_down_price);
    								echo"</pre>";
								    // exit();
								    if($trade_process->exchange == 1) 
								    {    
									    $ticker = ''; // Make sure you have an updated ticker object for this to work
									    //$balances = $api->balances($ticker);
    									/*echo substr($trade->pair,0,-4);
    				  					$total_asset = $balances[substr($trade->pair,0,-4)]['available'];
    									$total_asset = str_replace(",",'',$total_asset);*/
									
    									$send_pair=substr($trade->pair,0,-4);
    									$total_asset='0';
    									$balances=binance_balance1($key,$secret,$send_pair);
                                        if($balances)
                                        {
                                            $total_asset=$balances;
                                        }
    								
								    }
								    
								    else if($trade_process->exchange=='5')
								    {
								        $send_pair=substr($trade->pair,0,-4);
								        $account = $userid_bind_process->account;
                                	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                                	    $bybitApi = new BybitApi($key, $secret);
                                	    $total_asset = $bybitApi->getBalance($send_pair,$acc_type);
                                	    
								        
								    }
							        $quantity = str_replace(',', '', $quantity);
                                    $total_asset = str_replace(",",'',$total_asset);
								    if($total_asset < $quantity)
								    {
									    if($trade_process->pair == "BNBUSDT")
										    $quantity_fee = $total_asset * ( 0.65 / 100 );
									    else
										    $quantity_fee = $total_asset * ( 0.1 / 100 );
										
										$quantity_fee=number_format($quantity_fee,8);
										$quantity_los = $total_asset - $quantity_fee;
									} 

								    if($total_asset < $quantity)
								    {
									    $quantity = $total_asset;
								    }
								
							
                                    echo"<pre>";
                                    print_r("total asset ".$total_asset);
                                    print_r("quantity ".$quantity);
                                    echo"</pre>";
								    echo"xh:". $trade_process->exchange;
    								echo "sell_limit =>".$trade->sell_limit;
    								echo "live_price =>".$live_price;
								
						
    								if($trade->sell_limit == $live_price)
    								{
    								   
    									if(!empty($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))
    									{
                                            $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))
								                $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) )
								                $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;
							}
						}

					    	/*buy records*/
					    	
					    	
					    	
						    
						}
						
					}
					else if($last_buy->type == 2 && $last_buy->description != 'manual_sell')
					{
			
                        echo 'last_buy:2';
						if($trade_process->open_position_doubled != 'on' || $trade_process->open_position_doubled == ''){
								$quantity = 1;
						}
						else
						{
								$quantity = 2;
						}
						        //$quantity='1';
								$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>";
		

								if($trade_process->exchange == 1) 
								{ 
									  $ticker = '';
									  $total_asset='0';
									  $balances=binance_balance($key,$secret);
                                      if($balances)
                                      {
                                            $total_asset=$balances;
                                      }
								}
								else if($trade_process->exchange=='5')
							    {
							        $send_pair=substr($trade->pair,0,-4);
							        $account = $userid_bind_process->account;
                            	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                            	    $bybitApi = new BybitApi($key, $secret);
                            	    $total_asset = $bybitApi->getBalance('USDT',$acc_type);
                            	    
							        
							    }
							
								$k = "";
								$description = "";

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

								if($total_asset >= $quantity)
								{
									$gas_balance = gas_wallet_bal($userid[$i]);
									if($gas_balance>=$min_gas_required)
									{
										$buy_result = $this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair,$description);
									}
									else
									{
										$message="Gas wallet fuel insufficent for order buy";
									
										$this->notify1($userid[$i],$trade_process->id,$message);
									}
								}
								else
								{
								    
								    $api_trade_data_update = array('trade_log' => '3','trade_status' => '0');
								    $this->db->table('trade_process')->set($api_trade_datas)->where("id",$trade_process->id)->update();
                                    $message="Insufficent USDT Balance low on quantity buy for quantity:".$quantity."asset only balance for".$total_asset;
                                    //$message="Binance API Balance Retrive Down for maintance..revert back shortly";
									$this->notify($userid[$i],$trade_process->id,$message);
								}
										
								$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
				{
				   
                        echo 'last_buy:3';
                        
				        if($last_buy->type == 2 && $last_buy->description != 'manual_sell') 
				        {  //after take profit call market up buyincallback call

		  			    	if($trade_process->open_position_doubled != 'on' || $trade_process->open_position_doubled == '')
								$quantity = 1;
						    else
								$quantity = 2;
								
								//$quantity='1';
								
								$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();

								if($trade_process->exchange == 1) 
								{ 
									$ticker = ''; // Make sure you have an updated ticker object for this to work
									//$balances = $api->balances($ticker);
									//$total_asset = $balances['USDT']['available'];
									$total_asset='0';
								    $balances=binance_balance($key,$secret);
                                    if($balances)
                                    {
                                        $total_asset=$balances;
                                    }
								}
								else if($trade_process->exchange=='5')
							    {
							        $send_pair=substr($trade->pair,0,-4);
							        $account = $userid_bind_process->account;
                            	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                            	    $bybitApi = new BybitApi($key, $secret);
                            	    $total_asset = $bybitApi->getBalance('USDT',$acc_type);
                            	}
							
								echo"<pre>";
								print_r("profit buy");
								echo"</pre>";
								$total_asset = str_replace(",",'',$total_asset);
								$k = "";
								$description = "";
								if($total_asset >= $quantity)
								{

									$gas_balance = gas_wallet_bal($userid[$i]);
									if($gas_balance>=$min_gas_required)
									{
										$buy_result = $this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair,$description);
									}
									else
									{
										$message="Gas wallet fuel insufficent for order buy";
									    //$message="Binance API Balance Retrive Down for maintance..revert back shortly";
										$this->notify1($userid[$i],$trade_process->id,$message);
									}
								}
								else 
								{
									//$message="Insufficent USDT Balance low on quantity buy";
									//$message="Binance API Balance Retrive Down for maintance..revert back shortly";
									
									$api_trade_data_update = array('trade_log' => '3','trade_status' => '0');
							        $this->db->table('trade_process')->set($api_trade_datas)->where("id",$trade_process->id)->update();
                                    $message="Insufficent USDT Balance low on quantity buy for quantity:".$quantity."asset only balance for".$total_asset;
										
									$this->notify($userid[$i],$trade_process->id,$message);
								}
								$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',
								'trade_close' => 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;
                            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);
							    $max_increase_price = sprintf('%.8f', floatval($max_increase_price));
                                $max_down_price = sprintf('%.8f', floatval($max_down_price));
						        echo"<pre>";
    							print_r("MAX ".$max_increase_price);
    							print_r("LIVE PRICE ".$live_price);
    							print_r("MAX DOWN  ".$max_down_price);
    							echo"</pre>";
							    $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_increase_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>";
                                if($trade->flag == 1) 
                                {
                                    $trade_where = array(
									'uuserid' => $userid[$i],
									'type' => '1',
									'trade_close' => 0,
									'trade_process_id' => $trade_process->id,
								    );
							
    								$trade_where2 = array(
    									'trade_process_id' => $trade_process->id,
    									'uuserid' => $userid[$i],
    									'type' => '2',
    									'description' => 'manual_sell',
    									'status' => 0
    								);

                               	    $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where)->orderBy('id','DESC')->get()->getRow();
								    $total_sell_amount = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where2)->get()->getRow();
								    if($total_sell_amount->received_amount == "")
									    $total_sell_amount->received_amount = 0;
                                    //$total_position_amount = $total_position_amount1->received_amount - $total_sell_amount->received_amount;
								    $total_position_amount=$total_position_amount1->received_amount;
								    
								    $CQuantity = $total_position_amount * 0.1/100;
                                    $total_position_amount = $total_position_amount - $CQuantity;
                        
								    $quantity = number_format($total_position_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
								    echo"<pre>";
    								print_r("MAX ".$max_increase_price);
    								print_r("LIVE PRICE ".$live_price);
    								print_r("MAX DOWN  ".$max_down_price);
    								echo"</pre>";
								    // exit();
								    if($trade_process->exchange == 1) 
								    {    
									    $ticker = ''; // Make sure you have an updated ticker object for this to work
									    //$balances = $api->balances($ticker);
    									/*echo substr($trade->pair,0,-4);
    				  					$total_asset = $balances[substr($trade->pair,0,-4)]['available'];
    									$total_asset = str_replace(",",'',$total_asset);*/
									
    									$send_pair=substr($trade->pair,0,-4);
    									$total_asset='0';
    									$balances=binance_balance1($key,$secret,$send_pair);
                                        if($balances)
                                        {
                                            $total_asset=$balances;
                                        }
    								
								    }
								    else if($trade_process->exchange=='5')
								    {
								        $send_pair=substr($trade->pair,0,-4);
								        $account = $userid_bind_process->account;
                                	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                                	    $bybitApi = new BybitApi($key, $secret);
                                	    $total_asset = $bybitApi->getBalance($send_pair,$acc_type);
                                	    
								        
								    }
							        $quantity = str_replace(',', '', $quantity);
                                    $total_asset = str_replace(",",'',$total_asset);
								    if($total_asset < $quantity)
								    {
									    if($trade_process->pair == "BNBUSDT")
										    $quantity_fee = $total_asset * ( 0.65 / 100 );
									    else
										    $quantity_fee = $total_asset * ( 0.1 / 100 );
										
										$quantity_fee=number_format($quantity_fee,8);
										$quantity_los = $total_asset - $quantity_fee;
									} 

								    if($total_asset < $quantity)
								    {
									    $quantity = $total_asset;
								    }
								
							
                                    echo"<pre>";
                                    print_r("total asset ".$total_asset);
                                    print_r("quantity ".$quantity);
                                    echo"</pre>";
                                    
                                    echo "exchange:".$trade_process->exchange;
								
    								echo "sell_limit =>".$trade->sell_limit;
    								echo "live_price =>".$live_price;
								
						
    								if($trade->sell_limit == $live_price)
    								{
    								   
    									if(!empty($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))
    									{
                                            $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))
								                $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) )
								                $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);
		$trade_process = $this->db->table('trade_process')->where('uusersid',$userid)->where('trade_status','1')->where('id',$trade_process_id)->get()->getRow();
		if($trade_process->exchange == 1) 
		{ 
		    $flags['isQuoteOrder'] = true;
            $quantity = str_replace(',', '', $quantity);
			$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid)->where('type','1')->get()->getRow();
    		$key = $userid_bind_process->api_key;	
    		$secret = $userid_bind_process->secret_key;	
		    //$order=binance_buy($key,$secret,$pair,$quantity,$flags);
            $order=binance_order($key,$secret,"BUY", $pair, $quantity, 0,"MARKET",$flags);
            $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,
			'date' => date('Y-m-d',time()),
			'description' => $description,
			'strategy_mode' => $trade_process->strategy_mode,
			'strategy_type' =>$trade_process->strategy_type,
			'exchange' => $trade_process->exchange,
			'status' => 0,
		    );
	}
	else if($trade_process->exchange == 5)
	{
	    
	        $get_response=$this->db->query("select * from bybit_orders where type='1' and status='0' and mode!='first_buy'")->getRow();
	        if(empty($get_response))
	        {
    	        echo "margin_call:".$margin_call_drops;
        	    $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$userid."' and type='5'");
            	$ref=$referral1->getRow();
            	$key = $ref->api_key;
            	$secret = $ref->secret_key;
            	$account = $ref->account;
            	$acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
            	$bybitApi = new BybitApi($key, $secret);
    	        $quantity = str_replace(',', '', $quantity);
    	    	$orderlinkid = "ByBit_".rand(11111111,99999999);
    			$other = ['orderLinkId' => $orderlinkid]; // User customised order ID. A max of 36 characters. Combinations of numbers, letters (upper and lower cases), dashes, and underscores are supported. it will be returned .
    		
    			$order = $bybitApi->order('spot',$pair,'Buy','Market',"$quantity","0",$other,'1');
    			
    		    $orderid = isset($order['result']['orderId']) ? $order['result']['orderId'] : false;
    		    
            	if($orderid)
    			{
    			   
    			    	$order_det = array(
    					'orderid' => $orderid,
    					'uusersid'=> $userid,
    					'type' => '1',
    					'trade_process_id'  => $trade_process->id,
    					'status' => '0',
    					'mode'=> $margin_call_drops
    			    	);
    				    $this->db->table('bybit_orders')->insert($order_det);
    			}
	        }
	    
	    
	}
	else if($trade_process->exchange == 2)
	{
        	$new = substr_replace( $pair, '-', -4, 0 );
			$order_check=$api->trade()->postOrder([
		        'instId'=> $new,
		        'tdMode'=>'cash',
		        'side'=>'buy',
		        'ordType'=>'market',
		        'sz'=> $quantity
		    ]);

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

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

		

			echo"<pre>";
			print_r($order);
			echo"</pre>";
    		$order = $order['data'][0];
            $order_history = array(
			'pair' => str_replace('-', '', $order['instId']),
			'order_id' => $order['ordId'],
			'trade_process_id' => $trade_process_id,
			'uuserid' => $userid,
			'type' => '1',
			'quantity' => $order['sz'],
			'description' => $description,
			'original_quantity' => $quantity,
			'time' => $order['fillTime'],
			'received_amount' => $order['fillSz'] - $order['fee'],
			'live_price' => $order['fillPx'],
			'margin_call_drops' => $margin_call_drops,
			'date' => date('Y-m-d',time()),
			'strategy_mode' => $trade_process->strategy_mode,
			'strategy_type' =>$trade_process->strategy_type,
			'status' => 0,
			'exchange' => $trade_process->exchange
		);
	}
	
		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();
           }



		$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 manual_strategy() {  // manual buy and sell process
            $strategy_users = $this->db->table('api_manual_trade')->select('uuserid')->distinct()->where('status','1')->get()->getResult();
            $userid = array();
				$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();
				       if($trade_process->exchange == 1)
				       {
				    	$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid[$i])->where('type','1')->get()->getRow();
				       }
				       else if($trade_process->exchange == 5)
				       {
					    $userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid[$i])->where('type','5')->get()->getRow();
				       }
				       
	                  if($userid_bind_process && $trade_process && $trade_process->trade_status == '1') 
	                  {
						    $key = $userid_bind_process->api_key;
						    $secret = $userid_bind_process->secret_key;
						    if($trade_process->exchange == 2)
							    $passphrase = $userid_bind_process->pass_phrase;
            				    if($trade_process->exchange == 1)
            				    {
            					    
        						$previous_high_price=candleprice($key,$secret,$trade_process->pair);
        						
        						$live_price='';
            					//$high_price='';
                                foreach ($data_binance as $datas) 
                                {
                                        if ($datas['symbol'] == $trade_process->pair) 
                                        {
                                            $live_price=$datas['lastPrice'];
                                            //$high_price=$datas['closePrice'];
                                           break;   
                                        }
                                }
                                
                                    $live_price=getliveprice($trade_process->pair);
                                 
                                    $live_price=number_format($live_price,9);
                                    $live_price=str_replace(',','',$live_price);
				              }
				              else if($trade_process->exchange=='5')
				              {
				                  $account = $userid_bind_process->account;
                            	  $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                            	  $bybitApi = new BybitApi($key, $secret);
                            	  $tickers = $bybitApi->ticker(['category' => 'linear', 'symbol' => $trade_process->pair]); 
                                  $live_price = $tickers['lastPrice'];
				                  
				                  
				              }
			
                             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";

                           	    if($trade_process->exchange == 1) { 
								$ticker =''; // Make sure you have an updated ticker object for this to work
								//$balances = $api->balances($ticker);
								//$total_asset = $balances['USDT']['available'];
								$total_asset=0;
								$balances=binance_balance($key,$secret);
                                if($balances)
                                {
                                    $total_asset=$balances;
                                }
                                
								
								}
								else if($trade_process->exchange == 2)
								{
								       $result_pre =$api->account()->getBalance([
										]);
										$result = $result_pre['data'][0]['details'];
										if(!empty($result)) { 
										foreach ($result as $key => $value) {
										if($value['ccy'] == "USDT"){
										$total_asset = $value['availBal'];
										break;
										}else
										$total_asset = 0;
										}
										}else{
										$total_asset = 0;
										}
								}
								else if($trade_process->exchange=='5')
							    {
							        $send_pair=substr($trade->pair,0,-4);
							        $account = $userid_bind_process->account;
                            	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                            	    $bybitApi = new BybitApi($key, $secret);
                            	    $total_asset = $bybitApi->getBalance('USDT',$acc_type);
                            	}
								$k = "";
                                    $total_asset=str_replace(',','',$total_asset);
									if($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 = "";
            					if($trade_process->exchange == 1) 
            					{ 
								    $ticker = ''; 
				                    
				                    $send_pair=substr($trade_process->pair,0,-4);
									$total_asset='0';
									$balances=binance_balance1($key,$secret,$send_pair);
                                    if($balances)
                                    {
                                        $total_asset=$balances;
                                    }
				            	}
				            	else if($trade_process->exchange=='5')
							    {
							        $send_pair=substr($trade->pair,0,-4);
							        $account = $userid_bind_process->account;
                            	    $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                            	    $bybitApi = new BybitApi($key, $secret);
                            	    $total_asset = $bybitApi->getBalance($send_pair,$acc_type);
                            	}
							
								$k = "";
								$quantity = str_replace(',', '', $quantity);
								

                                if($total_asset < $quantity){
                                	$quantity = $total_asset;
                                }

									if($quantity > 0)
									{
										$result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records,$description,$manual_sell->flag);
										if($result){
											$buy_record_update = $this->db->table('api_manual_trade')->set('status','2')->where("id",$manual_sell->id)->update();
											if($manual_sell->flag == 1)
												$buy_record_update = $this->db->table('api_trade_history')->set('status','1')->where($trade_where)->update();
										}
									}

								}	

                           }

				       }
			    }		
			 }   
		}

		public function notify($userid,$trade_process_id,$message)
		{

			$buy_records = $this->db->table('trade_process')->where("id",$trade_process_id)->orderBy('id','DESC')->get()->getRow();
			$pair=$buy_records->pair;

			$api_trade_data = array(
				'trade_log' => '3',
				'trade_status' => '0'
			);

			$trade_update = $this->db->table('trade_process')->set($api_trade_data)->where("id",$trade_process_id)->update();
			
			$notification = array(
				'uusersid' => $userid, 
				'message'  => $message.' for pair:'.$pair,
				'created_date' => date('Y-m-d H:i:s')
			);
			$this->db->table('notification_table')->insert($notification);

		}


		public function notify1($userid,$trade_process_id,$message)
		{

			$buy_records = $this->db->table('trade_process')->where("id",$trade_process_id)->orderBy('id','DESC')->get()->getRow();
			$pair=$buy_records->pair;

			$api_trade_data = array(
				'trade_log' => '2',
				'trade_status' => '0'
				
			  );
			$trade_update = $this->db->table('trade_process')->set($api_trade_data)->where("id",$trade_process_id)->update();

			$notification = array(
				'uusersid' => $userid, 
				'message'  => $message.' for pair:'.$pair,
				'created_date' => date('Y-m-d H:i:s')
			);
			$this->db->table('notification_table')->insert($notification);

		}


		public function marketsell($userid,$trade_process_id,$quantity,$margin_call_drops,$api,$pair)
		{
		    
		    $trade_process = $this->db->table('trade_process')->where('uusersid',$userid)->where('id',$trade_process_id)->get()->getRow();

			$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',
			'strategy_mode' => $trade_process->strategy_mode,
			'strategy_type' =>$trade_process->strategy_type,
			'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 truncate_number( $number, $precision = 2) {
    // Zero causes issues, and no need to truncate
    // if ( 0 == (int)$number ) {
    //     return $number;
    // }
    // Are we negative?
    $negative = $number / abs($number);
    // Cast the number to a positive to solve rounding
    $number = abs($number);
    // Calculate precision number for dividing / multiplying
    $precision = pow(10, $precision);
    // Run the math, re-applying the negative value to ensure returns correctly negative / positive
    return floor( $number * $precision ) / $precision * $negative;
}

public function bybit_sells($userid)
{
     $db = db_connect();
	 $admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
	 $fuel_fee_percent = $admin_settings->min_fuel_fee;
	 $uusersid=$userid;
	 
	 $get_order=$this->db->query("select * from bybit_orders where uusersid='".$uusersid."' and status='0'")->getResult();
     if($get_order)
     {
         
         foreach($get_order as $order_info)
         {
           
             $check_record=$this->db->query("select * from  api_trade_history where order_id='".$order_info->orderid."'")->getRow();
             if(empty($check_record))
             {
                 $type=$order_info->type;
                 $tradeid=$order_info->trade_process_id;
                 $orderid=$order_info->orderid;
                 $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='5'");
            	 $ref=$referral1->getRow();
            	 $key = $ref->api_key;
            	 $secret = $ref->secret_key;
            	 $account = $ref->account;
            	 $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
            	 $bybitApi = new BybitApi($key, $secret);
            	 $order_det = $bybitApi->GetOrders(['category' => 'spot','orderId' => $orderid]);
            	
                 $qry_new = $this->db->query("SELECT * FROM trade_process WHERE id='".$tradeid."'")->getRowArray();
                 if($type=='1')
                 {
            
            	    if(isset($order_det['result']['list']) && !empty($order_det['result']['list']))
            	    {
        			    $history = $order_det['result']['list'][0];
            			    $order_history = array(
            				'pair' => $qry_new['pair'],
            				'order_id' => $orderid,
            				'trade_process_id' => $qry_new['id'],
            				'uuserid' => $qry_new['uusersid'],
            				'type' => '1',
            				'strategy_mode' => $qry_new['strategy_mode'],
            				'strategy_type' => $qry_new['strategy_type'],
            				'quantity' => $history['cumExecValue'],
            				'original_quantity' => $history['qty'],
            				'time' => $history['createdTime'],
            				'received_amount' => $history['cumExecQty'],
            				'date' => date('Y-m-d',time()),
            				'description'=>$order_info->mode,
            				'margin_call_drops'=>$order_info->mode,
            				'live_price' => $history['avgPrice'],
            				'exchange'  => $qry_new['exchange'],
            				'status' => 0
            			);
        			
            			$this->db = db_connect();
                		$this->db->table('api_trade_history')->insert($order_history);
            	        $sell_record_update = $this->db->table('bybit_orders')->set('status','1')->where("id",$order_info->id)->update();
             
                    }
                 }
                 else
                 {
                    $order = $order_det['result']['list'][0];
                    $pos_qty = $order['cumExecValue'];
                    $res_qty = $order['cumExecQty'];
                    $time= $order['updatedTime'];
                    $price=$order['avgPrice'];
                    $trade_process = $this->db->query("SELECT * FROM trade_process WHERE id='".$tradeid."'")->getRow();
                    
                    /*$total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process->id)->where("trade_close",'2')->orderBy('id','DESC')->get()->getRow();
                    $total_position_amount=$total_position_amount1->quantity;
                    $sell_quantity=$pos_qty;*/
                    
                    
                    if($order_info->mode=='close_trade')
                    {
                        $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process->id)->where("trade_close",'2')->orderBy('id','DESC')->get()->getRow();
                        $total_position_amount=$total_position_amount1->quantity;
                        $sell_quantity=$pos_qty;
                        if($sell_quantity > $total_position_amount)
                    	{
                    		$profit=$sell_quantity-$total_position_amount;
                    	}
                    	else
                    	{
                    	    $profit=$sell_quantity-$total_position_amount;
                    	}
                    	
                    	 if($total_position_amount > 0)
                            $profit_percentage=($profit/$total_position_amount)*100;
                        else
                            $profit_percentage='0';
                            
                    }
                    else
                    {
                        $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('received_amount')->where("trade_process_id",$trade_process->id)->where("trade_close",'0')->where('type','1')->orderBy('id','DESC')->get()->getRow();
                        $total_position_amount1=$total_position_amount1->received_amount;
                        
                        
                        $total_position_amount2 = $this->db->table('api_trade_history')->selectSum('received_amount')->where("trade_process_id",$trade_process->id)->where("description",'manual_sell')->where('type','2')->orderBy('id','DESC')->get()->getRow();
                        $total_position_amount2=$total_position_amount2->received_amount;
                        
                        $total_position_amount= $total_position_amount1-$total_position_amount2;
                        
                        $CQuantity = $total_position_amount * 0.1/100;
                        $total_position_amount = $total_position_amount - $CQuantity;
                        
                        
                        if($order_info->exe_per=='quarter')
                        {
                            $per='25';
                        }
                        else if($order_info->exe_per='half')
                        {
                            $per='50';
                        }
                        else if($order_info->exe_per='onebuythree')
                        {
                            $per='75';
                        }
                        else
                        {
                            $per='100';
                        }
                        
                        $get_percentage_amount=$total_position_amount * $per/100;
                        
                        $original_quantity=$get_percentage_amount * $order_info->avg_price;
                        
                        $sell_quantity=$pos_qty;
                        
                       
                        if($sell_quantity > $original_quantity)
                    	{
                    		$profit=$sell_quantity-$original_quantity;
                    	}
                    	else
                    	{
                    	    $profit=$sell_quantity-$original_quantity;
                    	} 
                       
                       
                        
                        $profit_percentage=($profit/$original_quantity)*100;
                        
                    }
                    
                    $profit=number_format($profit,4);
                    $profit_percentage=number_format($profit_percentage,4);
                    
                    $fuel_fee = $profit * ($fuel_fee_percent / 100);
                    $status=1;
                	  $order_history = array(
                        'pair' => $trade_process->pair,
                    	'order_id' => $orderid,
                    	'trade_process_id' => $trade_process->id,
                    	'uuserid' => $trade_process->uusersid,
                    	'type' => '2',
                    	'quantity' => $pos_qty,
                    	'original_quantity' => $pos_qty,
                    	'time' => $time,
                    	'received_amount' => $res_qty,
                    	'description'=>$order_info->mode,
                    	'date' => date('Y-m-d',time()),
                    	'flag' => $status,
                    	'live_price' => $price,
                    	'comm_price' => $profit,
                        'profit_percentage' => $profit_percentage,
                    	'strategy_mode' => $trade_process->strategy_mode,
                        'strategy_type' => $trade_process->strategy_type,
                    	'exchange' => $trade_process->exchange,
                    	'status' => 0
                        );
                        
                        
                        $this->db->table('api_trade_history')->insert($order_history);
                        $sell_record_update = $this->db->table('bybit_orders')->set('status','1')->where("id",$order_info->id)->update();
                        
                       // echo $this->db->last_query();
                 
                        
                        if($order_info->mode!='manual_sell')
                        {
                              $sell_record_update = $this->db->table('api_trade_history')->set('trade_close','1')->where('trade_close','2')->where("trade_process_id",$trade_process->id)->update();
                        }
                      
                        
                        if($order_info->mode=='close_trade')
                        {
                            $sell_record_update = $this->db->table('api_trade_history')->set('trade_close','1')->where('trade_close','2')->where("trade_process_id",$trade_process->id)->update();
                            $sell_record_update = $this->db->table('trade_process')->set('trade_status','2')->where("id",$trade_process->id)->update();
                            
                        }
                        
                    	if($fuel_fee> 0)
                    	{
                            $deposit_data = array(           // fuel fee deduction
                            'uusersid' => $trade_process->uusersid,
                            'amount'  => $fuel_fee,
                            'depositid' => $this->db->InsertID(),
                            'type'  => 'deducted_gaswallet', 
                            'description'  => 'fuel fee deduction for order no '.$orderid,
                            'date'  => date('Y-m-d H:i:s'),
                            'currency' => 1,
                            'transactionid' => $trade_process->id
                            );
                    		$this->db->table('history')->insert($deposit_data); 
                        
                    	}
     
                 }
                 
                 
             }
         }
     }
	 
    
}

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


        print_r("userid".$userid);
		print_r("sell pair".$pair);
		print_r("sell amount".$quantity);
        echo "<br>";
	    $quantity = str_replace(',', '', $quantity);
	     $trade_process = $this->db->table('trade_process')->where('uusersid',$userid)->where('trade_status','1')->where('id',$trade_process_id)->get()->getRow();
	     
	     print_r($trade_process);
	     
	        
	         if($trade_process->exchange=='5')
	         {
	            
	             $userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid)->where('type',$trade_process->exchange)->get()->getRow();
        		 $api_key = $userid_bind_process->api_key;	
        		 $api_secret = $userid_bind_process->secret_key;	
		         $account = $userid_bind_process->account;
                 $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
                 $bybitApi = new BybitApi($api_key, $api_secret);
		         $orderlinkid = "ByBit_".rand(11111111,99999999);
		         $other = ['orderLinkId' => $orderlinkid]; // User customised order ID. A max of 36 characters. Combinations of numbers, letters (upper and lower cases), dashes, and underscores are supported. it will be returned .
		         $params=['category' => 'spot', 'symbol' => $pair];
		         $exchange_info=$bybitApi->getMarketInfo($params);
	             $lotSizeFilter=$exchange_info['lotSizeFilter'];
	             $basePrecision  =$lotSizeFilter['basePrecision'];
                 $quotePrecision =$lotSizeFilter['quotePrecision'];
                 $minOrderQty    = $lotSizeFilter['minOrderQty'];
                 $maxOrderQty    = $lotSizeFilter['maxOrderQty'];
                 $minOrderAmt    = $lotSizeFilter['minOrderAmt'];
                 $maxOrderAmt   = $lotSizeFilter['maxOrderAmt'];
                 $decimal_digits = getDecimalDigits($basePrecision);
                 $quantity=number_format($quantity,$decimal_digits);
                 $quantity=str_replace(',','',$quantity);
                 
                 $get_response=$this->db->query("select * from bybit_orders where trade_process_id='".$trade_process->id."' and type='2' and status='0'")->getRow();
                if(empty($get_response))
                {
                    $order = $bybitApi->order('spot',$pair,'SELL','Market',"$quantity","0",$other,'2');
                    $orderid = isset($order['result']['orderId']) ? $order['result']['orderId'] : false;
                }
		         
		         if(empty($orderid))
		         {
		             $ret_msg=$order['retMsg'];
		             if($ret_msg=='Insufficient balance.')
		             {
		                  if($trade_process->pair == "BNBUSDT")
                            $quantity_fee = $quantity * ( 0.65 / 100 );
                          else
                            $quantity_fee = $quantity * ( 0.1 / 100 );
                         
                           $quantity=$quantity-$quantity_fee;
                           $quantity=number_format($quantity,$decimal_digits);
                          $quantity=str_replace(',','',$quantity);
                         
                         $order = $bybitApi->order('spot',$pair,'SELL','Market',"$quantity","0",$other,'2');
                 
                         $orderid = isset($order['result']['orderId']) ? $order['result']['orderId'] : false;
                     }
		             
		         }
		         
		         if($orderid)
		         {
	             
	             	$order_det = array(
							'orderid' => $orderid,
							'uusersid'=> $userid,
							'type' => '2',
							'trade_process_id'  => $trade_process_id,
							'status' => '0'
					    	);
				    $this->db->table('bybit_orders')->insert($order_det);
				    $sell_record_update = $this->db->table('api_trade_history')->set('trade_close','2')->where('trade_close','0')->where("trade_process_id",$trade_process_id)->update();
				     
				    
		        }
	             
	         }
	         else if($trade_process->exchange == 1) 
			 { 
					//$exchange_info = $api->exchangeInfo();
					
					$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid)->get()->getRow();
					
    				$api_key = $userid_bind_process->api_key;	
    				$api_secret = $userid_bind_process->secret_key;	
    				
    				 $exchange_info=binance_exchangeinfo($api_key);
		
			   
			  
                    $filters='';
    				foreach($exchange_info as $key => $value) 
    				{
    				   
    					if($value['symbol']==$pair)
    					{
    						 $filters=$value['filters'];
    						    break;
    					}
    				}
				
    				$lotSizeFilter = null;
                    foreach ($filters as $filter) {
                      //  print_r($filter);
                        if ($filter['filterType'] === 'LOT_SIZE') {
                            $lotSizeFilter = $filter;
                            break;
                        }
                    }
                    
					$minQty = $lotSizeFilter['minQty'];
                    $maxQty = $lotSizeFilter['maxQty'];
                    $stepsize = $lotSizeFilter['stepSize'];
                        
                    $stepsize1 = fmod($stepsize, 1);
					$total_no = str_replace('.', '', $stepsize1);
					$count = strlen($total_no);

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

                    echo $pair;
                    echo "<br>";
                    echo $quantity;
                    echo "<br>";
                    
			    	//$order = $api->sell($pair,$quantity,0,"MARKET");
			    	//$order=binance_sell($key,$secret,$pair,$quantity,"MARKET");
			    	$order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
			    	
			
					if(empty($order['orderId'])) 
					{
						$quantity = $this->truncate_number($quantity,$current); 
						$quantity = str_replace(',', '', $quantity);
						//$order = $api->sell($pair,$quantity,0,"MARKET");
						//$order=binance_sell($key,$secret,$pair,$quantity,"MARKET");
						$order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
						
					}
				}
				else if($trade_process->exchange == 2)
				{
					$new = substr_replace( $pair, '-', -4, 0 );
					$order_check=$api->trade()->postOrder([
					'instId'=> $new,
					'tdMode'=>'cash',
					'side'=>'sell',
					'ordType'=>'market',
					'sz'=> $quantity
					]);

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

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

		

					echo"<pre>";
					print_r($order);
					echo"</pre>";
					$order = $order['data'][0];
					$ticker =  $api->market()->getTicker([
					'instId'=> $order['instId'].'-SWAP',
					]);
					if(empty($ticker['data']) || $ticker['code'] == 51001){
					$result_okex=$api->market()->getTickers([
					'instType'=>'SPOT',
				]);
				
				if($result_okex['data'])
				{
					foreach ($result_okex['data'] as $key => $value) {
						if($value['instId'] == $order['instId']){
						$ticker = $value;
						break;
						}
          			}
      				$live_price = $ticker['last'];
        		}
				}
				else
				{
					$live_price = $ticker['data'][0]['last'];
				}
				$position_quantity_pre = $order['sz'] * $live_price;
				$position_quantity = $position_quantity_pre - $order['fee'];

			}

			echo"<pre>";
			print_r("stepsize");
			echo "<br>";
			print_r($current);
			echo "<br>";
			print_r($quantity);
			echo"</pre>";

			echo"<pre>";
			print_r($quantity);
			echo"</pre>";
			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();
			
			}

	     $db = db_connect();
		 $admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
		 $fuel_fee_percent = $admin_settings->min_fuel_fee;
		 $total_avg_price = $avg_price->quantity;
		 
		 echo $total_avg_price;
		 
		 if($avg_price=='')
		    $avg_price=$total_avg_price;
	
        
		if($trade_process->exchange == 1)
		{
		    
		
		    $position_quantity=$quantity;
	         if($subsell_status != 1)
		     $avg_price1 = $position_quantity - $total_avg_price; 
		     else
		     $avg_price1 = $position_quantity - $total_avg_price;

			$orderid = $order['orderId'];
			$pos_qty = $order['cummulativeQuoteQty'];
			$time_order = $order['transactTime'];
			$res_qty = $order['executedQty'];

            $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process_id)->where("trade_close",'0')->orderBy('id','DESC')->get()->getRow();
    
            $total_position_amount=$total_position_amount1->quantity;
            
            echo "total_position_amount  =>" .$total_position_amount;
            
    		$sell_quantity=$pos_qty;
    		
    		
    		echo "Sell Quantity =>" .$sell_quantity;
    
    		$fuel_loss=0;
    		if($sell_quantity > $total_position_amount)
    		{
    			$profit=$sell_quantity-$total_position_amount;
    			
    		}
    		else
    		{
    			$profit=$sell_quantity- $total_position_amount;
    		}
    
    		$profit_percentage=($profit/$total_position_amount)*100;
    
    		$fuel_fee = $profit * ($fuel_fee_percent / 100);
    
           
        	if($orderid > 0)
        	{
    		$order_history = array(
    			'pair' => $pair,
    			'order_id' => $orderid,
    			'trade_process_id' => $trade_process_id,
    			'uuserid' => $userid,
    			'type' => '2',
    			'quantity' => $pos_qty,
    			' original_quantity' => $pos_qty,
    			'time' => $time_order,
    			'received_amount' => $res_qty,
    			'live_price' => $stopPrice,
    			'avg_price' => $avg_price1,
    			'comm_price' => $profit,
    			'profit_percentage' => $profit_percentage,
    			'description' => $description,
    			'date' => date('Y-m-d',time()),
    			'strategy_mode' => $trade_process->strategy_mode,
    			'strategy_type' => $trade_process->strategy_type,
    			'flag' => $flag ? $flag : 0,
    			'status' => 0,
    			'exchange' => $trade_process->exchange
    		);
        	$this->db->table('api_trade_history')->insert($order_history);
    	
        	if($fuel_fee > 0)
        	{
                $deposit_data = array(           // fuel fee deduction
                'uusersid' => $userid,
                'amount'  => $fuel_fee,
                'depositid' => $this->db->InsertID(),
                'type'  => 'deducted_gaswallet', 
                'description'  => 'fuel fee deduction for order no '.$orderid,
                'date'  => date('Y-m-d H:i:s'),
                'currency' => 1,
                'transactionid' => $trade_process_id
                );
        		$this->db->table('history')->insert($deposit_data); 
        	}
    	
    	  }
    	  
    	  $sell_record_update = $this->db->table('api_trade_history')->set('trade_close','1')->where('trade_close','0')->where("trade_process_id",$trade_process_id)->update();
    	}
		$return = true;
	}
	else
	{
		/*$duplicate_check = $this->db->table('notification_table')->where('uusersid',$userid)->like('message','Binance '.$pair)->like('created_date',date('Y-m-d'))->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;
	}

}
?>