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

bybit . API V5 . 웹소켓 Trade . 실시간 시세 수신

by i.got.it 2023. 10. 25.

 

 

웹소켓 으로 실시간 시세 수신. 

 

 

웹소켓 구독 해지 공통사항 : https://igotit.tistory.com/4946

 

웹소켓 Trade 요청하기.  

subscribe Topic 

publicTrade.{symbol}

 

 

 

subscribe 구문 예 

- 아래는 종목명  BTCUSDT 실시간 Trade 정보 요청한 것인데, 웹소켓 주소가 현물 서버이면  현물 BTCUSDT , 선물 서버이면  선물 BTCUSDT  정보 수신됨. 웹소켓 주소 상세보기  


{
    "req_id": "test", // optional
    "op": "subscribe",
    "args": [
        "publicTrade.BTCUSDT"
    ]
}

 

 

VC++ 에서 subscribe, unscribe 구현예 


/*
2023.10.25
v5 에서의 subscribe 구문.

{
    "req_id": "test", // optional
    "op": "subscribe",
    "args": [
        "publicTrade.BTCUSDT"
    ]
}

v5 에서의 unsubscribe 구문.
{
    "op": "unsubscribe",
    "args": [
        "publicTrade.ETHUSD"
    ],
    "req_id": "customised_id"
}

*/
int CCyWebSocketBybit_Spot::Subscribe_Execution(CCyD_CyFinSymbol::Symbol* p_symbol, int sub_unsub)
{
    std::string str_symbol = p_symbol->map_FieldValue["name_api"];

    std::string str_data;
    if (sub_unsub == 1) {
        str_data = "{\"op\": \"subscribe\", \"args\": [ \"publicTrade." + str_symbol + "\"]}";

        if (0 < m_CCyWebSocket_Public.send_websocket(str_data)) { // 구독성공. 
            Regi_Symbol(p_symbol, 1);
        }

    }
    else if (sub_unsub == 0) {
        str_data = "{\"op\": \"unsubscribe\", \"args\": [ \"publicTrade." + str_symbol + "\"],\"req_id\":\"customised_id\"}";

        if (m_CCyWebSocket_Public.send_websocket(str_data)) { // 구독해지 성공. 
            Regi_Symbol(p_symbol, 0);
        }

    }
    else {
        return -1;
    }


    //   Display_Status_Ext("w_spot", "Subscribe_Execution : " + str_symbol);

    return 1;
}

 

 

 

웹소켓 Trade . 수신 데이터 예 

 

{
    "topic": "publicTrade.BTCUSDT",
    "type": "snapshot",
    "ts": 1672304486868,
    "data": [
        {
            "T": 1672304486865,
            "s": "BTCUSDT",
            "S": "Buy",
            "v": "0.001",
            "p": "16578.50",
            "L": "PlusTick",
            "i": "20f43950-d8dd-5b31-9112-a178eb6023af",
            "BT": false
        }
    ]
}

 

각 데이터 항목 의미 . 

Parameter Type Comment
     
id string Message id. Unique field for option
topic string Topic name
type string Data type. snapshot
ts number The timestamp (ms) that the system generates the data
data array Object. The element in the array is sort by matching time in ascending order
> T number The timestamp (ms) that the order is filled
> s string Symbol name
> S string Side of taker. Buy,Sell
> v string Trade size
> p string Trade price
L string Direction of price change. Unique field for future
> i string Trade ID
> BT boolean Whether it is a block trade order or not

 

 

VC++ 에서 실시간 수신데이터부 구현예.  

 




/*
2023.10.25 
api v5 로 수정함. 

data 부분이 [{}] 이므로 1회 수신당, 틱데이터 {} 여럿 가능함.  
{
    "topic": "publicTrade.BTCUSDT",
    "type": "snapshot",
    "ts": 1672304486868,
    "data": [
        {
            "T": 1672304486865,
            "s": "BTCUSDT",
            "S": "Buy",
            "v": "0.001",
            "p": "16578.50",
            "L": "PlusTick",
            "i": "20f43950-d8dd-5b31-9112-a178eb6023af",
            "BT": false
        }
    ]
}

*/
int CCyWebSocketBybit_Spot::Proc_TopicTrade()
{

    if (!m_RJDoc_Public.HasMember("data")) return -1;

    const rapidjson::Value& rj_val = m_RJDoc_Public["data"]; //

    int num_trade = rj_val.Size();//{}이 몇개인지 받음. 
    std::string symbol;

    g_CCSection_Symbol_Spot_Bybit.Lock();

    for (rapidjson::SizeType i = 0; i < num_trade; i++)
    {
        symbol = rj_val[i]["s"].GetString(); // 종목 

        if (map_pSymbol_Target.count(symbol) < 1) continue; // 지정 심볼 아니면 무처리 스킵

        CCyD_CyFinSymbol::Execution* p_exec = map_pSymbol_Target[symbol]->m_pExecution;

        p_exec->str_Price = rj_val[i]["p"].GetString(); // 가격. 
        p_exec->str_Qty = rj_val[i]["v"].GetString(); // 수량 
        p_exec->str_Side = rj_val[i]["S"].GetString(); // 사이드. Buy/Sell

        p_exec->time_usec_exec = 1000 * rj_val[i]["T"].GetInt64(); // 거래체결된시각. 밀리초 받아 마이크로초로 저장.  
        p_exec->time_usec_tx = 1000 * m_RJDoc_Public["ts"].GetInt64(); // 본정보를 서버에서 생성한 시각. 상기 거래체결시각보다 늦음. 
        p_exec->time_usec_rx = CyUtilTime::get_time_us();// 데이터 수신한 현재시각  

        p_exec->Reliability = 1;

        // Series_Execution 에 누적 저장처리. 상기 1샘플 데이터들 기록 이후 호출해야함. 
        p_exec->Insert_Series();

        p_exec->Notify_OnEventExecution(map_pSymbol_Target[symbol], map_pSymbol_Target[symbol]->m_pPrecision->dbl_Tick_price); // 필요한 곳에서 활용위한 사전 등록된 콜백들 호출.

        // PostMessage 송신도 지원함. 
        p_exec->Post_Message(map_pSymbol_Target[symbol]->map_FieldValue["CFS_ID"], map_pSymbol_Target[symbol]->m_pPrecision->dbl_Tick_price);

    } // 1회 수신시 여러 틱 루프. 


    g_CCSection_Symbol_Spot_Bybit.Unlock();

    return 1;
}

 

 

 

 

JavaScript 코드 구현예 

- 자바스크립트로 웹브라우저에서 실시간 시세 수신 구현.

 

bybit . 웹소켓 . 자바스크립트 실시간 시세 수신 구현 예

자바스크립트 코드 전체 HTML 삽입 미리보기할 수 없는 소스 위 코드에 있는 내용처럼 2개의 파일 ws_bybit.js , ws_bybit.html 을 동일 폴더에 만들고, 웹브라우저에서 ws_bybit.html 열면 아래 처럼 브라우

igotit.tistory.com

 

 

연관

 

 

웹소켓 구독 해지 공통사항. 

 

bybit . API V5 . 웹소켓 . subscribe, unsubscribe

암호화폐 거래 정보 실시간 수신 바이비트 거래소의 웹소켓 기반 실시간 정보(호가, 시세 , 캔들 ,... 등 ) 수신 받기 위해서 내 프로그램에서 정보 종류와 종목 지정하여 요청(subscribe ) 한다. 이후

igotit.tistory.com

 

 

 

상위정리

 

 

bybit api v5 . 활용방법 정리

bybit API v5 . 서버 주소 bybit. API V5. 서버 주소 정리. 암호화폐 거래소 bybit 의 API V5 서버 주소 bybit 전종목 Rest 서버 - Rest 서버는 전 종목 동일 주소. 실거래 서버 시험용 서버 Rest 서버 주소 https://api.

igotit.tistory.com


첫 등록 : 2023.10.25

최종 수정 : 

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

 


 

댓글



 

비트코인




암호화폐       외환/나스닥/골드       암호화폐/외환/나스닥/골드 암호화폐/외환/나스닥/골드   암호화폐/외환/나스닥/골드
     
현물 |선물 인버스 |선물 USDT       전략매니저(카피트레이딩)     롤오버 이자 없는 스왑프리계좌
( 스왑프리 암호화폐도 거래 가능 )    
MT4, MT5 , cTrader 모두 지원     FTMO 계좌 매매운용. MT4,MT5