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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
def send_chat_request():
|
5 |
# Define the URL of the API endpoint
|
6 |
url = 'https://www.blackbox.ai/api/chat'
|
@@ -84,9 +392,40 @@ def send_chat_request_v2(first):
|
|
84 |
|
85 |
second = response.text# Print the response text
|
86 |
return second
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
|
|
|
|
90 |
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
92 |
|
|
|
|
|
|
1 |
import requests
|
2 |
import json
|
3 |
+
import datetime
|
4 |
+
import base64
|
5 |
+
import re
|
6 |
+
from tabulate import tabulate
|
7 |
+
import time
|
8 |
|
9 |
+
|
10 |
+
# GitHub credentials and repository details
|
11 |
+
username = "omarnuwrar"
|
12 |
+
token = "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"
|
13 |
+
repository_name = "btcaiwalletstart"
|
14 |
+
user_json_path = "wallet.json"
|
15 |
+
|
16 |
+
# CoinDesk API endpoint for current BTC price
|
17 |
+
btc_price_api = "https://api.coindesk.com/v1/bpi/currentprice.json"
|
18 |
+
|
19 |
+
# Function to get current BTC price
|
20 |
+
def get_btc_price():
|
21 |
+
response = requests.get(btc_price_api)
|
22 |
+
data = response.json()
|
23 |
+
return float(data["bpi"]["USD"]["rate"].replace(",", ""))
|
24 |
+
|
25 |
+
# Function to update wallet.json file on GitHub
|
26 |
+
def update_wallet(btc_amount, money_amount):
|
27 |
+
# Get current wallet data
|
28 |
+
response = requests.get(f"https://raw.githubusercontent.com/{username}/{repository_name}/main/{user_json_path}")
|
29 |
+
wallet_data = response.json()
|
30 |
+
|
31 |
+
# Update wallet data
|
32 |
+
wallet_data["BTC"] = btc_amount
|
33 |
+
wallet_data["Money"] = money_amount
|
34 |
+
|
35 |
+
# Convert wallet data to JSON string
|
36 |
+
wallet_json = json.dumps(wallet_data)
|
37 |
+
|
38 |
+
# Convert JSON string to Base64-encoded string
|
39 |
+
wallet_json_base64 = base64.b64encode(wallet_json.encode()).decode()
|
40 |
+
|
41 |
+
# Get current file SHA
|
42 |
+
response = requests.get(f"https://api.github.com/repos/{username}/{repository_name}/contents/{user_json_path}", headers={"Authorization": f"Bearer {token}"})
|
43 |
+
file_sha = response.json()["sha"]
|
44 |
+
|
45 |
+
# Update wallet.json file on GitHub
|
46 |
+
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
47 |
+
response = requests.put(f"https://api.github.com/repos/{username}/{repository_name}/contents/{user_json_path}", headers=headers, data=json.dumps({"message": "Update wallet", "content": wallet_json_base64, "sha": file_sha}))
|
48 |
+
if response.status_code == 200:
|
49 |
+
print("Wallet updated successfully!")
|
50 |
+
else:
|
51 |
+
print("Error updating wallet:", response.text)
|
52 |
+
def get_wallet_balance():
|
53 |
+
API_KEY = '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'
|
54 |
+
REPO_OWNER = 'omarnuwrar'
|
55 |
+
REPO_NAME = 'btcaiwalletstart'
|
56 |
+
BRANCH = 'main' # The branch name
|
57 |
+
FILE_PATH = 'wallet.json' # Assuming the file is in the root directory
|
58 |
+
|
59 |
+
# GitHub API URL for the file
|
60 |
+
url = f'https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{FILE_PATH}?ref={BRANCH}'
|
61 |
+
|
62 |
+
# Headers for authentication
|
63 |
+
headers = {
|
64 |
+
'Authorization': f'token {API_KEY}',
|
65 |
+
'Accept': 'application/vnd.github.v3.raw'
|
66 |
+
}
|
67 |
+
|
68 |
+
# Make the request
|
69 |
+
response = requests.get(url, headers=headers)
|
70 |
+
|
71 |
+
content = response.json()
|
72 |
+
money = float(content["Money"])
|
73 |
+
btc = float(content["BTC"])
|
74 |
+
|
75 |
+
return money, btc
|
76 |
+
# Function to execute trade
|
77 |
+
def parse_ai_response(ai_response):
|
78 |
+
try:
|
79 |
+
# Modify regex to handle JSON section surrounded by text
|
80 |
+
json_match = re.search(r'\{.*\}', ai_response, re.DOTALL)
|
81 |
+
|
82 |
+
if json_match:
|
83 |
+
# Parse the JSON string
|
84 |
+
trade_data = json.loads(json_match.group(0))
|
85 |
+
|
86 |
+
# Extract and clean the "BUY" amount (removing the dollar sign)
|
87 |
+
buy_amount_str = trade_data.get("BUY", "0").replace("$", "").strip()
|
88 |
+
buy_amount = float(buy_amount_str) if buy_amount_str else None
|
89 |
+
|
90 |
+
# Extract the "SELL AT" time and handle multiple time formats
|
91 |
+
sell_at_str = trade_data.get("SELL AT", "").strip()
|
92 |
+
sell_at = parse_sell_time(sell_at_str)
|
93 |
+
|
94 |
+
return buy_amount, sell_at
|
95 |
+
else:
|
96 |
+
print("Error: No valid JSON found in the AI response.")
|
97 |
+
return None, None
|
98 |
+
except json.JSONDecodeError as e:
|
99 |
+
print(f"Error decoding JSON: {e}")
|
100 |
+
return None, None
|
101 |
+
except Exception as e:
|
102 |
+
print(f"Unexpected error: {e}")
|
103 |
+
return None, None
|
104 |
+
|
105 |
+
# Function to handle multiple time formats for the sell time
|
106 |
+
def parse_sell_time(sell_at_str):
|
107 |
+
date_formats = [
|
108 |
+
"%Y-%m-%d %H:%M:%S.%f", # With microseconds
|
109 |
+
"%Y-%m-%d %H:%M:%S", # Without microseconds
|
110 |
+
"%Y-%m-%d %H:%M", # Without seconds
|
111 |
+
"%Y-%m-%d %H" # Without minutes
|
112 |
+
]
|
113 |
+
|
114 |
+
for date_format in date_formats:
|
115 |
+
try:
|
116 |
+
return datetime.datetime.strptime(sell_at_str, date_format)
|
117 |
+
except ValueError:
|
118 |
+
continue
|
119 |
+
|
120 |
+
print(f"Error: Could not parse 'SELL AT' date format: {sell_at_str}")
|
121 |
+
return None
|
122 |
+
|
123 |
+
# Updated function to execute trade
|
124 |
+
def execute_trade(ai_response):
|
125 |
+
# Parse AI response to get buy amount and sell time
|
126 |
+
buy_amount, sell_at = parse_ai_response(ai_response)
|
127 |
+
|
128 |
+
if buy_amount is not None and sell_at is not None:
|
129 |
+
print(f"AI suggests buying BTC with ${buy_amount} and selling at {sell_at}")
|
130 |
+
|
131 |
+
# Get current wallet balance
|
132 |
+
money, btc = get_wallet_balance()
|
133 |
+
|
134 |
+
# Check if user has sufficient funds to buy BTC
|
135 |
+
if buy_amount > money:
|
136 |
+
print("Error: Insufficient funds to buy BTC. Available balance: $", money)
|
137 |
+
return
|
138 |
+
|
139 |
+
# Get current BTC price and ensure it's a float
|
140 |
+
btc_price = get_btc_price()
|
141 |
+
|
142 |
+
# Perform the buy operation (calculate the amount of BTC)
|
143 |
+
btc_amount = buy_amount / btc_price
|
144 |
+
update_wallet(btc_amount, money - buy_amount)
|
145 |
+
|
146 |
+
# Wait until sell time
|
147 |
+
print(f"Waiting until {sell_at} to execute sell order...")
|
148 |
+
while datetime.datetime.now() < sell_at:
|
149 |
+
pass
|
150 |
+
|
151 |
+
# Get current wallet balance again before selling
|
152 |
+
money, btc = get_wallet_balance()
|
153 |
+
|
154 |
+
# Check if user has sufficient BTC to sell
|
155 |
+
if btc < btc_amount:
|
156 |
+
print("Error: Insufficient BTC to sell. Available balance: ", btc)
|
157 |
+
return
|
158 |
+
|
159 |
+
# Sell BTC
|
160 |
+
btc_price = get_btc_price()
|
161 |
+
revenue = btc_amount * btc_price
|
162 |
+
update_wallet(0, money + revenue)
|
163 |
+
|
164 |
+
print("Trade executed successfully!")
|
165 |
+
else:
|
166 |
+
print("Error: AI response is invalid or missing required information.")
|
167 |
+
|
168 |
+
|
169 |
+
#####################################################################################################################################################################################################
|
170 |
+
|
171 |
+
############################################## AI SYSTEM ####################################################################
|
172 |
+
|
173 |
+
def clean_response(text):
|
174 |
+
# Remove any string between $@$ and $@$
|
175 |
+
cleaned_text = re.sub(r"\$@\$.*?\$@\$", "", text)
|
176 |
+
return cleaned_text.strip()
|
177 |
+
|
178 |
+
|
179 |
+
def convert_to_unix():
|
180 |
+
current_date = datetime.datetime.now()
|
181 |
+
unix_timestamp = current_date.timestamp()
|
182 |
+
return int(unix_timestamp)
|
183 |
+
|
184 |
+
|
185 |
+
def get_historic_btc_price():
|
186 |
+
start = convert_to_unix()
|
187 |
+
end = "1722124800"
|
188 |
+
url = f"https://query1.finance.yahoo.com/v8/finance/chart/BTC-USD?events=capitalGain%7Cdiv%7Csplit&formatted=true&includeAdjustedClose=true&interval=1d&period1={end}&period2={start}&symbol=BTC-USD&userYfid=true&lang=en-US®ion=US"
|
189 |
+
|
190 |
+
headers = {
|
191 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
|
192 |
+
}
|
193 |
+
|
194 |
+
response = requests.get(url, headers=headers)
|
195 |
+
|
196 |
+
if response.status_code == 200:
|
197 |
+
data = response.json()
|
198 |
+
quote = data["chart"]["result"][0]["indicators"]["quote"][0]
|
199 |
+
adjclose_values = quote["close"]
|
200 |
+
timestamp = data["chart"]["result"][0]["timestamp"]
|
201 |
+
|
202 |
+
open_values = quote["open"]
|
203 |
+
close_values = quote["close"]
|
204 |
+
low_values = quote["low"]
|
205 |
+
high_values = quote["high"]
|
206 |
+
volume_values = quote["volume"]
|
207 |
+
|
208 |
+
# Convert Unix timestamp to date
|
209 |
+
converted_timestamp = [datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') for ts in timestamp]
|
210 |
+
|
211 |
+
# Create a table with the data
|
212 |
+
table_data = []
|
213 |
+
for i in range(len(converted_timestamp)):
|
214 |
+
open_val = f'{open_values[i]:,.2f}' if open_values[i] is not None else 'N/A'
|
215 |
+
high_val = f'{high_values[i]:,.2f}' if high_values[i] is not None else 'N/A'
|
216 |
+
low_val = f'{low_values[i]:,.2f}' if low_values[i] is not None else 'N/A'
|
217 |
+
close_val = f'{close_values[i]:,.2f}' if close_values[i] is not None else 'N/A'
|
218 |
+
adjclose_val = f'{adjclose_values[i]:,.2f}' if adjclose_values[i] is not None else 'N/A'
|
219 |
+
volume_val = f'{volume_values[i]:,.0f}' if volume_values[i] is not None else 'N/A'
|
220 |
+
|
221 |
+
table_data.append([converted_timestamp[i], open_val, high_val, low_val, close_val, adjclose_val, volume_val])
|
222 |
+
|
223 |
+
# Print the table
|
224 |
+
headers = ["Timestamp", "Open", "High", "Low", "Close", "Adj Close", "Volume"]
|
225 |
+
History_Btc = tabulate(table_data, headers=headers, tablefmt="grid")
|
226 |
+
|
227 |
+
|
228 |
+
return History_Btc
|
229 |
+
else :
|
230 |
+
return "No History BTC DATA AVAILABLE"
|
231 |
+
|
232 |
+
def get_current_datetime():
|
233 |
+
current_datetime = datetime.datetime.now()
|
234 |
+
return current_datetime
|
235 |
+
|
236 |
+
|
237 |
+
|
238 |
+
|
239 |
+
|
240 |
+
def ai_chat(computer , news , His):
|
241 |
+
# API endpoint
|
242 |
+
url = "https://www.blackbox.ai/api/chat"
|
243 |
+
|
244 |
+
# Headers
|
245 |
+
headers = {
|
246 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.3",
|
247 |
+
"Content-Type": "application/json"
|
248 |
+
}
|
249 |
+
|
250 |
+
# Payload
|
251 |
+
payload = {
|
252 |
+
"agentMode": {
|
253 |
+
"mode": True,
|
254 |
+
"id": "AIBTCD3UCPYp",
|
255 |
+
"name": "AI BTC"
|
256 |
+
},
|
257 |
+
"id": "7PdZTlN0_GaoIEc2B62SR",
|
258 |
+
"clickedAnswer2": False,
|
259 |
+
"clickedAnswer3": False,
|
260 |
+
"clickedForceWebSearch": False,
|
261 |
+
"codeModelMode": True,
|
262 |
+
"githubToken": None,
|
263 |
+
"isChromeExt": False,
|
264 |
+
"isMicMode": False,
|
265 |
+
"maxTokens": 1024,
|
266 |
+
"messages": [
|
267 |
+
{
|
268 |
+
"id": "7PdZTlN0_GaoIEc2B62SR",
|
269 |
+
"content": f"Here the News :\n\n{news}",
|
270 |
+
"role": "user"
|
271 |
+
},
|
272 |
+
{
|
273 |
+
"id": "7PdZTlN0_GaoIEc2B62SR",
|
274 |
+
"content": f"got you please give me the Historical from Yahoo",
|
275 |
+
"role": "assistant",
|
276 |
+
},
|
277 |
+
{
|
278 |
+
"id": "7PdZTlN0_GaoIEc2B62SR",
|
279 |
+
"content": f"Here is the Historical BTC from yahoo:\n\n{His}",
|
280 |
+
"role": "user"
|
281 |
+
},
|
282 |
+
{
|
283 |
+
"id": "7PdZTlN0_GaoIEc2B62SR",
|
284 |
+
"content": f"thank yuo now other information",
|
285 |
+
"role": "assistant"
|
286 |
+
},
|
287 |
+
{
|
288 |
+
"id": "7PdZTlN0_GaoIEc2B62SR",
|
289 |
+
"content": f"{computer}",
|
290 |
+
"role": "user"
|
291 |
+
},
|
292 |
+
],
|
293 |
+
"mobileClient": False,
|
294 |
+
"previewToken": None,
|
295 |
+
"trendingAgentMode": {},
|
296 |
+
"userId": None,
|
297 |
+
"visitFromDelta": False
|
298 |
+
}
|
299 |
+
|
300 |
+
# Send the POST request to the API
|
301 |
+
response = requests.post(url, headers=headers, json=payload)
|
302 |
+
|
303 |
+
# Check if the request was successful
|
304 |
+
if response.status_code == 200:
|
305 |
+
# Get the raw AI response text
|
306 |
+
ai_response = response.text
|
307 |
+
|
308 |
+
# Clean the response by removing the unwanted string
|
309 |
+
cleaned_response = clean_response(ai_response)
|
310 |
+
|
311 |
+
return cleaned_response
|
312 |
def send_chat_request():
|
313 |
# Define the URL of the API endpoint
|
314 |
url = 'https://www.blackbox.ai/api/chat'
|
|
|
392 |
|
393 |
second = response.text# Print the response text
|
394 |
return second
|
395 |
+
def main_loop():
|
396 |
+
while True:
|
397 |
+
try:
|
398 |
+
# Fetch chat responses and data
|
399 |
+
first = send_chat_request()
|
400 |
+
second = send_chat_request_v2(first)
|
401 |
+
news = f"{first}{second}"
|
402 |
+
Wallet = get_wallet_balance()
|
403 |
+
Timedate = get_current_datetime()
|
404 |
+
His = get_historic_btc_price()
|
405 |
+
Btc = get_btc_price()
|
406 |
+
|
407 |
+
# Define the format
|
408 |
+
formate = '''{
|
409 |
+
"BUY": "1000",
|
410 |
+
"SELL AT": "2023-03-15 14:30:00"
|
411 |
+
}'''
|
412 |
+
|
413 |
+
# Prepare the message
|
414 |
+
computer = f"Computer :\n\nWallet : \n{Wallet}\n\nBTC PRICE NOW : {Btc}\n\nTimedate Now : {Timedate} here Example format : {formate}\n\nWhat did you understand from News and Historical ?\n\nMR,OMAR : Hello Freind please i want low and quicke profit so play on Short term mean IN MINITUNS and trade with full money i have"
|
415 |
+
|
416 |
+
# Get AI response
|
417 |
+
ai_response = ai_chat(computer, His, news)
|
418 |
+
print(ai_response)
|
419 |
|
420 |
+
# Execute the trade based on AI response
|
421 |
+
execute_trade(ai_response)
|
422 |
|
423 |
+
except Exception as e:
|
424 |
+
# If any error occurs, print it and continue
|
425 |
+
print(f"An error occurred: {e}")
|
426 |
+
|
427 |
+
# Pause for a moment before the next loop iteration
|
428 |
+
time.sleep(5) # Adjust the sleep time if necessary
|
429 |
|
430 |
+
if __name__ == "__main__":
|
431 |
+
main_loop()
|