<?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 Strategythird extends Model {

		public function __construct(){
			$this->db = \Config\Database::connect();


			$this->common_model = model('CommonModel');
		}

		public function index(){

		}


		public function third_strategy(){

			$third_strategy_users = $this->db->table('trade_process')->select('uusersid')->where('strategy_mode','3')->distinct()->where('trade_status','1')->get()->getResult();

			if ($third_strategy_users) {
				
				$i=0;
				foreach ($third_strategy_users as $key => $value) {
					$userid[$i] = $value->uusersid;
					$i++;
				}

				$userid[0] = 158;

				// $userid = explode(',', $userid);

				// $userid = array_filter($userid);

				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','3')->get()->getResult();

					echo"<pre>";
					print_r($userid_bind_process);
					print_r($trade_process_array);
					echo"</pre>";
					

					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;

					$live_price =  $ticker[$trade_process->pair];
					// $live_price = '398';
					print_r($last_buy_live_price);
					echo "<br>";
					print_r($live_price);
					// exit();

					if ($last_buy_live_price > $live_price) {


						$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);
						// echo '<br>';
						// print_r(count($exploded));
						// exit();

						$old_price = '';

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

							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
							);
							// echo "<br>";
							// print_r($k);
							// echo '<br>';
							//exit();


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

							if (!$call_drop) {

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

								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;

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

									if ($trade_process->margin_call == '1' ) {
										$this->marketbuy($userid[$i],$trade_process->id,$quantity,$k,$api,$trade_process->pair);
									}

									$call_drop_where = 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_where)->get()->getRow();
								$old_price = $call_drop->live_price;

								}

							}else{

								$call_drop_where = 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_where)->get()->getRow();

								$old_price = $call_drop->live_price;
							}
						}
					}else{
						$margins = ['NULL','1','2','3','4'];
						
						$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)->whereIn('margin_call_drops',$margins)->orderBy('id','DESC')->get()->getRow();

						echo"<pre>";
						print_r($buy_records);
						echo "\n";
						echo"</pre>";
// Full warehouse part split (Margin call 1 to 4)
						if ($buy_records->live_price > 0  && $buy_records != '' && 0) {

							$avg_price = $buy_records->live_price * $trade_process->whole_profit_ratio / 100;

							$max_increase_price = $buy_records->live_price + $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("MAX DOWN  ".$max_down_price);
								echo"</pre>";
                            
                            if ($live_price >= $max_increase_price) {
                            	$sell_record_update = $this->db->table('trade_process')->set('flag','1')->where("id",$trade_process->id)->update();
                            }


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

                        

							//$live_price = $max_increase_price;
							if ($trade->flag == 1) {

								$buyed_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where)->whereIn('margin_call_drops',$margins)->orderBy('id','DESC')->get()->getRow();
								
								$trade_where = array(
									'uuserid' => $userid[$i],
									'type' => '1',
									'status' => 0,
									'trade_process_id' => $trade_process->id,
								);

							

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

								if($max_down_price == $live_price){
								$result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records->live_price,0);
								} else if($live_price > $avg_price && $max_down_price >= $live_price){
								$result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$buy_records->live_price,0);
								}
								

								// $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$stopPrice,$api,$trade_process->pair,$buy_records->live_price);

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

								// check one shot strategy

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

								/// check last 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);

								$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;
							}
						}

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

						$explode = explode(',', $trade_process->sub_position);



						$explode = array_filter($explode);

						$buy_records = $this->db->table('api_trade_history')->where($trade_where)->orderBy('id','ASC')->get()->getResult();
                  
						
// Subbin split (Margin call > 5)

						$l = 0;
						foreach ($buy_records as $key => $value) {
							
							if ($value->live_price > 0) {
								
								$avg_price = $value->live_price * $explode[$l] / 100;

								$max_increase_price = $value->live_price + $avg_price ;

								$max_increase_price = round($max_increase_price,8);

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

								$max_down_price = $max_increase_price - $max_down_percentage;

								$max_down_price = round($max_down_price,8);

								$avg_price = $live_price - $value->live_price;

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


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


								//$live_price = $max_increase_price;
								if ($trade->flag == 1) {

									$quantity = round($value->received_amount,8);
									$price = $max_increase_price; // Try to sell it for 0.5 btc
									$stopPrice = $max_down_price; // Sell immediately if price goes below 0.4 btc
								
									$trade_where = array(
										'uuserid' => $userid[$i],
										'type' => '1',
										'status' => 0,
										'trade_process_id' => $trade_process->id,
										'margin_call_drops' => $value->margin_call_drops,
									);

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

									if($max_down_price == $live_price){
									$result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$avg_price,1);
									} else if($live_price > $value->live_price && $max_down_price >= $live_price){
									$result = $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$live_price,$api,$trade_process->pair,$avg_price,1);
									}
									// $this->take_profit($userid[$i],$trade_process->id,$quantity,$price,$stopPrice,$api,$trade_process->pair,$avg_price);
									if($result){
										$buy_record_update = $this->db->table('api_trade_history')->set('status','1')->where($trade_where)->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();	
									// }
									}
								}

							}

							$l++;

						}
					}
				}
			}
		}
	}

}




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

// 		// print_r($api);
// 		// exit();

// 	$flags['isQuoteOrder'] = true;
// 				// $order = $api->buy("BNBUSDT", "10",0,"MARKET",$flags);
// 				// $order = $api->marketQuoteSell("BNBUSDT", "100",$flags);
// 	$order = $api->marketQuoteBuy($pair, $quantity,$flags);

// 	$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,
// 		'strategy_mode' => $trade_process->strategy_mode,
// 		'status' => 0,
// 	);

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

// 	return true;
// }

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

		// print_r($api);
		// exit();
        if($quantity <= 10){
        	$quantity = 10.3;
        }
		$flags['isQuoteOrder'] = true;
				// $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>";

		$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,
			'strategy_mode' => $trade_process->strategy_mode,
			'status' => 0,
		);

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

		return true;
	}

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);

	return true;

}


	public function take_profit($userid,$trade_process_id,$quantity,$price,$stopPrice,$api,$pair,$avg_price,$subsell_status){
		// $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) { 
        	$buy_record_update = $this->db->table('trade_process')->set('flag','0')->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' => $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_price,
			'margin_call_drops' => '',
			'strategy_mode' => $trade_process->strategy_mode,
			'subsell_status' => $subsell_status,
			'status' => 0,

		);
	

		$this->db->table('api_trade_history')->insert($order_history);
		$return = true;
	}else{
		$return = false;
	}

		return $return;
	}

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

// 	$order = $api->sell($pair, $quantity, $price, "TAKE_PROFIT_LIMIT", ["stopPrice"=>$stopPrice]);

// 	$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' => $pair,
// 		'order_id' => $order['orderId'],
// 		'trade_process_id' => $trade_process_id,
// 		'uuserid' => $userid,
// 		'type' => '2',
// 		'quantity' => $quantity,
// 		' original_quantity' => '',
// 		'time' => $order['transactTime'],
// 		'received_amount' => '',
// 		'live_price' => $stopPrice,
// 		'avg_price' => $avg_price,
// 		'margin_call_drops' => '',
// 		'strategy_mode' => $trade_process->strategy_mode,
// 		'status' => 0,

// 	);

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



// 	return true;
// }

}