-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathderibit.php
504 lines (479 loc) · 24.9 KB
/
deribit.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
<?php
namespace ccxt;
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
use Exception as Exception; // a common import
class deribit extends Exchange {
public function describe () {
return array_replace_recursive (parent::describe (), array (
'id' => 'deribit',
'name' => 'Deribit',
'countries' => array ( 'NL' ), // Netherlands
'version' => 'v1',
'userAgent' => null,
'rateLimit' => 2000,
'has' => array (
'CORS' => true,
'editOrder' => true,
'fetchOrder' => true,
'fetchOrders' => false,
'fetchOpenOrders' => true,
'fetchClosedOrders' => true,
'fetchMyTrades' => true,
'fetchTickers' => false,
),
'timeframes' => array (),
'urls' => array (
'test' => 'https://test.deribit.com',
'logo' => 'https://user-images.githubusercontent.com/1294454/41933112-9e2dd65a-798b-11e8-8440-5bab2959fcb8.jpg',
'api' => 'https://www.deribit.com',
'www' => 'https://www.deribit.com',
'doc' => array (
'https://docs.deribit.com/',
'https://github.com/deribit',
),
'fees' => 'https://www.deribit.com/pages/information/fees',
'referral' => 'https://www.deribit.com/reg-1189.4038',
),
'api' => array (
'public' => array (
'get' => array (
'test',
'getinstruments',
'index',
'getcurrencies',
'getorderbook',
'getlasttrades',
'getsummary',
'stats',
'getannouncments',
),
),
'private' => array (
'get' => array (
'account',
'getopenorders',
'positions',
'orderhistory',
'orderstate',
'tradehistory',
'newannouncements',
),
'post' => array (
'buy',
'sell',
'edit',
'cancel',
'cancelall',
),
),
),
'exceptions' => array (
// 0 or absent Success, No error
'9999' => '\\ccxt\\PermissionDenied', // "api_not_enabled" User didn't enable API for the Account
'10000' => '\\ccxt\\AuthenticationError', // "authorization_required" Authorization issue, invalid or absent signature etc
'10001' => '\\ccxt\\ExchangeError', // "error" Some general failure, no public information available
'10002' => '\\ccxt\\InvalidOrder', // "qty_too_low" Order quantity is too low
'10003' => '\\ccxt\\InvalidOrder', // "order_overlap" Rejection, order overlap is found and self-trading is not enabled
'10004' => '\\ccxt\\OrderNotFound', // "order_not_found" Attempt to operate with order that can't be found by specified id
'10005' => '\\ccxt\\InvalidOrder', // "price_too_low {Limit}" Price is too low, {Limit} defines current limit for the operation
'10006' => '\\ccxt\\InvalidOrder', // "price_too_low4idx {Limit}" Price is too low for current index, {Limit} defines current bottom limit for the operation
'10007' => '\\ccxt\\InvalidOrder', // "price_too_high {Limit}" Price is too high, {Limit} defines current up limit for the operation
'10008' => '\\ccxt\\InvalidOrder', // "price_too_high4idx {Limit}" Price is too high for current index, {Limit} defines current up limit for the operation
'10009' => '\\ccxt\\InsufficientFunds', // "not_enough_funds" Account has not enough funds for the operation
'10010' => '\\ccxt\\OrderNotFound', // "already_closed" Attempt of doing something with closed order
'10011' => '\\ccxt\\InvalidOrder', // "price_not_allowed" This price is not allowed for some reason
'10012' => '\\ccxt\\InvalidOrder', // "book_closed" Operation for instrument which order book had been closed
'10013' => '\\ccxt\\PermissionDenied', // "pme_max_total_open_orders {Limit}" Total limit of open orders has been exceeded, it is applicable for PME users
'10014' => '\\ccxt\\PermissionDenied', // "pme_max_future_open_orders {Limit}" Limit of count of futures' open orders has been exceeded, it is applicable for PME users
'10015' => '\\ccxt\\PermissionDenied', // "pme_max_option_open_orders {Limit}" Limit of count of options' open orders has been exceeded, it is applicable for PME users
'10016' => '\\ccxt\\PermissionDenied', // "pme_max_future_open_orders_size {Limit}" Limit of size for futures has been exceeded, it is applicable for PME users
'10017' => '\\ccxt\\PermissionDenied', // "pme_max_option_open_orders_size {Limit}" Limit of size for options has been exceeded, it is applicable for PME users
'10019' => '\\ccxt\\PermissionDenied', // "locked_by_admin" Trading is temporary locked by admin
'10020' => '\\ccxt\\ExchangeError', // "invalid_or_unsupported_instrument" Instrument name is not valid
'10022' => '\\ccxt\\InvalidOrder', // "invalid_quantity" quantity was not recognized as a valid number
'10023' => '\\ccxt\\InvalidOrder', // "invalid_price" price was not recognized as a valid number
'10024' => '\\ccxt\\InvalidOrder', // "invalid_max_show" max_show parameter was not recognized as a valid number
'10025' => '\\ccxt\\InvalidOrder', // "invalid_order_id" Order id is missing or its format was not recognized as valid
'10026' => '\\ccxt\\InvalidOrder', // "price_precision_exceeded" Extra precision of the price is not supported
'10027' => '\\ccxt\\InvalidOrder', // "non_integer_contract_amount" Futures contract amount was not recognized as integer
'10028' => '\\ccxt\\DDoSProtection', // "too_many_requests" Allowed request rate has been exceeded
'10029' => '\\ccxt\\OrderNotFound', // "not_owner_of_order" Attempt to operate with not own order
'10030' => '\\ccxt\\ExchangeError', // "must_be_websocket_request" REST request where Websocket is expected
'10031' => '\\ccxt\\ExchangeError', // "invalid_args_for_instrument" Some of arguments are not recognized as valid
'10032' => '\\ccxt\\InvalidOrder', // "whole_cost_too_low" Total cost is too low
'10033' => '\\ccxt\\NotSupported', // "not_implemented" Method is not implemented yet
'10034' => '\\ccxt\\InvalidOrder', // "stop_price_too_high" Stop price is too high
'10035' => '\\ccxt\\InvalidOrder', // "stop_price_too_low" Stop price is too low
'11035' => '\\ccxt\\InvalidOrder', // "no_more_stops {Limit}" Allowed amount of stop orders has been exceeded
'11036' => '\\ccxt\\InvalidOrder', // "invalid_stoppx_for_index_or_last" Invalid StopPx (too high or too low) as to current index or market
'11037' => '\\ccxt\\InvalidOrder', // "outdated_instrument_for_IV_order" Instrument already not available for trading
'11038' => '\\ccxt\\InvalidOrder', // "no_adv_for_futures" Advanced orders are not available for futures
'11039' => '\\ccxt\\InvalidOrder', // "no_adv_postonly" Advanced post-only orders are not supported yet
'11040' => '\\ccxt\\InvalidOrder', // "impv_not_in_range 0..499%" Implied volatility is out of allowed range
'11041' => '\\ccxt\\InvalidOrder', // "not_adv_order" Advanced order properties can't be set if the order is not advanced
'11042' => '\\ccxt\\PermissionDenied', // "permission_denied" Permission for the operation has been denied
'11044' => '\\ccxt\\OrderNotFound', // "not_open_order" Attempt to do open order operations with the not open order
'11045' => '\\ccxt\\ExchangeError', // "invalid_event" Event name has not been recognized
'11046' => '\\ccxt\\ExchangeError', // "outdated_instrument" At several minutes to instrument expiration, corresponding advanced implied volatility orders are not allowed
'11047' => '\\ccxt\\ExchangeError', // "unsupported_arg_combination" The specified combination of arguments is not supported
'11048' => '\\ccxt\\ExchangeError', // "not_on_this_server" The requested operation is not available on this server.
'11050' => '\\ccxt\\ExchangeError', // "invalid_request" Request has not been parsed properly
'11051' => '\\ccxt\\ExchangeNotAvailable', // "system_maintenance" System is under maintenance
'11030' => '\\ccxt\\ExchangeError', // "other_reject {Reason}" Some rejects which are not considered as very often, more info may be specified in {Reason}
'11031' => '\\ccxt\\ExchangeError', // "other_error {Error}" Some errors which are not considered as very often, more info may be specified in {Error}
),
'options' => array (
'fetchTickerQuotes' => true,
),
));
}
public function fetch_markets ($params = array ()) {
$marketsResponse = $this->publicGetGetinstruments ();
$markets = $marketsResponse['result'];
$result = array ();
for ($p = 0; $p < count ($markets); $p++) {
$market = $markets[$p];
$id = $market['instrumentName'];
$base = $market['baseCurrency'];
$quote = $market['currency'];
$base = $this->common_currency_code($base);
$quote = $this->common_currency_code($quote);
$result[] = array (
'id' => $id,
'symbol' => $id,
'base' => $base,
'quote' => $quote,
'active' => $market['isActive'],
'precision' => array (
'amount' => $market['minTradeSize'],
'price' => $market['tickSize'],
),
'limits' => array (
'amount' => array (
'min' => $market['minTradeSize'],
),
'price' => array (
'min' => $market['tickSize'],
),
),
'type' => $market['kind'],
'spot' => false,
'future' => $market['kind'] === 'future',
'option' => $market['kind'] === 'option',
'info' => $market,
);
}
return $result;
}
public function fetch_balance ($params = array ()) {
$account = $this->privateGetAccount ();
$result = array (
'BTC' => array (
'free' => $account['result']['availableFunds'],
'used' => $account['result']['maintenanceMargin'],
'total' => $account['result']['equity'],
),
);
return $this->parse_balance($result);
}
public function fetch_deposit_address ($currency, $params = array ()) {
$account = $this->privateGetAccount ();
return array (
'currency' => 'BTC',
'address' => $account['depositAddress'],
'tag' => null,
'info' => $account,
);
}
public function parse_ticker ($ticker, $market = null) {
$timestamp = $this->safe_integer($ticker, 'created');
$iso8601 = ($timestamp === null) ? null : $this->iso8601 ($timestamp);
$symbol = $this->find_symbol($this->safe_string($ticker, 'instrumentName'), $market);
$last = $this->safe_float($ticker, 'last');
return array (
'symbol' => $symbol,
'timestamp' => $timestamp,
'datetime' => $iso8601,
'high' => $this->safe_float($ticker, 'high'),
'low' => $this->safe_float($ticker, 'low'),
'bid' => $this->safe_float($ticker, 'bidPrice'),
'bidVolume' => null,
'ask' => $this->safe_float($ticker, 'askPrice'),
'askVolume' => null,
'vwap' => null,
'open' => null,
'close' => $last,
'last' => $last,
'previousClose' => null,
'change' => null,
'percentage' => null,
'average' => null,
'baseVolume' => null,
'quoteVolume' => $this->safe_float($ticker, 'volume'),
'info' => $ticker,
);
}
public function fetch_ticker ($symbol, $params = array ()) {
$this->load_markets();
$market = $this->market ($symbol);
$response = $this->publicGetGetsummary (array_merge (array (
'instrument' => $market['id'],
), $params));
return $this->parse_ticker($response['result'], $market);
}
public function parse_trade ($trade, $market = null) {
$id = $this->safe_string($trade, 'tradeId');
$symbol = null;
if ($market !== null)
$symbol = $market['symbol'];
$timestamp = $this->safe_integer($trade, 'timeStamp');
return array (
'info' => $trade,
'id' => $id,
'timestamp' => $timestamp,
'datetime' => $this->iso8601 ($timestamp),
'symbol' => $symbol,
'order' => null,
'type' => null,
'side' => $trade['direction'],
'price' => $this->safe_float($trade, 'price'),
'amount' => $this->safe_float($trade, 'quantity'),
);
}
public function fetch_trades ($symbol, $since = null, $limit = null, $params = array ()) {
$this->load_markets();
$market = $this->market ($symbol);
$request = array (
'instrument' => $market['id'],
);
if ($limit !== null) {
$request['limit'] = $limit;
} else {
$request['limit'] = 10000;
}
$response = $this->publicGetGetlasttrades (array_merge ($request, $params));
return $this->parse_trades($response['result'], $market, $since, $limit);
}
public function fetch_order_book ($symbol, $limit = null, $params = array ()) {
$this->load_markets();
$market = $this->market ($symbol);
$response = $this->publicGetGetorderbook (array ( 'instrument' => $market['id'] ));
$timestamp = intval ($response['usOut'] / 1000);
$orderbook = $this->parse_order_book($response['result'], $timestamp, 'bids', 'asks', 'price', 'quantity');
return array_merge ($orderbook, array (
'nonce' => $this->safe_integer($response, 'tstamp'),
));
}
public function parse_order_status ($status) {
$statuses = array (
'open' => 'open',
'cancelled' => 'canceled',
'filled' => 'closed',
);
if (is_array ($statuses) && array_key_exists ($status, $statuses)) {
return $statuses[$status];
}
return $status;
}
public function parse_order ($order, $market = null) {
//
// {
// "orderId" => 5258039, // ID of the $order
// "$type" => "limit", // not documented, but present in the actual response
// "instrument" => "BTC-26MAY17", // instrument name ($market $id)
// "direction" => "sell", // $order direction, "buy" or "sell"
// "$price" => 1860, // float, USD for futures, BTC for options
// "label" => "", // label set by the owner, up to 32 chars
// "quantity" => 10, // quantity, in contracts ($10 per contract for futures, ฿1 — for options)
// "filledQuantity" => 3, // $filled quantity, in contracts ($10 per contract for futures, ฿1 — for options)
// "avgPrice" => 1860, // $average fill $price of the $order
// "commission" => -0.000001613, // in BTC units
// "created" => 1494491899308, // creation $timestamp
// "state" => "open", // open, cancelled, etc
// "postOnly" => false // true for post-only orders only
// open orders --------------------------------------------------------
// "$lastUpdate" => 1494491988754, // $timestamp of the last $order state change (before this cancelorder of course)
// closed orders ------------------------------------------------------
// "tstamp" => 1494492913288, // $timestamp of the last $order state change, documented, but may be missing in the actual response
// "modified" => 1494492913289, // $timestamp of the last db write operation, e.g. trade that doesn't change $order $status, documented, but may missing in the actual response
// "adv" => false // advanced $type (false, or "usd" or "implv")
// "trades" => array (), // not documented, injected from the outside of the parseOrder method into the $order
// }
//
$timestamp = $this->safe_integer($order, 'created');
$lastUpdate = $this->safe_integer($order, 'lastUpdate');
$lastTradeTimestamp = $this->safe_integer_2($order, 'tstamp', 'modified');
$id = $this->safe_string($order, 'orderId');
$price = $this->safe_float($order, 'price');
$average = $this->safe_float($order, 'avgPrice');
$amount = $this->safe_float($order, 'quantity');
$filled = $this->safe_float($order, 'filledQuantity');
if ($lastTradeTimestamp === null) {
if ($filled !== null) {
if ($filled > 0) {
$lastTradeTimestamp = $lastUpdate;
}
}
}
$remaining = null;
$cost = null;
if ($filled !== null) {
if ($amount !== null) {
$remaining = $amount - $filled;
}
if ($price !== null) {
$cost = $price * $filled;
}
}
$status = $this->parse_order_status($this->safe_string($order, 'state'));
$side = $this->safe_string($order, 'direction');
if ($side !== null) {
$side = strtolower ($side);
}
$feeCost = $this->safe_float($order, 'commission');
if ($feeCost !== null) {
$feeCost = abs ($feeCost);
}
$fee = array (
'cost' => $feeCost,
'currency' => 'BTC',
);
$type = $this->safe_string($order, 'type');
return array (
'info' => $order,
'id' => $id,
'timestamp' => $timestamp,
'datetime' => $this->iso8601 ($timestamp),
'lastTradeTimestamp' => $lastTradeTimestamp,
'symbol' => $order['instrument'],
'type' => $type,
'side' => $side,
'price' => $price,
'amount' => $amount,
'cost' => $cost,
'average' => $average,
'filled' => $filled,
'remaining' => $remaining,
'status' => $status,
'fee' => $fee,
'trades' => null, // todo => parse trades
);
}
public function fetch_order ($id, $symbol = null, $params = array ()) {
$this->load_markets();
$response = $this->privateGetOrderstate (array ( 'orderId' => $id ));
return $this->parse_order($response['result']);
}
public function create_order ($symbol, $type, $side, $amount, $price = null, $params = array ()) {
$this->load_markets();
$request = array (
'instrument' => $this->market_id($symbol),
'quantity' => $amount,
'type' => $type,
);
if ($price !== null)
$request['price'] = $price;
$method = 'privatePost' . $this->capitalize ($side);
$response = $this->$method (array_merge ($request, $params));
$order = $this->safe_value($response['result'], 'order');
if ($order === null) {
return $response;
}
return $this->parse_order($order);
}
public function edit_order ($id, $symbol, $type, $side, $amount = null, $price = null, $params = array ()) {
$this->load_markets();
$request = array (
'orderId' => $id,
);
if ($amount !== null)
$request['quantity'] = $amount;
if ($price !== null)
$request['price'] = $price;
$response = $this->privatePostEdit (array_merge ($request, $params));
return $this->parse_order($response['result']['order']);
}
public function cancel_order ($id, $symbol = null, $params = array ()) {
$this->load_markets();
$response = $this->privatePostCancel (array_merge (array ( 'orderId' => $id ), $params));
return $this->parse_order($response['result']['order']);
}
public function fetch_open_orders ($symbol = null, $since = null, $limit = null, $params = array ()) {
$this->load_markets();
$market = $this->market ($symbol);
$request = array (
'instrument' => $market['id'],
);
$response = $this->privateGetGetopenorders (array_merge ($request, $params));
return $this->parse_orders($response['result'], $market, $since, $limit);
}
public function fetch_closed_orders ($symbol = null, $since = null, $limit = null, $params = array ()) {
$this->load_markets();
$market = $this->market ($symbol);
$request = array (
'instrument' => $market['id'],
);
$response = $this->privateGetOrderhistory (array_merge ($request, $params));
return $this->parse_orders($response['result'], $market, $since, $limit);
}
public function fetch_my_trades ($symbol = null, $since = null, $limit = null, $params = array ()) {
$this->load_markets();
$market = $this->market ($symbol);
$request = array (
'instrument' => $market['id'],
);
if ($limit !== null) {
$request['count'] = $limit; // default = 20
}
$response = $this->privateGetTradehistory (array_merge ($request, $params));
return $this->parse_trades($response['result'], $market, $since, $limit);
}
public function nonce () {
return $this->milliseconds ();
}
public function sign ($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
$query = '/' . 'api/' . $this->version . '/' . $api . '/' . $path;
$url = $this->urls['api'] . $query;
if ($api === 'public') {
if ($params) {
$url .= '?' . $this->urlencode ($params);
}
} else {
$this->check_required_credentials();
$nonce = (string) $this->nonce ();
$auth = '_=' . $nonce . '&_ackey=' . $this->apiKey . '&_acsec=' . $this->secret . '&_action=' . $query;
if ($method === 'POST') {
$params = $this->keysort ($params);
$auth .= '&' . $this->urlencode ($params);
}
$hash = $this->hash ($this->encode ($auth), 'sha256', 'base64');
$signature = $this->apiKey . '.' . $nonce . '.' . $this->decode ($hash);
$headers = array (
'x-deribit-sig' => $signature,
);
if ($method !== 'GET') {
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
$body = $this->urlencode ($params);
}
}
return array ( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
}
public function handle_errors ($httpCode, $reason, $url, $method, $headers, $body, $response) {
if (!$response) {
return; // fallback to default $error handler
}
//
// array ("usOut":1535877098645376,"usIn":1535877098643364,"usDiff":2012,"testnet":false,"success":false,"message":"order_not_found","$error":10004)
//
$error = $this->safe_string($response, 'error');
if (($error !== null) && ($error !== '0')) {
$feedback = $this->id . ' ' . $body;
$exceptions = $this->exceptions;
if (is_array ($exceptions) && array_key_exists ($error, $exceptions)) {
throw new $exceptions[$error] ($feedback);
}
throw new ExchangeError ($feedback); // unknown message
}
}
}