Guest User

Stream kraken ticker

a guest
Sep 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. from sanic import Sanic
  2. from sanic.response import json
  3. from sanic.response import stream
  4. import asyncio
  5. import psycopg2
  6. import ccxt.async_support as ccxt
  7. import json
  8. import logging
  9.  
  10. logger = logging.getLogger("ozzo")
  11. try:
  12.     conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' port='5432' password='password'")
  13. except:
  14.     print("I am unable to connect to the database")
  15.  
  16. app = Sanic()
  17.  
  18. kraken = ccxt.kraken({
  19.     'apiKey': "hEvQNMDIeoCJbr7W/ZBb5CGOrx3G0lWF5B3zqa1JBxdZlEaL8EK+D0Mw",
  20.     'secret': "JaE9wI6Nwgh5oRxiHcVxurwzwBxwc05W/qv/k1srGg4s3EYuXPpNkLLM5NYbbWpM8rCyijIeDavRuqWbU0ZV9A==",
  21. })
  22.  
  23. async def poll(seconds):
  24.     while True:
  25.         try:
  26.             yield await asyncio.Task(kraken.fetch_ticker('BTC/USD'))
  27.         except RuntimeError:
  28.             logger.exception("Something went wrong while calling kraken")
  29.         if seconds * 1000 < kraken.rateLimit:
  30.             raise ("poll rate exceed the rate limit")
  31.         await asyncio.sleep(seconds)
  32.  
  33. @app.get('/')
  34. async def test(request):
  35.     async def stream_from_exchange(response):
  36.         async for ticker in poll(5):
  37.             payload = json.dumps(ticker)
  38.             print("payload:", payload)
  39.             await response.write(f"{payload}\n")
  40.     return stream(
  41.         stream_from_exchange,
  42.         content_type='application/stream+json'
  43.     )
  44.  
  45. async def main():
  46.     async for ticker in poll(5):
  47.         print(ticker)
  48.  
  49.  
  50. if __name__ == '__main__':
  51.     app.run(host='0.0.0.0', port=8000)
Add Comment
Please, Sign In to add comment