Skip to content

Instantly share code, notes, and snippets.

@korrio
Created July 8, 2024 02:52
Show Gist options
  • Save korrio/f68e1fef951d8f11b3e2a964902e78aa to your computer and use it in GitHub Desktop.
Save korrio/f68e1fef951d8f11b3e2a964902e78aa to your computer and use it in GitHub Desktop.
Arbitrage between CEX and DEX
const ccxt = require('ccxt');
const ethers = require('ethers');
const Web3 = require('web3');
// Configuration
const config = {
bybit: {
apiKey: 'YOUR_BYBIT_API_KEY',
secret: 'YOUR_BYBIT_SECRET',
},
bnb: {
rpcUrl: 'https://bsc-dataseed.binance.org/',
privateKey: 'YOUR_PRIVATE_KEY',
pancakeswapRouterAddress: '0x10ED43C718714eb63d5aA57B78B54704E256024E',
},
tradingPair: 'BNB/USDT',
minProfitPercentage: 1.5, // 1.5%
};
// Initialize exchanges and providers
const bybit = new ccxt.bybit(config.bybit);
const web3 = new Web3(config.bnb.rpcUrl);
const wallet = new ethers.Wallet(config.bnb.privateKey);
const provider = new ethers.providers.JsonRpcProvider(config.bnb.rpcUrl);
const signer = wallet.connect(provider);
// Pancakeswap Router ABI (simplified)
const pancakeswapRouterABI = [
// Add relevant functions from PancakeswapV2Router02 ABI
];
const pancakeswapRouter = new ethers.Contract(
config.bnb.pancakeswapRouterAddress,
pancakeswapRouterABI,
signer
);
async function checkArbitrageOpportunity() {
try {
// Get prices from Bybit
const bybitOrderbook = await bybit.fetchOrderBook(config.tradingPair);
const bybitBestBid = bybitOrderbook.bids[0][0];
const bybitBestAsk = bybitOrderbook.asks[0][0];
// Get prices from Pancakeswap
const pancakeswapPrice = await getPancakeswapPrice();
// Check for arbitrage opportunities
if (pancakeswapPrice > bybitBestAsk * (1 + config.minProfitPercentage / 100)) {
// Arbitrage opportunity: Buy on Bybit, sell on Pancakeswap
await executeBuyOnBybit();
await executeSellOnPancakeswap();
} else if (bybitBestBid > pancakeswapPrice * (1 + config.minProfitPercentage / 100)) {
// Arbitrage opportunity: Buy on Pancakeswap, sell on Bybit
await executeBuyOnPancakeswap();
await executeSellOnBybit();
}
} catch (error) {
console.error('Error in checkArbitrageOpportunity:', error);
}
}
async function getPancakeswapPrice() {
// Implement price fetching from Pancakeswap
}
async function executeBuyOnBybit() {
// Implement buy order on Bybit
}
async function executeSellOnBybit() {
// Implement sell order on Bybit
}
async function executeBuyOnPancakeswap() {
// Implement buy transaction on Pancakeswap
}
async function executeSellOnPancakeswap() {
// Implement sell transaction on Pancakeswap
}
// Main loop
async function main() {
while (true) {
await checkArbitrageOpportunity();
await new Promise(resolve => setTimeout(resolve, 5000)); // Wait for 5 seconds
}
}
main().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment