"""
BTC 15-Min Simple Momentum Bot
Enters on any significant price movement
"""

import os
import json
import time
from datetime import datetime

os.environ['KALSHI_API_KEY_ID'] = '81fe00fc-27b2-48ca-85f8-9c37ec1dc82f'
os.environ['KALSHI_PRIVATE_KEY_PATH'] = './kalshi_private_key'

from pykalshi import KalshiClient

PAPER_BALANCE = 1500
TARGET = 0.15
STOP = 0.10
POSITION = 0.25

print("🚀 BTC 15m Simple Bot")
print(f"   ${PAPER_BALANCE} | Target: +{TARGET*100:.0f}% | Stop: -{STOP*100:.0f}%")
print()

client = KalshiClient()
balance = PAPER_BALANCE
positions = []
trades = []
prices = {}

for cycle in range(40):
    # Get markets
    markets = client.get_markets(series_ticker='KXBTC15M')
    active = [m for m in markets if m.volume > 0]
    
    # Show status
    open_pos = len([p for p in positions if p['status'] == 'open'])
    print(f"[{cycle+1}] Active: {len(active)} | Open: {open_pos} | Balance: ${balance:.0f}")
    
    # Check exits
    market_dict = {m.ticker: m for m in active}
    
    for p in positions:
        if p['status'] != 'open':
            continue
        if p['ticker'] not in market_dict:
            continue
        
        m = market_dict[p['ticker']]
        yes_mid = (m.yes_bid + m.yes_ask) / 200 if m.yes_bid or m.yes_ask else 0
        
        if p['side'] == 'YES':
            pnl_pct = (yes_mid - p['entry']) / p['entry'] if p['entry'] > 0 else 0
        else:
            pnl_pct = (p['entry'] - yes_mid) / p['entry'] if p['entry'] > 0 else 0
        
        if pnl_pct >= TARGET:
            pnl = pnl_pct * p['contracts']
            balance += p['contracts'] + pnl
            p['status'] = 'closed'
            p['pnl'] = pnl
            trades.append(p)
            print(f"  ✅ WIN +${pnl:.0f}")
        elif pnl_pct <= -STOP:
            pnl = pnl_pct * p['contracts']
            balance += p['contracts'] + pnl
            p['status'] = 'closed'
            p['pnl'] = pnl
            trades.append(p)
            print(f"  ❌ LOSS ${pnl:.0f}")
    
    # Check entries - simple momentum
    for m in active:
        if any(p['status'] == 'open' and p['ticker'] == m.ticker for p in positions):
            continue
        
        yes_mid = (m.yes_bid + m.yes_ask) / 200 if m.yes_bid or m.yes_ask else 0
        if yes_mid == 0:
            continue
        
        # Track price
        if m.ticker not in prices:
            prices[m.ticker] = []
        prices[m.ticker].append(yes_mid)
        
        if len(prices[m.ticker]) < 2:
            continue
        
        first = prices[m.ticker][0]
        change = yes_mid - first
        
        # Enter on 3%+ move
        if abs(change) >= 0.03:
            side = 'YES' if change > 0 else 'NO'
            contracts = int(balance * POSITION)
            
            if contracts >= 1:
                pos = {
                    'ticker': m.ticker,
                    'side': side,
                    'entry': yes_mid,
                    'contracts': contracts,
                    'status': 'open'
                }
                positions.append(pos)
                balance -= contracts
                print(f"  📝 ENTER {side} @ {yes_mid*100:.0f}c | ${contracts}")
    
    time.sleep(2)

# Final
print("\n" + "="*50)
print(f"FINAL: ${balance:.2f}")

closed = [t for t in trades if t['status'] == 'closed']
if closed:
    wins = len([t for t in closed if t.get('pnl', 0) > 0])
    print(f"Trades: {len(closed)} | Wins: {wins} | Win Rate: {wins/len(closed)*100:.0f}%")

with open('btc15m_simple_results.json', 'w') as f:
    json.dump({'balance': balance, 'trades': trades}, f, indent=2, default=str)
print("💾 Saved")
