Exemplo n.º 1
0
def main():
    logging.basicConfig(
        level=logging.DEBUG,
        filename=os.path.basename(__file__) + '.log',
        format=
        "{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
        style="{")

    binance_websocket_api_manager = BinanceWebSocketApiManager(
        exchange="binance.com-futures")

    config_open = open("./param.json", "r")
    param_json = json.load(config_open)
    param = robot_param(param_json)
    binance = Binance(api_key=param.api_key, api_secret=param.api_secret)

    worker_thread = threading.Thread(target=robot,
                                     args=(binance_websocket_api_manager,
                                           binance))
    worker_thread.start()

    print(
        "\r\n=========================== Starting aggTrade ===========================\r\n"
    )

    markets = [rename_pair(param.pair)]

    aggtrade_stream_id = binance_websocket_api_manager.create_stream(
        ["aggTrade", "depth5"], markets)
    time.sleep(7)
 def setUp(self):
     self.binance_org_testnet = BinanceWebSocketApiManager(
         exchange="binance.org-testnet")
     stream_id = self.binance_org_testnet.create_stream(
         ['orders', 'transfers', 'accounts'],
         "tbnb1unxhf8fat985ksajatfa5jea58j2kzg7mfy0e7")
     self.binance_org_testnet.unsubscribe_from_stream(
         stream_id, "tbnb1unxhf8fat985ksajatfa5jea58j2kzg7mfy0e7")
Exemplo n.º 3
0
 def __init__(self):
     self.binance_websocket_api_manager = BinanceWebSocketApiManager(
         exchange="binance.com", output_default="UnicornFy")
     self.binance_websocket_api_manager.create_stream(
         ['depth5'],
         self.symbols,
         stream_label="UnicornFy",
         output="UnicornFy")
class TestBinanceOrgManager(unittest.TestCase):
    # Test binance.org (Binance Chain Dex)

    def setUp(self):
        self.binance_org_testnet = BinanceWebSocketApiManager(
            exchange="binance.org-testnet")
        stream_id = self.binance_org_testnet.create_stream(
            ['orders', 'transfers', 'accounts'],
            "tbnb1unxhf8fat985ksajatfa5jea58j2kzg7mfy0e7")
        self.binance_org_testnet.unsubscribe_from_stream(
            stream_id, "tbnb1unxhf8fat985ksajatfa5jea58j2kzg7mfy0e7")

    def tearDown(self):
        self.binance_org_testnet.stop_manager_with_all_streams()
Exemplo n.º 5
0
def get_oldest_event(binance_ws_api_manager: BinanceWebSocketApiManager,
                     stream_id: str) -> str or dict or False:
    """
    Returns the oldest event in a Binance WS Api Manager stream's buffer.
    """
    return binance_ws_api_manager.pop_stream_data_from_stream_buffer(
        stream_buffer_name=stream_id)
Exemplo n.º 6
0
def create_binance_ws_stream(api_manager: BinanceWebSocketApiManager,
                             channels: str,
                             markets: str,
                             stream_label: str,
                             api_key=False,
                             api_secret=False,
                             symbols=False,
                             **kwargs):
    """
    Create a new Binance websocket stream and return the stream id.
    """
    stream_id = api_manager.create_stream(channels,
                                          markets,
                                          symbols=symbols,
                                          stream_label=stream_label,
                                          stream_buffer_name=True,
                                          api_key=api_key,
                                          api_secret=api_secret,
                                          **kwargs)

    if not stream_id:
        raise CreateBinanceStreamFailedException(
            f"Failed to create stream {stream_label}.")

    logging.info(
        f"Stream {stream_label} created. Channels: {channels}. Markets: {markets}. Symbols: {symbols}. Stream id: {stream_id}."
    )
    return stream_id
