WebSocket example sma
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import time | |
import json | |
import logging | |
import socketio | |
import websocket | |
from collections import deque | |
logging.basicConfig( | |
level=logging.DEBUG, | |
filename='./socketio.log', | |
format='%(levelname)s : %(asctime)s : %(message)s' | |
) | |
logger = logging.getLogger(__name__) | |
sio = socketio.Client( | |
reconnection=True, | |
reconnection_attempts=0, | |
reconnection_delay=1, | |
reconnection_delay_max=30, | |
logger=True | |
) | |
logger.info('Created socketio client') | |
def run(url): | |
sio.connect(url, transports=['websocket']) | |
logger.info('socketio process connected') | |
def stop(): | |
sio.disconnect() | |
logger.info('socketio process disconnected') | |
@sio.event | |
def connect(): | |
logger.info('connected to server') | |
sio.emit('join-room', 'transactions_btc_jpy') | |
@sio.event | |
def message(data): | |
transactions = data['message']['data']['transactions'] | |
# print('transaction type: {}'.format(type(transactions))) | |
# print(json.dumps(transactions, indent=2)) | |
for num, transaction in enumerate(transactions): | |
print('transaction {0}: {1}'.format(num, transaction)) | |
executions.appendleft(int(transaction['price'])) | |
@sio.event | |
def disconnect(): | |
logger.info('disconnected from server') | |
if __name__ == '__main__': | |
executions = deque(maxlen=100) | |
url = 'wss://stream.bitbank.cc' | |
run(url) | |
sma = 5 | |
while True: | |
try: | |
current = int(round(time.time()*1000)) | |
print('current timestamp: {}'.format(current)) | |
execution_num = len(executions) | |
if execution_num == 0: | |
print('executions are empty') | |
elif sma <= execution_num: | |
l = list(executions)[0:sma] | |
print('executions average in queue: {}'.format(int(round(sum(l)/len(l))))) | |
elif sma > execution_num: | |
sma = execution_num | |
l = list(executions)[0:sma] | |
print('executions average in queue: {}'.format(int(round(sum(l)/len(l))))) | |
else: | |
print('unknown status') | |
time.sleep(5) | |
except KeyboardInterrupt: | |
stop() | |
exit() | |
except Exception as e: | |
exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment