Skip to content

Commit

Permalink
CL-1904: update streaming API (tradingview#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
illetid authored Mar 13, 2024
1 parent 38f9f45 commit 64d350f
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 30 deletions.
3 changes: 0 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@
src="charting_library_cloned_data/charting_library/charting_library.js">
</script>

<!-- The script for CryptoCompare WebSocket -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.4/socket.io.js"></script>

<!-- Custom datafeed module -->
<script type="module" src="src/main.js"></script>
</head>
Expand Down
2 changes: 1 addition & 1 deletion src/datafeed.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const lastBarsCache = new Map();
const configurationData = {
// Represents the resolutions for bars supported by your datafeed
supported_resolutions: ['1D', '1W', '1M'],

// The `exchanges` arguments are used for the `searchSymbols` method if a user selects the exchange
exchanges: [{
value: 'Bitfinex',
Expand Down
7 changes: 6 additions & 1 deletion src/helpers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
// Get a CryptoCompare API key CryptoCompare https://www.cryptocompare.com/coins/guides/how-to-use-our-api/
export const apiKey =
"<api-key>";
// Makes requests to CryptoCompare API
export async function makeApiRequest(path) {
try {
const response = await fetch(`https://min-api.cryptocompare.com/${path}`);
const url = new URL(`https://min-api.cryptocompare.com/${path}`);
url.searchParams.append('api_key',apiKey)
const response = await fetch(url.toString());
return response.json();
} catch (error) {
throw new Error(`CryptoCompare request error: ${error.status}`);
Expand Down
65 changes: 40 additions & 25 deletions src/streaming.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import { parseFullSymbol } from './helpers.js';
import { parseFullSymbol, apiKey } from './helpers.js';

const socket = io('wss://streamer.cryptocompare.com');
const socket = new WebSocket(
'wss://streamer.cryptocompare.com/v2?api_key=' + apiKey
);
const channelToSubscription = new Map();

socket.on('connect', () => {
socket.addEventListener('open', () => {
console.log('[socket] Connected');
});

socket.on('disconnect', (reason) => {
socket.addEventListener('close', (reason) => {
console.log('[socket] Disconnected:', reason);
});

socket.on('error', (error) => {
socket.addEventListener('error', (error) => {
console.log('[socket] Error:', error);
});

socket.on('m', data => {
socket.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
console.log('[socket] Message:', data);
const [
eventTypeStr,
exchange,
fromSymbol,
toSymbol,
,
,
tradeTimeStr,
,
tradePriceStr,
] = data.split('~');
const {
TYPE: eventTypeStr,
M: exchange,
FSYM: fromSymbol,
TSYM: toSymbol,
TS: tradeTimeStr,
P: tradePriceStr,
} = data;

if (parseInt(eventTypeStr) !== 0) {
// Skip all non-trading events
Expand Down Expand Up @@ -65,7 +65,7 @@ socket.on('m', data => {
subscriptionItem.lastDailyBar = bar;

// Send data to every subscriber of that symbol
subscriptionItem.handlers.forEach(handler => handler.callback(bar));
subscriptionItem.handlers.forEach((handler) => handler.callback(bar));
});

function getNextDailyBarTime(barTime) {
Expand All @@ -80,7 +80,7 @@ export function subscribeOnStream(
onRealtimeCallback,
subscriberUID,
onResetCacheNeededCallback,
lastDailyBar,
lastDailyBar
) {
const parsedSymbol = parseFullSymbol(symbolInfo.full_name);
const channelString = `0~${parsedSymbol.exchange}~${parsedSymbol.fromSymbol}~${parsedSymbol.toSymbol}`;
Expand All @@ -101,25 +101,40 @@ export function subscribeOnStream(
handlers: [handler],
};
channelToSubscription.set(channelString, subscriptionItem);
console.log('[subscribeBars]: Subscribe to streaming. Channel:', channelString);
socket.emit('SubAdd', { subs: [channelString] });
console.log(
'[subscribeBars]: Subscribe to streaming. Channel:',
channelString
);
const subRequest = {
action: 'SubAdd',
subs: [channelString],
};
socket.send(JSON.stringify(subRequest));
}

export function unsubscribeFromStream(subscriberUID) {
// Find a subscription with id === subscriberUID
for (const channelString of channelToSubscription.keys()) {
const subscriptionItem = channelToSubscription.get(channelString);
const handlerIndex = subscriptionItem.handlers
.findIndex(handler => handler.id === subscriberUID);
const handlerIndex = subscriptionItem.handlers.findIndex(
(handler) => handler.id === subscriberUID
);

if (handlerIndex !== -1) {
// Remove from handlers
subscriptionItem.handlers.splice(handlerIndex, 1);

if (subscriptionItem.handlers.length === 0) {
// Unsubscribe from the channel if it was the last handler
console.log('[unsubscribeBars]: Unsubscribe from streaming. Channel:', channelString);
socket.emit('SubRemove', { subs: [channelString] });
console.log(
'[unsubscribeBars]: Unsubscribe from streaming. Channel:',
channelString
);
const subRequest = {
action: 'SubRemove',
subs: [channelString],
};
socket.send(JSON.stringify(subRequest));
channelToSubscription.delete(channelString);
break;
}
Expand Down

0 comments on commit 64d350f

Please sign in to comment.