File size: 14,882 Bytes
c03acd5 53e0c96 c03acd5 53e0c96 b987d5f 53e0c96 c03acd5 53e0c96 c03acd5 53e0c96 c03acd5 53e0c96 c03acd5 53e0c96 |
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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 |
import requests
import json
import datetime
import base64
import re
from tabulate import tabulate
import time
# GitHub credentials and repository details
username = "omarnuwrar"
token = "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"
repository_name = "btcaiwalletstart"
user_json_path = "wallet.json"
# CoinDesk API endpoint for current BTC price
btc_price_api = "https://api.coindesk.com/v1/bpi/currentprice.json"
# Function to get current BTC price
def get_btc_price():
response = requests.get(btc_price_api)
data = response.json()
return float(data["bpi"]["USD"]["rate"].replace(",", ""))
# Function to update wallet.json file on GitHub
def update_wallet(btc_amount, money_amount):
# Get current wallet data
response = requests.get(f"https://raw.githubusercontent.com/{username}/{repository_name}/main/{user_json_path}")
wallet_data = response.json()
# Update wallet data
wallet_data["BTC"] = btc_amount
wallet_data["Money"] = money_amount
# Convert wallet data to JSON string
wallet_json = json.dumps(wallet_data)
# Convert JSON string to Base64-encoded string
wallet_json_base64 = base64.b64encode(wallet_json.encode()).decode()
# Get current file SHA
response = requests.get(f"https://api.github.com/repos/{username}/{repository_name}/contents/{user_json_path}", headers={"Authorization": f"Bearer {token}"})
file_sha = response.json()["sha"]
# Update wallet.json file on GitHub
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
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}))
if response.status_code == 200:
print("Wallet updated successfully!")
else:
print("Error updating wallet:", response.text)
def get_wallet_balance():
API_KEY = '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'
REPO_OWNER = 'omarnuwrar'
REPO_NAME = 'btcaiwalletstart'
BRANCH = 'main' # The branch name
FILE_PATH = 'wallet.json' # Assuming the file is in the root directory
# GitHub API URL for the file
url = f'https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{FILE_PATH}?ref={BRANCH}'
# Headers for authentication
headers = {
'Authorization': f'token {API_KEY}',
'Accept': 'application/vnd.github.v3.raw'
}
# Make the request
response = requests.get(url, headers=headers)
content = response.json()
money = float(content["Money"])
btc = float(content["BTC"])
return money, btc
# Function to execute trade
def parse_ai_response(ai_response):
try:
# Modify regex to handle JSON section surrounded by text
json_match = re.search(r'\{.*\}', ai_response, re.DOTALL)
if json_match:
# Parse the JSON string
trade_data = json.loads(json_match.group(0))
# Extract and clean the "BUY" amount (removing the dollar sign)
buy_amount_str = trade_data.get("BUY", "0").replace("$", "").strip()
buy_amount = float(buy_amount_str) if buy_amount_str else None
# Extract the "SELL AT" time and handle multiple time formats
sell_at_str = trade_data.get("SELL AT", "").strip()
sell_at = parse_sell_time(sell_at_str)
return buy_amount, sell_at
else:
print("Error: No valid JSON found in the AI response.")
return None, None
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None, None
except Exception as e:
print(f"Unexpected error: {e}")
return None, None
# Function to handle multiple time formats for the sell time
def parse_sell_time(sell_at_str):
date_formats = [
"%Y-%m-%d %H:%M:%S.%f", # With microseconds
"%Y-%m-%d %H:%M:%S", # Without microseconds
"%Y-%m-%d %H:%M", # Without seconds
"%Y-%m-%d %H" # Without minutes
]
for date_format in date_formats:
try:
return datetime.datetime.strptime(sell_at_str, date_format)
except ValueError:
continue
print(f"Error: Could not parse 'SELL AT' date format: {sell_at_str}")
return None
# Updated function to execute trade
def execute_trade(ai_response):
# Parse AI response to get buy amount and sell time
buy_amount, sell_at = parse_ai_response(ai_response)
if buy_amount is not None and sell_at is not None:
print(f"AI suggests buying BTC with ${buy_amount} and selling at {sell_at}")
# Get current wallet balance
money, btc = get_wallet_balance()
# Check if user has sufficient funds to buy BTC
if buy_amount > money:
print("Error: Insufficient funds to buy BTC. Available balance: $", money)
return
# Get current BTC price and ensure it's a float
btc_price = get_btc_price()
# Perform the buy operation (calculate the amount of BTC)
btc_amount = buy_amount / btc_price
update_wallet(btc_amount, money - buy_amount)
# Wait until sell time
print(f"Waiting until {sell_at} to execute sell order...")
while datetime.datetime.now() < sell_at:
pass
# Get current wallet balance again before selling
money, btc = get_wallet_balance()
# Check if user has sufficient BTC to sell
if btc < btc_amount:
print("Error: Insufficient BTC to sell. Available balance: ", btc)
return
# Sell BTC
btc_price = get_btc_price()
revenue = btc_amount * btc_price
update_wallet(0, money + revenue)
print("Trade executed successfully!")
else:
print("Error: AI response is invalid or missing required information.")
#####################################################################################################################################################################################################
############################################## AI SYSTEM ####################################################################
def clean_response(text):
# Remove any string between $@$ and $@$
cleaned_text = re.sub(r"\$@\$.*?\$@\$", "", text)
return cleaned_text.strip()
def convert_to_unix():
current_date = datetime.datetime.now()
unix_timestamp = current_date.timestamp()
return int(unix_timestamp)
def get_historic_btc_price():
start = convert_to_unix()
end = "1722124800"
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"
headers = {
"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"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
quote = data["chart"]["result"][0]["indicators"]["quote"][0]
adjclose_values = quote["close"]
timestamp = data["chart"]["result"][0]["timestamp"]
open_values = quote["open"]
close_values = quote["close"]
low_values = quote["low"]
high_values = quote["high"]
volume_values = quote["volume"]
# Convert Unix timestamp to date
converted_timestamp = [datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') for ts in timestamp]
# Create a table with the data
table_data = []
for i in range(len(converted_timestamp)):
open_val = f'{open_values[i]:,.2f}' if open_values[i] is not None else 'N/A'
high_val = f'{high_values[i]:,.2f}' if high_values[i] is not None else 'N/A'
low_val = f'{low_values[i]:,.2f}' if low_values[i] is not None else 'N/A'
close_val = f'{close_values[i]:,.2f}' if close_values[i] is not None else 'N/A'
adjclose_val = f'{adjclose_values[i]:,.2f}' if adjclose_values[i] is not None else 'N/A'
volume_val = f'{volume_values[i]:,.0f}' if volume_values[i] is not None else 'N/A'
table_data.append([converted_timestamp[i], open_val, high_val, low_val, close_val, adjclose_val, volume_val])
# Print the table
headers = ["Timestamp", "Open", "High", "Low", "Close", "Adj Close", "Volume"]
History_Btc = tabulate(table_data, headers=headers, tablefmt="grid")
return History_Btc
else :
return "No History BTC DATA AVAILABLE"
def get_current_datetime():
current_datetime = datetime.datetime.now()
return current_datetime
def ai_chat(computer , news , His):
# API endpoint
url = "https://www.blackbox.ai/api/chat"
# Headers
headers = {
"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",
"Content-Type": "application/json"
}
# Payload
payload = {
"agentMode": {
"mode": True,
"id": "AIBTCD3UCPYp",
"name": "AI BTC"
},
"id": "7PdZTlN0_GaoIEc2B62SR",
"clickedAnswer2": False,
"clickedAnswer3": False,
"clickedForceWebSearch": False,
"codeModelMode": True,
"githubToken": None,
"isChromeExt": False,
"isMicMode": False,
"maxTokens": 1024,
"messages": [
{
"id": "7PdZTlN0_GaoIEc2B62SR",
"content": f"Here the News :\n\n{news}",
"role": "user"
},
{
"id": "7PdZTlN0_GaoIEc2B62SR",
"content": f"got you please give me the Historical from Yahoo",
"role": "assistant",
},
{
"id": "7PdZTlN0_GaoIEc2B62SR",
"content": f"Here is the Historical BTC from yahoo:\n\n{His}",
"role": "user"
},
{
"id": "7PdZTlN0_GaoIEc2B62SR",
"content": f"thank yuo now other information",
"role": "assistant"
},
{
"id": "7PdZTlN0_GaoIEc2B62SR",
"content": f"{computer}",
"role": "user"
},
],
"mobileClient": False,
"previewToken": None,
"trendingAgentMode": {},
"userId": None,
"visitFromDelta": False
}
# Send the POST request to the API
response = requests.post(url, headers=headers, json=payload)
# Check if the request was successful
if response.status_code == 200:
# Get the raw AI response text
ai_response = response.text
# Clean the response by removing the unwanted string
cleaned_response = clean_response(ai_response)
return cleaned_response
def send_chat_request():
# Define the URL of the API endpoint
url = 'https://www.blackbox.ai/api/chat'
# Headers
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
'Content-Type': 'application/json' # Assuming the API expects JSON format
}
# Payload
payload = {
"agentMode": {},
"clickedAnswer2": False,
"clickedAnswer3": False,
"clickedForceWebSearch": False,
"codeModelMode": True,
"githubToken": None,
"id": "hFnU6fo",
"isChromeExt": False,
"isMicMode": False,
"maxTokens": 1024,
"messages": [
{
"id": "hFnU6fo",
"content": "GIve me FULL NEWS ABOUT BTC YOU CAN GET IT FROM WEB",
"role": "user"
}
],
"mobileClient": False,
"previewToken": None,
"trendingAgentMode": {},
"userId": None,
"userSelectedModel": None,
"visitFromDelta": False
}
# Send the POST request
response = requests.post(url, headers=headers, data=json.dumps(payload))
first = response.text# Print the response text
return first
def send_chat_request_v2(first):
# Define the URL of the API endpoint
url = 'https://www.blackbox.ai/api/chat'
# Headers
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
'Content-Type': 'application/json' # Assuming the API expects JSON format
}
# Payload
payload = {
"agentMode": {},
"id": "hFnU6fo",
"messages": [
{
"id": "hFnU6fo",
"content": "GIve me FULL NEWS ABOUT BTC YOU CAN GET IT FROM WEB",
"role": "user"
},
{
"id": "9RsMsaM",
"createdAt": "2024-09-21T08:11:09.953Z",
"content": first
,
"role": "assistant"
}
],
"mobileClient": False,
"mode": "continue",
"trendingAgentMode": {},
"userId": None
}
# Send the POST request
response = requests.post(url, headers=headers, data=json.dumps(payload))
second = response.text# Print the response text
return second
def main_loop():
while True:
try:
# Fetch chat responses and data
first = send_chat_request()
second = send_chat_request_v2(first)
news = f"{first}{second}"
Wallet = get_wallet_balance()
Timedate = get_current_datetime()
His = get_historic_btc_price()
Btc = get_btc_price()
# Define the format
formate = '''{
"BUY": "1000",
"SELL AT": "2023-03-15 14:30:00"
}'''
# Prepare the message
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"
# Get AI response
ai_response = ai_chat(computer, His, news)
print(ai_response)
# Execute the trade based on AI response
execute_trade(ai_response)
except Exception as e:
# If any error occurs, print it and continue
print(f"An error occurred: {e}")
# Pause for a moment before the next loop iteration
time.sleep(5) # Adjust the sleep time if necessary
if __name__ == "__main__":
main_loop() |