Update bots/httpTest.py

This commit is contained in:
2025-12-13 17:04:46 -05:00
parent 0b510393f4
commit 2aa087ecdd

View File

@@ -2,6 +2,18 @@ import requests
import time
BASE_URL = 'http://localhost:5000'
log_file = "tradeLog.txt"
dayRun = 100
# Create a session object to maintain cookies/session across requests
session = requests.Session()
def log(message):
"""Print to console and write to file"""
print(message)
if log_file:
log_file.write(message + '\n')
log_file.flush()
def find_cheapest_stock(stocks):
@@ -17,94 +29,132 @@ def get_holding_amount(holdings, stock_id):
def wait_for_server():
for i in range(10):
for i in range(30):
try:
requests.get(f'{BASE_URL}/api/game-state', timeout=1)
session.get(f'{BASE_URL}/api/game-state', timeout=1)
return True
except:
print(f"Waiting for server... ({i+1}/10)")
time.sleep(1)
log(f"Waiting for server... ({i+1}/10)")
return False
def main():
global log_file
log_file = open('tradeLog.txt', 'w')
if not wait_for_server():
print("Server not available!")
log("Server not available!")
log_file.close()
return
response = session.post(f'{BASE_URL}/api/start', json={'days': dayRun})
if response.status_code != 200:
log(f"Error starting game: {response.status_code} - {response.text}")
log_file.close()
return
response = requests.post(f'{BASE_URL}/api/start', json={'days': 100})
data = response.json()
print("Game started!")
print(f"Balance: ${data['balance']}")
log("Game started!")
log(f"Balance: ${data['balance']}")
cheapest = find_cheapest_stock(data['stocks'])
print(f"\nCheapest stock: {cheapest['name']} at ${cheapest['price']}")
log(f"\nCheapest stock: {cheapest['name']} at ${cheapest['price']}")
shares_to_buy = data['balance'] // cheapest['price']
if shares_to_buy > 0:
response = requests.post(f'{BASE_URL}/api/buy',
response = session.post(f'{BASE_URL}/api/buy',
json={
'stock_id': cheapest['id'],
'amount': shares_to_buy
})
if response.status_code != 200:
log(f"Error buying stock: {response.status_code} - {response.text}")
log_file.close()
return
data = response.json()
print(f"Bought {shares_to_buy} shares of {cheapest['name']}")
print(f"Balance: ${data['balance']}")
log(f"Bought {shares_to_buy} shares of {cheapest['name']}")
#log(f"Balance: ${data['balance']}")
current_stock_id = cheapest['id']
while data['daysleft'] > 0:
response = requests.post(f'{BASE_URL}/api/next-day')
response = session.post(f'{BASE_URL}/api/next-day')
if response.status_code != 200:
log(f"Error on next day: {response.status_code} - {response.text}")
break
data = response.json()
print(f"\n--- Day {data['day']} ---")
log(f"\n--- Day {data['day']} ---")
new_cheapest = find_cheapest_stock(data['stocks'])
print(f"Cheapest stock now: {new_cheapest['name']} at ${new_cheapest['price']}")
log(f"Cheapest stock now: {new_cheapest['name']} at ${new_cheapest['price']}")
if new_cheapest['id'] != current_stock_id:
print(f"Different stock is cheaper! Switching...")
log(f"Different stock is cheaper! Switching...")
current_holdings = get_holding_amount(data['holdings'], current_stock_id)
if current_holdings > 0:
response = requests.post(f'{BASE_URL}/api/sell',
response = session.post(f'{BASE_URL}/api/sell',
json={
'stock_id': current_stock_id,
'amount': current_holdings
})
if response.status_code != 200:
log(f"Error selling stock: {response.status_code} - {response.text}")
break
data = response.json()
print(f"Sold {current_holdings} shares")
print(f"Balance: ${data['balance']}")
log(f"Sold {current_holdings} shares")
log(f"Balance: ${data['balance']}")
shares_to_buy = data['balance'] // new_cheapest['price']
if shares_to_buy > 0:
response = requests.post(f'{BASE_URL}/api/buy',
response = session.post(f'{BASE_URL}/api/buy',
json={
'stock_id': new_cheapest['id'],
'amount': shares_to_buy
})
if response.status_code != 200:
log(f"Error buying stock: {response.status_code} - {response.text}")
break
data = response.json()
print(f"Bought {shares_to_buy} shares of {new_cheapest['name']}")
print(f"Balance: ${data['balance']}")
log(f"Bought {shares_to_buy} shares of {new_cheapest['name']}")
current_stock_id = new_cheapest['id']
else:
print("Same stock is still cheapest, holding position.")
log("Same stock is still cheapest, holding position.")
print(f"\n=== GAME OVER - SELLING ALL ===")
log(f"\n=== GAME OVER - SELLING ALL ===")
for h in data['holdings']:
if h['amount'] > 0:
response = requests.post(f'{BASE_URL}/api/sell',
response = session.post(f'{BASE_URL}/api/sell',
json={
'stock_id': h['id'],
'amount': h['amount']
})
data = response.json()
print(f"Sold {h['amount']} shares of {h['name']}")
if response.status_code != 200:
log(f"Error selling: {response.status_code} - {response.text}")
continue
print(f"\n=== FINAL RESULTS ===")
print(f"Starting balance: $1000")
print(f"Ending balance: ${data['balance']}")
print(f"Profit: ${data['balance'] - 1000}")
data = response.json()
log(f"Sold {h['amount']} shares of {h['name']}")
log(f"\n=== FINAL RESULTS ===")
log(f"Starting balance: $1000")
log(f"Ending balance: ${data['balance']}")
log(f"Profit: ${data['balance'] - 1000}")
response = session.post(f'{BASE_URL}/api/save-score',
json={
'name': 'AutoTrader',
})
if response.status_code == 200:
log("Score saved successfully!")
else:
log(f"Error saving score: {response.status_code}")
log_file.close()
main()