Skip to content

Instantly share code, notes, and snippets.

@m-root
Last active March 25, 2023 04:30
Show Gist options
  • Save m-root/bc10e00ea202f45167a70fad59e3999a to your computer and use it in GitHub Desktop.
Save m-root/bc10e00ea202f45167a70fad59e3999a to your computer and use it in GitHub Desktop.
Basis Perp-Spot Spread is a script that fetches and calculates the spread between the perpetual contract price and the spot price of a cryptocurrency on different exchanges. The script uses the Binance and Bybit APIs to fetch the perpetual and spot contract prices respectively, and then calculates the basis as the difference between the two pric…
// Importing Binance and Bybit Node Packages
const {CoinMClient} = require('binance');
const RestClientV5 = require('bybit-api').RestClientV5;
// Set the API keys for the Binance and Bybit APIs
// Set the API keys for the Binance and Bybit APIs
const apiKeyBinance = 'your-binance-api-key';
const apiSecretBinance = 'your-binance-api-secret';
const apiKeyBybit = 'your-bybit-api-key';
const apiSecretBybit = 'your-bybit-api-secret';
// Create a new instance of Binance and Bybit APIs
const clientBinance = new CoinMClient({
api_key: apiKeyBinance,
api_secret: apiSecretBinance,
}
);
const clientBybit = new RestClientV5({
key: apiKeyBybit,
secret: apiSecretBybit,
});
// Define symbol for Binance Perpetual Contracts and Bybit Spot
const perpBinanceSymbol = 'BTCUSD_PERP';
const spotBybitSymbol = 'BTCUSDT';
// Define the formula for calculating the basis
const calculateBasis = ( prepResponse , spotResponse ) => {
// Basis = Perpetual contract price - Spot price
const perpAsk = parseFloat(prepResponse[0].askPrice);
const perpBid = parseFloat(prepResponse[0].bidPrice);
const spotAsk = parseFloat(spotResponse.result.a[0][0]);
const spotBid = parseFloat(spotResponse.result.b[0][0]);
const perpPrice = (perpBid + perpAsk) / 2;
const spotPrice = (spotBid + spotAsk) / 2;
return perpPrice - spotPrice;
}
// Fetch the spot and futures prices from Binance and Bybit
const fetchSpotFuturesPrices = async () => {
try {
const [prepResponse, spotResponse] = await Promise.all(
[
clientBinance.getSymbolOrderBookTicker({symbol : perpBinanceSymbol }),// Perpertual
clientBybit.getOrderbook({ category: 'linear', symbol: spotBybitSymbol }) // Spot
]
);
console.log(`Basis Perp-Spot Spread: ${ calculateBasis(prepResponse, spotResponse) }`);
} catch (error) {
console.log(error)
}
}
setInterval(fetchSpotFuturesPrices, 2000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment