Code Monkey home page Code Monkey logo

python-bittrex-websocket-aio's Introduction

logo bittrex-websocket-aio

pypi-v pypi-pyversions pypi-l pypi-wheel

What is bittrex-websocket-aio?

Python Bittrex WebSocket (PBW) is the first unofficial Python wrapper for the Bittrex Websocket API. It provides users with a simple and easy to use interface to the Bittrex Exchange.

Users can use it to access real-time public data (e.g exchange status, summary ticks and order fills) and account-level data such as order and balance status. The goal of the package is to serve as a foundation block which users can use to build upon their applications. Examples usages can include maintaining live order books, recording trade history, analysing order flow and many more.

The version is built upon asyncio which is Python's standard asynchronous I/O framework.

If you are looking for a non-async version or you are using Python=2.7, then take a look at my other library: bittrex-websocket.


Documentation
http://python-bittrex-websocket-docs.readthedocs.io/en/latest/
Getting started/How-to
http://python-bittrex-websocket-docs.readthedocs.io/en/latest/howto.html
Methods
http://python-bittrex-websocket-docs.readthedocs.io/en/latest/methods.html
Changelog
http://python-bittrex-websocket-docs.readthedocs.io/en/latest/changelog.html#bittrex-websocket-aio

I am constantly working on new features. Make sure you stay up to date by regularly checking the official docs!

Having an issue or a question? Found a bug or perhaps you want to contribute? Open an issue!

Quick Start

pip install bittrex-websocket-aio
#!/usr/bin/python
# /examples/ticker_updates.py

# Sample script showing how subscribe_to_exchange_deltas() works.

# Overview:
# ---------
# 1) Creates a custom ticker_updates_container dict.
# 2) Subscribes to N tickers and starts receiving market data.
# 3) When information is received, checks if the ticker is
#    in ticker_updates_container and adds it if not.
# 4) Disconnects when it has data information for each ticker.

from bittrex_websocket.websocket_client import BittrexSocket
from time import sleep

def main():
    class MySocket(BittrexSocket):

        async def on_public(self, msg):
            name = msg['M']
            if name not in ticker_updates_container:
                ticker_updates_container[name] = msg
                print('Just received market update for {}.'.format(name))

    # Create container
    ticker_updates_container = {}
    # Create the socket instance
    ws = MySocket()
    # Enable logging
    ws.enable_log()
    # Define tickers
    tickers = ['BTC-ETH', 'BTC-NEO', 'BTC-ZEC', 'ETH-NEO', 'ETH-ZEC']
    # Subscribe to ticker information
    for ticker in tickers:
        sleep(0.01)
        ws.subscribe_to_exchange_deltas([ticker])

    # Users can also subscribe without introducing delays during invoking but
    # it is the recommended way when you are subscribing to a large list of tickers.
    # ws.subscribe_to_exchange_deltas(tickers)

    while len(ticker_updates_container) < len(tickers):
        sleep(1)
    else:
        print('We have received updates for all tickers. Closing...')
        ws.disconnect()
        sleep(10)

if __name__ == "__main__":
    main()

Disclaimer

I am not associated with Bittrex. Use the library at your own risk, I don't bear any responsibility if you end up losing your money.

python-bittrex-websocket-aio's People

Contributors

slazarov 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-bittrex-websocket-aio's Issues

Task was destroyed but it is pending!

Randomly getting this "error", but without any exception.

Basically doesn't stop the script working but it seems I stop getting data from the private ws stream. Looks like public still stays online.

I did some research and I am trying to fix it by changing this line on websocket_client-aio.py : 136

for future in (self.futures if not (future.done() or future.cancelled())) + self.connection.conn._Connection__transport.futures

async on_public receive 'None' in msg['M'] with 'query_exchange_state'

Hi,
In actual version (0.0.0.2.8), function async on_public receive 'None' in msg['M'] with subscription to 'query_exchange_state', in version 0.0.0.2.7 works OK.

You can check with:

from bittrex_websocket import BittrexSocket, BittrexMethods
from time import sleep

# Define a new method to check if we have received all the data
def are_we_finished():
    ticker_cnt = len(tickers)
    exch_delta_cnt = len(exchange_deltas)
    summ_delta_cnt = len(summary_deltas)

    if exch_delta_cnt == summ_delta_cnt:
        num = (exch_delta_cnt + summ_delta_cnt) / ticker_cnt
        # E.g with 2 tickers the equation will be: (2 + 2) / 2 = 2
        if num == 2:
            return True
    return False

class MySocket(BittrexSocket):

    async def on_public(self, msg):
        if msg['invoke_type'] == BittrexMethods.QUERY_EXCHANGE_STATE:
            name = msg['M']
            if name not in exchange_deltas:
                exchange_deltas[name] = msg
                print('Just received exchange state for {}.'.format(name))
        elif msg['invoke_type'] == BittrexMethods.SUBSCRIBE_TO_SUMMARY_DELTAS:
            for summary in msg['D']:
                name = summary['M']
                if name in tickers and name not in summary_deltas:
                    summary_deltas[name] = summary
                    print('Just received summary delta update for {}.'.format(name))

