Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Sinir krizi geçirmek üzereyim! nonce = "3000" #607

Open
quant3458 opened this issue Feb 14, 2025 · 1 comment
Open

Sinir krizi geçirmek üzereyim! nonce = "3000" #607

quant3458 opened this issue Feb 14, 2025 · 1 comment

Comments

@quant3458
Copy link

Merhaba,

Websocket için api anahtar yetkilendirmesi ile bağlantı sağlayamıyorum, api anahtarsız örneğin orderbook verilerini alıyorum ancak yetki işin içine girince olmuyor.

nonce = "3000" sabit tanımladım dün çalışıyordu ancak bugün çalışmıyor, yardımınızı rica ederim

import asyncio
import base64
import hashlib
import hmac
import json
import time
import websockets
import nest_asyncio

nest_asyncio.apply()

class InterfaceWS:
def init(self, publicKey, privateKey, uri="wss://ws-feed-pro.btcturk.com/"):
self.publicKey = publicKey
self.privateKey = privateKey # Private key base64 formatında olmalıdır.
self.uri = uri
self.ws = None

async def connect(self):
    self.ws = await websockets.connect(
        self.uri,
        ping_interval=20,
        ping_timeout=10,
        close_timeout=10,
        max_size=2**23,
        compression=None
    )
    print("WebSocket connection established")

async def authenticate(self, scenario=1, overall_timeout=10):
    if not self.ws:
        await self.connect()

    if scenario == 1:
        nonce = "3000"
        timestamp = str(round(time.time() * 1000))
        base_string = f"{self.publicKey}{nonce}".encode("utf-8")
    elif scenario == 2:
        nonce_int = int(time.time() * 1000)
        nonce = str(nonce_int)
        timestamp = str(nonce_int)
        base_string = f"{self.publicKey}{nonce}".encode("utf-8")
    elif scenario == 3:
        nonce_int = int(time.time() * 1000)
        nonce = str(nonce_int)
        timestamp = str(nonce_int)
        base_string = f"{self.publicKey}{nonce}{timestamp}".encode("utf-8")
    elif scenario == 4:
        nonce_int = int(time.time() * 1000)
        nonce = nonce_int
        timestamp = nonce_int
        base_string = f"{self.publicKey}{nonce}".encode("utf-8")
    else:
        print("Invalid scenario value. Use 1, 2, 3 or 4.")
        return False

    signature = hmac.new(
        base64.b64decode(self.privateKey),
        base_string,
        hashlib.sha256
    ).digest()
    signature = base64.b64encode(signature).decode("utf-8")

    auth_message = [
        114,
        {
            "type": 114,
            "publicKey": self.publicKey,
            "signature": signature,
            "nonce": nonce,
            "timestamp": timestamp
        }
    ]
    print(f"\nAuth message being sent (scenario {scenario}):")
    print(json.dumps(auth_message, indent=2))
    
    await self.ws.send(json.dumps(auth_message))

    start_time = time.time()
    while time.time() - start_time < overall_timeout:
        try:
            response = await asyncio.wait_for(self.ws.recv(), timeout=2)
            data = json.loads(response)
            print("\nReceived auth response message:")
            print(json.dumps(data, indent=2))
            if isinstance(data, list) and data[0] == 991:
                print("Received informational message, waiting for actual login result...")
                continue
            if isinstance(data, list) and data[0] == 114 and data[1].get("ok") is True:
                print(f"\n✅ Authentication successful for scenario {scenario}")
                return True
            if isinstance(data, list) and data[0] == 114:
                print(f"\n❌ Authentication failed for scenario {scenario}, response: {data}")
                return False
        except asyncio.TimeoutError:
            print("Timeout waiting for a message, retrying...")
            continue
        except Exception as e:
            print(f"\n⚠️ Error waiting for authentication response: {e}")
            return False

    print(f"\n❌ Overall timeout reached. Authentication failed for scenario {scenario}.")
    return False

async def main():
publicKey = "aaaaaaaaaa"
privateKey = "bbbbbbbbb"

