본문 바로가기
트레이딩/암호화폐

암호화폐. API. bybit. 주문 체결 정보 실시간 받기. websocket

by i.got.it 2021. 1. 4.

 

개요 

- 거래소 바이빗의 USD 종목, USDT 종목  주문한 것이 체결될 때  WebSocket 으로 실시간 수신되는 정보. 

- 1회 수신 데이터에 여러 종목의 데이터가 같이 제공될 수 있음. 

 

사전준비 

- 파이썬 웹소켓 기본 코딩 달성하고 인증 코딩 까지 달성한 상태. 

 

 

USD 종목에서의 체결 정보 

 

execution 요청 구문. 

 

websocket.send('{"op": "subscribe", "args": ["execution"]}')

 

상기 요청 한번만 요청하면 이후 내 주문이 체결 된 경우 아래와 같은 정보요소들이 json 형식으로 실시간 수신됨.

 

 

Response Parameters

 

parameter type comments
symbol string Symbol
side string Side
order_id string Order ID
exec_id string Transaction ID
order_link_id string Order link ID
price string Transaction price
order_qty number Order qty
exec_type string Exec Type Enum 4종 : Trade, AdlTrade, Funding, BustTrade 
exec_qty number Transaction qty
exec_fee string Transaction fee
leaves_qty number Number of unfilled contracts from the order's size
is_maker bool Is maker
trade_time string Transaction timestamp

 

 

 

{
    "topic": "execution",
    "data": [
        {
            "symbol": "BTCUSD",
            "side": "Buy",
            "order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
            "exec_id": "xxxxxxxx-xxxx-xxxx-8b66-c3d2fcd352f6",
            "order_link_id": "",
            "price": "8300",
            "order_qty": 1,
            "exec_type": "Trade",
            "exec_qty": 1,
            "exec_fee": "0.00000009",
            "leaves_qty": 0,
            "is_maker": false,
            "trade_time": "2020-01-14T14:07:23.629Z" // trade time
        }
    ]
}


예 : EOSUSD 주문수량 1달러 시장가 매도, 매수 주문한 것이 체결된 시점 수신된 데이터. 

 

 

USDT 종목에서의 체결 정보 

execution 요청 구문. 

websocket.send('{"op": "subscribe", "args": ["execution"]}')

 

한번만 요청하면 이후 내 주문이 체결 된 경우 아래와 같은 정보요소들이 json 형식으로 실시간 수신됨.

 

Response Parameters

parameter type comments
symbol string Symbol
side string Side
order_id string Order ID
exec_id string Transaction ID
order_link_id string Order link ID
price string Transaction price
order_qty number Order qty
exec_type string Exec Type Enum 4종 : Trade, AdlTrade, Funding, BustTrade 
exec_qty number Transaction qty
exec_fee string Transaction fee
trade_time string Transaction timestamp

비교 : USD 종목에 있는 leaves_qty, is_maker 는 USDT 종목에서는 제공안됨. 그외 동일. 

 

예:

{
    "topic": "execution",
    "data": [
        {
            "symbol": "BTCUSDT",
            "side": "Sell",
            "order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
            "exec_id": "xxxxxxxx-xxxx-xxxx-8b66-c3d2fcd352f6",
            "order_link_id": "",
            "price": 11527.5,
            "order_qty": 0.001,
            "exec_type": "Trade",
            "exec_qty": 0.001,
            "exec_fee": 0.00864563,
            "leaves_qty": 0,
            "is_maker": false,
            "trade_time": "2020-08-12T21:16:18.142746Z"
        }
    ]
}

 

 

 

execution  활용 코드 예. 

- 아래코드는 실시간 execution 활용 코드 전체 골격 예  보인다. 

 

- 라인 92 에서 execution 요청하였고, 이후 실시간으로 수신되는 데이터들을 문자열로 확보하는 곳이 라인 94 while 문 내의 라인 95   data_rcv_strjson 에서 확보된다. 

 

- 라인 97 함수 processing_all_ws_received(data_rcv_strjson)  을 호출하여 수신된 데이터가 어떤 형식의 데이터 이냐에 따른  분리 처리 수행한다. 

 

- 라인 34 def processing_all_ws_received(str_json): 함수 내부에서 수신한 웹소켓 수신 데이터 중에 execution 인 경우 실행되는 것은 라인 75  조건문의 함수 processing_execution(data_dic_one)  이다. 

 

- 라인 2 함수 def processing_execution(data_dic_one):  가 execution 으로 수신된 정보 처리기 이며 ,  라인 3의 leaves_qty 는 미체결 잔량인데 전량 체결된 경우에는 이 값이 0 이된다. 본 코드예에서는 주문한 수량이 모두 체결된 경우에만 처리하는 코드예 이기 때문에 leaves_qty 가 0보다 큰 경우에는 처리하지 않고 무처리 리턴(라인 4, 5)하고 있다.

 

- 라인 24~ 28 이 전량체결 에 대응한 주문 처리하는 구간이며 라인 25 조건은 매수 주문한 것이 전량 체결된 것일 때, 라인 26 에서 신규 매도 주문 송신하고 , 라인 27  매도 주문한것이 전량 체결이라면 신규 매수 주문 송신한다. 

 

 

