import os, sys, hmac, hashlib, time, json, urllib.request, urllib.parse

api_key = "b8QjUZkZN85SlHGD4P"
api_secret = "kcLmFW8Z5pqlKP8xqeLwR6b7QbpOmVjFsLVD"
base = "https://api-demo.bybit.com"

ts = str(int(time.time() * 1000))
body = {
    "category": "linear",
    "symbol": "WIFUSDT",
    "side": "Buy",
    "orderType": "Limit",
    "qty": "9868",
    "price": "0.1520",
    "timeInForce": "GTC",
    "positionIdx": 0
}
param_str = json.dumps(body, separators=(", ", ": "))
recv_window = "5000"
sign_payload = ts + api_key + recv_window + param_str
signature = hmac.new(api_secret.encode(), sign_payload.encode(), hashlib.sha256).hexdigest()
headers = {
    "X-BAPI-API-KEY": api_key,
    "X-BAPI-SIGN": signature,
    "X-BAPI-TIMESTAMP": ts,
    "X-BAPI-RECV-WINDOW": recv_window,
    "Content-Type": "application/json"
}
url = base + "/v5/order/create"
req = urllib.request.Request(url, data=param_str.encode(), headers=headers, method="POST")
try:
    r = urllib.request.urlopen(req, timeout=15)
    print(r.read().decode())
except urllib.error.HTTPError as e:
    print(f"HTTP {e.code}: {e.read().decode()}")
