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

bybit. API. 웹소켓. kineV2. 캔들 실시간 수신, 캔들완성 검출 . 파이썬

by i.got.it 2020. 11. 2.

 

개요 

- bybit api 에서 캔들 실시간 요청 klineV2 

- 캔들완성 시점 검출. 

 

 

klineV2 subscribe구문.

# klineV2.번호 에 가능한값 
# 1 3 5 15 30 60 120 240 360 D W M 
# 번호.종목명.

ws.send('{"op":"subscribe","args":["klineV2.1.BTCUSD"]}')

# 상기와 같이 1회 요청하면 이후 해당 종목의 캔들 데이터 수신됨. 


 

klineV2 수신데이터 형식. 

{
    "topic": "klineV2.1.BTCUSD",                //topic name
    "data": [{
        "start": 1572425640,                    //start time of the candle
        "end": 1572425700,                      //end time of the candle
        "open": 9200,                           //open price
        "close": 9202.5,                        //close price
        "high": 9202.5,                         //max price
        "low": 9196,                            //min price
        "volume": 81790,                        //volume
        "turnover": 8.889247899999999,          //turnover
        "confirm": False,                       //snapshot flag
        "cross_seq": 297503466,                 
        "timestamp": 1572425676958323           //cross time
    }],
    "timestamp_e6": 1572425677047994            //server time
}

confirm 이 True 이면 해당 캔들의 마지막 틱을 의미. 

- 주의사항 : confirm True 인 것이 1개만 수신될것으로 예상되나, 실제 2개이상 수신되는 경우 허다함. 중복데이터 제거처리 요구됨. 

 

 

klineV2 이용한 캔들 완성 시점 검출 코드. 

 

 

 

import asyncio
import websockets
import json
import time
import hmac
def proc_klineV2_usd(str_json):
data_dict = json.loads(str_json);
data_list = data_dict.get('data',0)
if data_list == 0: # not key 'data' in string.
print('proc_klineV2_usd : not found data')
return
num_data_list = len(data_list)
# Detecting the complete the one minute candle.
for data_dict_one in data_list:
data_confirm = data_dict_one.get('confirm',0)
if data_confirm == True: # If confirm is True, the data is the final tick for the interval. Otherwise, it is a snapshot.!!!CAUTION : Duplicated same data received.
TimeOpen_Candle_1M_Now = data_dict_one.get('start')
if TimeOpen_Candle_1M_Now > proc_klineV2_usd.TimeOpen_Candle_1M_Prev: # 중복데이터 제거처리. 오픈시각이 직전보다 큰것만 골라.
print(str(data_dict_one)) # completed the one minute candle.
proc_klineV2_usd.TimeOpen_Candle_1M_Prev = TimeOpen_Candle_1M_Now
proc_klineV2_usd.TimeOpen_Candle_1M_Prev =0 #
def processing_all_usd(str_json):
if '"success":true' in str_json: # subscrive 한것에 대한 응답 수신된것.
print('response : ' + str_json);
elif '"topic":"trade.' in str_json:
proc_trade_usd(json.loads(str_json));
elif '"orderBookL2_25.' in str_json:
#print(str_jsontype)
proc_orderBookL2_25_delta_usd(str_json)
elif '"topic":"klineV2.1.EOSUSD"' in str_json:
#print(str_json)
proc_klineV2_usd(str_json)
else:
print('processing_all_usd. not supporting type : ' + str_json)
def get_args_secret(_api_key, _api_secrete):
expires = str(int(round(time.time())+5000))+"000"
_val = 'GET/realtime' + expires
signature = str(hmac.new(bytes(_api_secrete, "utf-8"), bytes(_val, "utf-8"), digestmod="sha256").hexdigest())
auth = {}
auth["op"] = "auth"
auth["args"] = [_api_key, expires, signature]
args_secret = json.dumps(auth)
return args_secret
####################### for bybit Inverse . BTCUSD, ETHUSD, EOSUSD, XRPUSD
async def my_loop_WebSocket_bybit():
async with websockets.client.Connect(url_ws_inverse_bybit) as websocket:
await websocket.send(get_args_secret(api_key, api_secret)); # secret
while True:
data_rcv_strjson = await websocket.recv()
if 'success' in data_rcv_strjson:
break # exit while
await websocket.send('{"op":"subscribe","args":["klineV2.1.EOSUSD"]}'); # candle 1minute EOSUSD
print('entry while websocket receive for usd')
while True: # main while. read from websocket
data_rcv_strjson = await websocket.recv()
#print(data_rcv_strjson)
processing_all_usd(data_rcv_strjson)
my_loop = asyncio.get_event_loop();
my_loop.run_until_complete(my_loop_WebSocket_bybit());
#my_loop.run_until_complete(asyncio.gather(*[my_loop_WebSocket_bybit(),my_loop_WebSocket_usdt_private_bybit(),my_loop_WebSocket_usdt_public_bybit()]));
my_loop.close();

 

 

실행모습. 

- 1분 단위로 봉완성 시점에만 1회 출력 확인. 

 

 

 

연관

 

 

bybit. API. WebSocket 서버 3개 동시 접속 파이썬 코드.

개요 - bybit 의 USD 종목용 websocket 서버 1개와 , USDT 종목용 websocket 서버 2개에 동시 접속 파이썬 코딩.  작동방식. 1. 파이썬 코드 실행되면 파일 apikey_url_bybit.txt 를 읽어서 접속서버주소와 api k..

igotit.tistory.com

 

 

 

암호화폐 매매 정보 정리.

- 암호화폐 매매 관련 정보 정리 - 암화폐거래소. - 암호화폐 API 등. - 접근성 좋은 거래소 쾌적한 매매 환경이 장점 - 유동성 풍부. 변동성 양호. - 완전한 연속거래시장. 거래 휴일 없음. 암호화폐

igotit.tistory.com

 


첫 등록 : 2020.11.02

최종 수정 : 

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

 


 

 



비트코인




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