Search code examples
pythonwebsocketrestalgorithmic-trading

Use REST API while streaming Websocket


How do you request via REST API, while streaming via Websocket?

Example:
Communication between a client and an exchange server for trading using the exchange's API.
Specifically, I want to send an order using REST API request,
then I want to receive my order information from the exchange via a private Websocket.

Below is the code.
If I start subscribing to Websocket (See 1), it is going to be in a ws.run_forever() loop.
How can I execute the 2. within the ws.run_forever() loop, so that once the order is executed I immediately receive the order information from the exchange server?

1. Streaming via Websocket

# Subscribing to order information from an exchange via WebSocket API

import json
import websocket

def on_open(self):
    message = {
        "command": "subscribe",
        "channel": "orderEvent"
    }
    ws.send(json.dumps(message))
    
def on_message(self, message):
    # do something...

endpoint = "url"
ws = websocket.WebSocketApp(endpoint,
                            on_open=on_open,
                            on_message=on_message
                            )
ws.run_forever()

2. Send order via REST API

# Sending order

import requests

    reqBody = {
        "side": BUY,
        "amount" : AMOUNT,
    }

    requests.post("request_url", headers=headers, data=json.dumps(reqBody))

Solution

  • While you're processing the message you can make the determination to submit an order. Something like this should work

    def on_message(self, message):
        if something:
            response = buy_stock(AMOUNT)
        
    def buy_stock(AMOUNT):
        reqBody = {
            "side": BUY,
            "amount" : AMOUNT,
        }
    
        r = requests.post("request_url", headers=headers, data=json.dumps(reqBody))
        return r