Giter Site home page Giter Site logo

pybit's Introduction

pybit

All Contributors

Build Status Build Status contributions welcome

Official Python3 API connector for Bybit's HTTP and WebSockets APIs.

Table of Contents

About

Put simply, pybit (Python + Bybit) is the official lightweight one-stop-shop module for the Bybit HTTP and WebSocket APIs. Originally created by Verata Veritatis, it's now maintained by Bybit employees โ€“ however, you're still welcome to contribute!

It was designed with the following vision in mind:

I was personally never a fan of auto-generated connectors that used a mosh-pit of various modules you didn't want (sorry, bravado) and wanted to build my own Python3-dedicated connector with very little external resources. The goal of the connector is to provide traders and developers with an easy-to-use high-performing module that has an active issue and discussion board leading to consistent improvements.

Development

pybit is being actively developed, and new Bybit API changes should arrive on pybit very quickly. pybit uses requests and websocket-client for its methods, alongside other built-in modules. Anyone is welcome to branch/fork the repository and add their own upgrades. If you think you've made substantial improvements to the module, submit a pull request and we'll gladly take a look.

Installation

pybit requires Python 3.9.1 or higher. The module can be installed manually or via PyPI with pip:

pip install pybit

Usage

You can retrieve a specific market like so:

from pybit.unified_trading import HTTP

Create an HTTP session and connect via WebSocket for Inverse on mainnet:

session = HTTP(
    testnet=False,
    api_key="...",
    api_secret="...",
)

Information can be sent to, or retrieved from, the Bybit APIs:

# Get the orderbook of the USDT Perpetual, BTCUSDT
session.get_orderbook(category="linear", symbol="BTCUSDT")

# Create five long USDC Options orders.
# (Currently, only USDC Options support sending orders in bulk.)
payload = {"category": "option"}
orders = [{
  "symbol": "BTC-30JUN23-20000-C",
  "side": "Buy",
  "orderType": "Limit",
  "qty": "0.1",
  "price": i,
} for i in [15000, 15500, 16000, 16500, 16600]]

payload["request"] = orders
# Submit the orders in bulk.
session.place_batch_order(payload)

Check out the example python files or the list of endpoints below for more information on available endpoints and methods. Usage examples on the HTTP methods can be found in the examples folder.

Contact

You can reach out for support on the BybitAPI Telegram group chat.

Contributors

Thanks goes to these wonderful people (emoji key):


dextertd

๐Ÿ’ป ๐Ÿ“–

ervuks

๐Ÿ’ป ๐Ÿ“–

verata-veritatis

๐Ÿ’ป ๐Ÿ“–

APF20

๐Ÿ’ป

Cameron Harder-Hutton

๐Ÿ’ป

Tom Rumpf

๐Ÿ’ป

OnJohn

๐Ÿ’ป

Todd Conley

๐Ÿค”

This project follows the all-contributors specification. Contributions of any kind welcome!

pybit's People

Contributors

addestromberg avatar allcontributors[bot] avatar apf20 avatar blacksabbather avatar cameronhh avatar cryptverse avatar daler-sz avatar dextertd avatar ervuks avatar joesham avatar kamsby avatar kevinwon96 avatar kuegi avatar leftcoastgeek avatar lucilae avatar pjrdata avatar sheungon avatar tomcru avatar verata-veritatis avatar windhamwong avatar woodliang10 avatar yusufsahinhamza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pybit's Issues

Can't query active order - session.query_active_order()

Hi!

I'm not able to query all active unfilled orders - session.query_active_order(symbol='BTCUSDT') returns an empty array.

In the same time, session.get_active_order(symbol='BTCUSDT') works well and returns orders. Also, query works when I specify the order id - session.query_active_order(order_id='...', symbol='BTCUSDT')

Am I doing something wrong?

Pybit version: 2.4.0

Impossible to open trailing stop on MergedSingle

It does not make any sense that it is impossible to open trailing stop for MergedSingle position mode through API (pybit). In the meantime it is possible to set up trailing stop through the bybit app in a MergedSingle position mode. Could you please fix it
Thx

Get order records fail - Upgrade to Bybit v3

I don't see in documentation, but I suppose pybit is based on Bybit v2 API/Websockets as I've some fails like 'Get order records fail' that I've been told are solved in Bybit v3 API.

example folder

hello there,

im sad to say that it is super disappointing that the "examples" in the example folder, cant even be called examples.

it is "inspiration" at best.

an example is something that is complete...not barely started.

something you can run and it will work out of the box.

it is nice that the basics of creating the connection have been done already.

but just looking at the ocean of functions...how to use them in a safe/correct manner together...

seems more like a try at making people lose their money than an attempt to help if you ask silly me. (im your text-book customer who needs examples to figure out how to use this repo)

ergo, if a person like me gives it 2 out of 5 stars. then there is something seriously wrong.

no hate, just informing.

  • have a nice day :)

https://github.com/bybit-exchange/pybit/tree/master/examples

position_idx is not present in close_position function.

