以毫秒(Binance Websocket)获取现场价格

发布于 2025-02-01 18:08:28 字数 611 浏览 6 评论 0原文

如何更改代码,以便每100毫秒获得信息?

import asyncio
from binance import AsyncClient, BinanceSocketManager


async def main():
    client = await AsyncClient.create()
    bm = BinanceSocketManager(client)
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket('BTCBUSD')
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)

    await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

我会得到我能得到的每个答案,非常感谢!

how can i change my code so i get the informations every 100 milliseconds ?

import asyncio
from binance import AsyncClient, BinanceSocketManager


async def main():
    client = await AsyncClient.create()
    bm = BinanceSocketManager(client)
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket('BTCBUSD')
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)

    await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

i apperciate every answer i can get , thanks a lot !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡紫姑娘! 2025-02-08 18:08:28

尝试一下:

import asyncio
import websockets
import json

async def hello():
    async with websockets.connect("wss://stream.binance.com:9443/ws/btcusdt@bookTicker") as ws:
        while True:
            response = await asyncio.wait_for(ws.recv(), timeout=2)
            response=json.loads(response)
            print(response)
            await asyncio.sleep(0.5)

asyncio.get_event_loop().run_until_complete(hello())

Try this out:

import asyncio
import websockets
import json

async def hello():
    async with websockets.connect("wss://stream.binance.com:9443/ws/btcusdt@bookTicker") as ws:
        while True:
            response = await asyncio.wait_for(ws.recv(), timeout=2)
            response=json.loads(response)
            print(response)
            await asyncio.sleep(0.5)

asyncio.get_event_loop().run_until_complete(hello())
玩世 2025-02-08 18:08:28

您询问了“如何以毫秒(Binance websocket)获得实时价格”,

这是一个可用的binance流的列表,其中包含“ update speed”的可用选项: https://github.com/binance/binance/binance-binance-spot-apot-api-docs一下/blob/master/web-socket-streams.md#detailed-stream-information

因为我理解大多数流类型都在更新一次(更新速度:1000ms)。

只有深度流可以更新10次每秒10次(1000ms和100ms间隔)

贸易流(AGG和正常),并且BookTicker(个人和所有)是实时的。这意味着,只要有此信息,您就会收到...

如果没有交易,您将不会收到任何东西,因为价格没有变化...但是,一旦交易发生,它就会报告了给你。

如果您想知道,当前的买卖价格可用于资产,您可以使用Bookticker,而Bookticker与深度和差异相比要少得多。深度流...如果您需要的是当前订单的最初位置,我建议使用本地深度缓存: https://www.lucit.tech/unicorn-binance-local-local-depth-cache.html

要获得稳定的Websocket连接,我建议使用 Unicorn Binance binance binance websocket api ,它会捕获大多数例外,并在脱节后自动重新连接(它使用asyncio insions(它)回调函数在事件循环中),使用它的语法很容易:

from unicorn_binance_websocket_api.manager import BinanceWebSocketApiManager


def process_new_receives(stream_data, stream_buffer_name=False):
    print(str(stream_data))


ubwa = BinanceWebSocketApiManager(exchange="binance.com")
ubwa.create_stream('trade',
                   ['ethbtc', 'btcusdt', 'bnbbtc', 'ethbtc'],
                   process_stream_data=process_new_receives)

You asked about "how to get live price in milliseconds (Binance Websocket)"

Here is a list of available streams on binance with the available options for "update speed": https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md#detailed-stream-information

For my understand most stream types are updating once a second (update speed: 1000ms).

Only depth streams are possible to update 10 times per second (1000ms and 100ms interval)

Trade streams (agg and normal) and Bookticker (individual and all) are in real time. That means, as soon this info is available, you will receive it...

If there is no trade, you will not receive anything, because there is no change in price... but as soon a trade happens, it will get reported to you.

If you want to know, the current buy and sell price for that an asset is available you can use the bookticker which is much less data compared to depth and diff. depth streams... if you need more than the first positions of the current orderbook i recommend using a local depth cache: https://www.lucit.tech/unicorn-binance-local-depth-cache.html

To get a stable websocket connection i recommend using UNICORN Binance WebSocket API, it catches most exceptions and reconnects automatically after a disconnect, it uses asyncio inside (callback function is inside an event loop) and the syntax to use it is easy:

from unicorn_binance_websocket_api.manager import BinanceWebSocketApiManager


def process_new_receives(stream_data, stream_buffer_name=False):
    print(str(stream_data))


ubwa = BinanceWebSocketApiManager(exchange="binance.com")
ubwa.create_stream('trade',
                   ['ethbtc', 'btcusdt', 'bnbbtc', 'ethbtc'],
                   process_stream_data=process_new_receives)
淡淡的优雅 2025-02-08 18:08:28

由于您似乎很着急,所以下面是我使用的,尽管我正在使用WebSockets库来拨打电话。当我有更多时间看看是否可以接到更快的电话时,我会看一下Binance API,但这应该可以实现您想要的。

您可以通过更改的睡眠时间来更改请求之间的延迟。 (违反政策)要求太多;然后发送1008(违反政策)请求太多

import asyncio
import websockets
import json

msg = {"method": "SUBSCRIBE", "params":
        [
        "btcusdt@depth"
        ],
        "id": 1
        }

async def call_api():
    async with websockets.connect('wss://stream.binance.com:9443/ws/btcusdt@depth') as ws:
        while True:
            await ws.send(json.dumps(msg))
            response = await asyncio.wait_for(ws.recv(), timeout=2)
            response = json.loads(response)
            print(response)
            await asyncio.sleep(0.5)

asyncio.get_event_loop().run_until_complete(call_api())

Since you seem in a rush, below is what I use although I'm using the websockets library to make the calls. I'll take a look at the binance api when I have some more time to see if I can get the calls to be faster but this should hopefully achieve what you want.

You can change the delay between the requests by changing the time of sleep in await asyncio.sleep(0.5) but if you put it any lower than 0.5 seconds it will trigger an error: received 1008 (policy violation) Too many requests; then sent 1008 (policy violation) Too many requests

import asyncio
import websockets
import json

msg = {"method": "SUBSCRIBE", "params":
        [
        "btcusdt@depth"
        ],
        "id": 1
        }

async def call_api():
    async with websockets.connect('wss://stream.binance.com:9443/ws/btcusdt@depth') as ws:
        while True:
            await ws.send(json.dumps(msg))
            response = await asyncio.wait_for(ws.recv(), timeout=2)
            response = json.loads(response)
            print(response)
            await asyncio.sleep(0.5)

asyncio.get_event_loop().run_until_complete(call_api())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文