Files
Stock-Game/bots/httpTest.py
2025-12-12 12:54:49 -05:00

111 lines
3.8 KiB
Python

import requests
import time
BASE_URL = 'http://localhost:5000'
def find_cheapest_stock(stocks):
cheapest = min(stocks, key=lambda s: s['price'])
return cheapest
def get_holding_amount(holdings, stock_id):
for h in holdings:
if h['id'] == stock_id:
return h['amount']
return 0
def wait_for_server():
for i in range(10):
try:
requests.get(f'{BASE_URL}/api/game-state', timeout=1)
return True
except:
print(f"Waiting for server... ({i+1}/10)")
time.sleep(1)
return False
def main():
if not wait_for_server():
print("Server not available!")
return
response = requests.post(f'{BASE_URL}/api/start', json={'days': 100})
data = response.json()
print("Game started!")
print(f"Balance: ${data['balance']}")
cheapest = find_cheapest_stock(data['stocks'])
print(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',
json={
'stock_id': cheapest['id'],
'amount': shares_to_buy
})
data = response.json()
print(f"Bought {shares_to_buy} shares of {cheapest['name']}")
print(f"Balance: ${data['balance']}")
current_stock_id = cheapest['id']
while data['daysleft'] > 0:
response = requests.post(f'{BASE_URL}/api/next-day')
data = response.json()
print(f"\n--- Day {data['day']} ---")
new_cheapest = find_cheapest_stock(data['stocks'])
print(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...")
current_holdings = get_holding_amount(data['holdings'], current_stock_id)
if current_holdings > 0:
response = requests.post(f'{BASE_URL}/api/sell',
json={
'stock_id': current_stock_id,
'amount': current_holdings
})
data = response.json()
print(f"Sold {current_holdings} shares")
print(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',
json={
'stock_id': new_cheapest['id'],
'amount': shares_to_buy
})
data = response.json()
print(f"Bought {shares_to_buy} shares of {new_cheapest['name']}")
print(f"Balance: ${data['balance']}")
current_stock_id = new_cheapest['id']
else:
print("Same stock is still cheapest, holding position.")
print(f"\n=== GAME OVER - SELLING ALL ===")
for h in data['holdings']:
if h['amount'] > 0:
response = requests.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']}")
print(f"\n=== FINAL RESULTS ===")
print(f"Starting balance: $1000")
print(f"Ending balance: ${data['balance']}")
print(f"Profit: ${data['balance'] - 1000}")
main()