Profit Like a Pro: Uncovering Hidden Opportunities with Cross-Market Arbitrage using Python & Websocket

Algotron
3 min readMar 26, 2023

--

Have you ever wondered if it’s possible to make a profit by buying low on one exchange and selling high on another? This is called cross market arbitrage, and it’s a popular trading strategy among investors.

In this blog post, we will explore how to detect cross market arbitrages between Binance and Bybit spot prices for the AVAXUSDT trading pair using Python and Websocket API. We will also write a function that sends orders to both exchanges.

What is Cross Market Arbitrage?

Cross market arbitrage is a trading strategy that involves buying assets on one exchange where the price is lower and simultaneously selling the same assets on another exchange where the price is higher. The price difference between the two exchanges can be exploited for profit by taking advantage of the price discrepancy.

Connecting to Binance and Bybit Websocket API

To connect to Binance and Bybit Websocket API, we will use Python and the websocket library. Here's how to get started:

import websocket
import json
def on_message(ws, message):
data = json.loads(message)
# Parse data to extract AVAXUSDT spot prices
# Compare spot prices and execute orders if profitable
def on_error(ws, error):
print(error)
def on_close(ws):
print("Connection closed")
def on_open(ws):
# Start subscribing to AVAXUSDT ticker data
ws.send('{"method": "SUBSCRIBE", "params": ["avaxusdt@ticker"], "id": 1}')
if __name__ == "__main__":
# Connect to Binance and Bybit Websocket API
binance_ws = websocket.WebSocketApp("wss://stream.binance.com:9443/ws/avaxusdt@ticker", on_message=on_message, on_error=on_error, on_close=on_close)
bybit_ws = websocket.WebSocketApp("wss://stream.bybit.com/realtime_public?subscribe=instrument_info.1000ms.AVAXUSDT", on_message=on_message, on_error=on_error, on_close=on_close)
# Start listening to Websocket API
binance_ws.on_open = on_open
bybit_ws.on_open = on_open
binance_ws.run_forever()
bybit_ws.run_forever()

Sending Orders to Binance and Bybit

To send orders to Binance and Bybit, we will use the REST API and send authenticated requests. Here’s an example function that sends a buy order to Binance:

import requests
import hashlib
import hmac
import time
def send_order_binance(api_key, secret_key, symbol, side, quantity, price):
# Define request parameters
timestamp = int(time.time() * 1000)
base_url = "<https://api.binance.com>"
endpoint = "/api/v3/order"
params = {
"symbol": symbol,
"side": side,
"type": "LIMIT",
"timeInForce": "GTC",
"quantity": quantity,
"price": price,
"recvWindow": 5000,
"timestamp": timestamp
}
# Create signature
query_string = "&".join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(secret_key.encode(), query_string.encode(), hashlib.sha256).hexdigest()
# Send authenticated request
headers = {
"X-MBX-APIKEY": api_key
}
url = f"{base_url}{endpoint}?{query_string}&signature={signature}"
response = requests.post(url, headers=headers)
return response.json()
def send_order_bybit(api_key, secret_key, symbol, side, quantity, price):
# Define request parameters
timestamp = int(time.time() * 1000)
base_url = "<https://api.bybit.com>"
endpoint = "/v2/private/order/create"
params = {
"symbol": symbol,
"side": side.lower(),
"order_type": "Limit",
"qty": quantity,
"price": price,
"time_in_force": "GoodTillCancel",
"timestamp": timestamp
}
# Create signature
query_string = "&".join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(secret_key.encode(), query_string.encode(), hashlib.sha256).hexdigest()
# Send authenticated request
headers = {
"api-key": api_key,
"sign": signature,
"Content-Type": "application/json"
}
url = f"{base_url}{endpoint}"
response = requests.post(url, headers=headers, data=json.dumps(params))
return response.json()

Detecting Cross Market Arbitrages

To detect cross market arbitrages between Binance and Bybit, we will use Python and Websocket API. Here are the steps involved:

  1. Connect to Binance and Bybit Websocket API to receive real-time market data for the AVAXUSDT trading pair.
  2. Parse the market data to extract the spot prices of AVAXUSDT on both exchanges.
  3. Compare the spot prices of AVAXUSDT on both exchanges.
  4. If the price difference is significant enough to cover trading fees, execute a buy order on Binance and a sell order on Bybit using the send_order_binance and send_order_bybit functions, respectively.
  5. Monitor the market data continuously to detect new arbitrage opportunities.

Here’s an example implementation of step 3 and 4:

binance_price = 0
bybit_price = 0
def on_message(ws, message):
global binance_price, bybit_price
data = json.loads(message)
if 'binance' in data['stream']:
binance_price = float(data['data']['p'])
elif 'bybit' in data['topic']:
bybit_price = float(data['data'][0]['last_price'])
if binance_price and bybit_price:
# Calculate price difference and trading fees
price_diff = bybit_price - binance_price
binance_fee_rate = 0.001
bybit_fee_rate = 0.00075
min_profit = 0.0001
# Check if profitable arbitrage opportunity exists
if price_diff > (binance_fee_rate + bybit_fee_rate + min_profit):
# Execute orders
binance_api_key = "<BINANCE_API_KEY>"
binance_secret_key = "<BINANCE_SECRET_KEY>"
bybit_api_key = "<BYBIT_API_KEY>"
bybit_secret_key = "<BYBIT_SECRET_KEY>"
symbol = "AVAXUSDT"
quantity = 1
binance_buy_price = binance_price
bybit_sell_price = bybit_price
send_order_binance(binance_api_key, binance_secret_key, symbol, "BUY", quantity, binance_buy_price)
send_order_bybit(bybit_api_key, bybit_secret_key, symbol, "SELL", quantity, bybit_sell_price)
print("Arbitrage executed!")
# Rest of the code

Conclusion

Cross market arbitrage can be a profitable trading strategy if executed correctly. By using Python and Websocket API to receive real-time market data from exchanges like Binance and Bybit, we can automate the process of detecting arbitrage opportunities and increase our chances of making a profit.

To get started with detecting cross market arbitrages, check out the Binance and Bybit API documentation and start experimenting with Python. Happy trading!

--

--