<?php

$a = 7;
$b = -2.431;
$c = 5600;
$pair = "DOT_USDT";
$futures_leverage = 3;

$bfpair = str_replace("_","",$pair);
$bfpair = str_replace("USDT","USD",$bfpair);

$longs = file_get_contents("https://api-pub.bitfinex.com/v2/stats1/pos.size:1h:t".$bfpair.":long/hist");
$shorts = file_get_contents("https://api-pub.bitfinex.com/v2/stats1/pos.size:1h:t".$bfpair.":short/hist");
$candles = file_get_contents("https://api-pub.bitfinex.com/v2/candles/trade:1h:t".$bfpair."/hist");
	
$longs_data = json_decode($longs,true);
$shorts_data = json_decode($shorts,true);
$candles_data = json_decode($candles,true);

$data = $longs = $shorts = $opens = $closes = array();
$flong = $fshort = 0;

foreach ($longs_data as $l){
	if (!$flong)$flong = substr($l[0],0,-3);
	$data[substr($l[0],0,-3)]['longs'] = $l[1];
	$longs[] = $l[1];
	$ts[] = substr($l[0],0,-3);
}

foreach ($shorts_data as $s){
	if (!$fshort)$fshort = substr($s[0],0,-3);
	$data[substr($s[0],0,-3)]['shorts'] = $s[1];
	$shorts[] = $s[1];
}

foreach ($candles_data as $cc){
	$data[substr($cc[0],0,-3)]['open'] = $cc[1];
	$data[substr($cc[0],0,-3)]['close'] = $cc[2];
	$opens[] = $cc[1];
	$closes[] = $cc[2];
}

function gateio_query($path, array $req = array(),$method = 'GET') {	
	// API settings, add your Key and Secret at here
	$key = '248dd48b2cd392e1650b4e9785db5fcb';
	$secret = '28ebeb7e0e90f2bad6c01f65dfe5865ba69f86672c7d8a4c1ec7e6adbcd01996';
 
	// generate a nonce to avoid problems with 32bits systems
	$time = time();
 
	// generate the POST data string
	if ($method == 'POST' ){
		//$post_data = http_build_query($req, '', '&');
		$post_data = json_encode($req);
		//echo $post_data;
		$path2 = '';
		$path2f = '';
	}
	else if ($method == 'DELETE'){
		$post_data = http_build_query($req, '', '&');		
		$path2 = '';
		$path2f = '';
	}
	else{
		$post_data = '';
		$path2 = ((count($req)>0)?'':'').http_build_query($req, '', '&');
		$path2f = '?'.$path2;
	}
	
	$sign_str = $method."\n"."/api/v4/".$path."\n".$path2."\n".hash('sha512', ((count($req)>0 && $method == 'POST')?json_encode($req):''))."\n".$time;
	//echo $sign_str;
	//echo json_encode($req);
	$sign = hash_hmac('sha512', $sign_str, $secret);
 
	// generate the extra headers
	$headers = array(
		'KEY: '.$key,
		'SIGN: '.$sign,
		'Timestamp: '.$time		
	);
	
	if ($method == 'POST'){
		$headers[] = 'Content-Type: application/json';
	}

	//!!! please set Content-Type to application/x-www-form-urlencoded if it's not the default value

	// curl handle (initialize if required)
	static $ch = null;
	if (is_null($ch)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 
			'Mozilla/4.0 (compatible; GATEIO PHP bot; '.php_uname('a').'; PHP/'.phpversion().')'
			);
	}
	//TODO meghatározni a legjobb szervert
	//https://api.gateio.ws/api/v4 ?
	
	curl_setopt($ch, CURLOPT_URL, 'https://api.gateio.ws/api/v4/'.$path.$path2f);
	if ($method == 'POST'){
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);		
	}
	else if ($method == 'DELETE'){
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
	}
	else {
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
	}
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

	// run the query
	$res = curl_exec($ch);
	//if ($res === false) throw new Exception('Curl error: '.curl_error($ch));
	//echo $res;
	$dec = json_decode($res, true);
	
	global $query_counter,$time_start,$ratelimit;
	$query_counter++;
	
	//if (!$dec) throw new Exception('Invalid data: '.$res);
	return $dec;
}