Exemplo n.º 7
0
def threaded_func(q1, conn, t):
    with conn:
        binance_websocket_api_manager = BinanceWebSocketApiManager(
            exchange="binance.com")
        binance_websocket_api_manager.create_stream(
            ['bookTicker'], [t['trade']['pair'].replace('.', '').lower()])
        while True:
            oldest_stream_data_from_stream_buffer = binance_websocket_api_manager \
                .pop_stream_data_from_stream_buffer()
            if oldest_stream_data_from_stream_buffer:
                res_bnb = oldest_stream_data_from_stream_buffer
                if 'result' not in res_bnb:
                    conn.sendall(res_bnb.encode())
                    conn.recv(2)
            else:
                continue
Exemplo n.º 8
0
async def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('127.0.0.1', 45620))
        s.listen()
        conn, addr = s.accept()
        with conn:
            binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")
            binance_websocket_api_manager.create_stream(['depth5@100ms'], ['etheur'])
            while True:
                oldest_stream_data_from_stream_buffer = binance_websocket_api_manager\
                    .pop_stream_data_from_stream_buffer()
                if oldest_stream_data_from_stream_buffer:
                    res_bnb = oldest_stream_data_from_stream_buffer
                    if 'result' not in res_bnb:
                        conn.sendall(res_bnb.encode())
                else:
                    continue
Exemplo n.º 9
0
    def _start(self):
        self.exchange = "binance.com-futures" + ("-testnet"
                                                 if self.test else "")
        self.manager = BinanceWebSocketApiManager(exchange=self.exchange)
        self.manager.create_stream("arr",
                                   "!userData",
                                   api_key=self.key,
                                   api_secret=self.secret)

        logging.info("Spawning listener for futures user data")
        while True:
            buf = self.manager.pop_stream_data_from_stream_buffer()
            if not buf:
                time.sleep(0.05)
                continue
            try:
                msg = json.loads(buf)
                self._queue.sync_q.put(msg)
            except Exception as err:
                logging.error(f"Failed to decode message {buf}: {err}")
 def test_isolated_margin(self):
     binance_websocket_api_manager = BinanceWebSocketApiManager(
         exchange="binance.com-isolated_margin")
     stream_id = binance_websocket_api_manager.create_stream(
         'arr',
         '!userData',
         symbols="CELRBTC",
         api_key="key",
         api_secret="secret")
     time.sleep(10)
     binance_websocket_api_manager.print_stream_info(stream_id)
     binance_websocket_api_manager.stop_manager_with_all_streams()
Exemplo n.º 11
0
class TickParser:
    symbols = [
        'ethusdt',
        'bnbusdt',
        'ltcusdt',
        'btcusdt',
        'ethupusdt',
        'bnbupusdt',
        'ltcupusdt',
        'btcupusdt',
        'ethdownusdt',
        'bnbdownusdt',
        'ltcdownusdt',
        'btcdownusdt',
    ]

    def __init__(self):
        self.binance_websocket_api_manager = BinanceWebSocketApiManager(
            exchange="binance.com", output_default="UnicornFy")
        self.binance_websocket_api_manager.create_stream(
            ['depth5'],
            self.symbols,
            stream_label="UnicornFy",
            output="UnicornFy")
Exemplo n.º 12
0
class UserStream:
    def __init__(self, api_key, api_secret, test=False):
        self.test = test
        self.key = api_key
        self.secret = api_secret
        self._queue = janus.Queue()
        threading.Thread(target=self._start, daemon=True).start()

    @asynccontextmanager
    async def message(self):
        try:
            msg = await self._queue.async_q.get()
            yield msg
        finally:
            self._queue.async_q.task_done()

    def _start(self):
        self.exchange = "binance.com-futures" + ("-testnet"
                                                 if self.test else "")
        self.manager = BinanceWebSocketApiManager(exchange=self.exchange)
        self.manager.create_stream("arr",
                                   "!userData",
                                   api_key=self.key,
                                   api_secret=self.secret)

        logging.info("Spawning listener for futures user data")
        while True:
            buf = self.manager.pop_stream_data_from_stream_buffer()
            if not buf:
                time.sleep(0.05)
                continue
            try:
                msg = json.loads(buf)
                self._queue.sync_q.put(msg)
            except Exception as err:
                logging.error(f"Failed to decode message {buf}: {err}")
