Skip to content

Commit 4b8d1ed

Browse files
animiccarlosmiei
andauthored
feat: add proxy support to WS (sammchardy#1467)
* feat: add https_proxy support for ThreadedWebsocketManager and BinanceSocketManager * handle refactor * remove requirement * add readme --------- Co-authored-by: carlosmiei <43336371+carlosmiei@users.noreply.github.com>
1 parent 2eeeeae commit 4b8d1ed

File tree

5 files changed

+30
-4
lines changed

5 files changed

+30
-4
lines changed

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ Features
7777
- Futures Trading
7878
- Porfolio Margin Trading
7979
- Vanilla Options
80-
- Proxy support
80+
- Proxy support (REST and WS)
8181
- Orjson support for faster JSON parsing
8282
- Support other domains (.us, .jp, etc)
8383

binance/ws/reconnecting_websocket.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,16 @@
1919
except ImportError:
2020
from websockets import ConnectionClosedError # type: ignore
2121

22+
23+
Proxy = None
24+
proxy_connect = None
25+
try:
26+
from websockets_proxy import Proxy as w_Proxy, proxy_connect as w_proxy_connect
27+
Proxy = w_Proxy
28+
proxy_connect = w_proxy_connect
29+
except ImportError:
30+
pass
31+
2232
import websockets as ws
2333

2434
from binance.exceptions import BinanceWebsocketUnableToConnect
@@ -41,6 +51,7 @@ def __init__(
4151
prefix: str = "ws/",
4252
is_binary: bool = False,
4353
exit_coro=None,
54+
https_proxy: Optional[str] = None,
4455
**kwargs,
4556
):
4657
self._loop = get_loop()
@@ -57,6 +68,7 @@ def __init__(
5768
self.ws_state = WSListenerState.INITIALISING
5869
self._queue = asyncio.Queue()
5970
self._handle_read_loop = None
71+
self._https_proxy = https_proxy
6072
self._ws_kwargs = kwargs
6173

6274
def json_dumps(self, msg):
@@ -93,10 +105,20 @@ async def connect(self):
93105
self._log.debug("Establishing new WebSocket connection")
94106
self.ws_state = WSListenerState.RECONNECTING
95107
await self._before_connect()
108+
96109
ws_url = (
97110
f"{self._url}{getattr(self, '_prefix', '')}{getattr(self, '_path', '')}"
98111
)
99-
self._conn = ws.connect(ws_url, close_timeout=0.1, **self._ws_kwargs) # type: ignore
112+
113+
# handle https_proxy
114+
if self._https_proxy:
115+
if not Proxy or not proxy_connect:
116+
raise ImportError("websockets_proxy is not installed, please install it to use a websockets proxy (pip install websockets_proxy)")
117+
proxy = Proxy.from_url(self._https_proxy) # type: ignore
118+
self._conn = proxy_connect(ws_url, close_timeout=0.1, proxy=proxy, **self._ws_kwargs) # type: ignore
119+
else:
120+
self._conn = ws.connect(ws_url, close_timeout=0.1, **self._ws_kwargs) # type: ignore
121+
100122
try:
101123
self.ws = await self._conn.__aenter__()
102124
except Exception as e: # noqa

binance/ws/streams.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ def _get_socket(
8282
prefix=prefix,
8383
exit_coro=lambda p: self._exit_socket(f"{socket_type}_{p}"),
8484
is_binary=is_binary,
85+
https_proxy=self._client.https_proxy,
8586
**self.ws_kwargs,
8687
)
8788

@@ -104,6 +105,7 @@ def _get_account_socket(
104105
exit_coro=self._exit_socket,
105106
is_binary=is_binary,
106107
user_timeout=self._user_timeout,
108+
https_proxy=self._client.https_proxy,
107109
**self.ws_kwargs,
108110
)
109111

@@ -1094,10 +1096,11 @@ def __init__(
10941096
tld: str = "com",
10951097
testnet: bool = False,
10961098
session_params: Optional[Dict[str, Any]] = None,
1099+
https_proxy: Optional[str] = None,
10971100
loop: Optional[asyncio.AbstractEventLoop] = None,
10981101
):
10991102
super().__init__(
1100-
api_key, api_secret, requests_params, tld, testnet, session_params, loop
1103+
api_key, api_secret, requests_params, tld, testnet, session_params, https_proxy, loop
11011104
)
11021105
self._bsm: Optional[BinanceSocketManager] = None
11031106

binance/ws/threaded_stream.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ def __init__(
1515
tld: str = "com",
1616
testnet: bool = False,
1717
session_params: Optional[Dict[str, Any]] = None,
18+
https_proxy: Optional[str] = None,
1819
_loop: Optional[asyncio.AbstractEventLoop] = None,
1920
):
2021
"""Initialise the BinanceSocketManager"""
@@ -30,6 +31,7 @@ def __init__(
3031
"tld": tld,
3132
"testnet": testnet,
3233
"session_params": session_params,
34+
"https_proxy": https_proxy,
3335
}
3436

3537
async def _before_socket_listener_start(self): ...

setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
"six",
3535
"dateparser",
3636
"aiohttp",
37-
"ujson",
3837
"websockets",
3938
"pycryptodome",
4039
],

0 commit comments

Comments
 (0)