Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,205 changes: 1,205 additions & 0 deletions .codspeed/results_1740207625903.json

Large diffs are not rendered by default.

1,205 changes: 1,205 additions & 0 deletions .codspeed/results_1740207797034.json

Large diffs are not rendered by default.

1,205 changes: 1,205 additions & 0 deletions .codspeed/results_1740207841123.json

Large diffs are not rendered by default.

1,205 changes: 1,205 additions & 0 deletions .codspeed/results_1740207936629.json

Large diffs are not rendered by default.

1,179 changes: 1,179 additions & 0 deletions .codspeed/results_1740208013406.json

Large diffs are not rendered by default.

1,205 changes: 1,205 additions & 0 deletions .codspeed/results_1740208367753.json

Large diffs are not rendered by default.

6 changes: 1 addition & 5 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,7 @@ jobs:
test:
needs: lint
runs-on: ubuntu-22.04
timeout-minutes: 40
strategy:
max-parallel: 2
matrix:
python-version: ['3.8', '3.9', '3.10', '3.11', '3.12']
timeout-minutes: 20
env:
PROXY: "http://188.245.226.105:8911"
TEST_TESTNET: "true"
Expand Down
5 changes: 5 additions & 0 deletions .source/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// @ts-nocheck -- skip type checking
import { _runtime } from "fumadocs-mdx/runtime/next"
import _source from "../source.config"

export const map = _runtime.docs(_source.docs || [], _source.meta || []).toFumadocsSource()
10 changes: 10 additions & 0 deletions .source/source.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// source.config.ts
import { defineConfig, defineDocs } from "fumadocs-mdx/config";
var source_config_default = defineConfig({
docs: defineDocs({
dir: "content/docs"
})
});
export {
source_config_default as default
};
1 change: 1 addition & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python 3.12.8
41 changes: 41 additions & 0 deletions 1530.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import asyncio
import sys

sys.path.append(".")
from binance.async_client import AsyncClient
from binance import BinanceSocketManager

# set log level to debug AND PRINT TO CONSOLE
import logging

logging.basicConfig(level=logging.DEBUG)


async def handle_user_socket():
# Initialize the client
client = await AsyncClient.create()
try:
# Initialize socket manager
bm = BinanceSocketManager(client)
# Start user socket with proper context management
async with bm.ticker_socket() as socket:
while True:
res = await socket.recv()
finished = do_something(res)
if finished:
break
finally:
# Ensure client is properly closed
print("Closing client")
await client.close_connection()


def do_something(res):
# Implement your message handling logic here
print(f"Received message: {res}")
return True # Return True when you want to stop the loop


# Run the async function
if __name__ == "__main__":
asyncio.run(handle_user_socket())
46 changes: 46 additions & 0 deletions 1543.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from binance import ThreadedWebsocketManager

import time
import threading

twm: ThreadedWebsocketManager
symbol = "BTCUSDT"


def handle_socket_message(msg):
print("handle_socket_message", msg)


def test_threaded_socket_manager():
"""This thread will only process messages"""
print("test_threaded_socket_manager run")
print("id:", id(twm))
print("type:", type(twm))

# Just wait and process messages
time.sleep(10)

print("test_threaded_socket_manager stop")


if __name__ == "__main__":
# Create and start TWM in main thread
twm = ThreadedWebsocketManager(api_key="", api_secret="", testnet=False)
twm.start()
print("id:", id(twm))
print("type:", type(twm))

# Start socket in main thread where TWM was created
sock_id = twm.start_kline_futures_socket(
callback=handle_socket_message, symbol=symbol
)

# Create thread for processing
t = threading.Thread(target=test_threaded_socket_manager)
t.start()
t.join()

# Cleanup in main thread
twm.stop_socket(sock_id)
twm.stop()
print("quit")
44 changes: 44 additions & 0 deletions 1575.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from binance import ThreadedWebsocketManager, AsyncClient
import asyncio

api_key = ""
api_secret = ""


async def run_websocket_operations():
symbol = "BNBBTC"

# Create async client
client = await AsyncClient.create(api_key=api_key, api_secret=api_secret)

try:
# Get account status using async call
account = await client.ws_get_symbol_ticker(symbol=symbol)
print(f"account: {account}")
finally:
await client.close_connection()


def handle_socket_message(msg):
print(f"message type: {msg['e']}")
# print(msg)


def main():
# Start ThreadedWebsocketManager
twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret)
twm.start()

# Start kline socket
twm.start_kline_socket(callback=handle_socket_message, symbol="BNBBTC")

# Run async operations in a separate event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(run_websocket_operations())

twm.join()


if __name__ == "__main__":
main()
42 changes: 42 additions & 0 deletions 1589.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import asyncio
import logging
from binance import AsyncClient, BinanceSocketManager
from binance.ws.reconnecting_websocket import ReconnectingWebsocket

