Last active
February 27, 2023 17:39
-
-
Save anurag-roy/6df7f3cc6eef6b299a9140aa94c16548 to your computer and use it in GitHub Desktop.
Example to parse a full tick from Kite Websocket.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Tick structure reference: https://kite.trade/docs/connect/v3/websocket/#message-structure | |
const parseBinary = (dataView: DataView) => { | |
const numberOfPackets = dataView.getInt16(0); | |
let index = 4; | |
const ticks: { token: number; firstBid: number; firstAsk: number }[] = []; | |
for (let i = 0; i < numberOfPackets; i++) { | |
const size = dataView.getInt16(index - 2); | |
// Parse whatever you need | |
ticks.push({ | |
token: dataView.getInt32(index), | |
firstBid: dataView.getInt32(index + 68) / 100, | |
firstAsk: dataView.getInt32(index + 128) / 100, | |
}); | |
index = index + 2 + size; | |
} | |
return ticks; | |
}; | |
const API_KEY = 'INSERT_API_KEY_HERE'; | |
const ACCESS_TOKEN = 'INSERT_ACCESS_TOKEN_HERE'; | |
const ws = new WebSocket( | |
`wss://ws.kite.trade?api_key=${API_KEY}&access_token=${ACCESS_TOKEN}` | |
); | |
ws.onopen = (_event) => { | |
console.log('Connected to Zerodha Kite Socket!'); | |
const setModeMessage = { a: 'mode', v: ['full', [61512711]] }; | |
ws.send(JSON.stringify(setModeMessage)); | |
}; | |
ws.onerror = (error) => { | |
console.log('Some error occurred', error); | |
}; | |
ws.onmessage = async (message) => { | |
if (message.data instanceof Blob && message.data.size > 2) { | |
const arrayBuffer = await message.data.arrayBuffer(); | |
const dataView = new DataView(arrayBuffer); | |
const ticks = parseBinary(dataView); | |
console.log(ticks); | |
} | |
}; | |
export {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment