Api.php
3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
namespace trader\exchange\bitget;
require_once __DIR__ . '/../../struct/ApiInfo.php';
require_once __DIR__ . '/../../../jiaoyin/func.php';
require_once __DIR__ . '/../../../jiaoyin/Curl.php';
use trader\struct\ApiInfo;
use Jiaoyin\Curl;
use function Jiaoyin\getMicrotime;
class Api
{
private $host = 'https://api.bitget.com';
private ?ApiInfo $apiInfo;
public function __construct(?ApiInfo $apiInfo)
{
$this->apiInfo = $apiInfo;
}
public function setHost($host)
{
$this->host = $host;
}
//----------- public interface ------------
// 获取交易对信息
public function instruments($param)
{
$path = '/api/v2/mix/market/contracts';
$method = 'GET';
return $this->request($path, $method, $param);
}
// 获取K线数据
public function klines($param)
{
$path = '/api/v2/mix/market/candles';
$method = 'GET';
return $this->request($path, $method, $param);
}
//----------- private interface ------------
// 下单
public function placeOrder($param)
{
$path = '/api/v2/mix/order/place-order';
$method = 'POST';
return $this->request($path, $method, $param, true);
}
// 查询持仓
public function getPositions($param)
{
$path = '/api/v2/mix/position/positions';
$method = 'GET';
return $this->request($path, $method, $param, true);
}
// 设置杠杆
public function setLeverage($param)
{
$path = '/api/v2/mix/account/set-leverage';
$method = 'POST';
return $this->request($path, $method, $param, true);
}
// 查询账户余额
public function accountBalance($param)
{
$path = '/api/v2/mix/account/account';
$method = 'GET';
return $this->request($path, $method, $param, true);
}
//-------------------------------------
private function createSign($timestamp, $method, $requestPath, $body = '')
{
$message = $timestamp . $method . $requestPath . $body;
return base64_encode(hash_hmac('sha256', $message, $this->apiInfo->secret, true));
}
private function request($path, $method, $param, $auth = false)
{
$header = [];
$body = '';
$fullPath = $path;
if ($method == 'GET' && !empty($param)) {
$fullPath = $path . '?' . http_build_query($param);
} else {
$header[] = 'Content-Type: application/json';
$body = json_encode($param);
}
if ($auth) {
$timestamp = (string)getMicrotime();
$header[] = 'ACCESS-KEY: ' . $this->apiInfo->key;
$header[] = 'ACCESS-TIMESTAMP: ' . $timestamp;
$header[] = 'ACCESS-PASSPHRASE: ' . $this->apiInfo->passphrase;
$header[] = 'ACCESS-SIGN: ' . $this->createSign($timestamp, $method, $fullPath, $body);
}
$url = $this->host . $path;
$result = "";
if ($method == 'POST') {
$result = Curl::httpPost($url, $param, $header);
} else {
$result = Curl::httpGet($url, $param, $header);
}
return json_decode($result, true);
}
}