logging.basicConfig(level=logging.DEBUG)

# Explicitly set the log level for the binance package
logging.getLogger("binance").setLevel(logging.DEBUG)

logger = logging.getLogger(__name__)


async def main():
# Set MAX_RECONNECTS to 0 to simulate permanent disconnect
ReconnectingWebsocket.MAX_RECONNECTS = 3

client = await AsyncClient.create()
bm = BinanceSocketManager(client)

async with bm.multiplex_socket(["btcusdt@kline_1s"]) as tscm:
logger.info("Websocket started")
count = 0
while True:
logger.info("Awaiting message...")
t = await tscm.recv()
logger.info("Message received")
count += 1
try:
if count == 5:
logger.info("Simulating connection drop (code 1001)")
await tscm.ws.close(code=1001, reason="going away")
print(t["data"])
except KeyError as e:
logger.warning(f"Error: {e} with data {t}")
logger.info("Loop continues")

await client.close_connection()


if __name__ == "__main__":
asyncio.run(main())
101 changes: 101 additions & 0 deletions 1608.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import asyncio
import logging
import subprocess
import time

Check failure on line 4 in 1608.py

View workflow job for this annotation

GitHub Actions / lint

Ruff (F401)

1608.py:4:8: F401 `time` imported but unused

Check failure on line 4 in 1608.py

View workflow job for this annotation

GitHub Actions / lint

Ruff (F401)

1608.py:4:8: F401 `time` imported but unused
from binance import AsyncClient, BinanceSocketManager
from binance.ws.reconnecting_websocket import ReconnectingWebsocket

Check failure on line 6 in 1608.py

View workflow job for this annotation

GitHub Actions / lint

Ruff (F401)

1608.py:6:47: F401 `binance.ws.reconnecting_websocket.ReconnectingWebsocket` imported but unused

Check failure on line 6 in 1608.py

View workflow job for this annotation

GitHub Actions / lint

Ruff (F401)

1608.py:6:47: F401 `binance.ws.reconnecting_websocket.ReconnectingWebsocket` imported but unused

logging.basicConfig(level=logging.DEBUG)

# Explicitly set the log level for the binance package
logging.getLogger("binance").setLevel(logging.DEBUG)

logger = logging.getLogger(__name__)


async def simulate_network_disconnect():
"""Simulate network disconnect by temporarily disabling network interface"""
logger.info("=== SIMULATING NETWORK DISCONNECT ===")
try:
# Get the active network interface
result = subprocess.run(
["route", "get", "default"], capture_output=True, text=True, check=True
)
interface = None
for line in result.stdout.split("\n"):
if "interface:" in line:
interface = line.split(":")[1].strip()
break

if not interface:
logger.error("Could not determine network interface")
return False

logger.info(f"Temporarily disabling network interface: {interface}")

# Disable the network interface
subprocess.run(["sudo", "ifconfig", interface, "down"], check=True)

# Wait for disconnect to take effect
logger.info("Network interface disabled - waiting 10 seconds...")
await asyncio.sleep(10)

# Re-enable the network interface
logger.info(f"Re-enabling network interface: {interface}")
subprocess.run(["sudo", "ifconfig", interface, "up"], check=True)

# Wait a bit for network to come back up
await asyncio.sleep(3)
logger.info("Network interface restored")

except Exception as e:
logger.error(f"Network interface manipulation failed: {e}")
logger.info("This method requires sudo privileges")
return False

return True


async def main():
client = await AsyncClient.create()
bm = BinanceSocketManager(client)

# Test futures kline socket to reproduce the 1001 reconnection issue
async with bm.multiplex_socket(["btcusdt@kline_1s"]) as tscm:
logger.info("Futures kline websocket started")
count = 0
while True:
try:
logger.info("Awaiting message...")
t = await tscm.recv()
logger.info("Message received")
count += 1

# Simulate realistic network disconnect after receiving some messages
if count == 5:
logger.info("Triggering network disconnect simulation...")
# Run network disconnect simulation in background
asyncio.create_task(simulate_network_disconnect())

print(f"Message {count}: {t}")

except Exception as e:
logger.error(f"Error occurred: {e}")
logger.error(f"Error type: {type(e)}")
# Check if we get the ConnectionClosedOK error
if "ConnectionClosedOK" in str(e) or "1001" in str(e):
logger.error(
"Got the 1001 'going away' error - this should trigger reconnection"
)
logger.error(
"Waiting to see if websocket reconnects automatically..."
)
await asyncio.sleep(5) # Wait to see if reconnection happens
else:
raise e

await client.close_connection()


if __name__ == "__main__":
asyncio.run(main())
Loading
Loading