I've been trying to close a position but i had the error "position_idx not match with my position mode", so to fix it, i had to add position_idx field to close_position function, but i cant do this inside a docker container.
image

Occasionally face "error sign!" when calling USDC methods

Getting issue while trying to get wallet balances or positions.

`

from pybit import usdc_options, usdc_perpetual

def connect():
bybit_client = usdc_options.HTTP(
endpoint=base_url,
api_key='XX',
api_secret='XX',
recv_window=10000
)
return bybit_client

base_url = "https://api.bybit.com"
bybit_client = connect()

balances_response = bybit_client.get_wallet_balance()
print(balances_response)
`

Not always there is an issue, but fails frequently.
My time is sync with UTC time only.

This is the error message,

raise InvalidRequestError(
pybit.exceptions.InvalidRequestError: Error sign! (ErrCode: 10004) (ErrTime: 07:45:20).

@lucilae @Kamsby @dextertd @songhaitao @sangechen

Exceptions

What relevant exceptions Pybit could raise? Like if authentication fail or some another relevant situation?

WebSocketConnectionClosedException: socket is already closed

I'm trying to use pybit websocket to get kline data:

from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_perpetual.WebSocket(
    test=False,
    ping_interval=30,  # the default is 30
    ping_timeout=10,  # the default is 10
    domain="bybit"  # the default is "bybit"
    )
    def handle_message(msg):
        print(msg)

    ws_linear.kline_stream(
        handle_message, "BTCUSDT", "5"
    )
    while True:
        sleep(1)

Traceback (most recent call last):
File "/trader/scripts/xxx.py", line 14, in
trace_logging=True
File "/usr/local/lib/python3.6/site-packages/pybit/inverse_perpetual.py", line 709, in init
self._connect(WSS)
File "/usr/local/lib/python3.6/site-packages/pybit/_websocket_stream.py", line 167, in _connect
self._auth()
File "/usr/local/lib/python3.6/site-packages/pybit/_websocket_stream.py", line 192, in _auth
"args": [self.api_key, expires, signature]
File "/usr/local/lib/python3.6/site-packages/websocket/_app.py", line 203, in send
if not self.sock or self.sock.send(data, opcode) == 0:
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 283, in send
return self.send_frame(frame)
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 311, in send_frame
l = self._send(data)
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 525, in _send
return send(self.sock, data)
File "/usr/local/lib/python3.6/site-packages/websocket/_socket.py", line 146, in send
raise WebSocketConnectionClosedException("socket is already closed.")
websocket._exceptions.WebSocketConnectionClosedException: socket is already closed.
[root@iTrade ~]# websocket._exceptions.WebSocketConnectionClosedException: socket is already closed

what is causing this problem on Centos 7?

Unsubscribe from websocket topic (including individual symbols)

I've been trying to unsubscribe from certain topics and would prefer to avoid resetting the handler which has existing position and execution callbacks running.

# message
unsubscribe = sjson.dumps({
    "op": "unsubscribe",
    "args":["orderBookL2_25.BTCUSDT"]
})

# unsubscribe
self.client_bybit_ws.ws_private.ws.send(unsubscribe)
self.client_bybit_ws.ws_private._pop_callback("orderBookL2_25.BTCUSDT")

Is there a suggested method to accomplish unsubs?

pybit.exceptions.InvalidRequestError: Not modified (ErrCode: 130127)

I'm getting this error, trying to set a stoploss with set_trading_stop() for a short position at market price with place_active_order().

raise InvalidRequestError(
pybit.exceptions.InvalidRequestError: Not modified (ErrCode: 130127) (ErrTime: 08:54:26).
Request โ†’ POST https://api-testnet.bybit.com/private/linear/position/trading-stop: {'api_key': 'Te5LfVGIdMkQhbdVHz', 'recv_window': 5000, 'side': 'Sell', 'stoploss': 39754.92, 'symbol': 'BTCUSDT', 'timestamp': 1650790466271, 'sign': '813620351e4f189022f342a0fc3012d1b33bcd787c895bc85ea1a6eb31968ebe'}.

USDC http request "error sign" when set recv_window

Issue description

When set recv_window=2000 or others, just a number not equal to 5000,
USDC http request throws an error Error sign.

Troubleshoot

In __http_manager.py, line 268, "X-BAPI-RECV-WINDOW"="5000" is hard code.
It should be a variable.

How to edit stop loss on open position? ErrCode: 10001

Hello

I have a problem because I want to change stop loss on the open position but I get always errors.

This is my code:
entry_price: 1489

actual_bid_price: 1495.8

bybitAPI.session_auth.set_trading_stop(
    symbol=symbol,
    side="Buy",
    quantity= amount,
    tp_sl_mode= "Full",
    stop_loss= 1493
)
================ set up a new stop loss for LONG POSITION ================
long_position:  {'user_id': 2622388, 'symbol': 'ETHUSDT', 'side': 'Buy', 'size': 0.01, 
'position_value': 14.89, 'entry_price': 1489, 'liq_price': 1000.15, 'bust_price': 992.7, 
'leverage': 3, 'auto_add_margin': 0, 'is_isolated': True, 'position_margin': 4.96333324,
 'occ_closing_fee': 0.0059562, 'realised_pnl': -0.1003701, 'cum_realised_pnl': 458.48459275,
 'free_qty': -0.01, 'tp_sl_mode': 'Partial', 'unrealised_pnl': 0.075, 'deleverage_indicator': 2,
 'risk_id': 11, 'stop_loss': 0, 'take_profit': 0, 'trailing_stop': 0, 'position_idx': 1, 'mode': 'BothSide'}
Traceback (most recent call last):
  File "D:\Python\Trading Bot\ccxt\ccxt_bot_bybit.py", line 167, in <module>
    bybitAPI.session_auth.set_trading_stop(
  File "C:\Users\kuczy\AppData\Local\Programs\Python\Python310\lib\site-packages\pybit\usdt_perpetual.py", line 475, in set_trading_stop
    return self._submit_request(
  File "C:\Users\kuczy\AppData\Local\Programs\Python\Python310\lib\site-packages\pybit\_http_manager.py", line 385, in _submit_request
    raise InvalidRequestError(
pybit.exceptions.InvalidRequestError: Param validation for 'side' failed on the 'linear_side' tag (ErrCode: 10001) (ErrTime: 14:54:12).
Request โ†’ POST https://api.bybit.com/private/linear/position/trading-stop: 
{'api_key': '', 'quantity': 0.01, 'recv_window': 5000, 'side': 'buy', 'stop_loss': 1493,
 'symbol': 'ETHUSDT', 'timestamp': 1658415251697, 'tp_sl_mode': 'full', 'sign': 
'97f37cfc10c80ec26e74a4e7a17c1ae118837c95f9c527942b5b063def56936a'}.

examples are not working properly

I am using the Websocket example, to get kline data periodically. The sample program I am starting with is:

from pybit import inverse_perpetual
from pybit import spot

# Set up logging (optional)
import logging
logging.basicConfig(filename="pybit.log", level=logging.DEBUG,
                    format="%(asctime)s %(levelname)s %(message)s")
def kline_stream_callback(message):
    print("recieved " + message)
ws_spot = spot.WebSocket(test=False)
# ws_spot.kline_stream(kline_stream_callback, "BTCUSDT", 5)
while True:
    sleep(1)

This is the result:

Traceback (most recent call last):
  File "/home/mansour/workspace/bot/./bot.py", line 19, in <module>
    ws_spot = spot.WebSocket(test=False)
  File "/home/mansour/workspace/bot/lib/python3.9/site-packages/pybit/spot.py", line 396, in __init__
    self.public_kwargs = _make_public_kwargs(self.kwargs)
  File "/home/mansour/workspace/bot/lib/python3.9/site-packages/pybit/_websocket_stream.py", line 662, in _make_public_kwargs
    public_kwargs.pop("api_key")
KeyError: 'api_key'

I am using 2.2.1:

Name: pybit
Version: 2.1.1
Summary: Python3 Bybit HTTP/WebSocket API Connector
Home-page: https://github.com/bybit-exchange/pybit

Issue with USDT Perp Liquidation_Stream

I've spent several hours trying to figure this roadblock out but haven't had any luck. I'm somewhat new to pybit so hopefully this is a simple fix. I'm trying to consume the usdt perp liquidation stream. My results have been fairly inconsistent.

When I run the following code, I am able to print the liquidation stream to the console:
image

If I try to manipulate the websocket feed, I don't get any response from the websocket nor does it print the liquidation stream to console:
image

Any ideas would be appreciated!

ping/pong timed out

After that error message:

WebSocket USDT Perp encountered error: ping/pong timed out.

it just stop working and no reconnect

Error on object has no attribute 'endpoint'

self._connect(self.endpoint)

Error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/websocket/_app.py", line 424, in _callback
    callback(self, *args)
  File "/usr/local/lib/python3.10/site-packages/pybit/_websocket_stream.py", line 84, in <lambda>
    on_error=lambda ws, err: self._on_error(err)
  File "/usr/local/lib/python3.10/site-packages/pybit/_websocket_stream.py", line 147, in _on_error
    self._connect(self.endpoint)
AttributeError: '_FuturesWebSocketManager' object has no attribute 'endpoint'

Looks like the line should be self._connect(url) instead referenceing def __init__, however url is not a class variable, and it is limited within the scope of __init__. Should the variable url be stored as self.url instead?

For USDC Perp wallet_fund_records() has wrong endpoint

Repro:

            from pybit import usdc_perpetual as exchange
            from pybit.usdc_perpetual import HTTP

            self.session = HTTP(
                endpoint=endpoint,
                api_key=PadmaConfig().TRADE_KEY,
                api_secret=PadmaConfig().TRADE_SEC
            )

        fundings = self.session.wallet_fund_records(limit=50)

Error message:

...
raise FailedRequestError(
pybit.exceptions.FailedRequestError: Http status code is not 200. (ErrCode: 404) (ErrTime: 13:09:41).
Request โ†’ POST https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/query-transaction-log: {'limit': 50}.

Issue get fixed by changing line # 258 in usdc_perpetual.py from:

suffix = "/perpetual/usdc/openapi/private/v1/query-transaction-log"
to:

suffix = "/option/usdc/openapi/private/v1/query-transaction-log"

Is there a way to interact with bots?

Hi,

I would like to be able to interact with grid bots. Ideally, monitor the specific bot and being able to terminate it. Is there a way to do this in this API?

Thanks for any help!

Connection reset by peer - randomly occurring

I seem to be "randomly" getting the following error:
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

I am not sure what the cause for this is, after the bot has just started there does not seem to be any issue at all, it's after it has been running for a little while (it seems like). This error occurs while trying to poll wallet data as well as trying to place orders (so kind of a big deal..)

Is it intended to create a new HTTP session each time you want to perform some actions?
For example every time I try to create an order and add multiple trading stops, I recreate a new http session?

EDIT: The weird part is that it seems to go back to working a little bit after the failed attempt (but only temporarily)
It's as if the connection goes into some kind of sleep state then gets nudged to wake up and slowly restores itself (temporarily)
This does NOT happen quickly though, sometimes I can ask to poll the wallet info 3-5 times over the span of a couple of minutes before it finally works again.

Get Leverage

Hello,

is there any way how to retrieve currently set leverage? I've found only set leverage, max_leverage etc in sources here and no success with ByBit API Docs. Thanks

Websocket usdt_perpetual query_kline returns 0 results in docker

Hi,

I was trying to use usdt_perpetual query_kline method from latest stable version + 2.4.1rc0 version. For both versions it works well locally, but once I'm wrapping up application inside docker it stops to return results.

`
self.session = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key=BYBIT_API_KEY,
api_secret=BYBIT_API_SECRET
)
def __get_timestamp_now(self):
date_time = time.mktime(datetime.utcnow().timetuple())
return date_time

klines = self.session.query_kline(symbol=ticker,interval=interval, from_time=self.__get_timestamp_now())

`

requirements.txt

pandas==1.4.2 pymongo==4.1.1 dnspython==2.2.1 requests>=2.22.0 websocket-client>=0.57.0 pybit==2.4.1rc0

Dockerfile
`
FROM python:3.8

COPY ./app/ ./

RUN pip install -r requirements.txt

CMD ["python", "main.py"]

`

Current API endpoint isn't uptodate for Deposit and Withdrawals

Function :
def wallet_fund_records uses
'/v2/private/wallet/fund/records

based on the documentation it doesn't show all transfers
'Deposit or withdrawal records which occurred after 2021-07-15 will not be shown by this endpoint. To fetch records after this date you should call the Query Deposit Records and Query Withdraw Records endpoints. This is due to the introduction of the spot wallet at this time.'

any chance to include
/asset/v1/private/withdraw/record/query
/asset/v1/private/deposit/record/query

to get accurate transaction histories ?

Spot websocket kline_v2_stream

Hey,

i am getting error on kline v2 1 minute subscription for multiple symbols

 raise Exception("Spot subscription failed.")
Exception: Spot subscription failed.
 self.ws_spot.kline_v2_stream(callback=self.process_candles, symbol=["BTCUSDT", "ETHUSDT"], interval='1m')

for one symbol as string and not list works OK

Thank you for help.

Websocket Spot topics don't resubscribe after connection errors

When using websocket in Spot, the list self.subscriptions is always empty. So in case of a connection error, when the connection is reopen, previous topics aren't resubscribed.

I simply fixed it adding self.subscriptions.append(json.dumps(topic)) at the end of the subscribe method inside _SpotWebSocketManager class.

query symbol info by sybmol

i want to know specific info like the min trade quantity of a symbol but i have to do a for loop to get to the symbol then i can look for the min quantity

do you guys plan on allowing us to send the symbol as a parameter ... doesn't seem like it should be necessary to for loop to get the info of a symbol

min_trading_qty = 0
for i in pybit_bybit_test_ex.query_symbol()['result']:
if i['name'] == tradingPair_pybit:
min_trading_qty = i['lot_size_filter']['min_trading_qty']

i should just be able to do
pybit_bybit_test_ex.query_symbol(tradingPair_pybit)['lot_size_filter']['min_trading_qty']

Websocket Stream Disconnects

Errors: (just a collection of the error msgs recieved from bybit)
WebSocket USDT Perp encountered error: ping/pong timed out.
WebSocket USDT Perp (Auth) encountered error: Handshake status 502 Bad Gateway.
WebSocket USDT Perp (Auth) encountered error: [Errno 104] Connection reset by peer.
WebSocket USDT Perp (Auth) encountered error: Connection to remote host was lost..
WebSocket USDT Perp (Auth) encountered error: socket is already closed.

These are the errors I keep getting at random times. I am using a VPS.

The problem is maintaining the connection to the websocket stream. I need a constant stream of price data. I am well within any rate limits. Pybit will reconnect but sometimes hang or timeout. It takes 4 seconds max to restart my script with a bash script compared to 1min+ waiting for Pybit. If I completely restart my connection I get far less future errors which with ping/pong times can stack up. For some reason restarting like this seems to reset something on their side.

-ping_interval=20, ping_timeout=20
-pybit is up to date

Access deined for API

Python 3.7.13 (default, Mar 16 2022, 21:15:28) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pybit import usdt_perpetual
>>> API_KEY = "I0q5hohm2cp4wkeccf"
>>> API_SECRET = "VO3kERin4RyEqWPolGgf8XChRk2TKXZtkGwp"
>>> IS_TEST = True #set to True if you  are using testnet
>>> 
>>> session = usdt_perpetual.HTTP(
...     endpoint='https://api.bybit.com', 
...     api_key=API_KEY,
...     api_secret=API_SECRET
... )
>>> 
>>> session.place_active_order(
...     position_idx=1,
...     symbol="BTCUSDT",
...     side="Buy",
...     order_type="Market",
...     qty=0.004,
...     time_in_force="GoodTillCancel",
...     reduce_only=False,
...     close_on_trigger=False
... )
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.7/site-packages/requests/models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "/app/.heroku/python/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/app/.heroku/python/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/app/.heroku/python/lib/python3.7/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.7/site-packages/pybit/_http_manager.py", line 259, in _submit_request
    s_json = s.json()
  File "/app/.heroku/python/lib/python3.7/site-packages/requests/models.py", line 917, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: [Errno Expecting value] <HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>
 
You don't have permission to access "http&#58;&#47;&#47;api&#46;bybit&#46;com&#47;private&#47;linear&#47;order&#47;create" on this server.<P>
Reference&#32;&#35;18&#46;df4fde17&#46;1649587484&#46;3877d12d
</BODY>
</HTML>
: 0

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
  File "/app/.heroku/python/lib/python3.7/site-packages/pybit/usdt_perpetual.py", line 142, in place_active_order
    auth=True
  File "/app/.heroku/python/lib/python3.7/site-packages/pybit/_http_manager.py", line 272, in _submit_request
    time=dt.utcnow().strftime("%H:%M:%S")
pybit.exceptions.FailedRequestError: Conflict. could not decode json. (ErrCode: 409) (ErrTime: 10:44:44).
Request โ†’ POST https://api.bybit.com/private/linear/order/create: {'api_key': 'I0q5hohm2cp4wkeccf', 'close_on_trigger': False, 'order_type': 'Market', 'position_idx': 1, 'qty': 0.004, 'recv_window': 5000, 'reduce_only': False, 'side': 'Buy', 'symbol': 'BTCUSDT', 'time_in_force': 'GoodTillCancel', 'timestamp': 1649587484932, 'sign': '618b588c8887a794f591fed3fee1388b0ddcb9d2934d1eb34c542851835078eb'}.
>>> 

Cannot establish connection with usdt_perpetual module

ISSUE: I cannot establish a wss connection using the usdt_perpetual modul, whereas with the inverse_perpetual it works fine.

HOW TO REPRODUCE:
Clone the example here https://github.com/bybit-exchange/pybit/blob/master/examples/websocket_example.py and replace the inverse_perpetual with usdt_perpetual. Instead or printing the public order book data as it does with the inverse_perpetual module it returns an error: "Couldn't subscribe to topic.Error: error:handler not found."

POTENTIAL TRIGGER:
I have investigated both modules and found that for the inverse_perpetual the wss URL is built as "wss://stream-testnet.bybit.com/realtime" where as in the usdt_perpetual the url is built as

PUBLIC_WSS = "wss://{SUBDOMAIN}.{DOMAIN}.com/realtime_public"
PRIVATE_WSS = "wss://{SUBDOMAIN}.{DOMAIN}.com/realtime_private"

which are as the official urls from the docs at https://bybit-exchange.github.io/docs/linear/#t-websocket
However, they just do not work. When I hack the usdt_perpetual module and change the URLs to

PUBLIC_WSS = "wss://{SUBDOMAIN}.{DOMAIN}.com/realtime"
PRIVATE_WSS = "wss://{SUBDOMAIN}.{DOMAIN}.com/realtime"

connection is established and order data is received. So either the URLs are broken or I am missing something.

Cannot authenticate private WebSocket subscription

pybit-2.0.1
python 3.8

applied API key/secret was valid for placing orders, so the key/secret should be ok.
problem:
...DEBUG Authorization for Inverse Perp (Auth) failed. Please check your API keys and restart.
...ERROR Couldn't subscribe to topic.Error: error:topic:position needs auth first.

" needs auth first??" are there other methods to do auth?

#https://github.com/bybit-exchange/pybit
from time import sleep
from pybit import inverse_perpetual
import logging

logging.basicConfig(filename="pybit3.log", level=logging.DEBUG,
                    format="%(asctime)s %(levelname)s %(message)s")

api_key = '*********************'
api_secret = '*****************************'
# Connect with authentication!
ws = inverse_perpetual.WebSocket(
    test=False,
    api_key=api_key,
    api_secret=api_secret,
    domain="bybit"
)

def handle_position(message):
    print(message)
ws.position_stream(handle_position)

while True:
    sleep(0.1)
#
# LOG output:
# DEBUG WebSocket Inverse Perp (Auth) closed.
# DEBUG WebSocket Inverse Perp (Auth) opened.
# DEBUG Authorization for Inverse Perp (Auth) failed. Please check your API keys and restart.
# ERROR Couldn't subscribe to topic.Error: error:topic:position needs auth first.

Websocket usdt_perpetual stream disconnects and can't reconnect

Hello,

I'm using the usdt_perpetual module to stream Bybit klines.
It works fine for a few hours, but then disconnects.
I enabled trace_logging=True, and it doesn't seem to be able to reconnect. Here are the logs :

++Rcv raw: b'\x81~\x01\x1b{"topic":"candle.5.AXSUSDT","data":[{"start":1662243600,"end":1662243900,"period":"5","open":15.29,"close":15.22,"high":15.325,"low":15.205,"volume":"935.2","turnover":"14273.646","confirm":false,"cross_seq":15485606634,"timestamp":1662243850641934}],"timestamp_e6":1662243850641934}'
++Rcv decoded: fin=1 opcode=1 data=b'{"topic":"candle.5.AXSUSDT","data":[{"start":1662243600,"end":1662243900,"period":"5","open":15.29,"close":15.22,"high":15.325,"low":15.205,"volume":"935.2","turnover":"14273.646","confirm":false,"cross_seq":15485606634,"timestamp":1662243850641934}],"timestamp_e6":1662243850641934}'
++Rcv raw: b'\x81~\x01\x1b{"topic":"candle.5.AXSUSDT","data":[{"start":1662243600,"end":1662243900,"period":"5","open":15.29,"close":15.22,"high":15.325,"low":15.205,"volume":"935.2","turnover":"14273.646","confirm":false,"cross_seq":15485606634,"timestamp":1662243850644262}],"timestamp_e6":1662243850644262}'
++Rcv decoded: fin=1 opcode=1 data=b'{"topic":"candle.5.AXSUSDT","data":[{"start":1662243600,"end":1662243900,"period":"5","open":15.29,"close":15.22,"high":15.325,"low":15.205,"volume":"935.2","turnover":"14273.646","confirm":false,"cross_seq":15485606634,"timestamp":1662243850644262}],"timestamp_e6":1662243850644262}'
++Sent raw: b'\x89\x80\xad\x07\x9c2'
++Sent decoded: fin=1 opcode=9 data=b''
WebSocket USDT Perp encountered error: ping/pong timed out.
++Sent raw: b'\x88\x82\xec\xf1\x0f\x85\xef\x19'
++Sent decoded: fin=1 opcode=8 data=b'\x03\xe8'
++Sent raw: b'\x81\xb1\xf2\xc9\x9e\xfa\x89\xeb\xf1\x8a\xd0\xf3\xbe\xd8\x81\xbc\xfc\x89\x91\xbb\xf7\x98\x97\xeb\xb2\xda\xd0\xa8\xec\x9d\x81\xeb\xa4\xda\xa9\xeb\xfd\x9b\x9c\xad\xf2\x9f\xdc\xfc\xb0\xbb\xaa\x9a\xcb\xa9\xb6\x9d\xbc\xa7\x8f'
++Sent decoded: fin=1 opcode=1 data=b'{"op": "subscribe", "args": ["candle.5.AXSUSDT"]}'
error from callback <function _WebSocketManager._connect.<locals>.<lambda> at 0x00000222BF23CC10>: socket is already closed.
WebSocket USDT Perp encountered error: socket is already closed..
--- request header ---
GET /realtime_public HTTP/1.1
Upgrade: websocket
Host: stream-testnet.bybit.com
Origin: https://stream-testnet.bybit.com
Sec-WebSocket-Key: HF5PXGToDNRnc7JCO3ZDUQ==
Sec-WebSocket-Version: 13
Connection: Upgrade


-----------------------
--- response header ---
websocket disconnected (retrying in 5 seconds) [7 frames in stack]
HTTP/1.1 101 Switching Protocols
Sec-WebSocket-Accept: jVFinKapUVFnjs3B0R5fx5dZoF4=
Expires: Sat, 03 Sep 2022 22:24:55 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Sat, 03 Sep 2022 22:24:55 GMT
Upgrade: websocket
Connection: Upgrade
-----------------------
websocket connected
websocket disconnected (retrying in 5 seconds) [7 frames in stack]
--- request header ---
GET /realtime_public HTTP/1.1
Upgrade: websocket
Host: stream-testnet.bybit.com
Origin: https://stream-testnet.bybit.com
Sec-WebSocket-Key: ZMMWFVzHAzUmatblWoXGKw==
Sec-WebSocket-Version: 13
Connection: Upgrade


-----------------------
--- response header ---
--- request header ---
GET /realtime_public HTTP/1.1
Upgrade: websocket
Host: stream-testnet.bybit.com
Origin: https://stream-testnet.bybit.com
Sec-WebSocket-Key: GIlYLnCLUGZCaI5hROrnPw==
Sec-WebSocket-Version: 13
Connection: Upgrade


-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Sec-WebSocket-Accept: 2P12LiCY939ONnncphWCe5Bm4Ug=
Expires: Sat, 03 Sep 2022 22:25:00 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Sat, 03 Sep 2022 22:25:00 GMT
Upgrade: websocket
Connection: Upgrade
-----------------------
websocket connected
HTTP/1.1 101 Switching Protocols
Sec-WebSocket-Accept: MMXg+w5KwECRxBzcWxYP+n66txY=
Expires: Sat, 03 Sep 2022 22:25:01 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Sat, 03 Sep 2022 22:25:01 GMT
Upgrade: websocket
Connection: Upgrade
-----------------------
websocket connected
++Sent raw: b'\x89\x80\x9f\x89H\x84'
++Sent decoded: fin=1 opcode=9 data=b''
++Sent raw: b'\x89\x80\xe0\xe6\x15\x9f'
++Sent decoded: fin=1 opcode=9 data=b''
++Sent raw: b'\x89\x80\x91\x8f\xf3\xfc'
++Sent decoded: fin=1 opcode=9 data=b''
++Sent raw: b'\x89\x80\x8e\xb5\xf3\x91'
++Sent decoded: fin=1 opcode=9 data=b''
++Sent raw: b'\x89\x80~\xccC`'
++Sent decoded: fin=1 opcode=9 data=b''
++Sent raw: b'\x89\x80\xd4A\xa3\xc3'
++Sent decoded: fin=1 opcode=9 data=b''
++Sent raw: b'\x89\x80\xa7|\nX'
++Sent decoded: fin=1 opcode=9 data=b''

In the first lines, the stream still worked. Then it seems to disconnect, and I haven't received any new values from the stream since. At the end, the last lines ("Sent raw" and "Sent decoded") repeat indefinitely.

I am able to detect a lack of new values, indicating a stream disconnection. I tried some methods to relaunch the stream when I detect this disconnection, but they didn't work.

Thanks for your help !

Endpoints are unstable and not working over a prolonged period

Here is a traceback. It might be working for 1 hour, then it just starts timing out. Please fix this?

Traceback (most recent call last):
  File ".\main.py", line 39, in <module>
    print(ex)
  File ".\main.py", line 28, in start_trading
    endpoint=config['bybit_endpoint'],
  File "C:\Users\caspe\Documents\GitHub\TradingBot\core\transactions\bybit.py", line 45, in start_from_now
    return self._extract_data(get_data_from, interval=interval)
  File "C:\Users\caspe\Documents\GitHub\TradingBot\core\transactions\bybit.py", line 155, in _extract_data
    out = self.session.query_kline(
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\pybit\usdt_perpetual.py", line 30, in query_kline
    return self._submit_request(
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\pybit\_http_manager.py", line 291, in _submit_request
    raise e
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\pybit\_http_manager.py", line 278, in _submit_request
    s = self.client.send(r, timeout=self.timeout)
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\requests\sessions.py", line 701, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\requests\adapters.py", line 578, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='api-testnet.bybit.com', port=443): Read timed out. (read timeout=20)

pybit trying to subscribe to too many topics in a single WS subscription message

pybit trying to subscribe to too many topics in a single WS subscription message and returnin connection error

from pybit import spot
import time

count = 0

ws_spot = spot.WebSocket(
test=False,
domain="bybit",

)

spot = ['BITUSDT','EOSUSDT','DRIVUSDT','XRPUSDT','UNIUSDT','LGXUSDT','BITUSDC','LTCUSDT','SOLUSDT','ATOMUSDT','CHZUSDT','KOKUSDT','BITBTC','AVAXUSDT','SLGUSDT','SLPUSDT','DOGEUSDT','DYDXUSDT','COTUSDT','ALGOUSDT','GMXUSDT','BARUSDT','XLMUSDT','DASHUSDT','MANAUSDT','QNTUSDT','FTMUSDT','OPUSDT','RAINUSDT','SIDUSUSDT','INTERUSDT','XRPBTC','BELUSDT','MVUSDT','MATICUSDT','LINKUSDT','PSGUSDT','SEORUSDT','AZYUSDT','GALAUSDT','DOTUSDT','YFIUSDT','WAVESUSDT','MKRUSDT','LDOUSDT','BNBUSDT','BCHUSDT','MMCUSDT','CRVUSDT','ICPUSDT','APEUSDT','ETCUSDT','CULTUSDT','NXDUSDT','PLTUSDT','TAPUSDT','APEXUSDT','SANDUSDT','ADAUSDT','SLGUSDC','LUNCUSDT','DEFYUSDT','XRPUSDC','GSTSUSDT','EOSUSDC','BITDAI','KONUSDT','VINUUSDT','SHIBUSDT','CMPUSDT','XETAUSDT','USTCUSDT','GMTUSDT','PERPUSDT','XWGUSDT','SUSHIUSDT','NEARUSDT','CELUSDT','TELUSDT','GRTUSDT','KLAYUSDT','MNZUSDT','CITYUSDT','XDCUSDT','ACMUSDT','LUNAUSDT','FITFIUSDT','KUNCIUSDT','STATUSDT','SNXUSDT','WOOUSDT','FILUSDT','JUVUSDT','SPELLUSDT','AFCUSDT','DEVTUSDT','ZAMUSDT','ZRXUSDT','ENSUSDT','CRAFTUSDT','STRMUSDT','MXUSDT','FLOWUSDT','AAVEUSDT','FLOKIUSDT','KASTAUSDT','VPADUSDT','MBSUSDT','STGUSDT','CBXUSDT','SRMUSDT','ANKRUSDT','CAKEUSDT','C98USDT','OBXUSDT','CELOUSDT','ROSEUSDT','SOLOUSDT','GMUSDT','EGLDUSDT','TRIBEUSDT','THETAUSDT','RUNEUSDT','ERTHAUSDT','ZILUSDT','LRCUSDT','ZBCUSDT','POKTUSDT','FTTUSDT','FIUUSDT','HNTUSDT','ZECUSDT','ONEUSDT','DFIUSDT','BICOUSDT','DAIUSDT','IMXUSDT','DOMEUSDT','WLKNUSDT','COMPUSDT','JASMYUSDT','1SOLUSDT','GALUSDT','AXSUSDT','DOTUSDC','ENJUSDT','LFWUSDT','DICEUSDT','SOLUSDC','MANAUSDC','MELOSUSDT','WEMIXUSDT','QTUMUSDT','SISUSDT','LOOKSUSDT','BATUSDT','FCDUSDT','XEMUSDT','UMAUSDT','XTZUSDT','AGLDUSDT','GALFTUSDT','SAITAMAUSDT','KSMUSDT','RENUSDT','MOVEZUSDT','LTCUSDC','BOBAUSDT','THNUSDT','SDUSDT','GLMRUSDT','MINAUSDT','FORTUSDT','SCRTUSDT','GSTUSDT','LUNCUSDC','GENEUSDT','RACAUSDT','PAXGUSDT','SCUSDT','SOLBTC','RVNUSDT','MANABTC','RNDRUSDT','LTCBTC','AVAUSDT','REALUSDT','MATICUSDC','HBARUSDT','1INCHUSDT','FIDAUSDT','SFUNDUSDT','STXUSDT','HEROUSDT','DFLUSDT','GODSUSDT','IMEUSDT','PLYUSDT','SANDUSDC','WBTCUSDT','DOGEUSDC','DOTBTC','MOVRUSDT','KDAUSDT','JSTUSDT','USDDUSDT','ICXUSDT','OMGUSDT','BNTUSDT','GASUSDT','XLMUSDC','SANDBTC','MATICBTC','SYNRUSDT','CAPSUSDT','SOSUSDT','SONUSDT','BTTUSDT','ZENUSDT','BTGUSDT','AMPUSDT','AVAXUSDC','GGMUSDT','INSURUSDT','ACAUSDT','FAMEUSDT','ELTUSDT','OPUSDC','WBTCBTC','CUSDUSDT','XLMBTC','XYMUSDT','ARUSDT','XAVAUSDT','ADAUSDC','ALGOBTC','XECUSDT','SUNUSDT','PTUUSDT','WAXPUSDT','HOTUSDT','DGBUSDT','CTCUSDT','PSPUSDT','PSTAKEUSDT','IZIUSDT','NFTUSDT','TUSDT','KMAUSDT','MIXUSDT','KMONUSDT','ACHUSDT','SHILLUSDT','LMRUSDT','KRLUSDT','DCRUSDT','NEXOUSDT','POSIUSDT','RSS3USDT','CWARUSDT','TRVLUSDT',]

def handle_message(msg):
global count
count = count + 1
symbol = msg['symbol']
print('processing: ',symbol, count)

ws_spot.depth_v1_stream(handle_message, spot)

while True:

time.sleep(1)

photo_2022-08-24_13-47-51 (2)
photo_2022-08-24_13-47-51

USDC perpetual WebSocket auth returning False

Opening a USDC WebSocket correctly yields ws_auth.auth to be False.
By bypassing the auth check I can see orders appear so this means that the connection has been opened correctly.

Code for repro:

            from pybit import usdc_perpetual as exchange

            self.ws_auth = exchange.WebSocket(
                    test=False,
                    api_key=TRADE_KEY,
                    api_secret=RADE_SEC
            )
            time.sleep(3)

            if not self.ws_auth.auth:
                logger.error("WebSocket doesn't have Auth.")
                exit()
            else:
                logger.info("WebSocket Auth successful.")

Websocket handler needs to take extra arguments

The websocket handler has poor flexibility. It should be able to take in extra arguments to call the handler function, so a dataframe or database object can be passed, or so that it can be used in a class.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.