Last active
May 4, 2024 14:34
-
-
Save MtkN1/4b511c8328bf19ec378b3b7f3591a586 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from typing import Any, Dict | |
import motor.motor_asyncio | |
import pybotters | |
class BybitMongoDB: | |
def __init__(self): | |
client = motor.motor_asyncio.AsyncIOMotorClient() | |
db = client['bybit'] | |
self.collection = db['linear'] | |
self.queue = asyncio.Queue() | |
asyncio.create_task(self.consumer()) | |
def onmessage(self, msg: Dict[str, Any], ws): | |
if 'topic' in msg: | |
topic: str = msg['topic'] | |
if topic.startswith('publicTrade'): | |
self.queue.put_nowait(msg['data']) | |
async def consumer(self): | |
while True: | |
data = await self.queue.get() | |
await self.collection.insert_many(data) | |
async def main(): | |
async with pybotters.Client() as client: | |
db = BybitMongoDB() | |
ws = await client.ws_connect( | |
'wss://stream.bybit.com/v5/public/linear', | |
send_json={'op': 'subscribe', 'args': ['publicTrade.BTCUSDT']}, | |
hdlr_json=db.onmessage, | |
) | |
await ws.wait() | |
try: | |
asyncio.run(main()) | |
except KeyboardInterrupt: | |
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pip install pybotters motor |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pymongo | |
client = pymongo.MongoClient() | |
db = client['bybit'] | |
collection = db['linear'] | |
# 2021-05-30T05:59:18.000Z 以降のドキュメントを5件取得する | |
for doc in collection.find({'timestamp': {'$gte': '2021-05-30T05:59:18.000Z'}}, projection={'_id': False}).limit(5): | |
print(doc) | |
print('-' * 80) | |
# 最新のレコードを降順で1件取得する | |
doc = collection.find_one(sort=[('_id', pymongo.DESCENDING)], projection={'_id': False}) | |
print(doc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment