-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrades.py
199 lines (157 loc) · 6.76 KB
/
trades.py
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
196
197
198
199
import json
from time import sleep
from pycoingecko import CoinGeckoAPI
import pandas as pd
import requests
import asyncio
import aiohttp
import sys
import asyncio
# Initialize CoinGecko API
cg = CoinGeckoAPI()
# Global variable to store the coin data
coin_data_global = {}
# Handle the asynchronous fetching of coin data and store the results in a global variable.
# trades.py
# trades.py
async def fetch_data_periodically():
while True:
# Fetch the coin data
coin_data = await get_coin_data(25)
# Print a summary of the fetched data
print(f"Fetched data for {len(coin_data)} coins")
# Print a sample of the data (first few items)
sample_data = {k: coin_data[k] for k in list(coin_data)[:3]} # Adjust the number as needed
print(json.dumps(sample_data, indent=4)) # Print the sample data for debugging
# Store the result in the global variable
global coin_data_global
coin_data_global = coin_data
print("Updated global coin data (summary):", len(coin_data_global), "coins fetched.")
# Wait for a specified interval before fetching again
await asyncio.sleep(300) # Fetch data every 5 minutes
# Function to calculate percent difference between two numbers
def get_change(a, b):
if a == b:
return 0
try:
return (abs(a - b) / b) * 100.0
except ZeroDivisionError:
return float('inf')
# ------------------------------------------------------------------------------------------------------------
'''
# DEX Scanning Code (Currently only showing 0 values)
# Function to calculate profit from given ticker data (cg.get_coin_ticker_by_id)
def get_profit(coin_data):
tickers = coin_data['tickers']
prices = {}
# List of decentralized exchanges
dexs = ['Uniswap', 'Sushiswap', 'Balancer', 'Curve', '1inch', 'Kyber Network', '0xProtocol']
# Sort through all exchanges (with high trust scores) and add to dictionary
for exchange in tickers:
if (
(exchange['target'] == 'USDT' or exchange['target'] == 'USD') and
exchange['trust_score'] == 'green' and
exchange['market']['name'] in dexs # Only include decentralized exchanges
):
prices[str(exchange['market']['name'])] = exchange['last']
# Calculate highest and lowest from dictionary
high = max(prices, key=prices.get, default=0)
low = min(prices, key=prices.get, default=0)
# Calculate profit from potential trade
if (high == 0 or low == 0):
profit = 0
else:
profit = get_change(prices[low], prices[high])
return profit, high, low
'''
# ------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------
# CEX Scanning Code
def get_profit(coin_data):
tickers = coin_data['tickers']
prices = {}
# sort through all exchanges (with high trust scores) and add to dictionary
for exchange in tickers:
if (
(exchange['target'] == 'USDT' or exchange['target'] == 'USD') and
exchange['trust_score'] == 'green' and
exchange['market']['name'] != 'eToroX' # does not allow withdraw of crypto
):
prices[str(exchange['market']['name'])] = exchange['last']
# calculate hgihest and lowest from dictionary
high = max(prices, key=prices.get, default=0)
low = min(prices, key=prices.get, default=0)
# calculate profit from potential trade
if (high == 0 or low == 0):
profit = 0
else:
profit = get_change(prices[low], prices[high])
return profit, high, low
# ------------------------------------------------------------------------------------------------------------
# Function to return an array of top coins from CoinGecko
# Asynchronous function to fetch coin data
async def fetch_coin_data(session, coin_id):
url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/tickers"
async with session.get(url) as response:
return await response.json()
# Asynchronous function to get coin data for multiple coins
async def get_coin_data(numCoins):
coin_tickers = {}
coin_list = cg.get_coins_markets(vs_currency='usd', order='market_cap_desc')
async with aiohttp.ClientSession() as session:
tasks = [fetch_coin_data(session, coin['id']) for coin in coin_list[:numCoins]]
results = await asyncio.gather(*tasks)
for coin, result in zip(coin_list[:numCoins], results):
coin_tickers[coin['id']] = result
return coin_tickers
# Function to get possible trades based on coin data
def get_trades(coin_data):
possible_trades = {}
# Get most profitable trade for each coin
for ticker in coin_data:
profit, highExchange, lowExchange = get_profit(coin_data[ticker])
possible_trades[ticker] = {
'symbol': ticker,
'profit': profit,
'highExchange': highExchange,
'lowExchange': lowExchange
}
# Tether provides lots of false negatives, so remove it
if 'tether' in possible_trades:
del possible_trades['tether']
return possible_trades
# Function to find the highest profit trade from possible trades
def suggest_trade(possible_trades):
max_profit_ticker = ''
max_profit = 0
max_profit_highExchange = ''
max_profit_lowExchange = ''
# Find the most profitable trade
for trade in possible_trades:
if possible_trades[trade]['profit'] > max_profit:
highExchange = possible_trades[trade]['highExchange']
lowExchange = possible_trades[trade]['lowExchange']
max_profit = possible_trades[trade]['profit']
max_profit_ticker = trade
max_profit_highExchange = highExchange
max_profit_lowExchange = lowExchange
print("highest profit trade is with: " + max_profit_ticker + " for a profit of " + str(max_profit))
print("buy " + max_profit_ticker + " on " + max_profit_lowExchange + " and sell on " + max_profit_highExchange)
# Function to create and sort a DataFrame with a key from a dictionary
def create_sorted_dataframe(data, sort_key='% Difference'):
df = pd.DataFrame(data).T
print("DataFrame before sorting:", df.head()) # Print the first few rows
df.fillna(0, inplace=True)
if not df.empty and sort_key in df.columns:
df.sort_values(by=sort_key, ascending=False, inplace=True)
return df
# Test code (uncomment to run)
'''
async def main():
coin_data = await get_coin_data(5)
possible_trades = get_trades(coin_data)
suggest_trade(possible_trades)
sorted_trades_df = create_sorted_dataframe(possible_trades, 'profit')
print(sorted_trades_df)
asyncio.run(main())
'''