# Add the new summary delta container
exchange_deltas = {}
summary_deltas = {}

# Create the socket instance
ws = MySocket()

# Enable logging
ws.enable_log()

# Define tickers
tickers = ['BTC-ETH', 'BTC-ZEC']

# Invoke subscriptions
ws.query_exchange_state(tickers)
ws.subscribe_to_summary_deltas()

while are_we_finished() is False:
    sleep(1)
else:
    print('We have received updates for all tickers. Closing...')
    ws.disconnect()
    sleep(10)

uvloop - Windows no longer supported

It seems that this new version using asyncio depends on uvloop that is not supported in Windows systems.

C:>pip install bittrex-websocket-aio
Collecting bittrex-websocket-aio
Using cached bittrex_websocket_aio-0.0.0.2.2-py2.py3-none-any.whl
Collecting uvloop>=0.9.1 (from bittrex-websocket-aio)
Using cached uvloop-0.9.1.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users~\AppData\Local\Temp\pip-build-1qo1p6yg\uvloop\setup.py", line 10, in
raise RuntimeError('uvloop does not support Windows at the moment')
RuntimeError: uvloop does not support Windows at the moment

Coroutine on_public was never awaited error ?

/usr/lib/python3.6/site-packages/events/events.py:95: RuntimeWarning: coroutine 'Bittrex.on_public' was never awaited
f(*a, **kw)
^CTraceback (most recent call last):
File "async130.py", line 565, in
time.sleep(1337)

I am getting this error on 3.6.5 but strangely on 3.6.3 I dont get it.

PS: thanks for the lib, is this possible to donate BTC somewhere?

InvalidStatusCode

I'm getting the following error intermittently while running ~35 connections to subscribe_to_exchange_deltas

Exception in thread SocketConnection:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.6/dist-packages/bittrex_websocket/websocket_client.py", line 76, in _connection_handler
    self.connection.conn.start()
  File "/usr/local/lib/python3.6/dist-packages/signalr_aio/_connection.py", line 36, in start
    self.__transport.start()
  File "/usr/local/lib/python3.6/dist-packages/signalr_aio/transports/_transport.py", line 47, in start
    self.ws_loop.run_until_complete(self.socket(self.ws_loop))
  File "/usr/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete
    return future.result()
  File "/usr/local/lib/python3.6/dist-packages/signalr_aio/transports/_transport.py", line 59, in socket
    loop=loop) as self.ws:
  File "/usr/local/lib/python3.6/dist-packages/websockets/client.py", line 386, in __aenter__
    return (yield from self)
  File "/usr/local/lib/python3.6/dist-packages/websockets/client.py", line 400, in __await__
    extra_headers=protocol.extra_headers,
  File "/usr/local/lib/python3.6/dist-packages/websockets/client.py", line 263, in handshake
    raise InvalidStatusCode(status_code)
websockets.exceptions.InvalidStatusCode: Status code not 101: 524

multiple 'query_summary_state' not working

Hi,
Not more that one query_summary_state is succesfully made when previosuly "authentication" is performed.
I did solve it by adding:

self.invokes.append({'invoke': invoke, 'ticker': None})

at _handle_subscribe function for the invoke == BittrexMethods.AUTHENTICATE case.

BR.

Queston: Authorization Logic when submit orders

Good afternoon!
I am making a trading application and since the buy/sell orders are submitted through REST API, I wonder how to implement the authorization logic:

  1. authorize through REST API and authorize independently through Websocket ?
  2. do you have any example of to API working together?

Thanks

What am I missing? (subscribe_to_orderbook)

bittrex_websocket.websocket_client - INFO - Establishing connection to Bittrex through https://beta.bittrex.com/signalr.
ws.subscribe_to_orderbook(tickers)
AttributeError: 'MySocket' object has no attribute 'subscribe_to_orderbook
bittrex_websocket.websocket_client - INFO - cfscrape detected, using it to bypass Cloudflare.'

Because this happens, the record_trades and ticket_updates go correctly.

websocket_client doesn't use custom url

Line 59 of websocket_client.py is:

connection = Connection(BittrexParameters.URL, Session())

Shouldn't it be:

connection = Connection(self.url, Session())

?

Periodic "Bittrex connection successfully closed."

First of all thanks for this library - very helpful. However I'm noticing that my connections periodically close without much information as to why. Its not that big of a deal, except I don't see a way to poll the connection object to make sure that it is still connected (https://github.com/slazarov/python-signalr-client/blob/master/signalr_aio/_connection.py).

Here is the log message I'm receiving:

2019-12-27 23:35:51 - bittrex_websocket.websocket_client - INFO - Bittrex connection successfully closed.

It also doesn't appear to auto-reconnect. I'm wondering if anybody using this library has found a simple solution to improve connection stability, or to recover failed/closed connections quickly and seamlessly.

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.