import asyncio
import websockets
import json
import aiohttp

async def get_auth_token():
    async with aiohttp.ClientSession() as session:
        response = await session.post(
            'https://api.dydx.exchange/v4/auth',
            headers={'Content-Type': 'application/json'},
            data=json.dumps({
                "clientId": "0dc7c0a0-2148-746b-f9ff-9a76a71f54f7",
                "clientSecret": "ngaxLgD1e3P-pGadiqhwbHIVC0177M1Pzf3GIyRe"
            })
        )
        data = await response.json()
        return data['token']

async def get_orderbook_snapshot(auth_token):
    async with aiohttp.ClientSession() as session:
        async with session.get(
            'https://api.dydx.exchange/v4/orderbook/BTC-USD',
            headers={'Authorization': f'Bearer {auth_token}'}
        ) as response:
            data = await response.json()
            return data

async def connect_to_websocket(auth_token):
    async with websockets.connect(
        f"wss://api.dydx.exchange/v4/ws?token={auth_token}"
    ) as websocket:
        await websocket.send(json.dumps({
            "type": "subscribe",
            "channel": "orderbook",
            "id": "BTC-USD"
        }))

        while True:
            response = await websocket.recv()
            data = json.loads(response)
            print(data)

async def main():
    auth_token = await get_auth_token()
    snapshot = await get_orderbook_snapshot(auth_token)
    print("Orderbook Snapshot:")
    print(snapshot)

    await connect_to_websocket(auth_token)


if __name__ == '__main__':
    asyncio.run(main())
