python-binance icon indicating copy to clipboard operation
python-binance copied to clipboard

proxy for AsyncClient

Open hyperdesignir opened this issue 3 years ago • 5 comments

Error using proxy in AsyncClient

I use this code to create client:

from binance.client import AsyncClient
import asyncio

proxies = {
    'http': 'http://username:password@myip:port',
}
async def main():
    client = AsyncClient(api_key, secret_key, {'proxies': proxies})
    print(await client.get_symbol_ticker(symbol='BTCUSDT', requests_params={'proxies': proxies}))


loop = asyncio.get_event_loop()
server = loop.run_until_complete(main())

loop.run_forever()
loop.close()

Expected behavior I want to connect to binance api , but i get error.

TypeError: _request() got an unexpected keyword argument 'proxies'

  • Python version: 3.8
  • Virtual Env: virtualenv
  • OS: windows
  • python-binance version: 1.0.12

My error log is:

Traceback (most recent call last):
  File "C:/Projects/Targetbot/a.py", line 13, in <module>
    server = loop.run_until_complete(main())
  File "C:\Users\Amin\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "C:/Projects/Targetbot/a.py", line 10, in main
    print(await client.get_symbol_ticker(symbol='BTCUSDT', requests_params={'proxies': proxies}))
  File "C:\Projects\pythonProject\venv\lib\site-packages\binance\client.py", line 6836, in get_symbol_ticker
    return await self._get('ticker/price', data=params, version=self.PRIVATE_API_VERSION)
  File "C:\Projects\pythonProject\venv\lib\site-packages\binance\client.py", line 6551, in _get
    return await self._request_api('get', path, signed, version, **kwargs)
  File "C:\Projects\pythonProject\venv\lib\site-packages\binance\client.py", line 6514, in _request_api
    return await self._request(method, uri, signed, **kwargs)
  File "C:\Projects\pythonProject\venv\lib\site-packages\binance\client.py", line 6495, in _request
    async with getattr(self.session, method)(uri, **kwargs) as response:
  File "C:\Projects\pythonProject\venv\lib\site-packages\aiohttp\client.py", line 896, in get
    self._request(hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs)
TypeError: _request() got an unexpected keyword argument 'proxies'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001A5216A9BB0>

hyperdesignir avatar Sep 30 '21 17:09 hyperdesignir

The AsyncClient uses aoihttp which has some different parameters to requests which is used in the Client class.

Can you try using just proxy, see docs here https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.ClientSession, look for the requests definition.

print(await client.get_symbol_ticker(symbol='BTCUSDT', requests_params={'proxy': 'http://username:password@myip:port'}))

sammchardy avatar Oct 04 '21 03:10 sammchardy

Hi! I tried to run the above mentioned code and I can't get to work proxy with AsyncClient.

import asyncio
from binance import AsyncClient
import config

async def main():
    client = await AsyncClient.create(config.API_KEY, config.API_SECRET, requests_params={'verify_ssl' : False, 'proxy': config.proxy_address})

    print(await client.get_symbol_ticker(symbol='BTCUSDT'))

    await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Running it I receive the following error:

aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.binance.com:443 ssl:False [The parameter is incorrect]
Unclosed client session

@sammchardy If I use it like: await client.get_symbol_ticker(symbol='BTCUSDT', requests_params={'verify_ssl' : False, 'proxy': config.proxy_address}) Then I get error that "expected 1 argument, but received 2"

Even if I skip the verify_ssl argument, I get the same errors. Please help how to fix it or let me know a way around this. Thank you in advance.

ZsenialisTeknos avatar Nov 05 '21 18:11 ZsenialisTeknos

You can get full control to aiohttp session through this:

` from aiohttp_socks import ProxyConnector class CAsyncClient(AsyncClient): def init(self,*arg,**args): super().init(*arg, **args)

def _init_session(self) -> aiohttp.ClientSession:
    connector = ProxyConnector.from_url('socks5://127.0.0.1:1086')

    session = aiohttp.ClientSession(
        loop=self.loop,
        headers=self._get_headers(),
        connector=connector
    )
    return session`

use CAsyncClient replace AsyncClient, custom your session by modify my code. You should pip3 install aiohttp-socks first, by the way.

RogerWenXin avatar Jan 24 '22 12:01 RogerWenXin

You can get full control to aiohttp session through this:

` from aiohttp_socks import ProxyConnector class CAsyncClient(AsyncClient): def init(self,*arg,**args): super().init(*arg, **args)

def _init_session(self) -> aiohttp.ClientSession:
    connector = ProxyConnector.from_url('socks5://127.0.0.1:1086')

    session = aiohttp.ClientSession(
        loop=self.loop,
        headers=self._get_headers(),
        connector=connector
    )
    return session`

use CAsyncClient replace AsyncClient, custom your session by modify my code. You should pip3 install aiohttp-socks first, by the way.

IT DOES work with functions in AsyncClient class. but failed in BinanceSocketManager even pass the CAsyncClient to BinanceSocketManager ,could it be be possible with all?

alexflrl avatar Oct 30 '22 12:10 alexflrl

{'proxy': config.proxies["http"]} its worked for me in AsyncClient

nikitamikitin avatar Jul 25 '23 11:07 nikitamikitin