Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created October 11, 2020 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuyasugano/516559047f3f9cc4a38cc54be3d75bf5 to your computer and use it in GitHub Desktop.
Save yuyasugano/516559047f3f9cc4a38cc54be3d75bf5 to your computer and use it in GitHub Desktop.
WebSocket example sma
#!/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