hterhhrth / app.py
Dooratre's picture
Update app.py
b987d5f verified
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&region=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()