Exemplo n.º 13
0
    def stream(self):  # streams 24hour ticker & Asks Bids

        binance_websocket_api_manager = BinanceWebSocketApiManager(
            exchange="binance.com")  # websocket connection
        binance_websocket_api_manager.create_stream(
            ["ticker", "trade"],
            [self.symbol_unicorn])  # TODO we might be able to put this in self
        i = 0
        while (self.stay_alive):
            oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer(
            )
            if oldest_stream_data_from_stream_buffer:
                stream_data = UnicornFy.binance_com_websocket(
                    oldest_stream_data_from_stream_buffer)

                if (stream_data['event_type'] == "24hrTicker"):
                    # set 24hr change to the value there
                    self.change24hr = float(
                        stream_data['data'][0]['price_change_percent'])
                    self.bid = float(stream_data["data"][0]["best_bid_price"])
                    self.ask = float(stream_data["data"][0]["best_ask_price"])
                    self.ask_quantity = float(
                        stream_data["data"][0]["best_ask_quantity"])
                    self.bid_quantity = float(
                        stream_data["data"][0]["best_bid_quantity"])
                    if (i == 0):  # Will make loading boxes much faster
                        self.price = float(
                            stream_data['data'][0]['last_price'])
                        i += 1
                elif (stream_data["event_type"] == "trade"):
                    self.price = float(stream_data["price"])

            while (self.paused):
                time.sleep(5)

            time.sleep(self.SUPER.a * (1 / 4))

        binance_websocket_api_manager.stop_manager_with_all_streams()
        self.shut_down_count += 2
        if (self.messages):
            print(self.symbol_ccxt, "24hr stream succesfully shut down", "\n")
Exemplo n.º 14
0

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)
            pass


# create instance of BinanceWebSocketApiManager for Binance Chain DEX
binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")

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

#markets = ['xrpusdt', 'rvnbtc']
markets = ['xrpusdt']
stream_id = binance_websocket_api_manager.create_stream(["kline_1m"], markets)


time.sleep(5)
binance_websocket_api_manager.get_stream_subscriptions(stream_id)
#binance_websocket_api_manager.subscribe_to_stream(stream_id,
#                                                  channels=['kline_1m', 'kline_5m', 'marketDepth',
#                                                            'ticker', 'miniTicker', 'marketDiff'])
Exemplo n.º 15
0
#
# 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

# create instance of BinanceWebSocketApiManager
binance_websocket_api_manager = BinanceWebSocketApiManager()

# get version of the used UNICORN Binance WebSocket API
if binance_websocket_api_manager.is_update_availabe():
    print("please upgrade to " + binance_websocket_api_manager.get_latest_version() + ", you are on",
          binance_websocket_api_manager.get_version())

    latest_release_info = binance_websocket_api_manager.get_latest_release_info()
    if latest_release_info:
        print("please download the latest release or run `pip install unicorn-binance-websocket-api --upgrade`: ")
        print("\ttar: " + latest_release_info["tarball_url"])
        print("\tzip: " + latest_release_info["zipball_url"])
        print("release info:")
        print(latest_release_info["body"])
else:
    print(binance_websocket_api_manager.get_version(), "is the latest version!")
import os
try:
    from unicorn_fy.unicorn_fy import UnicornFy
except ImportError:
    print("Please install `unicorn-fy`! https://pypi.org/project/unicorn-fy/")
    sys.exit(1)


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

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

markets = {'bnbbtc', 'ethbtc', 'btcusdt', 'bchabcusdt', 'xrpusdt', 'rvnbtc', 'ltcusdt', 'adausdt', 'eosusdt',
           'neousdt', 'bnbusdt', 'adabtc', 'ethusdt', 'trxbtc', 'bchabcbtc', 'ltcbtc', 'xrpbtc',
           'ontbtc', 'bttusdt', 'eosbtc', 'xlmbtc', 'bttbtc', 'tusdusdt', 'xlmusdt', 'qkcbtc', 'zrxbtc',
           'neobtc', 'adaeth', 'icxusdt', 'btctusd', 'icxbtc', 'btcusdc', 'wanbtc', 'zecbtc', 'wtcbtc',
           'batbtc', 'adabnb', 'etcusdt', 'qtumusdt', 'xmrbtc', 'trxeth', 'adatusd', 'trxxrp', 'trxbnb',
           'dashbtc', 'rvnbnb', 'bchabctusd', 'etcbtc', 'bnbeth', 'ethpax', 'nanobtc', 'xembtc', 'xrpbnb',
           'bchabcpax', 'xrpeth', 'bttbnb', 'ltcbnb', 'agibtc', 'zrxusdt', 'xlmbnb', 'ltceth', 'eoseth',
           'ltctusd', 'polybnb', 'scbtc', 'steembtc', 'trxtusd', 'npxseth', 'kmdbtc', 'polybtc', 'gasbtc',
           'engbtc', 'zileth', 'xlmeth', 'eosbnb', 'xrppax', 'lskbtc', 'npxsbtc', 'xmrusdt', 'ltcpax',
           'ethtusd', 'batusdt', 'mcobtc', 'neoeth', 'bntbtc', 'eostusd', 'lrcbtc', 'funbtc', 'zecusdt',
           'bnbpax', 'linkusdt', 'hceth', 'zrxeth', 'icxeth', 'xmreth', 'neobnb', 'etceth', 'zeceth', 'xmrbnb',
           'wanbnb', 'zrxbnb', 'agibnb', 'funeth', 'arketh', 'engeth'}

binance_get_kline_1m_bnbbtc = binance_websocket_api_manager.create_stream('kline_1m', markets=markets)
Exemplo n.º 17
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()

# 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(["!ticker"],
                                                                   ["arr"])
miniticker_stream_id = binance_websocket_api_manager.create_stream(
    ["arr"], ["!miniTicker"])

markets = {
# 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 class to process stream data
from unicorn_binance_websocket_api_process_streams import BinanceWebSocketApiProcessStreams

# https://docs.python.org/3/library/logging.html#logging-levels
logging.getLogger('unicorn-log').setLevel(logging.INFO)
logging.getLogger('unicorn-log').addHandler(logging.StreamHandler())

# create instance of BinanceWebSocketApiManager and provide the function for stream processing
binance_websocket_api_manager = BinanceWebSocketApiManager(BinanceWebSocketApiProcessStreams.process_stream_data)

# define markets
markets = {'bnbbtc', 'ethbtc', 'btcusdt', 'bchabcusdt', 'eosusdt'}

markets_mega_list = {'xrpusdt', 'rvnbtc', 'ltcusdt', 'adausdt', 'eosusdt', 'xmrusdt', 'xmrbnb',
                     'neousdt', 'bnbusdt', 'adabtc', 'ethusdt', 'trxbtc', 'bchabcbtc', 'ltcbtc', 'xrpbtc',
                     'ontbtc', 'bttusdt', 'eosbtc', 'xlmbtc', 'bttbtc', 'tusdusdt', 'xlmusdt', 'qkcbtc', 'zrxbtc',
                     'neobtc', 'adaeth', 'icxusdt', 'btctusd', 'icxbtc', 'btcusdc', 'wanbtc', 'zecbtc', 'wtcbtc',
                     'batbtc', 'adabnb', 'etcusdt', 'qtumusdt', 'xmrbtc', 'trxeth', 'adatusd', 'trxxrp', 'trxbnb',
                     'dashbtc', 'rvnbnb', 'bchabctusd', 'etcbtc', 'bnbeth', 'ethpax', 'nanobtc', 'xembtc', 'xrpbnb',
                     'bchabcpax', 'xrpeth', 'bttbnb', 'ltcbnb', 'agibtc', 'zrxusdt', 'xlmbnb', 'ltceth', 'eoseth',
                     'ltctusd', 'polybnb', 'scbtc', 'steembtc', 'trxtusd', 'npxseth', 'kmdbtc', 'polybtc', 'gasbtc',
                     'engbtc', 'zileth', 'xlmeth', 'eosbnb', 'xrppax', 'lskbtc', 'npxsbtc', 'ltcpax',
                     'ethtusd', 'batusdt', 'mcobtc', 'neoeth', 'bntbtc', 'eostusd', 'lrcbtc', 'funbtc', 'zecusdt',
                     'bnbpax', 'linkusdt', 'hceth', 'zrxeth', 'icxeth', 'xmreth', 'neobnb', 'etceth', 'zeceth',
Exemplo n.º 19
0

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)
            pass


binance_websocket_api_manager = BinanceWebSocketApiManager(
    exchange="binance.com")

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

markets = [
    'bnbbtc', 'ethbtc', 'btcusdt', 'bchabcusdt', 'xrpusdt', 'rvnbtc',
    'ltcusdt', 'adausdt', 'eosusdt', 'neousdt', 'bnbusdt', 'adabtc', 'ethusdt',
    'trxbtc', 'trxbtc', 'bchabcbtc', 'ltcbtc', 'xrpbtc', 'ontbtc', 'bttusdt',
    'eosbtc', 'xlmbtc', 'bttbtc', 'tusdusdt', 'xlmusdt', 'qkcbtc', 'zrxbtc',
    'neobtc', 'adaeth', 'icxusdt', 'btctusd', 'icxbtc', 'btcusdc', 'wanbtc',
    'zecbtc', 'wtcbtc'
]
import time
import threading
import logging

# import class to process stream data
from example_process_streams import BinanceWebSocketApiProcessStreams

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

# create instance of BinanceWebSocketApiManager and provide the function for stream processing
binance_websocket_api_manager = BinanceWebSocketApiManager(
    BinanceWebSocketApiProcessStreams.process_stream_data)
# binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")


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:
            #pass
            print(oldest_stream_data_from_stream_buffer)

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)
            pass


