CryptoCurrency Trading on HitBTC with a Python Bot - Streaming API

in #eso6 years ago (edited)

​The REST API example in my last post was a simple way to get the information we need to start analyzing price data for decision making and ultimately setting buy or sell threshold values.

It is however very inefficient in that we have to send a request to the HitBTC servers every x seconds regardless of whether there is new data to retrieve or not. Furthermore, every request is a new TCP connection that sends a full HTTPs POST request to the server. When it comes to trading, every second (or millisecond) counts so every bit of speed we can add will give us a further advantage.

Next up, converting and optimizing our streaming script into a usable class

Step in Streaming

Streaming the data directly from HitBTC via version 2 of the API will allow us to set up a single TCP connection which will only send data to our script when something changes. Even better, we can 'subscribe' to multiple functions through the same connection rather than slamming the REST API with various requests, all of which have new TCP connections. Streaming via a single TCP port will give us a significant edge but is slightly more complicated to implement.

Our goal will to of course build this into a class to make using it very simple with built-in error checking and recovery, but for now, here is an example script to show how it works.


CODE


import asyncio
import websockets
import json

async def test():

    async with websockets.connect('wss://api.hitbtc.com/api/2/ws') as websocket:
    #Client async code
        await websocket.send('{"method": "subscribeTicker","params": {"symbol": "EOSUSD"},"id": 123}')

        # Listen to the socket for an incoming response, this is not needed as
        # it is just confirmation all is working.  This could be used for error
        # checking
        jsondata = await websocket.recv()

        # Loop forever until Ctl^c is hit
        while True:
            # Clear the screen
            os.system('clear')
            # Listen to the socket for an incoming response

            jsondata = await websocket.recv()
            
            # Convert the return string to JSON
            jsondata = json.loads(jsondata)

            # Print out just the key values we want
            print("Symbol      : %s" % (jsondata['params']['symbol']))
            print("Last Price  : %s" % (jsondata['params']['last']))
            print("Highest Bid : %s" % (jsondata['params']['bid']))
            print("Lowest Ask  : %s" % (jsondata['params']['ask']))

#Starting the async flow
asyncio.get_event_loop().run_until_complete(test())

OUTPUT


Symbol : EOSUSD
Last Price : 17.65018
Highest Bid : 17.63877
Lowest Ask : 17.65492

As you can see, the output is exactly the same except now, the values only change when there is a change to be made.

As a side note, it is also important to know that geographical location of where the script is run will be a factor in how fast our data is sent and received​. I am in the USA and if I ping www.hitbtc.com I get a good round trip time.

ping www.hitbtc.com
PING www.hitbtc.com (104.31.78.244): 56 data bytes
64 bytes from 104.31.78.244: icmp_seq=0 ttl=54 time=24.678 ms
64 bytes from 104.31.78.244: icmp_seq=1 ttl=54 time=20.047 ms

But..... in our script we are hitting api.hitbtc.com, let's​ see how that looks.

ping api.hitbtc.com
PING api.hitbtc.com (145.239.0.27): 56 data bytes
64 bytes from 145.239.0.27: icmp_seq=0 ttl=45 time=121.731 ms
64 bytes from 145.239.0.27: icmp_seq=1 ttl=45 time=127.588 ms

That is quite a difference!!!

Next up, creating a class that will stream the data and methods to subscribe to the functions we need.

Sort:  

sneaky-ninja-sword-xs.jpg
Sneaky Ninja Attack! You have just been defended with a 1.80% upvote!
I was summoned by @sku77-poprocks. I have done their bidding and now I will vanish...

woosh
A portion of the proceeds from your bid was used in support of youarehope and tarc.

Abuse Policy
Rules
How to use Sneaky Ninja
How it works
Victim of grumpycat?

Coin Marketplace

STEEM 0.28
TRX 0.11
JST 0.034
BTC 66274.97
ETH 3175.04
USDT 1.00
SBD 4.06