-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgptArb1.ts
195 lines (151 loc) · 5.96 KB
/
gptArb1.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { BalancerSDK, BalancerSdkConfig, Network } from '@balancer-labs/sdk';
const foundArbitrageOpportunities = new Set<string>();
async function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function findArbitrageOpportunities() {
const config: BalancerSdkConfig = {
network: Network.MAINNET,
rpcUrl: `https://mainnet.infura.io/v3/f5363227615e463db096757712e53f20`,
};
const balancer = new BalancerSDK(config);
while(true){
try {
await balancer.data.pools;
const { pools } = balancer.data;
const allPools = await pools.all();
const filteredPools = allPools.filter(pool => {
if (pool.totalSwapVolume === undefined) {
return false;
}
const swapVolume = parseFloat(pool.totalSwapVolume);
return swapVolume > 10000;
});
const graph = buildTokenGraph(filteredPools);
const arbitrageOpportunities = findArbitrageOpportunitiesBellmanFord(graph, filteredPools);
const uniqueOpportunities = arbitrageOpportunities.filter(opportunity => !foundArbitrageOpportunities.has(opportunity));
if (uniqueOpportunities.length > 0) {
console.log('Arbitrage opportunities found:', uniqueOpportunities);
uniqueOpportunities.forEach(opportunity => foundArbitrageOpportunities.add(opportunity));
} else {
console.log('No new arbitrage opportunities found.');
}
const minDelay = 1 * 60 * 1000; // 1 minute
const maxDelay = 5 * 60 * 1000; // 5 minutes
const randomDelay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;
await sleep(randomDelay);
} catch (error) {
console.error('An error occurred:', error);
}
}}
function buildTokenGraph(pools: any[]): Map<string, Map<string, number>> {
const graph = new Map();
for (const pool of pools) {
const tokens = pool.tokens.map((token: any) => token.address);
for (let i = 0; i < tokens.length; i++) {
const tokenA = tokens[i];
const priceTokenA = parseFloat(pool.tokens[i].token?.latestUSDPrice || '0');
if (!graph.has(tokenA)) {
graph.set(tokenA, new Map());
}
for (let j = i + 1; j < tokens.length; j++) {
const tokenB = tokens[j];
const priceTokenB = parseFloat(pool.tokens[j].token?.latestUSDPrice || '0');
if (!graph.has(tokenB)) {
graph.set(tokenB, new Map());
}
const wrtPriceAB = priceTokenA / priceTokenB;
const wrtPriceBA = priceTokenB / priceTokenA;
const slippageTolerance = 0.005;
const spotPriceAtoB = wrtPriceAB * (1 + parseFloat(pool.swapFee)) * (1 - slippageTolerance);
const spotPriceBtoA = wrtPriceBA * (1 + parseFloat(pool.swapFee)) * (1 - slippageTolerance);
graph.get(tokenA).set(tokenB, Math.log(spotPriceAtoB));
graph.get(tokenB).set(tokenA, Math.log(spotPriceBtoA));
}
}
}
return graph;
}
// ... (previous code remains the same)
function findArbitrageOpportunitiesBellmanFord(graph: Map<string, Map<string, number>>, pools: any[]): string[] {
const vertices = Array.from(graph.keys());
const edges = getEdges(graph);
const distances = initializeDistances(vertices);
const predecessors = initializePredecessors(vertices);
for (let i = 0; i < vertices.length - 1; i++) {
for (const [u, v, weight] of edges) {
if (distances[u] + weight < distances[v]) {
distances[v] = distances[u] + weight;
predecessors[v] = u;
}
}
}
for (const [u, v, weight] of edges) {
if (distances[u] + weight < distances[v]) {
const cycle = getCycle(predecessors, u, pools);
if (cycle.length > 0) {
return cycle;
}
}
}
return [];
}
function getEdges(graph: Map<string, Map<string, number>>): [string, string, number][] {
const edges: [string, string, number][] = [];
for (const [u, connections] of graph.entries()) {
for (const [v, weight] of connections.entries()) {
edges.push([u, v, weight]);
}
}
return edges;
}
// ... (rest of the code remains the same)
function initializeDistances(vertices: string[]): Record<string, number> {
const distances: Record<string, number> = {};
for (const vertex of vertices) {
distances[vertex] = Infinity;
}
distances[vertices[0]] = 0;
return distances;
}
function initializePredecessors(vertices: string[]): Record<string, string | null> {
const predecessors: Record<string, string | null> = {};
for (const vertex of vertices) {
predecessors[vertex] = null;
}
return predecessors;
}
function getCycle(predecessors: Record<string, string | null>, start: string, pools: any[]): string[] {
const cycle: string[] = [];
let current = start;
while (!cycle.includes(current)) {
cycle.push(current);
current = predecessors[current]!;
}
// Add the starting token to the end of the cycle to represent a closed loop
cycle.push(start);
// Check if the tokens in the cycle are in the same pools
const validCycle = isValidCycle(cycle, pools);
if (validCycle) {
return cycle;
} else {
return [];
}
}
function isValidCycle(cycle: string[], pools: any[]): boolean {
for (let i = 0; i < cycle.length - 1; i++) {
const tokenA = cycle[i];
const tokenB = cycle[i + 1];
const matchingPools = pools.filter(pool => {
const tokenAddresses = pool.tokens.map((token: any) => token.address);
return tokenAddresses.includes(tokenA) && tokenAddresses.includes(tokenB);
});
if (matchingPools.length < 2) {
return false;
}
}
return true;
}
// Run the function every 5 minutes
//no need
findArbitrageOpportunities();