Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to access isolated margin user data stream? #109

Closed
CryptoFuturesAU opened this issue Sep 10, 2020 · 38 comments
Closed

How to access isolated margin user data stream? #109

CryptoFuturesAU opened this issue Sep 10, 2020 · 38 comments
Assignees
Labels
question Further information is requested
Projects

Comments

@CryptoFuturesAU
Copy link

Hi Oliver,

I can successfully connect to user data stream and margin user data stream using :
"example_userdata_stream.py" modifying the exchange to binance.com-margin to access cross margin data

which parts of the "example_userdata_stream.py" code do I modify to access isolated margin user data through the websocket stream?

Thank you

@CryptoFuturesAU CryptoFuturesAU added the question Further information is requested label Sep 10, 2020
@oliver-zehentleitner
Copy link
Member

There are 3 Userdata streams in the example for 3 different endpoints. com, je and us i think. it should be obvious to you if you read the names of the vars!

You can try to comment full lines with # to disable the code row and test if its still working.

@CryptoFuturesAU
Copy link
Author

I'm sorry its not obvious to me of how to set this up, i'm new python and coding in general. PLEASE can you add an example of a isolated margin account line in the "example_userdata_stream.py". I'm sure i'm not alone and that more people would appreciate your guidance.

@oliver-zehentleitner
Copy link
Member

oliver-zehentleitner commented Sep 10, 2020

Its not tested, hope it works!

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
import logging
import time
import threading
import os


# https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.INFO,
                    filename=os.path.basename(__file__) + '.log',
                    format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
                    style="{")

def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            print(oldest_stream_data_from_stream_buffer)

binance_api_key = ""
binance_api_secret = ""

# create instances of BinanceWebSocketApiManager
binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com-margin", throw_exception_if_unrepairable=True)

# set api key and secret in api manager
binance_websocket_api_manager.set_private_api_config(binance_api_key, binance_api_secret)

# create the userData streams
user_data_stream_id = binance_websocket_api_manager.create_stream('arr', '!userData')

# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_websocket_api_manager,))
worker_thread.start()

# monitor the streams
while True:
    binance_websocket_api_manager.print_stream_info(user_data_stream_id)
    time.sleep(1)

Good luck!

@CryptoFuturesAU
Copy link
Author

I dont understand, is this supposed to work for ISOLATED margin accounts? I can only receive data from my CROSS margin account using this code. Nowhere is it obvious where to input the symbol pair for ISOLATED margin account needed.

@oliver-zehentleitner
Copy link
Member

uh, ok, i did not understand your request.

isolated margin is new for me, did not know that.

https://binance-docs.github.io/apidocs/spot/en/#user-data-streams

New endpoints for listenKey management of isolated margin account:
    POST /sapi/v1/userDataStream/isolated
    PUT /sapi/v1/userDataStream/isolated
    DELETE /sapi/v1/userDataStream/isolated

The lib just offers spot and margin support. we have to update the code to add isolated support.

@oliver-zehentleitner oliver-zehentleitner added this to To do in Todo Sep 11, 2020
@oliver-zehentleitner oliver-zehentleitner moved this from To do to In progress in Todo Sep 12, 2020
@oliver-zehentleitner
Copy link
Member

Here is a pre release with support for isolated_margin:
https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/releases/tag/1.17.0

I am not able to test it! Would you test it and give me feedback?

You can install it with this command:
pip install https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/archive/1.17.0.tar.gz --upgrade

Use it with:
BinanceWebSocketApiManager(exchange="binance.com-isolated_margin")

@oliver-zehentleitner oliver-zehentleitner moved this from In progress to Suspended in Todo Sep 12, 2020
@CryptoFuturesAU
Copy link
Author

installed update 1.17.0:

with code

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
import logging
import time
import threading
import os
import keys


# https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.INFO,
                    filename=os.path.basename(__file__) + '.log',
                    format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
                    style="{")

