import websocket
import json
import time

# WebSocket
DTC_SERVER = "ws://127.0.0.1:11099"
ws = websocket.create_connection(DTC_SERVER)

# Logon 
logon_request = {
    "Type": 1,  
    "ProtocolVersion": 8,
    "Username": "<your_username>",
    "Password": "<your_password>",
    "HeartbeatIntervalInSeconds": 30
    "TradeMode": trade_mode, 
    "Integer1": 0x4 | 0x80 | 0x800 | 0x80000 | 0x100000
}
ws.send(json.dumps(logon_request, ensure_ascii=True).encode('latin-1') + b'\x00')

# Response
logon_response = ws.recv()
print("Logon Response:", logon_response)

if '"Result":1' not in logon_response:
    print("Logon Failed!")
    ws.close()
    exit(

# Orders
order_request = {
    "Type": 6,  
    "RequestID": order_id,
    "Symbol": symbol,
    "Exchange": "",
    "OrderType": order_type,   
    "BuySell": buy_sell,  
    "Price1": price,
    "Quantity": quantity,
    "TimeInForce": 1   
}
ws.send(json.dumps(order_request, ensure_ascii=True).encode('latin-1') + b'\x00')

# Modify Order
cancel_replace_order = {
    "Type": 9,  
    "RequestID": order_id,
    "OrigServerOrderID": "<Existing_Order_ID>",
    "Price1": price,  
    "Quantity": quantity
}
ws.send(json.dumps(cancel_replace_order, ensure_ascii=True).encode('latin-1') + b'\x00')

# Heartbeat 
while True:
    heartbeat_message = {"Type": 2}  
    ws.send(json.dumps(heartbeat_message, ensure_ascii=True).encode('latin-1') + b'\x00')
    print("Heartbeat sent.")
    time.sleep(30)
