기본 실행법 (JavaScript)

Node.js 의 경우 아래의 방식으로 WebSocket 연결이 가능합니다

주의사항

  • 웹소켓 주소: wss://real.okex.com:8443/ws/v3?brokerId=89
const pako = require('pako');
const WebSocket = require('ws');
const crypto = require('crypto');

const signRequest = (key, secret, passPhrase, method, path, options) => {
    const timestamp = Date.now() / 1000;
    const what = timestamp + method.toUpperCase() + path + (options.body || '');
    const hmac = crypto.createHmac('sha256', secret);
    const signature = hmac.update(what).digest('base64');
    return {
        key,
        passPhrase,
        signature,
        timestamp,
    };
};

const getSignature = (
    key,
    secret,
    passPhrase,
    method,
    relativeURI,
    opts = {}
) => {
    const sig = signRequest(key, secret, passPhrase, method, relativeURI, opts);

    return {
        'OK-ACCESS-KEY': sig.key,
        'OK-ACCESS-PASSPHRASE': sig.passPhrase,
        'OK-ACCESS-SIGN': sig.signature,
        'OK-ACCESS-TIMESTAMP': sig.timestamp,
    };
};

// url
const ws = new WebSocket('wss://real.okex.com:8443/ws/v3?brokerId=89'); // 공식 웹소켓 주소

const { API_KEY, SECRET_KEY, PASS_PHRASE } = process.env;

const pingpongV3 = () => {
    ws.send('ping');
    setTimeout(pingpongV3, 10000);
};

ws.on('open', function open() {
    const sign = getSignature(
        API_KEY,
        SECRET_KEY,
        PASS_PHRASE,
        'GET',
        '/users/self/verify',
        {}
    );
    console.log(sign);

    // 인증 : 내 체결 데이터 수신을 위해 필요 spot/account:*
    ws.send(
        `{"op":"login","args":["${sign['OK-ACCESS-KEY']}","${sign['OK-ACCESS-PASSPHRASE']}","${sign['OK-ACCESS-TIMESTAMP']}","${sign['OK-ACCESS-SIGN']}"]}`
    );

    // 마켓데이터 수신은 인증 필요 없음.
    ws.send(
        '{"op": "subscribe", "args": ["spot/ticker:BTC-KRW","spot/candle60s:BTC-KRW"]}'
    );

    pingpongV3();
});

ws.on('message', function incoming(data) {
    if (data instanceof String) {
        console.log('plain', data);
    } else {
        try {
            const dd = pako.inflateRaw(data, { to: 'string' });
            if (dd == '{"event":"login","success":true}')
                ws.send('{"op": "subscribe", "args": ["spot/account:*"]}'); // 내 체결 데이터 수신
            console.log(dd);
        } catch (err) {
            console.log(err);
        }
    }
});