def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            print(oldest_stream_data_from_stream_buffer)

binance_api_key = keys.api_key
binance_api_secret = keys.api_secret

# create instances of BinanceWebSocketApiManager
binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com-isolated_margin", throw_exception_if_unrepairable=True)

# set api key and secret in api manager
binance_websocket_api_manager.set_private_api_config(keys.api_key, keys.api_secret)

# create the userData streams
user_data_stream_id = binance_websocket_api_manager.create_stream('arr', 'trxbtc')

# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_websocket_api_manager,))
worker_thread.start()

i get error:

Exception in thread Thread-52:
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\asus\Documents\Personal\Corporate\Python\red_robin_isolatedmargin\websocket test.py", line 21, in print_stream_data_from_stream_buffer
    time.sleep(0.01)
NameError: name 'time' is not defined
Release unicorn-binance-websocket-api_1.16.9 is available, please consider updating! (Changelog: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/CHANGELOG.md)

@oliver-zehentleitner
Copy link
Member

  File "C:\Users\asus\Documents\Personal\Corporate\Python\red_robin_isolatedmargin\websocket test.py", line 21, in print_stream_data_from_stream_buffer
    time.sleep(0.01)
NameError: name 'time' is not defined

This error is in your test.py not in the lib!

Its in line 21: time.sleep(0.01)

Even if you wrote it in the code you posted here, i guess you forgot the import time part?!

@CryptoFuturesAU
Copy link
Author

I got the stream running using that same code a second time (not sure why) but the stream doesnt receive any updates of userdata.
In the api doc https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin it states that symbol sent is mandatory. Where do i input the symbol in the code?
When i try this the websocket receives no data:

user_data_stream_id = binance_websocket_api_manager.create_stream('arr', '!userData')

When i try this the websocket receives no data either:

user_data_stream_id = binance_websocket_api_manager.create_stream('arr', 'trxbtc')

@oliver-zehentleitner
Copy link
Member

Well, adding a symbol is different to all other userDataStreams. I dont know, how binance want the extra parameter, i will ask them in telegram.

@oliver-zehentleitner oliver-zehentleitner moved this from Suspended to In progress in Todo Sep 14, 2020
@oliver-zehentleitner
Copy link
Member

The answer:
You need to pass symbol when you create listenKey. Then you can use the key in the same manner as you do for other user stream

Thats different to the other userDataStreams, so it needs further code modifications...

oliver-zehentleitner added a commit that referenced this issue Sep 14, 2020
@oliver-zehentleitner
Copy link
Member

Can you test this please: 7313da1

ubwa.create_stream('arr', '!userData', symbol="trxbtc")

If not, please post me also the log files, but be careful and remove your api keys and listen_keys before posting them!

@oliver-zehentleitner
Copy link
Member

I found a bug and fixed it here: 3673e5e

@oliver-zehentleitner oliver-zehentleitner moved this from In progress to Suspended in Todo Sep 15, 2020
@CryptoFuturesAU
Copy link
Author

When I add this code to the existing code previous:

user_data_stream_id = binance_websocket_api_manager.create_stream(
    'arr', '!userData', symbol = 'MATICBTC')

I get this error:

TypeError: create_stream() got an unexpected keyword argument 'symbol'

How am I supposed to update the code properly?

@oliver-zehentleitner
Copy link
Member

I am going to prepare a release.

@CryptoFuturesAU
Copy link
Author

Current code:

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager \
import BinanceWebSocketApiManager
import logging
import time
import threading
import os
import keys


# https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.INFO,
                    filename=os.path.basename(__file__) + '.log',
                    format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
                    style="{")


def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = \
            binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            print(oldest_stream_data_from_stream_buffer)


# configure api key and secret for binance.com
api_key = keys.api_key
api_secret = keys.api_secret

# create instances of BinanceWebSocketApiManager
ubwa_com = BinanceWebSocketApiManager(exchange="binance.com")

