Notifying Binance P2P Sellers About Payment Transfers Using Python WebSocket Automation
In the realm of crypto trading automation, seamless communication with your counterparty is still essential. On Binance P2P, a common task is to inform the seller that payment has been sent. This can be handled automatically using WebSocket and Python ā no manual actions required.
Below, weāll explore how to retrieve chat credentials, connect to Binanceās WebSocket service, and programmatically send a message to the P2P chat notifying the seller of a payment. This approach is particularly relevant for those developing P2P bots or streamlining trade processing workflows.
āļø This approach is based on practical examples and methodologies circulating among active developers in the crypto automation space.
š Getting Chat Credentials for WebSocket
To begin, youāll need to fetch the chatWssUrl, listenKey, and listenToken, which are required to connect to Binance's chat WebSocket.
ā ļø Code may look unformatted ā Binance editor doesnāt support code blocks.
š¦ The retrieveChatCredential Function
def retrieveChatCredential(): # You Api Key on binance api_key = "11111" # You Apy Secret on binance secret_key = "11111" base_url = "https://api.binance.com" endpoint = "/sapi/v1/c2c/chat/retrieveChatCredential" timestamp = int(time.time() * 1000) query_string = f"timestamp={timestamp}" signature = hmac.new( secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256 ).hexdigest() headers = { "clientType": "web", "X-MBX-APIKEY": api_key } url = f"{base_url}{endpoint}?{query_string}&signature={signature}" response = requests.get(url, headers=headers) if response.status_code == 200: return response.json() else: print("Error:", response.status_code, response.text) return None
Once the credentials are obtained:
chatWssUrl = res_detail['data']['chatWssUrl']
listenKey = res_detail['data']['listenKey']
listenToken = res_detail['data']['listenToken']
chat_wss_url = f"{chatWssUrl}/{listenKey}?token={listenToken}&clientType=web"
š Establishing the WebSocket Connection
def connect_to_websocket():
global reconnect_attempts, ws
reconnect_attempts = 0
ws = websocket.WebSocketApp(
chat_wss_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
š” WebSocket Event Handlers
on_open ā triggered when the connection is established
on_message ā triggered on message receipt
on_error ā handles errors during connection
on_close ā reconnects on disconnection
āļø Sending a Chat Message
When youāre ready to notify the seller after sending funds:
send_message(content, order_no):
if ws_connection:
timestamp = int(time.time() * 1000)
message_uuid = generate_uuid()
response_message = {
"type": "text",
"uuid": message_uuid,
"orderNo": order_no,
"content": content,
"self": True,
"clientType": "web",
"createTime": timestamp,
"sendStatus": 0
}
try:
ws_connection.send(json.dumps(response_message))
print(f"Message sent to chat: {content}")
except Exception as e:
print(f"Message sending error: {str(e)}")
Example usage:
send_message("Hello, the payment has been made. Please release the crypto.", "789456123ABCDEF")
š§© Full Working Example
ReadMore: https://py-dev.top/blog/crypto-exchange-development/automatic-message-sending-to-binance-p2p-chat-via-websocket-using-python
#BinanceChat #websocket