-
Notifications
You must be signed in to change notification settings - Fork 1
/
BitMex.php
740 lines (586 loc) · 14.9 KB
/
BitMex.php
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
<?php
/*
* BitMex PHP REST API
*
* @author y0un1verse
* @version 0.1
* @link https://github.com/y0un1verse/bitmex-api-php
*/
class BitMex {
//const API_URL = 'https://testnet.bitmex.com';
const API_URL = 'https://www.bitmex.com';
const API_PATH = '/api/v1/';
const SYMBOL = 'XBTUSD';
private $apiKey;
private $apiSecret;
private $ch;
public $error;
public $printErrors = false;
public $errorCode;
public $errorMessage;
/*
* @param string $apiKey API Key
* @param string $apiSecret API Secret
*/
public function __construct($apiKey = '', $apiSecret = '') {
$this->apiKey = $apiKey;
$this->apiSecret = $apiSecret;
$this->curlInit();
}
/*
* Public
*/
/*
* Get Ticker
*
* @return ticker array
*/
public function getTicker() {
$symbol = self::SYMBOL;
$data['function'] = "instrument";
$data['params'] = array(
"symbol" => $symbol
);
$return = $this->publicQuery($data);
if(!$return || count($return) != 1 || !isset($return[0]['symbol'])) return false;
$return = array(
"symbol" => $return[0]['symbol'],
"last" => $return[0]['lastPrice'],
"bid" => $return[0]['bidPrice'],
"ask" => $return[0]['askPrice'],
"high" => $return[0]['highPrice'],
"low" => $return[0]['lowPrice']
);
return $return;
}
/*
* Get Candles
*
* Get candles history
*
* @param $timeFrame can be 1m 5m 1h
* @param $count candles count
* @param $offset timestamp conversion offset in seconds
*
* @return candles array (from past to present)
*/
public function getCandles($timeFrame,$count,$offset = 0) {
$symbol = self::SYMBOL;
$data['function'] = "trade/bucketed";
$data['params'] = array(
"symbol" => $symbol,
"count" => $count,
"binSize" => $timeFrame,
"partial" => "false",
"reverse" => "true"
);
$return = $this->publicQuery($data);
$candles = array();
// Converting
foreach($return as $item) {
$time = strtotime($item['timestamp']) + $offset; // Unix time stamp
$candles[$time] = array(
'timestamp' => date('Y-m-d H:i:s',$time), // Local time human-readable time stamp
'time' => $time,
'open' => $item['open'],
'high' => $item['high'],
'close' => $item['close'],
'low' => $item['low']
);
}
// Sorting candles from the past to the present
ksort($candles);
return $candles;
}
/*
* Get Order
*
* Get order by order ID
*
* @return array or false
*/
public function getOrder($orderID,$count = 100) {
$symbol = self::SYMBOL;
$data['method'] = "GET";
$data['function'] = "order";
$data['params'] = array(
"symbol" => $symbol,
"count" => $count,
"reverse" => "true"
);
$orders = $this->authQuery($data);
foreach($orders as $order) {
if($order['orderID'] == $orderID) {
return $order;
}
}
return false;
}
/*
* Get Orders
*
* Get last 100 orders
*
* @return orders array (from the past to the present)
*/
public function getOrders($count = 100) {
$symbol = self::SYMBOL;
$data['method'] = "GET";
$data['function'] = "order";
$data['params'] = array(
"symbol" => $symbol,
"count" => $count,
"reverse" => "true"
);
return array_reverse($this->authQuery($data));
}
/*
* Get Open Orders
*
* Get open orders from the last 100 orders
*
* @return open orders array
*/
public function getOpenOrders() {
$symbol = self::SYMBOL;
$data['method'] = "GET";
$data['function'] = "order";
$data['params'] = array(
"symbol" => $symbol,
"reverse" => "true"
);
$orders = $this->authQuery($data);
$openOrders = array();
foreach($orders as $order) {
if($order['ordStatus'] == 'New' || $order['ordStatus'] == 'PartiallyFilled') $openOrders[] = $order;
}
return $openOrders;
}
/*
* Get Open Positions
*
* Get all your open positions
*
* @return open positions array
*/
public function getOpenPositions() {
$symbol = self::SYMBOL;
$data['method'] = "GET";
$data['function'] = "position";
$data['params'] = array(
"symbol" => $symbol
);
$positions = $this->authQuery($data);
$openPositions = array();
foreach($positions as $position) {
if(isset($position['isOpen']) && $position['isOpen'] == true) {
$openPositions[] = $position;
}
}
return $openPositions;
}
/*
* Get Positions
*
* Get all of your positions
*
* @return positions array
*/
public function getPositions() {
$symbol = self::SYMBOL;
$data['method'] = "GET";
$data['function'] = "position";
$data['params'] = array(
"symbol" => $symbol
);
$positions = $this->authQuery($data);
return $positions;
}
/*
* Close Position
*
* Close open position
*
* @return array
*/
public function closePosition($price) {
$symbol = self::SYMBOL;
$data['method'] = "POST";
$data['function'] = "order/closePosition";
$data['params'] = array(
"symbol" => $symbol,
"price" => $price
);
return $this->authQuery($data);
}
/*
* Edit Order Price
*
* Edit you open order price
*
* @param $orderID Order ID
* @param $price new price
*
* @return new order array
*/
public function editOrderPrice($orderID,$price) {
$data['method'] = "PUT";
$data['function'] = "order";
$data['params'] = array(
"orderID" => $orderID,
"price" => $price
);
return $this->authQuery($data);
}
/*
* Create Order
*
* Create new order
*
* @param $type can be "Limit"
* @param $side can be "Buy" or "Sell"
* @param $price BTC price in USD
* @param $quantity should be in USD (number of contracts)
* @param $maker forces platform to complete your order as a 'maker' only
*
* @return new order array
*/
public function createOrder($type,$side,$price,$quantity,$maker = false) {
$symbol = self::SYMBOL;
$data['method'] = "POST";
$data['function'] = "order";
$data['params'] = array(
"symbol" => $symbol,
"side" => $side,
"price" => $price,
"orderQty" => $quantity,
"ordType" => $type
);
if($maker) {
$data['params']['execInst'] = "ParticipateDoNotInitiate";
}
return $this->authQuery($data);
}
/*
* Create Limit Order
*
* Create new limit order
*
* @param $price number of contracts
* @param $quantity (number of contracts) positive for buy and negative for sell
* @param $maker forces platform to complete your order as a 'maker' only
*
* @return new order array
*/
public function createLimitOrder($quantity,$price,$instructions = false) {
$symbol = self::SYMBOL;
$data['method'] = "POST";
$data['function'] = "order";
$data['params'] = array(
"symbol" => $symbol,
"price" => $price,
"orderQty" => $quantity,
"ordType" => "Limit"
);
if($instructions) {
$data['params']['execInst'] = $instructions;
}
return $this->authQuery($data);
}
/*
* Create Stop Market Order
*
* Create new stop market order
*
* @param $stopPrice BTC trigger price
* @param $quantity should be in USD (number of contracts)
*
* @return new order array
*/
public function createStopMarketOrder($quantity,$stopPrice,$instructions = false) {
$symbol = self::SYMBOL;
$data['method'] = "POST";
$data['function'] = "order";
$data['params'] = array(
"symbol" => $symbol,
"stopPx" => $stopPrice,
"orderQty" => $quantity,
"ordType" => "Stop"
);
if($instructions) {
$data['params']['execInst'] = $instructions;
}
return $this->authQuery($data);
}
/*
* Create Stop Limit Order
*
* Create new stop limit order
*
* @param $quantity is a number of contracts
* @param $stopPrice is an order trigger price
* @param $price is an order execution price
*
* @return new order array
*/
public function createStopLimitOrder($quantity,$stopPrice,$price,$instructions = false) {
$symbol = self::SYMBOL;
$data['method'] = "POST";
$data['function'] = "order";
$data['params'] = array(
"symbol" => $symbol,
"stopPx" => $stopPrice,
"price" => $price,
"orderQty" => $quantity,
"ordType" => "StopLimit"
);
if($instructions) {
$data['params']['execInst'] = $instructions;
}
return $this->authQuery($data);
}
/*
* Cancel All Open Orders
*
* Cancels all of your open orders
*
* @param $text is a note to all closed orders
*
* @return all closed orders arrays
*/
public function cancelAllOpenOrders($text = "") {
$symbol = self::SYMBOL;
$data['method'] = "DELETE";
$data['function'] = "order/all";
$data['params'] = array(
"symbol" => $symbol,
"text" => $text
);
return $this->authQuery($data);
}
/*
* Get Wallet
*
* Get your account wallet
*
* @return array
*/
public function getWallet() {
$data['method'] = "GET";
$data['function'] = "user/wallet";
$data['params'] = array(
"currency" => "XBt"
);
return $this->authQuery($data);
}
/*
* Get Margin
*
* Get your account margin
*
* @return array
*/
public function getMargin() {
$data['method'] = "GET";
$data['function'] = "user/margin";
$data['params'] = array(
"currency" => "XBt"
);
return $this->authQuery($data);
}
/*
* Get Order Book
*
* Get L2 Order Book
*
* @return array
*/
public function getOrderBook($depth = 25) {
$symbol = self::SYMBOL;
$data['method'] = "GET";
$data['function'] = "orderBook/L2";
$data['params'] = array(
"symbol" => $symbol,
"depth" => $depth
);
return $this->authQuery($data);
}
/*
* Set Leverage
*
* Set position leverage
* $leverage = 0 for cross margin
*
* @return array
*/
public function setLeverage($leverage) {
$symbol = self::SYMBOL;
$data['method'] = "POST";
$data['function'] = "position/leverage";
$data['params'] = array(
"symbol" => $symbol,
"leverage" => $leverage
);
return $this->authQuery($data);
}
/*
* Private
*
*/
/*
* Auth Query
*
* Query for authenticated queries only
*
* @param $data consists method (GET,POST,DELETE,PUT),function,params
*
* @return return array
*/
private function authQuery($data) {
$method = $data['method'];
$function = $data['function'];
if($method == "GET" || $method == "POST" || $method == "PUT") {
$params = http_build_query($data['params']);
}
elseif($method == "DELETE") {
$params = json_encode($data['params']);
}
$path = self::API_PATH . $function;
$url = self::API_URL . self::API_PATH . $function;
if($method == "GET" && count($data['params']) >= 1) {
$url .= "?" . $params;
$path .= "?" . $params;
}
$nonce = $this->generateNonce();
if($method == "GET") {
$post = "";
}
else {
$post = $params;
}
$sign = hash_hmac('sha256', $method.$path.$nonce.$post, $this->apiSecret);
$headers = array();
$headers[] = "api-signature: $sign";
$headers[] = "api-key: {$this->apiKey}";
$headers[] = "api-nonce: $nonce";
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Keep-Alive: 90';
curl_reset($this->ch);
curl_setopt($this->ch, CURLOPT_URL, $url);
if($data['method'] == "POST") {
curl_setopt($this->ch, CURLOPT_POST, true);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
}
if($data['method'] == "DELETE") {
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
$headers[] = 'X-HTTP-Method-Override: DELETE';
}
if($data['method'] == "PUT") {
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "PUT");
//curl_setopt($this->ch, CURLOPT_PUT, true);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
$headers[] = 'X-HTTP-Method-Override: PUT';
}
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($this->ch);
if(!$return) {
$this->curlError();
$this->error = true;
return false;
}
$return = json_decode($return,true);
if(isset($return['error'])) {
$this->platformError($return);
$this->error = true;
return false;
}
$this->error = false;
$this->errorCode = false;
$this->errorMessage = false;
return $return;
}
/*
* Public Query
*
* Query for public queries only
*
* @param $data consists function,params
*
* @return return array
*/
private function publicQuery($data) {
$function = $data['function'];
$params = http_build_query($data['params']);
$url = self::API_URL . self::API_PATH . $function . "?" . $params;;
$headers = array();
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Keep-Alive: 90';
curl_reset($this->ch);
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
$return = curl_exec($this->ch);
if(!$return) {
$this->curlError();
$this->error = true;
return false;
}
$return = json_decode($return,true);
if(isset($return['error'])) {
$this->platformError($return);
$this->error = true;
return false;
}
$this->error = false;
$this->errorCode = false;
$this->errorMessage = false;
return $return;
}
/*
* Generate Nonce
*
* @return string
*/
private function generateNonce() {
$nonce = (string) number_format(round(microtime(true) * 100000), 0, '.', '');
return $nonce;
}
/*
* Curl Init
*
* Init curl header to support keep-alive connection
*/
private function curlInit() {
$this->ch = curl_init();
}
/*
* Curl Error
*
* @return false
*/
private function curlError() {
if ($errno = curl_errno($this->ch)) {
$this->errorCode = $errno;
$errorMessage = curl_strerror($errno);
$this->errorMessage = $errorMessage;
if($this->printErrors) echo "cURL error ({$errno}) : {$errorMessage}\n";
return true;
}
return false;
}
/*
* Platform Error
*
* @return false
*/
private function platformError($return) {
$this->errorCode = $return['error']['name'];
$this->errorMessage = $return['error']['message'];
if($this->printErrors) echo "BitMex error ({$return['error']['name']}) : {$return['error']['message']}\n";
return true;
}
}