Skip to content

Commit

Permalink
added support for Biance Jersy (www.binance.je) issue #21
Browse files Browse the repository at this point in the history
  • Loading branch information
oliver-zehentleitner committed Jun 18, 2019
1 parent 84e3108 commit 298ad08
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 13 deletions.
102 changes: 102 additions & 0 deletions example_binance_jersy.py
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# File: example_binance_jersy.py
#
# Part of ‘UNICORN Binance WebSocket API’
# Project website: https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api
# Documentation: https://www.unicorn-data.com/unicorn-binance-websocket-api.html
# PyPI: https://pypi.org/project/unicorn-binance-websocket-api/
#
# Author: UNICORN Data Analysis
# https://www.unicorn-data.com/
#
# Copyright (c) 2019, UNICORN Data Analysis
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

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


def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
time.sleep(30)
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)


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

# create instance of BinanceWebSocketApiManager
binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.je")

# set api key and secret for userData stream
binance_api_key = ""
binance_api_secret = ""
binance_websocket_api_manager.set_private_api_config(binance_api_key, binance_api_secret)
userdata_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!userData"])

ticker_all_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!ticker"])
miniticker_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!miniTicker"])

markets = {'bnbeur', 'bnbgbp', 'ethgbp', 'etheur', 'btceur', 'btcgbp'}

binance_websocket_api_manager.create_stream(["aggTrade"], markets)
binance_websocket_api_manager.create_stream(["trade"], markets)
binance_websocket_api_manager.create_stream(["kline_1m"], markets)
binance_websocket_api_manager.create_stream(["kline_5m"], markets)
binance_websocket_api_manager.create_stream(["kline_15m"], markets)
binance_websocket_api_manager.create_stream(["kline_1h"], markets)
binance_websocket_api_manager.create_stream(["kline_12h"], markets)
binance_websocket_api_manager.create_stream(["kline_1w"], markets)
binance_websocket_api_manager.create_stream(["ticker"], markets)
binance_websocket_api_manager.create_stream(["miniTicker"], markets)
binance_websocket_api_manager.create_stream(["depth"], markets)
binance_websocket_api_manager.create_stream(["depth5"], markets)
binance_websocket_api_manager.create_stream(["depth10"], markets)
binance_websocket_api_manager.create_stream(["depth20"], markets)
binance_websocket_api_manager.create_stream(["aggTrade"], markets)


channels = {'trade', 'kline_1m', 'kline_5m', 'kline_15m', 'kline_30m', 'kline_1h', 'kline_12h', 'kline_1w',
'miniTicker', 'depth20'}
binance_websocket_api_manager.create_stream(channels, markets)

# 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()

# show an overview
while True:
binance_websocket_api_manager.print_summary()
time.sleep(1)
Expand Up @@ -66,16 +66,20 @@ class BinanceWebSocketApiManager(threading.Thread):
:type process_stream_data: function
"""

def __init__(self, process_stream_data=False):
def __init__(self, process_stream_data=False, exchange="binance.com"):
threading.Thread.__init__(self)
self.version = "1.3.1.dev"
self.websocket_base_uri = "wss://stream.binance.com:9443/"
self.version = "1.3.10.dev"
if process_stream_data is False:
# no special method to process stream data provided, so we use write_to_stream_buffer:
self.process_stream_data = self.add_to_stream_buffer
else:
# use the provided method to process stream data:
self.process_stream_data = process_stream_data
self.exchange = exchange
if self.exchange == "binance.com":
self.websocket_base_uri = "wss://stream.binance.com:9443/"
elif self.exchange == "binance.je":
self.websocket_base_uri = "wss://stream.binance.je:9443/"
self.stop_manager_request = None
self._frequent_checks_restart_request = None
self._keepalive_streams_restart_request = None
Expand Down Expand Up @@ -248,7 +252,8 @@ def _frequent_checks(self):
< time.time() and (active_stream_list[stream_id]['last_static_ping_listen_key'] +
active_stream_list[stream_id]['listen_key_cache_time']) < time.time():
# keep-alive the listenKey
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.stream_list[stream_id]['api_key'],
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.exchange,
self.stream_list[stream_id]['api_key'],
self.stream_list[stream_id]['api_secret'],
self.get_version(),
self.binance_api_status)
Expand Down Expand Up @@ -448,16 +453,12 @@ def create_websocket_uri(self, channels, markets, stream_id=False, api_key=False
if response:
try:
uri = self.websocket_base_uri + "ws/" + str(response['listenKey'])
print(1)
return uri
except KeyError:
print(2)
return False
except TypeError:
print(3)
return False
else:
print(4)
return False
else:
return False
Expand All @@ -478,7 +479,8 @@ def delete_listen_key_by_stream_id(self, stream_id):
if self.stream_list[stream_id]['listen_key'] is not False:
logging.info("BinanceWebSocketApiManager->stop_manager_with_all_streams(" + str(
stream_id) + ")->delete_listen_key")
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.stream_list[stream_id]['api_key'],
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.exchange,
self.stream_list[stream_id]['api_key'],
self.stream_list[stream_id]['api_secret'],
self.get_version(),
self.used_weight)
Expand Down Expand Up @@ -632,8 +634,8 @@ def get_listen_key_from_restclient(self, stream_id, api_key, api_secret):
return response
# no cached listen_key or listen_key is older than 30 min
# acquire a new listen_key:
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(api_key, api_secret, self.get_version(),
self.binance_api_status)
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.exchange, api_key, api_secret,
self.get_version(), self.binance_api_status)
response = binance_websocket_api_restclient.get_listen_key()
del binance_websocket_api_restclient
if response:
Expand Down
Expand Up @@ -43,11 +43,16 @@


class BinanceWebSocketApiRestclient(object):
def __init__(self, binance_api_key, binance_api_secret, unicorn_binance_websocket_api_version, binance_api_status):
def __init__(self, exchange, binance_api_key, binance_api_secret, unicorn_binance_websocket_api_version,
binance_api_status):
self.exchange = exchange
self.api_key = copy.deepcopy(binance_api_key)
self.api_secret = copy.deepcopy(binance_api_secret)
self.unicorn_binance_websocket_api_version = unicorn_binance_websocket_api_version
self.restful_base_uri = "https://api.binance.com/"
if self.exchange == "binance.com":
self.restful_base_uri = "https://api.binance.com/"
elif self.exchange == "binance.je":
self.restful_base_uri = "https://api.binance.je/"
self.listen_key = False
self.binance_api_status = binance_api_status

Expand Down

0 comments on commit 298ad08

Please sign in to comment.