# create the userData streams
user_stream_id = ubwa_com.create_stream('arr', '!userData', 
                                        api_key = api_key, api_secret = api_secret)

# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer,
                                        args=(ubwa_com,))
worker_thread.start()

# configure api key and secret for binance.com Isolated Margin
api_key = keys.api_key
api_secret = keys.api_secret

# create instances of BinanceWebSocketApiManager
ubwa_com_im = BinanceWebSocketApiManager(exchange = "binance.com-isolated_margin")

# create the userData streams
user_stream_id = ubwa_com_im.create_stream(
    'arr', '!userData', symbol = "ankrbtc", api_key = api_key, api_secret = api_secret)

# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, 
                                                            args=(ubwa_com_im,))
worker_thread.start()

I get these critical errors in log file:

2020-09-18 11:39:17,162 [INFO    ] 34460 38864 unicorn_binance_websocket_api_manager: New instance of unicorn_binance_websocket_api_manager 1.17.0.dev started ...
2020-09-18 11:39:17,163 [INFO    ] 34460 17912 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_frequent_checks() new instance created with frequent_checks_id=1600393157.1633549
2020-09-18 11:39:17,164 [INFO    ] 34460 40772 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_keepalive_streams() new instance created with keepalive_streams_id=1600393157.1643517
2020-09-18 11:39:17,262 [INFO    ] 34460 38864 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->create_stream(['arr'], ['!userData'], None, False, False) with stream_id=44ed6582-b47c-4709-91bf-b4d6a37d99a4
2020-09-18 11:39:17,266 [INFO    ] 34460 39832 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_add_socket_to_socket_list(44ed6582-b47c-4709-91bf-b4d6a37d99a4, ['arr'], ['!userData'], None, False, False)
2020-09-18 11:39:17,266 [INFO    ] 34460 39832 unicorn_binance_websocket_api_socket: BinanceWebSocketApiSocket->start_socket(44ed6582-b47c-4709-91bf-b4d6a37d99a4, ['arr'], ['!userData'])
2020-09-18 11:39:17,266 [INFO    ] 34460 38864 unicorn_binance_websocket_api_manager: New instance of unicorn_binance_websocket_api_manager 1.17.0.dev started ...
2020-09-18 11:39:17,267 [INFO    ] 34460 39832 unicorn_binance_websocket_api_restclient: BinanceWebSocketApiRestclient->get_listen_key() symbol=False
2020-09-18 11:39:17,270 [INFO    ] 34460 20428 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_frequent_checks() new instance created with frequent_checks_id=1600393157.2709842
2020-09-18 11:39:17,276 [INFO    ] 34460 27364 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_keepalive_streams() new instance created with keepalive_streams_id=1600393157.2769673
2020-09-18 11:39:17,418 [INFO    ] 34460 38864 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->create_stream(['arr'], ['!userData'], None, False, ANKRBTC) with stream_id=49c563f7-756e-4bc8-98df-130b2a3a1747
2020-09-18 11:39:17,422 [INFO    ] 34460 13804 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_add_socket_to_socket_list(49c563f7-756e-4bc8-98df-130b2a3a1747, ['arr'], ['!userData'], None, False, ANKRBTC)
2020-09-18 11:39:17,423 [INFO    ] 34460 13804 unicorn_binance_websocket_api_socket: BinanceWebSocketApiSocket->start_socket(49c563f7-756e-4bc8-98df-130b2a3a1747, ['arr'], ['!userData'])
2020-09-18 11:39:17,423 [INFO    ] 34460 13804 unicorn_binance_websocket_api_restclient: BinanceWebSocketApiRestclient->get_listen_key() symbol=ANKRBTC
2020-09-18 11:39:17,545 [CRITICAL] 34460 39832 unicorn_binance_websocket_api_manager: Received known error code from rest client: {'code': -2014, 'msg': 'API-key format invalid.'}
2020-09-18 11:39:17,545 [CRITICAL] 34460 39832 unicorn_binance_websocket_api_connection: BinanceWebSocketApiConnection->await._conn.__aenter__(44ed6582-b47c-4709-91bf-b4d6a37d99a4, ['arr'], ['!userData']) -  error: 4 - API-key format invalid.
2020-09-18 11:39:17,546 [CRITICAL] 34460 39832 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->stream_is_crashing(44ed6582-b47c-4709-91bf-b4d6a37d99a4)
2020-09-18 11:39:17,672 [CRITICAL] 34460 13804 unicorn_binance_websocket_api_manager: Received unknown error code from rest client: {'code': -2008, 'msg': 'Invalid Api-Key ID.'}
2020-09-18 11:39:17,672 [CRITICAL] 34460 13804 unicorn_binance_websocket_api_connection: BinanceWebSocketApiConnection->await._conn.__aenter__(49c563f7-756e-4bc8-98df-130b2a3a1747, ['arr'], ['!userData']) -  error: 4 - Invalid Api-Key ID.
2020-09-18 11:39:17,672 [CRITICAL] 34460 13804 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->stream_is_crashing(49c563f7-756e-4bc8-98df-130b2a3a1747)

API keys are tested and working on cross margin

@oliver-zehentleitner
Copy link
Member

Please can you make one further test, but provide the key and secret with:

# set api key and secret in api manager
binance_websocket_api_manager.set_private_api_config(keys.api_key, keys.api_secret)

Is it working now? If yes, i have an idea where the problem is.

@CryptoFuturesAU
Copy link
Author

Using the same code as above I get error:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_manager.py", line 343, in _create_stream_thread
    loop.run_until_complete(binance_websocket_api_socket.start_socket())
  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_socket.py", line 59, in start_socket
    async with BinanceWebSocketApiConnection(self.handler_binance_websocket_api_manager, self.stream_id,
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_connection.py", line 101, in __aenter__
    self._conn = connect(uri, ping_interval=20, close_timeout=10,
  File "C:\ProgramData\Anaconda3\lib\site-packages\websockets\client.py", line 415, in __init__
    wsuri = parse_uri(uri)
  File "C:\ProgramData\Anaconda3\lib\site-packages\websockets\uri.py", line 59, in parse_uri
    parsed = urllib.parse.urlparse(uri)
  File "C:\ProgramData\Anaconda3\lib\urllib\parse.py", line 372, in urlparse
    url, scheme, _coerce_result = _coerce_args(url, scheme)
  File "C:\ProgramData\Anaconda3\lib\urllib\parse.py", line 124, in _coerce_args
    return _decode_args(args) + (_encode_result,)
  File "C:\ProgramData\Anaconda3\lib\urllib\parse.py", line 108, in _decode_args
    return tuple(x.decode(encoding, errors) if x else '' for x in args)
  File "C:\ProgramData\Anaconda3\lib\urllib\parse.py", line 108, in <genexpr>
    return tuple(x.decode(encoding, errors) if x else '' for x in args)
AttributeError: 'dict' object has no attribute 'decode'```

@oliver-zehentleitner
Copy link
Member

Ok, you dont get a valid listenkey and the error msg you have received is unknown and not handled by the lib.

I added handling of unknown error msg to the code.

Please start it again with 1.17.2 and tell me what error code you are receiving.

@CryptoFuturesAU
Copy link
Author

with this code:

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager \
import BinanceWebSocketApiManager
import logging
import time
import threading
import os
import keys


# https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.INFO,
                    filename=os.path.basename(__file__) + '.log',
                    format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
                    style="{")


def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = \
            binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            print(oldest_stream_data_from_stream_buffer)

# configure api key and secret for binance.com Isolated Margin
api_key = keys.api_key
api_secret = keys.api_secret

# create instances of BinanceWebSocketApiManager
ubwa_com_im = BinanceWebSocketApiManager(exchange = "binance.com-isolated_margin")

# create the userData streams
user_stream_id = ubwa_com_im.create_stream(
    'arr', '!userData', symbol="ANKRBTC", api_key=api_key, api_secret=api_secret)

# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, 
                                                            args=(ubwa_com_im,))
worker_thread.start()

I get error:

2020-09-21 13:33:37,857 [INFO    ] 14296 32512 unicorn_binance_websocket_api_manager: New instance of unicorn_binance_websocket_api_manager 1.17.2 started ...
2020-09-21 13:33:37,858 [INFO    ] 14296 23856 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_frequent_checks() new instance created with frequent_checks_id=1600659217.8586035
2020-09-21 13:33:37,859 [INFO    ] 14296 36884 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_keepalive_streams() new instance created with keepalive_streams_id=1600659217.8595998
2020-09-21 13:33:38,240 [INFO    ] 14296 32512 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->create_stream(['arr'], ['!userData'], None, False, ANKRBTC) with stream_id=0aabdfc2-b529-4a45-be30-8b235decc3b4
2020-09-21 13:33:38,243 [INFO    ] 14296 8300 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_add_socket_to_socket_list(0aabdfc2-b529-4a45-be30-8b235decc3b4, ['arr'], ['!userData'], None, False, ANKRBTC)
2020-09-21 13:33:38,244 [INFO    ] 14296 8300 unicorn_binance_websocket_api_socket: BinanceWebSocketApiSocket->start_socket(0aabdfc2-b529-4a45-be30-8b235decc3b4, ['arr'], ['!userData'])
2020-09-21 13:33:38,245 [INFO    ] 14296 8300 unicorn_binance_websocket_api_restclient: BinanceWebSocketApiRestclient->get_listen_key() symbol=ANKRBTC
2020-09-21 13:33:38,574 [CRITICAL] 14296 8300 unicorn_binance_websocket_api_manager: Received unknown error code from rest client: {'code': -1102, 'msg': "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed."}
2020-09-21 13:33:38,574 [CRITICAL] 14296 8300 unicorn_binance_websocket_api_connection: BinanceWebSocketApiConnection->await._conn.__aenter__(0aabdfc2-b529-4a45-be30-8b235decc3b4, ['arr'], ['!userData']) -  Received unknown error msg from Binance: Mandatory parameter 'symbol' was not sent, was empty/null, or malformed.
2020-09-21 13:33:38,574 [CRITICAL] 14296 8300 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->stream_is_crashing(0aabdfc2-b529-4a45-be30-8b235decc3b4)

theres something wrong with the symbol parameter sent. "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed."

@oliver-zehentleitner
Copy link
Member

I made a few changes and tested it up to the error msg "Isolated margin account does not exist.".

I did not add a upper() or lower() function, but in my tests upper case symbol responded a few seconds faster than lower case symbol. i belief it would be good to upper the symbol string before sending it, but i didnt added it for now. So you are able to test with ANKRBTC and ankrbtc. Please tell me how it works better!

@oliver-zehentleitner
Copy link
Member

1.17.3 released!

@CryptoFuturesAU
Copy link
Author

It works! You're amazing Oliver thank you.
It would be great if outboundAccountPosition was patched into unicornFy so I could receive isolated margin balances formatted into dict.

@oliver-zehentleitner
Copy link
Member

I rad the post in unicorn_fy.

In unicorn_fy I have a lot of open tasks. I think I will find the time for it in the next two weeks.

In the mean time you can download the unicorn_fy file, update it and use it. A pull request is appreciated :)

@oliver-zehentleitner
Copy link
Member

Please give me your feedback about upper and lower case symbol!

@CryptoFuturesAU
Copy link
Author

lowercase and uppercase function identically on my end.

@oliver-zehentleitner
Copy link
Member

Thanks!

@oliver-zehentleitner
Copy link
Member

oliver-zehentleitner commented Sep 21, 2020

Be aware that I made a small change within the next update!
The symbol is now behind api_key and api_secret! Only matters if you dont use "symbol="

user_stream_id = ubwa_com_im.create_stream(
    'arr', '!userData', api_key=api_key, api_secret=api_secret, symbol="ANKRBTC")

@oliver-zehentleitner
Copy link
Member

a made a new package with this update: 1.17.4

@oliver-zehentleitner
Copy link
Member

oliver-zehentleitner commented Sep 21, 2020

Connect to isolated_margin with multiple symbols #111

@oliver-zehentleitner oliver-zehentleitner moved this from Suspended to Done in Todo Sep 21, 2020
@oliver-zehentleitner
Copy link
Member

in 1.18.0 symbol will be changed to symbols

@CryptoFuturesAU
Copy link
Author

updated to 1.18.0
with this code:

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager \
import BinanceWebSocketApiManager
import logging
import time
import threading
import os
import keys


# https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.INFO,
                    filename=os.path.basename(__file__) + '.log',
                    format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
                    style="{")


def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = \
            binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            print(oldest_stream_data_from_stream_buffer)

# configure api key and secret for binance.com Isolated Margin
api_key = keys.api_key
api_secret = keys.api_secret

# create instances of BinanceWebSocketApiManager
ubwa_com_im = BinanceWebSocketApiManager(exchange = "binance.com-isolated_margin")

# create the userData streams
user_stream_id = ubwa_com_im.create_stream(
    'arr', '!userData', symbols = "ANKRBTC", api_key=api_key, api_secret=api_secret)

# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, 
                                                            args=(ubwa_com_im,))
worker_thread.start()

I get error:

Exception in thread Thread-14:
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_manager.py", line 351, in _create_stream_thread
    loop.run_until_complete(binance_websocket_api_socket.start_socket())
  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_socket.py", line 59, in start_socket
    async with BinanceWebSocketApiConnection(self.handler_binance_websocket_api_manager, self.stream_id,
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_connection.py", line 63, in __aenter__
    uri = self.handler_binance_websocket_api_manager.create_websocket_uri(self.channels, self.markets,
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_manager.py", line 922, in create_websocket_uri
    response = self.get_listen_key_from_restclient(stream_id, api_key, api_secret, symbols=symbols)
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_manager.py", line 1392, in get_listen_key_from_restclient
    response = binance_websocket_api_restclient.get_listen_key()
  File "C:\ProgramData\Anaconda3\lib\site-packages\unicorn_binance_websocket_api\unicorn_binance_websocket_api_restclient.py", line 211, in get_listen_key
    response = self._request(method, self.path_userdata, False, {'symbol': str(self.symbol)})
AttributeError: 'BinanceWebSocketApiRestclient' object has no attribute 'symbol'

@oliver-zehentleitner
Copy link
Member

I forgot to rename 2 vars :/

Should be fixed in 1.18.1!

@CryptoFuturesAU
Copy link
Author

with this code:

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager \
import BinanceWebSocketApiManager
import logging
import time
import threading
import os
import keys


# https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.INFO,
                    filename=os.path.basename(__file__) + '.log',
                    format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
                    style="{")


def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = \
            binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            print(oldest_stream_data_from_stream_buffer)

# configure api key and secret for binance.com Isolated Margin
api_key = keys.api_key
api_secret = keys.api_secret

# create instances of BinanceWebSocketApiManager
ubwa_com_im = BinanceWebSocketApiManager(exchange = "binance.com-isolated_margin")

# create the userData streams
user_stream_id = ubwa_com_im.create_stream(
    'arr', '!userData', symbols = "CELRBTC", api_key=api_key, api_secret=api_secret)

# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, 
                                                            args=(ubwa_com_im,))
worker_thread.start()

i receive this error:

2020-09-28 10:53:17,947 [INFO    ] 36304 9824 unicorn_binance_websocket_api_manager: New instance of unicorn_binance_websocket_api_manager 1.18.1 started ...
2020-09-28 10:53:17,948 [INFO    ] 36304 20320 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_frequent_checks() new instance created with frequent_checks_id=1601254397.9482331
2020-09-28 10:53:17,949 [INFO    ] 36304 19992 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_keepalive_streams() new instance created with keepalive_streams_id=1601254397.9492054
2020-09-28 10:53:24,958 [INFO    ] 36304 9824 unicorn_binance_websocket_api_manager: New instance of unicorn_binance_websocket_api_manager 1.18.1 started ...
2020-09-28 10:53:24,960 [INFO    ] 36304 15320 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_frequent_checks() new instance created with frequent_checks_id=1601254404.9601219
2020-09-28 10:53:24,961 [INFO    ] 36304 22924 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_keepalive_streams() new instance created with keepalive_streams_id=1601254404.9611447
2020-09-28 10:53:25,066 [INFO    ] 36304 9824 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->create_stream(['arr'], ['!userData'], None, False, CELRBTC) with stream_id=6c4a62bc-f356-43b2-9463-20821ce4a79a
2020-09-28 10:53:25,068 [INFO    ] 36304 6756 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->_add_socket_to_socket_list(6c4a62bc-f356-43b2-9463-20821ce4a79a, ['arr'], ['!userData'], None, False, CELRBTC)
2020-09-28 10:53:25,069 [INFO    ] 36304 6756 unicorn_binance_websocket_api_socket: BinanceWebSocketApiSocket->start_socket(6c4a62bc-f356-43b2-9463-20821ce4a79a, ['arr'], ['!userData'])
2020-09-28 10:53:25,070 [INFO    ] 36304 6756 unicorn_binance_websocket_api_restclient: BinanceWebSocketApiRestclient->get_listen_key() symbols=CELRBTC
2020-09-28 10:53:26,400 [CRITICAL] 36304 6756 unicorn_binance_websocket_api_manager: Received known error code from rest client: {'code': -1102, 'msg': "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed."}
2020-09-28 10:53:26,400 [CRITICAL] 36304 6756 unicorn_binance_websocket_api_connection: BinanceWebSocketApiConnection->await._conn.__aenter__(6c4a62bc-f356-43b2-9463-20821ce4a79a, ['arr'], ['!userData']) -  error: 4 - Mandatory parameter 'symbol' was not sent, was empty/null, or malformed.
2020-09-28 10:53:26,400 [CRITICAL] 36304 6756 unicorn_binance_websocket_api_connection: BinanceWebSocketApiConnection->await._conn.__aenter__(6c4a62bc-f356-43b2-9463-20821ce4a79a, ['arr'], ['!userData']) error: 6 - UUID('6c4a62bc-f356-43b2-9463-20821ce4a79a')
2020-09-28 10:53:26,400 [CRITICAL] 36304 6756 unicorn_binance_websocket_api_manager: BinanceWebSocketApiManager->stream_is_crashing(6c4a62bc-f356-43b2-9463-20821ce4a79a)

Everything is working fine using this code on 1.17.3 with "symbols" string set to "symbol"

@oliver-zehentleitner
Copy link
Member

sure. we changed symbol to symbols, but binance didnt :D

@oliver-zehentleitner
Copy link
Member

pip install unicorn-binance-websocket-api==1.18.2

BestCryptoKnight pushed a commit to BestCryptoKnight/unicorn-binance-websocket-api that referenced this issue Jul 10, 2022
BestCryptoKnight pushed a commit to BestCryptoKnight/unicorn-binance-websocket-api that referenced this issue Jul 10, 2022
Seven-112 pushed a commit to Seven-112/unicorn-binance-websocket-api that referenced this issue May 16, 2023
Seven-112 pushed a commit to Seven-112/unicorn-binance-websocket-api that referenced this issue May 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
Todo
  
Done
Development

No branches or pull requests

2 participants