for scenario in range(1, 5):
    print(f"\n### Testing Scenario {scenario} ###")
    ws_interface = InterfaceWS(publicKey, privateKey)
    success = await ws_interface.authenticate(scenario=scenario)
    if success:
        print(f"\n✅ Scenario {scenario} authenticated successfully!")
    else:
        print(f"\n❌ Scenario {scenario} authentication failed!")
    if ws_interface.ws:
        await ws_interface.ws.close()

asyncio.run(main())


Testing Scenario 1

WebSocket connection established

Auth message being sent (scenario 1):
[
114,
{
"type": 114,
"publicKey": "71588e61-f6dc-4a19-bc99-18e778cc945a",
"signature": "+KjFcqwqucn9Fma6lpf2Nreh8w+m+/0ns8lR8kgSxdk=",
"nonce": "3344000",
"timestamp": "1739513468879"
}
]

Received auth response message:
[
991,
{
"type": 991,
"current": "6.0.0",
"min": "2.3.0"
}
]
Received informational message, waiting for actual login result...

Received auth response message:
[
114,
{
"type": 114,
"id": 0,
"ok": false,
"message": "Unauthorized - Invalid Request"
}
]

❌ Authentication failed for scenario 1, response: [114, {'type': 114, 'id': 0, 'ok': False, 'message': 'Unauthorized - Invalid Request'}]

❌ Scenario 1 authentication failed!

Testing Scenario 2

WebSocket connection established

Auth message being sent (scenario 2):
[
114,
{
"type": 114,
"publicKey": "71588e61-f6dc-4a19-bc99-18e778cc945a",
"signature": "ITBm5Rtaamy5NMjqIWUsoFg7BqQ7RQSG/wctVKbsi1Y=",
"nonce": "1739513469520",
"timestamp": "1739513469520"
}
]

Received auth response message:
[
991,
{
"type": 991,
"current": "6.0.0",
"min": "2.3.0"
}
]
Received informational message, waiting for actual login result...

Received auth response message:
[
114,
{
"type": 114,
"id": 0,
"ok": false,
"message": "Unauthorized - Invalid Request"
}
]

❌ Authentication failed for scenario 2, response: [114, {'type': 114, 'id': 0, 'ok': False, 'message': 'Unauthorized - Invalid Request'}]

❌ Scenario 2 authentication failed!

Testing Scenario 3

WebSocket connection established

Auth message being sent (scenario 3):
[
114,
{
"type": 114,
"publicKey": "71588e61-f6dc-4a19-bc99-18e778cc945a",
"signature": "r5YpotLJ20vs7zFDfuTMc1yFwtvSaxMex5a3cfUr5LE=",
"nonce": "1739513470190",
"timestamp": "1739513470190"
}
]

Received auth response message:
[
991,
{
"type": 991,
"current": "6.0.0",
"min": "2.3.0"
}
]
Received informational message, waiting for actual login result...

Received auth response message:
[
114,
{
"type": 114,
"id": 0,
"ok": false,
"message": "Unauthorized - Invalid Request"
}
]

❌ Authentication failed for scenario 3, response: [114, {'type': 114, 'id': 0, 'ok': False, 'message': 'Unauthorized - Invalid Request'}]

❌ Scenario 3 authentication failed!

Testing Scenario 4

WebSocket connection established

Auth message being sent (scenario 4):
[
114,
{
"type": 114,
"publicKey": "71588e61-f6dc-4a19-bc99-18e778cc945a",
"signature": "gtnFPkrHJV3qA881IV8VPeAjXYUWhswgg7pypHi3cwk=",
"nonce": 1739513470905,
"timestamp": 1739513470905
}
]

Received auth response message:
[
991,
{
"type": 991,
"current": "6.0.0",
"min": "2.3.0"
}
]
Received informational message, waiting for actual login result...

Received auth response message:
[
114,
{
"type": 114,
"id": 0,
"ok": false,
"message": "Unauthorized - Invalid Request"
}
]

❌ Authentication failed for scenario 4, response: [114, {'type': 114, 'id': 0, 'ok': False, 'message': 'Unauthorized - Invalid Request'}]

❌ Scenario 4 authentication failed!

@akrepfatih
Copy link

uri="wss://ws-feed-pro.btcturk.com/

wss://ws.btcturk.com/ws

Acaba ??? Api anahtarı aldığına göre yetkili yere girmeye çalışsan...

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants