This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 174
/
__init__.py
2492 lines (2060 loc) · 84.9 KB
/
__init__.py
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
pybit
------------------------
pybit is a lightweight and high-performance API connector for the
RESTful and WebSocket APIs of the Bybit exchange.
Documentation can be found at
https://github.com/verata-veritatis/pybit
:copyright: (c) 2020-2021 verata-veritatis
:license: MIT License
"""
import time
import hmac
import json
import logging
import threading
import requests
import websocket
from datetime import datetime as dt
from concurrent.futures import ThreadPoolExecutor
from .exceptions import FailedRequestError, InvalidRequestError
# Requests will use simplejson if available.
try:
from simplejson.errors import JSONDecodeError
except ImportError:
from json.decoder import JSONDecodeError
# Versioning.
VERSION = '1.3.6'
class HTTP:
"""
Connector for Bybit's HTTP API.
:param endpoint: The endpoint URL of the HTTP API, e.g.
'https://api-testnet.bybit.com'.
:type endpoint: str
:param api_key: Your API key. Required for authenticated endpoints. Defaults
to None.
:type api_key: str
:param api_secret: Your API secret key. Required for authenticated
endpoints. Defaults to None.
:type api_secret: str
:param logging_level: The logging level of the built-in logger. Defaults to
logging.INFO. Options are CRITICAL (50), ERROR (40), WARNING (30),
INFO (20), DEBUG (10), or NOTSET (0).
:type logging_level: Union[int, logging.level]
:param log_requests: Whether or not pybit should log each HTTP request.
:type log_requests: bool
:param request_timeout: The timeout of each API request in seconds. Defaults
to 10 seconds.
:type request_timeout: int
:param recv_window: How long an HTTP request is valid in ms. Default is
5000.
:type recv_window: int
:param force_retry: Whether or not pybit should retry a timed-out request.
:type force_retry: bool
:param retry_codes: A list of non-fatal status codes to retry on.
:type retry_codes: set
:param ignore_codes: A list of non-fatal status codes to ignore.
:type ignore_codes: set
:param max_retries: The number of times to re-attempt a request.
:type max_retries: int
:param retry_delay: Seconds between retries for returned error or timed-out
requests. Default is 3 seconds.
:type retry_delay: int
:param referral_id: An optional referer ID can be added to each request for
identification.
:type referral_id: str
:returns: pybit.HTTP session.
"""
def __init__(self, endpoint=None, api_key=None, api_secret=None,
logging_level=logging.INFO, log_requests=False,
request_timeout=10, recv_window=5000, force_retry=False,
retry_codes=None, ignore_codes=None, max_retries=3,
retry_delay=3, referral_id=None, spot=False):
"""Initializes the HTTP class."""
# Set the endpoint.
if endpoint is None:
self.endpoint = 'https://api.bybit.com'
else:
self.endpoint = endpoint
# Setup logger.
self.logger = logging.getLogger(__name__)
if len(logging.root.handlers) == 0:
#no handler on root logger set -> we add handler just for this logger to not mess with custom logic from outside
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
)
handler.setLevel(logging_level)
self.logger.addHandler(handler)
self.logger.debug('Initializing HTTP session.')
self.log_requests = log_requests
# Set API keys.
self.api_key = api_key
self.api_secret = api_secret
# Set timeout.
self.timeout = request_timeout
self.recv_window = recv_window
self.force_retry = force_retry
self.max_retries = max_retries
self.retry_delay = retry_delay
# Set whitelist of non-fatal Bybit status codes to retry on.
if retry_codes is None:
self.retry_codes = {10002, 10006, 30034, 30035, 130035, 130150}
else:
self.retry_codes = retry_codes
# Set whitelist of non-fatal Bybit status codes to ignore.
if ignore_codes is None:
self.ignore_codes = set()
else:
self.ignore_codes = ignore_codes
# Initialize requests session.
self.client = requests.Session()
self.client.headers.update(
{
'User-Agent': 'pybit-' + VERSION,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
)
# Add referral ID to header.
if referral_id:
self.client.headers.update({'Referer': referral_id})
# If True, calls spot endpoints rather than futures endpoints.
self.spot = spot
def _exit(self):
"""Closes the request session."""
self.client.close()
self.logger.debug('HTTP session closed.')
def orderbook(self, **kwargs):
"""
Get the orderbook.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-orderbook.
:returns: Request results as dictionary.
"""
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/quote/v1/depth'
else:
suffix = '/v2/public/orderBook/L2'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs
)
def merged_orderbook(self, **kwargs):
"""
Get the merged orderbook.
:param kwargs: See
https://bybit-exchange.github.io/docs/spot/#t-mergedorderbook.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='GET',
path=self.endpoint + '/spot/quote/v1/depth/merged',
query=kwargs
)
def query_kline(self, **kwargs):
"""
Get kline.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-querykline.
:returns: Request results as dictionary.
"""
# Replace query param 'from_time' since 'from' keyword is reserved.
# Temporary workaround until Bybit updates official request params
if 'from_time' in kwargs:
kwargs['from'] = kwargs.pop('from_time')
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/quote/v1/kline'
elif kwargs.get('symbol', '').endswith('USDT'):
suffix = '/public/linear/kline'
else:
suffix = '/v2/public/kline/list'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs
)
def latest_information_for_symbol(self, **kwargs):
"""
Get the latest information for symbol.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-latestsymbolinfo.
:returns: Request results as dictionary.
"""
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/quote/v1/ticker/24hr'
else:
suffix = '/v2/public/tickers'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs
)
def last_traded_price(self, **kwargs):
"""
Get the last traded price.
:param kwargs: See
https://bybit-exchange.github.io/docs/spot/#t-lasttradedprice.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='GET',
path=self.endpoint + '/spot/quote/v1/ticker/price',
query=kwargs
)
def best_bid_ask_price(self, **kwargs):
"""
Get the best bid/ask price.
:param kwargs: See
https://bybit-exchange.github.io/docs/spot/#t-bestbidask.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='GET',
path=self.endpoint + '/spot/quote/v1/ticker/book_ticker',
query=kwargs
)
def public_trading_records(self, **kwargs):
"""
Get recent trades. You can find a complete history of trades on Bybit
at https://public.bybit.com/.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-publictradingrecords.
:returns: Request results as dictionary.
"""
# Replace query param 'from_id' since 'from' keyword is reserved.
# Temporary workaround until Bybit updates official request params
if 'from_id' in kwargs:
kwargs['from'] = kwargs.pop('from_id')
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/quote/v1/trades'
elif kwargs.get('symbol', '').endswith('USDT'):
suffix = '/public/linear/recent-trading-records'
else:
suffix = '/v2/public/trading-records'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs
)
def query_symbol(self, **kwargs):
"""
Get symbol info.
:returns: Request results as dictionary.
"""
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/v1/symbols'
else:
suffix = '/v2/public/symbols'
return self._submit_request(
method='GET',
path=self.endpoint + suffix
)
def liquidated_orders(self, **kwargs):
"""
Retrieve the liquidated orders. The query range is the last seven days
of data.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-query_liqrecords.
:returns: Request results as dictionary.
"""
# Replace query param 'from_id' since 'from' keyword is reserved.
# Temporary workaround until Bybit updates official request params
if 'from_id' in kwargs:
kwargs['from'] = kwargs.pop('from_id')
return self._submit_request(
method='GET',
path=self.endpoint + '/v2/public/liq-records',
query=kwargs
)
def query_mark_price_kline(self, **kwargs):
"""
Query mark price kline (like query_kline but for mark price).
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-markpricekline.
:returns: Request results as dictionary.
"""
# Replace query param 'from_time' since 'from' keyword is reserved.
# Temporary workaround until Bybit updates official request params
if 'from_time' in kwargs:
kwargs['from'] = kwargs.pop('from_time')
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/public/linear/mark-price-kline'
else:
suffix = '/v2/public/mark-price-kline'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs
)
def query_index_price_kline(self, **kwargs):
"""
Query index price kline (like query_kline but for index price).
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-queryindexpricekline.
:returns: Request results as dictionary.
"""
# Replace query param 'from_time' since 'from' keyword is reserved.
# Temporary workaround until Bybit updates official request params
if 'from_time' in kwargs:
kwargs['from'] = kwargs.pop('from_time')
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/public/linear/index-price-kline'
else:
suffix = '/v2/public/index-price-kline'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs
)
def query_premium_index_kline(self, **kwargs):
"""
Query premium index kline (like query_kline but for the premium index
discount).
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-querypremiumindexkline.
:returns: Request results as dictionary.
"""
# Replace query param 'from_time' since 'from' keyword is reserved.
# Temporary workaround until Bybit updates official request params
if 'from_time' in kwargs:
kwargs['from'] = kwargs.pop('from_time')
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/public/linear/premium-index-kline'
else:
suffix = '/v2/public/premium-index-kline'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs
)
def open_interest(self, **kwargs):
"""
Gets the total amount of unsettled contracts. In other words, the total
number of contracts held in open positions.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-marketopeninterest.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='GET',
path=self.endpoint + '/v2/public/open-interest',
query=kwargs
)
def latest_big_deal(self, **kwargs):
"""
Obtain filled orders worth more than 500,000 USD within the last 24h.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-marketbigdeal.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='GET',
path=self.endpoint + '/v2/public/big-deal',
query=kwargs
)
def long_short_ratio(self, **kwargs):
"""
Gets the Bybit long-short ratio.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-marketaccountratio.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='GET',
path=self.endpoint + '/v2/public/account-ratio',
query=kwargs
)
def place_active_order(self, **kwargs):
"""
Places an active order. For more information, see
https://bybit-exchange.github.io/docs/inverse/#t-activeorders.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-activeorders.
:returns: Request results as dictionary.
"""
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/v1/order'
elif kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/order/create'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/order/create'
else:
suffix = '/v2/private/order/create'
return self._submit_request(
method='POST',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def place_active_order_bulk(self, orders: list, max_in_parallel=10):
"""
Places multiple active orders in bulk using multithreading. For more
information on place_active_order, see
https://bybit-exchange.github.io/docs/inverse/#t-activeorders.
:param list orders: A list of orders and their parameters.
:param max_in_parallel: The number of requests to be sent in parallel.
Note that you are limited to 50 requests per second.
:returns: Future request result dictionaries as a list.
"""
with ThreadPoolExecutor(max_workers=max_in_parallel) as executor:
executions = [
executor.submit(
self.place_active_order,
**order
) for order in orders
]
executor.shutdown()
return [execution.result() for execution in executions]
def get_active_order(self, endpoint="", **kwargs):
"""
Gets an active order. For more information, see
https://bybit-exchange.github.io/docs/inverse/#t-getactive.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-getactive.
:param endpoint: The endpoint path, such as "/spot/v1/order".
This allows the user to choose between which endpoint to use to
fetch a spot order.
:returns: Request results as dictionary.
"""
if endpoint:
suffix = endpoint
else:
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/v1/history-orders'
elif kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/order/list'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/order/list'
else:
suffix = '/v2/private/order/list'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def cancel_active_order(self, **kwargs):
"""
Cancels an active order. For more information, see
https://bybit-exchange.github.io/docs/inverse/#t-cancelactive.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-cancelactive.
:returns: Request results as dictionary.
"""
method = 'POST'
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/v1/order'
method = 'DELETE'
elif kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/order/cancel'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/order/cancel'
else:
suffix = '/v2/private/order/cancel'
return self._submit_request(
method=method,
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def fast_cancel_active_order(self, **kwargs):
"""
Fast cancels an active order.
:param kwargs: See
https://bybit-exchange.github.io/docs/spot/#t-fastcancelactiveorder.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='DELETE',
path=self.endpoint + '/spot/v1/order/fast',
query=kwargs,
auth=True
)
def cancel_active_order_bulk(self, orders: list, max_in_parallel=10):
"""
Cancels multiple active orders in bulk using multithreading. For more
information on cancel_active_order, see
https://bybit-exchange.github.io/docs/inverse/#t-activeorders.
:param list orders: A list of orders and their parameters.
:param max_in_parallel: The number of requests to be sent in parallel.
Note that you are limited to 50 requests per second.
:returns: Future request result dictionaries as a list.
"""
with ThreadPoolExecutor(max_workers=max_in_parallel) as executor:
executions = [
executor.submit(
self.cancel_active_order,
**order
) for order in orders
]
executor.shutdown()
return [execution.result() for execution in executions]
def cancel_all_active_orders(self, **kwargs):
"""
Cancel all active orders that are unfilled or partially filled. Fully
filled orders cannot be cancelled.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-cancelallactive.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/order/cancel-all'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/order/cancelAll'
else:
suffix = '/v2/private/order/cancelAll'
return self._submit_request(
method='POST',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def batch_cancel_active_order(self, **kwargs):
"""
Batch cancels active orders.
:param kwargs: See
https://bybit-exchange.github.io/docs/spot/#t-batchcancelactiveorder.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='DELETE',
path=self.endpoint + '/spot/order/batch-cancel',
query=kwargs,
auth=True
)
def batch_fast_cancel_active_order(self, **kwargs):
"""
Batch fast cancels active orders.
:param kwargs: See
https://bybit-exchange.github.io/docs/spot/#t-batchfastcancelactiveorder.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='DELETE',
path=self.endpoint + '/spot/order/batch-fast-cancel',
query=kwargs,
auth=True
)
def batch_cancel_active_order_by_ids(self, **kwargs):
"""
Batch cancels active order by ids.
:param kwargs: See
https://bybit-exchange.github.io/docs/spot/#t-batchcancelactiveorderbyids.
:returns: Request results as dictionary.
"""
return self._submit_request(
method='DELETE',
path=self.endpoint + '/spot/order/batch-cancel-by-ids',
query=kwargs,
auth=True
)
def replace_active_order(self, **kwargs):
"""
Replace order can modify/amend your active orders.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-replaceactive.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/order/replace'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/order/replace'
else:
suffix = '/v2/private/order/replace'
return self._submit_request(
method='POST',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def replace_active_order_bulk(self, orders: list, max_in_parallel=10):
"""
Replaces multiple active orders in bulk using multithreading. For more
information on replace_active_order, see
https://bybit-exchange.github.io/docs/inverse/#t-replaceactive.
:param list orders: A list of orders and their parameters.
:param max_in_parallel: The number of requests to be sent in parallel.
Note that you are limited to 50 requests per second.
:returns: Future request result dictionaries as a list.
"""
with ThreadPoolExecutor(max_workers=max_in_parallel) as executor:
executions = [
executor.submit(
self.replace_active_order,
**order
) for order in orders
]
executor.shutdown()
return [execution.result() for execution in executions]
def query_active_order(self, **kwargs):
"""
Query real-time active order information.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-queryactive.
:returns: Request results as dictionary.
"""
if self.spot is True or kwargs.get('spot', '') is True:
suffix = '/spot/v1/open-orders'
elif kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/order/search'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/order'
else:
suffix = '/v2/private/order'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def place_conditional_order(self, **kwargs):
"""
Places a conditional order. For more information, see
https://bybit-exchange.github.io/docs/inverse/#t-placecond.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-placecond.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/stop-order/create'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/stop-order/create'
else:
suffix = '/v2/private/stop-order/create'
return self._submit_request(
method='POST',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def place_conditional_order_bulk(self, orders: list, max_in_parallel=10):
"""
Places multiple conditional orders in bulk using multithreading. For
more information on place_active_order, see
https://bybit-exchange.github.io/docs/inverse/#t-placecond.
:param orders: A list of orders and their parameters.
:param max_in_parallel: The number of requests to be sent in parallel.
Note that you are limited to 50 requests per second.
:returns: Future request result dictionaries as a list.
"""
with ThreadPoolExecutor(max_workers=max_in_parallel) as executor:
executions = [
executor.submit(
self.place_conditional_order,
**order
) for order in orders
]
executor.shutdown()
return [execution.result() for execution in executions]
def get_conditional_order(self, **kwargs):
"""
Gets a conditional order. For more information, see
https://bybit-exchange.github.io/docs/inverse/#t-getcond.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-getcond.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/stop-order/list'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/stop-order/list'
else:
suffix = '/v2/private/stop-order/list'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def cancel_conditional_order(self, **kwargs):
"""
Cancels a conditional order. For more information, see
https://bybit-exchange.github.io/docs/inverse/#t-cancelcond.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-cancelcond.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/stop-order/cancel'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/stop-order/cancel'
else:
suffix = '/v2/private/stop-order/cancel'
return self._submit_request(
method='POST',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def cancel_conditional_order_bulk(self, orders: list, max_in_parallel=10):
"""
Cancels multiple conditional orders in bulk using multithreading. For
more information on cancel_active_order, see
https://bybit-exchange.github.io/docs/inverse/#t-cancelcond.
:param list orders: A list of orders and their parameters.
:param max_in_parallel: The number of requests to be sent in parallel.
Note that you are limited to 50 requests per second.
:returns: Future request result dictionaries as a list.
"""
with ThreadPoolExecutor(max_workers=max_in_parallel) as executor:
executions = [
executor.submit(
self.cancel_conditional_order,
**order
) for order in orders
]
executor.shutdown()
return [execution.result() for execution in executions]
def cancel_all_conditional_orders(self, **kwargs):
"""
Cancel all conditional orders that are unfilled or partially filled.
Fully filled orders cannot be cancelled.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-cancelallcond.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/stop-order/cancel-all'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/stop-order/cancelAll'
else:
suffix = '/v2/private/stop-order/cancelAll'
return self._submit_request(
method='POST',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def replace_conditional_order(self, **kwargs):
"""
Replace conditional order can modify/amend your conditional orders.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-replacecond.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/stop-order/replace'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/stop-order/replace'
else:
suffix = '/v2/private/stop-order/replace'
return self._submit_request(
method='POST',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def replace_conditional_order_bulk(self, orders: list, max_in_parallel=10):
"""
Replaces multiple conditional orders in bulk using multithreading. For
more information on replace_active_order, see
https://bybit-exchange.github.io/docs/inverse/#t-replacecond.
:param list orders: A list of orders and their parameters.
:param max_in_parallel: The number of requests to be sent in parallel.
Note that you are limited to 50 requests per second.
:returns: Future request result dictionaries as a list.
"""
with ThreadPoolExecutor(max_workers=max_in_parallel) as executor:
executions = [
executor.submit(
self.replace_conditional_order,
**order
) for order in orders
]
executor.shutdown()
return [execution.result() for execution in executions]
def query_conditional_order(self, **kwargs):
"""
Query real-time conditional order information.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-querycond.
:returns: Request results as dictionary.
"""
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/stop-order/search'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/stop-order'
else:
suffix = '/v2/private/stop-order'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def my_position(self, endpoint="", **kwargs):
"""
Get my position list.
:param kwargs: See
https://bybit-exchange.github.io/docs/inverse/#t-myposition.
:param endpoint: The endpoint path, such as "/v2/private/position/list".
This allows the user to bypass the "symbol" arg, and instead specify
the desired market contract type (inverse perp, linear perp, etc)
and receive multiple symbols in the response.
:returns: Request results as dictionary.
"""
if endpoint:
suffix = endpoint
else:
if kwargs.get('symbol', '').endswith('USDT'):
suffix = '/private/linear/position/list'
elif kwargs.get('symbol', '')[-2:].isdigit():
suffix = '/futures/private/position/list'
else:
suffix = '/v2/private/position/list'
return self._submit_request(
method='GET',
path=self.endpoint + suffix,
query=kwargs,
auth=True
)
def set_auto_add_margin(self, **kwargs):
"""
For linear markets only. Set auto add margin, or Auto-Margin
Replenishment.
:param kwargs: See