binance_websocket_api_manager = BinanceWebSocketApiManager(
    exchange="binance.com")

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

markets = [
    'bnbbtc', 'ethbtc', 'btcusdt', 'bchabcusdt', 'xrpusdt', 'rvnbtc',
    'ltcusdt', 'adausdt', 'eosusdt', 'neousdt', 'bnbusdt', 'adabtc', 'ethusdt',
    'trxbtc', 'trxbtc', 'bchabcbtc', 'ltcbtc', 'xrpbtc', 'ontbtc', 'bttusdt',
    'eosbtc', 'xlmbtc', 'bttbtc', 'tusdusdt', 'xlmusdt', 'qkcbtc', 'zrxbtc',
    'neobtc', 'adaeth', 'icxusdt', 'btctusd', 'icxbtc', 'btcusdc', 'wanbtc',
    'zecbtc', 'wtcbtc'
]
Exemplo n.º 22
0
binance_api_key = ""
binance_api_secret = ""

channels = {
    'aggTrade', 'trade', 'kline_1m', 'kline_5m', 'kline_15m', 'kline_30m',
    'kline_1h', 'kline_2h', 'kline_4h', 'kline_6h', 'kline_8h', 'kline_12h',
    'kline_1d', 'kline_3d', 'kline_1w', 'kline_1M', 'miniTicker', 'ticker',
    'bookTicker', 'depth5', 'depth10', 'depth20', 'depth', 'depth@100ms'
}
arr_channels = {'!miniTicker', '!ticker', '!bookTicker'}
markets = []

try:
    binance_rest_client = Client(binance_api_key, binance_api_secret)
    binance_websocket_api_manager = BinanceWebSocketApiManager()
except requests.exceptions.ConnectionError:
    print("No internet connection?")
    sys.exit(1)

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

data = binance_rest_client.get_all_tickers()
for item in data:
    markets.append(item['symbol'])

binance_websocket_api_manager.set_private_api_config(binance_api_key,
                                                     binance_api_secret)
import logging
import time
import os

# import class to process stream data
from unicorn_binance_websocket_api_process_streams_without_output import BinanceWebSocketApiProcessStreams

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

# create instance of BinanceWebSocketApiManager and provide the function for stream processing
binance_websocket_api_manager = BinanceWebSocketApiManager(
    BinanceWebSocketApiProcessStreams.process_stream_data)

