|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +import websocket # pip install websocket-client |
| 5 | + |
| 6 | +from poloniex import Poloniex |
| 7 | + |
| 8 | +from multiprocessing.dummy import Process as Thread |
| 9 | +import json |
| 10 | +import logging |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | +class dictTicker(object): |
| 15 | + |
| 16 | + def __init__(self, api=None): |
| 17 | + self.api = api |
| 18 | + if not self.api: |
| 19 | + self.api = Poloniex(jsonNums=float) |
| 20 | + self.tick = {} |
| 21 | + |
| 22 | + iniTick = self.api.returnTicker() |
| 23 | + self._ids = {market: iniTick[market]['id'] for market in iniTick} |
| 24 | + for market in iniTick: |
| 25 | + self.tick[self._ids[market]] = iniTick[market] |
| 26 | + |
| 27 | + self._ws = websocket.WebSocketApp("wss://api2.poloniex.com/", |
| 28 | + on_open=self.on_open, |
| 29 | + on_message=self.on_message, |
| 30 | + on_error=self.on_error, |
| 31 | + on_close=self.on_close) |
| 32 | + |
| 33 | + def on_message(self, ws, message): |
| 34 | + message = json.loads(message) |
| 35 | + if 'error' in message: |
| 36 | + return logger.error(message['error']) |
| 37 | + |
| 38 | + if message[0] == 1002: |
| 39 | + if message[1] == 1: |
| 40 | + return logger.info('Subscribed to ticker') |
| 41 | + |
| 42 | + if message[1] == 0: |
| 43 | + return logger.info('Unsubscribed to ticker') |
| 44 | + |
| 45 | + data = message[2] |
| 46 | + data = [float(dat) for dat in data] |
| 47 | + self.tick[data[0]] = {'id': data[0], |
| 48 | + 'last': data[1], |
| 49 | + 'lowestAsk': data[2], |
| 50 | + 'highestBid': data[3], |
| 51 | + 'percentChange': data[4], |
| 52 | + 'baseVolume': data[5], |
| 53 | + 'quoteVolume': data[6], |
| 54 | + 'isFrozen': data[7], |
| 55 | + 'high24hr': data[8], |
| 56 | + 'low24hr': data[9] |
| 57 | + } |
| 58 | + |
| 59 | + def on_error(self, ws, error): |
| 60 | + logger.error(error) |
| 61 | + |
| 62 | + def on_close(self, ws): |
| 63 | + if self._t._running: |
| 64 | + try: |
| 65 | + self.stop() |
| 66 | + except Exception as e: |
| 67 | + logger.exception(e) |
| 68 | + try: |
| 69 | + self.start() |
| 70 | + except Exception as e: |
| 71 | + logger.exception(e) |
| 72 | + self.stop() |
| 73 | + else: |
| 74 | + logger.info("Websocket closed!") |
| 75 | + |
| 76 | + def on_open(self, ws): |
| 77 | + self._ws.send(json.dumps({'command': 'subscribe', 'channel': 1002})) |
| 78 | + |
| 79 | + @property |
| 80 | + def status(self): |
| 81 | + """ |
| 82 | + Returns True if the websocket is running, False if not |
| 83 | + """ |
| 84 | + try: |
| 85 | + return self._t._running |
| 86 | + except: |
| 87 | + return False |
| 88 | + |
| 89 | + def start(self): |
| 90 | + """ Run the websocket in a thread """ |
| 91 | + self._t = Thread(target=self._ws.run_forever) |
| 92 | + self._t.daemon = True |
| 93 | + self._t._running = True |
| 94 | + self._t.start() |
| 95 | + logger.info('Websocket thread started') |
| 96 | + |
| 97 | + def stop(self): |
| 98 | + """ Stop/join the websocket thread """ |
| 99 | + self._t._running = False |
| 100 | + self._ws.close() |
| 101 | + self._t.join() |
| 102 | + logger.info('Websocket thread stopped/joined') |
| 103 | + |
| 104 | + def __call__(self, market=None): |
| 105 | + """ returns ticker from mongodb """ |
| 106 | + if market: |
| 107 | + return self.tick[self._ids[market]] |
| 108 | + return self.tick |
| 109 | + |
| 110 | + if __name__ == "__main__": |
| 111 | + import pprint |
| 112 | + from time import sleep |
| 113 | + logging.basicConfig(level=logging.DEBUG) |
| 114 | + # websocket.enableTrace(True) |
| 115 | + ticker = dictTicker() |
| 116 | + try: |
| 117 | + ticker.start() |
| 118 | + for i in range(3): |
| 119 | + sleep(5) |
| 120 | + pprint.pprint(ticker('USDT_BTC')) |
| 121 | + except Exception as e: |
| 122 | + logger.exception(e) |
| 123 | + ticker.stop() |
0 commit comments