|
import requests |
|
import json |
|
import datetime |
|
import base64 |
|
import re |
|
from tabulate import tabulate |
|
import time |
|
|
|
|
|
|
|
|
|
username = "omarnuwrar" |
|
token = "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" |
|
repository_name = "btcaiwalletstart" |
|
user_json_path = "wallet.json" |
|
|
|
|
|
btc_price_api = "https://api.coindesk.com/v1/bpi/currentprice.json" |
|
|
|
|
|
def get_btc_price(): |
|
response = requests.get(btc_price_api) |
|
data = response.json() |
|
return float(data["bpi"]["USD"]["rate"].replace(",", "")) |
|
|
|
|
|
def update_wallet(btc_amount, money_amount): |
|
|
|
response = requests.get(f"https://raw.githubusercontent.com/{username}/{repository_name}/main/{user_json_path}") |
|
wallet_data = response.json() |
|
|
|
|
|
wallet_data["BTC"] = btc_amount |
|
wallet_data["Money"] = money_amount |
|
|
|
|
|
wallet_json = json.dumps(wallet_data) |
|
|
|
|
|
wallet_json_base64 = base64.b64encode(wallet_json.encode()).decode() |
|
|
|
|
|
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"] |
|
|
|
|
|
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' |
|
FILE_PATH = 'wallet.json' |
|
|
|
|
|
url = f'https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{FILE_PATH}?ref={BRANCH}' |
|
|
|
|
|
headers = { |
|
'Authorization': f'token {API_KEY}', |
|
'Accept': 'application/vnd.github.v3.raw' |
|
} |
|
|
|
|
|
response = requests.get(url, headers=headers) |
|
|
|
content = response.json() |
|
money = float(content["Money"]) |
|
btc = float(content["BTC"]) |
|
|
|
return money, btc |
|
|
|
def parse_ai_response(ai_response): |
|
try: |
|
|
|
json_match = re.search(r'\{.*\}', ai_response, re.DOTALL) |
|
|
|
if json_match: |
|
|
|
trade_data = json.loads(json_match.group(0)) |
|
|
|
|
|
buy_amount_str = trade_data.get("BUY", "0").replace("$", "").strip() |
|
buy_amount = float(buy_amount_str) if buy_amount_str else None |
|
|
|
|
|
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 |
|
|
|
|
|
def parse_sell_time(sell_at_str): |
|
date_formats = [ |
|
"%Y-%m-%d %H:%M:%S.%f", |
|
"%Y-%m-%d %H:%M:%S", |
|
"%Y-%m-%d %H:%M", |
|
"%Y-%m-%d %H" |
|
] |
|
|
|
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 |
|
|
|
|
|
def execute_trade(ai_response): |
|
|
|
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}") |
|
|
|
|
|
money, btc = get_wallet_balance() |
|
|
|
|
|
if buy_amount > money: |
|
print("Error: Insufficient funds to buy BTC. Available balance: $", money) |
|
return |
|
|
|
|
|
btc_price = get_btc_price() |
|
|
|
|
|
btc_amount = buy_amount / btc_price |
|
update_wallet(btc_amount, money - buy_amount) |
|
|
|
|
|
print(f"Waiting until {sell_at} to execute sell order...") |
|
while datetime.datetime.now() < sell_at: |
|
pass |
|
|
|
|
|
money, btc = get_wallet_balance() |
|
|
|
|
|
if btc < btc_amount: |
|
print("Error: Insufficient BTC to sell. Available balance: ", btc) |
|
return |
|
|
|
|
|
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.") |
|
|
|
|
|
|
|
|
|
|
|
|
|
def clean_response(text): |
|
|
|
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"] |
|
|
|
|
|
converted_timestamp = [datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') for ts in timestamp] |
|
|
|
|
|
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]) |
|
|
|
|
|
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): |
|
|
|
url = "https://www.blackbox.ai/api/chat" |
|
|
|
|
|
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 = { |
|
"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 |
|
} |
|
|
|
|
|
response = requests.post(url, headers=headers, json=payload) |
|
|
|
|
|
if response.status_code == 200: |
|
|
|
ai_response = response.text |
|
|
|
|
|
cleaned_response = clean_response(ai_response) |
|
|
|
return cleaned_response |
|
def send_chat_request(): |
|
|
|
url = 'https://www.blackbox.ai/api/chat' |
|
|
|
|
|
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' |
|
} |
|
|
|
|
|
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 |
|
} |
|
|
|
|
|
response = requests.post(url, headers=headers, data=json.dumps(payload)) |
|
|
|
first = response.text |
|
return first |
|
|
|
|
|
def send_chat_request_v2(first): |
|
|
|
url = 'https://www.blackbox.ai/api/chat' |
|
|
|
|
|
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' |
|
} |
|
|
|
|
|
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 |
|
} |
|
|
|
|
|
response = requests.post(url, headers=headers, data=json.dumps(payload)) |
|
|
|
second = response.text |
|
return second |
|
def main_loop(): |
|
while True: |
|
try: |
|
|
|
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() |
|
|
|
|
|
formate = '''{ |
|
"BUY": "1000", |
|
"SELL AT": "2023-03-15 14:30:00" |
|
}''' |
|
|
|
|
|
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" |
|
|
|
|
|
ai_response = ai_chat(computer, His, news) |
|
print(ai_response) |
|
|
|
|
|
execute_trade(ai_response) |
|
|
|
except Exception as e: |
|
|
|
print(f"An error occurred: {e}") |
|
|
|
|
|
time.sleep(5) |
|
|
|
if __name__ == "__main__": |
|
main_loop() |