# define some markets
markets = {
    'bnbbtc', 'ethbtc', 'btcusdt', 'bchabcusdt', 'xrpusdt', 'rvnbtc',
    'ltcusdt', 'adausdt', 'eosusdt', 'neousdt', 'bnbusdt', 'adabtc', 'ethusdt',
    'trxbtc', 'bchabcbtc', 'ltcbtc', 'xrpbtc', 'ontbtc', 'bttusdt', 'eosbtc',
    'xlmbtc', 'bttbtc', 'tusdusdt', 'xlmusdt', 'qkcbtc', 'zrxbtc', 'neobtc',
    'adaeth', 'icxusdt', 'btctusd', 'icxbtc', 'btcusdc', 'wanbtc', 'zecbtc',
    'wtcbtc', 'ethtusd', 'batusdt', 'mcobtc', 'neoeth', 'bntbtc', 'eostusd',
    'lrcbtc', 'funbtc', 'zecusdt', 'bnbpax', 'linkusdt', 'hceth', 'zrxeth',
    'icxeth', 'xmreth', 'neobnb', 'etceth', 'zeceth', 'xmrbnb', 'wanbnb',
    'zrxbnb', 'agibnb', 'funeth', 'arketh', 'engeth'
}

# create stream 1
Exemplo n.º 24
0
            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:
            try:
                print(oldest_stream_data_from_stream_buffer)
            except Exception:
                # not able to process the data? write it back to the stream_buffer
                binance_websocket_api_manager.add_to_stream_buffer(
                    oldest_stream_data_from_stream_buffer)


# create instance of BinanceWebSocketApiManager and provide the function for stream processing
binance_websocket_api_manager = BinanceWebSocketApiManager()

# start a worker process to 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()

print("testing ws/ single streams")

print(
    "\r\n========================================== Starting ticker all ========================================\r\n"
)
ticker_all_stream_id = binance_websocket_api_manager.create_stream(["arr"],
                                                                   ["!ticker"])
time.sleep(6)
binance_websocket_api_manager.stop_stream(ticker_all_stream_id)
# IN THE SOFTWARE.
#%%

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

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

binance_websocket_api_manager = BinanceWebSocketApiManager()


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:
            try:
                # remove # to activate the print function:
                print(oldest_stream_data_from_stream_buffer)
            except Exception:
                # not able to process the data? write it back to the stream_buffer
Exemplo n.º 26
0
from __future__ import print_function
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="{")

# create instance of BinanceWebSocketApiManager
binance_websocket_api_manager = BinanceWebSocketApiManager()

markets = [
    'xrpbearbusd', 'zeceth', 'cndbtc', 'dashbtc', 'atompax', 'perlbtc',
    'ardreth', 'zecbnb', 'bchabctusd', 'usdsbusdt', 'winbnb', 'xzcxrp',
    'bchusdc', 'wavesbnb', 'kavausdt', 'btsusdt', 'chzbnb', 'tusdbnb',
    'xtzbusd', 'bcptusdc', 'dogebnb', 'eosbearusdt', 'ambbnb', 'wrxbnb',
    'poabtc', 'wanbtc', 'ardrbtc', 'icnbtc', 'tusdusdt', 'atombusd', 'nxseth',
    'bnbusdt', 'trxxrp', 'erdpax', 'erdbtc', 'icxbusd', 'nulsbtc', 'hotusdt',
    'wavespax', 'zilbnb', 'arnbtc', 'nulsusdt', 'wintrx', 'npxsbtc', 'busdtry',
    'qtumbnb', 'eosbtc', 'xlmpax', 'tomobnb', 'eosbnb', 'engbtc', 'linketh',
    'xrpbtc', 'fetbtc', 'stratusdt', 'navbnb', 'bcneth', 'yoyobtc', 'nanobnb',
    'saltbtc', 'tfuelusdc', 'skybnb', 'fuelbtc', 'bnbusdc', 'inseth', 'btcpax',
    'batbtc', 'rlceth', 'arketh', 'ltcpax', 'ltcbusd', 'duskbtc', 'mftusdt',
    'bntusdt', 'mdabtc', 'enjbtc', 'poabnb', 'nanobusd', 'paxtusd', 'hotbtc',
    'bcdbtc', 'beambnb', 'trxeth', 'omgbnb', 'cdtbtc', 'eosusdc', 'dashbusd',
channels = {
    'aggTrade', 'trade', 'kline_1m', 'kline_5m', 'kline_15m', 'kline_30m',
    'kline_1h', 'kline_2h', 'kline_4h', 'kline_6h', 'kline_8h', 'kline_12h',
    'kline_1d', 'kline_3d', 'kline_1w', 'kline_1M', 'miniTicker', 'ticker',
    'bookTicker', 'depth5', 'depth10', 'depth20', 'depth', 'depth@100ms'
}
arr_channels = {'!miniTicker', '!ticker', '!bookTicker'}
markets = []

try:
    binance_api_key = ""
    binance_api_secret = ""
    binance_rest_client = unicorn_binance_rest_api.BinanceRestApiManager(
        binance_api_key, binance_api_secret)
    binance_websocket_api_manager = BinanceWebSocketApiManager()
except requests.exceptions.ConnectionError:
    print("No internet connection?")
    sys.exit(1)

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

print_summary_thread = threading.Thread(target=print_stream,
                                        args=(binance_websocket_api_manager, ))
print_summary_thread.start()

data = binance_rest_client.get_all_tickers()
for item in data:

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:
            pass
            #print(oldest_stream_data_from_stream_buffer)


# create instance of BinanceWebSocketApiManager for Binance Chain DEX
binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.org")

print("starting monitoring api!")
binance_websocket_api_manager.start_monitoring_api()

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

# userAddress streams
binance_dex_user_address = ""
id = binance_websocket_api_manager.create_stream('orders', binance_dex_user_address)
binance_websocket_api_manager.create_stream('accounts', binance_dex_user_address)
binance_websocket_api_manager.create_stream('transfers', binance_dex_user_address)
user_address_multi_stream_id = binance_websocket_api_manager.create_stream(['orders', 'transfers', 'accounts'],
                                                                           binance_dex_user_address)
# 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 class to process stream data
from unicorn_binance_websocket_api_process_streams import BinanceWebSocketApiProcessStreams

# https://docs.python.org/3/library/logging.html#logging-levels
logging.getLogger('unicorn-log').setLevel(logging.INFO)
logging.getLogger('unicorn-log').addHandler(logging.StreamHandler())

# create instance of BinanceWebSocketApiManager and provide the function for stream processing
binance_websocket_api_manager = BinanceWebSocketApiManager(
    BinanceWebSocketApiProcessStreams.process_stream_data)

print(
    "\r\n========================================== Starting aggTrade ==========================================\r\n"
)
# start
markets = {'bnbbtc', 'ethbtc', 'btcusdt', 'bchabcusdt', 'eosusdt'}
aggtrade_stream_id = binance_websocket_api_manager.create_stream(["aggTrade"],
                                                                 markets)
time.sleep(3)
# stop
binance_websocket_api_manager.stop_stream(aggtrade_stream_id)
time.sleep(2)
print(
    "\r\n=========================================== Stopped aggTrade ==========================================\r\n"
)
Exemplo n.º 30
0
import sys
import time
import os
try:
    from unicorn_fy.unicorn_fy import UnicornFy
except ImportError:
    print("Please install `unicorn-fy`! https://pypi.org/project/unicorn-fy/")
    sys.exit(1)

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

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

binance_api_key = "I25sjQLfPuTBzMGNiHGPFq7UpxSZ9kdjjvgBri20sDHxJqFG21WabzpHAk1P9To1"
binance_api_secret = "ogrjfEnUpokY8VKKtlPNNUS3iWTqX9QuwS5vYwcs8fBThIRhQn4AyNL35cRWhuz5"

binance_websocket_api_manager.set_private_api_config(binance_api_key,
                                                     binance_api_secret)
userdata_stream_id = binance_websocket_api_manager.create_stream(
    ["!userData"], ["arr"], "userData stream")

ubwa = binance_websocket_api_manager
IPython.embed()