function gateio_depth($pair){
    $data = gateio_query("futures/usdt/order_book",array('contract' => $pair));
    foreach ($data['bids'] as &$ba){
		$ba[0] = $ba['p'];
		$ba[1] = $ba['s'];
		unset($ba['p']);
		unset($ba['s']);
	}
	foreach ($data['asks'] as &$ba){
		$ba[0] = $ba['p'];
		$ba[1] = $ba['s'];
		unset($ba['p']);
		unset($ba['s']);
	}
	return $data;
} 

function savelog($text,$prefix='log'){
	global $start_time;
    $fp = fopen($prefix.'.txt', 'a');
    fwrite($fp, date("Y-m-d G:i:s")."[".(microtime(true)-$start_time)."]"." - ".$text."\n");
    fclose($fp);
}

//TODO

$last_ts = file_get_contents("last_ts.txt");
echo $last_ts." < ".$ts[0];
if ($last_ts < $ts[0]){
	$depth = gateio_depth($pair);	
	$last_val = $a*$data[$ts[1]]['longs']+$b*$data[$ts[1]]['shorts'];
	$last_val2 = $a*$data[$ts[2]]['longs']+$b*$data[$ts[2]]['shorts'];

	if ($a*$data[$ts[0]]['longs']+$b*$data[$ts[0]]['shorts'] < $last_val - $c && $last_val > $last_val2){				
		//TODO SELL
		$futures_balance = gateio_query('futures/usdt/accounts');
		$futures_balance['maximum_position'] = floor($futures_balance['total'] * $futures_leverage / $depth['asks'][0][0]);

		
		$futures_positions = gateio_query('futures/usdt/positions');
		$actual_size = 0;
		foreach ($futures_positions as $position){
			$actual_size += $position['size'];
		}  		
		$futures_balance['actual_size'] = $actual_size;

		$amount = $futures_balance['maximum_position'] + $futures_balance['actual_size'];
				
		$new_order = gateio_query('futures/usdt/orders',$order_info = array('contract' => $pair, 'price' => $depth['bids'][0][0], 'size' => -$amount, 'tif' => 'gtc'),'POST');

			
		savelog("new sell order: ".print_r($order_info,1)." ".print_r($new_order,1),"orders/sell".date("Ymd"));

		
	}
	else if ($data[$ts[0]]['close'] && $a*$data[$ts[0]]['longs']+$b*$data[$ts[0]]['shorts'] > $last_val + $c && $last_val < $last_val2){				
		//TODO BUY
		$futures_balance = gateio_query('futures/usdt/accounts');
		$futures_balance['maximum_position'] = floor($futures_balance['total'] * $futures_leverage / $depth['asks'][0][0]);

		
		$futures_positions = gateio_query('futures/usdt/positions');
		$actual_size = 0;
		foreach ($futures_positions as $position){
			$actual_size += $position['size'];
		}  		
		$futures_balance['actual_size'] = $actual_size;

		$amount = $futures_balance['maximum_position'] - $futures_balance['actual_size'];
		
		$new_order = gateio_query('futures/usdt/orders',$order_info = array('contract' => $pair, 'price' => $depth['asks'][0][0], 'size' => $amount, 'tif' => 'gtc'),'POST');
			
		savelog("new buy order: ".print_r($order_info,1)." ".print_r($new_order,1),"orders/buy".date("Ymd"));
		
	}

	file_put_contents("last_ts.txt",$ts[0]);
}
if (!$futures_balance){
	$futures_balance = gateio_query('futures/usdt/accounts');
}	
savelog("TOTAL:".($futures_balance['total'])." AVAILABLE:".($futures_balance['available']),"funds/LIVEFUNDS".date("Ymd"));