def processing_execution(data_dic_one):
leaves_qty = dic_json.get('leaves_qty')
if leaves_qty > 0 :
return
## 여기 이하 전량체결 이벤트일 때 수행됨.
## 봇에서 주문 낸 지정가 주문(지정가 의도했으나 시장가 체결된것 포함) 이 전량체결 시점임.
_symbol = dic_json.get('symbol')
_order_qty = dic_json.get('order_qty') # 주문수량. = (총체결수량). 인버스 종목은 주문수량 최소단위 1이므로 정수로 처리해도 됨.
_price_str = dic_json.get('price') # 체결가격. 문자열로 기록되어있음.
_side = dic_json.get('side') # Buy 혹은 Sell
is_maker = dic_json.get('is_maker') # true 이면 지정가 주문, false 이면 시장가 주문.
if is_maker == False: # 시장가 주문으로 체결된 이벤트임. 봇에서 지정가 주문의도하였으나, 시장가 주문 체결된것임.
print('!!!Bot try order by limit but filled market order. symbol = ' + _symbol )
print('order all qty were filled symbol = ' + _symbol + '. qty = ' + str(_order_qty) + '. price = ' + _price_str + '. side = ' + _side)
#여기서 체결완료된것 대응처리 수행.
if _side == 'Buy': # 매수 주문한것이 체결완료되었음.
# 신규 매도 주문 송신.
elif _side == 'Sell' : # 매도 주문한것이 체결완료되었음.
# 신규 매수 주문 송신.
# 웹소켓 수신데이터 분지 처리기. 메인.
def processing_all_ws_received(str_json):
#print('received data from bybit: ' + str_json)
if '"ret_msg":"pong"' in str_json: # ping 응답 수신.
processing_response_ping(str_json)
elif '"success":true' in str_json : # subscribe 한것의 응답이 이 단계에서 수신되는 경우임. 아래 topic 오는 구문에는 "success":true 없음.
print('response success for request : ' + str_json)
elif '"topic":"' in str_json: # subscribe 한것들의 이벤트 수신. 모두 공통적으로 리스트형식의 data 키가 있음.
dic_json = json.loads(str_json);
topic = dic_json.get('topic',0)
if topic == 0 :
print('!!! the key topic not found:processing_all_ws_received. full string received= '+ str_json)
return
data_list = dic_json.get('data',0) # topic 키가 있는 문자열에는 공통적으로 리스트 형식의 data 있음.
if data_list == 0 :
print('!!! the key data not found:processing_all_ws_received. full string received= '+ str_json)
return
### 요청한 종목에 대해서만 데이터 수신되는것 2개 . trade, klineV2
if '"topic":"trade.' in str_json: # 시장 체결틱 수신. subscribe trade 에 의하여 수신되는것. topic 에 종목이름이 부착되어있음. 예 . trade.BTCUSD
#print('received trade. string received = ' + str_json )
processing_trade(data_list)
elif '"topic":"klineV2.1.' in str_json: # 캔들 1분봉. topic 에 캔들 타임프레임과 종목이름 부착되어있음. 예 . klineV2.1.BTCUSD
#print('received klineV2.1. string received = ' + str_json )
processing_klineV2_1minute(data_list)
## 모든 인버스 종목에 대하여 데이터 수신되는것. 심볼 지정하여 요청못함. 심볼 정보는 list_data 내의 symbol 키값 확인해야 알 수 있음.
else :
## data 리스트 룹 돌리면서 처리대상 심볼에 대해서만 처리하도록 하며, 각 세부 처리기는 리스트요소 1개 단위로 처리 호출함.
for data_dic_one in data_list:
symbol = data_dic_one.get('symbol') # 심볼 받았다.
if SYMBOL_DIC.get(symbol,0) == 0: # 본 코드에서 처리하기로 지정된 심볼이 아닌 경우. 스킵처리임
continue # 아래 부분 실행되지 않고 스킵하는것임.
if topic == 'order': #if '"topic":"order' in str_json:
#print('received order. string received = ' + str_json )
processing_order(data_dic_one)
elif topic == 'execution': #elif '"topic":"execution' in str_json:
#print('received execution. string received = ' + str_json )
processing_execution(data_dic_one)
elif topic == 'position': #elif '"topic":"position' in str_json:
#print('received position. string received = ' + str_json )
processing_position(data_dic_one)
#end of for data_dic_one in data_list:
else:
print('!!! not supporting type in processing_all_ws_received. full string received = ' + str_json)
async def my_loop_WebSocket_usdt_private_bybit():
중략...
# 필요한 실시간 정보들 요청.
await ws_usdt_private.send('{"op": "subscribe", "args": ["execution"]}');
중략...
while True:
data_rcv_strjson = await ws_usdt_private.recv()
#print('received data from bybit: ' + data_rcv_strjson)
processing_all_ws_received(data_rcv_strjson)

 

 

 

 

연관 

 

 

 

 

 

 

암호화폐. API. bybit. 나의 주문 정보 실시간 받기. websocket

개요 거래소 바이빗의 USD 종목, USDT 종목 내가 주문 송신한것에 의한 WebSocket 으로 실시간 수신되는 주문응답. USD 종목에서의 주문 실시간 정보 order 실시간 정보 요청 구문. websocket.send('{"op": "subsc

igotit.tistory.com

 

 

 

 

암호화폐. API. bybit. 나의 주문 정보 받기. http request

개요 - 바이빗의 USD 종목 , USDT종목의 내 주문정보 HTTP Request 로 받기. USD 종목 의 주문정보 받기 HTTP Request GET /v2/private/order Request Parameters parameter required type comments order_id fals..

igotit.tistory.com

 

 

 


첫 등록 : 2021.01.04

최종 수정 : 2022.05.30

단축 주소 : https://igotit.tistory.com/2745

 


 



비트코인




암호화폐       외환/나스닥/골드         암호화폐/외환/나스닥/골드
     
현물 |선물 인버스 |선물 USDT       전략매니저(카피트레이딩)         프랍 트레이더 온라인 지원가능. MT4,MT5