Oleg make weather betting script for Kalshi.com climate markets.

Script uses Robert Lichello AIM money management. (ask your ai to explain)

Here script. Not financial advice, Oleg IQ 72.

import os
import uuid
import time
from kalshi_python import ApiClient, Configuration, KalshiClient
from kalshi_python.models import CreateOrderRequest

# --- CONFIGURATION ---
# 1. Paste your Key ID here
API_KEY_ID = "your-api-key-id" 
# 2. Ensure this file is in the same directory as this script
PRIVATE_KEY_PATH = "private_key.pem"
# 3. Toggle to False when you are ready for real money
IS_DEMO = True 

# Strategy Settings
TARGET_MIN_PROB = 25  # Expanded range: 25% chance (25 cents)
TARGET_MAX_PROB = 75  # Expanded range: 75% chance (75 cents)
SAFE_IDLE_TIME = 3600 # 1 hour between scans

# --- AIM (Robert Lichello) Parameters ---
SAFE_NON_TRADE_ZONE = 0.10  # 10% "Vealie" buffer
CASH_RESERVE_TARGET = 0.50  # Aim for 50% cash / 50% assets initially

# Expanded Climate Market Series
CLIMATE_SERIES = [
    "KXHIGHNY", "KXHIGHCH", "KXHIGHTX", "KXHIGHLA", 
    "KXHIGHMIA", "KXHIGHSEA", "KXHIGHPHL", "KXHIGHBOS"
]

aim_state = {
    "portfolio_control": 0, 
    "last_market_value": 0,
    "active_ticker": None # Track which specific market we are currently trading
}

def get_client():
    """Initializes the modern KalshiClient."""
    host = "https://demo-api.kalshi.co/trade-api/v2" if IS_DEMO else "https://api.elections.kalshi.com/trade-api/v2"
    
    if not os.path.exists(PRIVATE_KEY_PATH):
        raise FileNotFoundError(f"CRITICAL: {PRIVATE_KEY_PATH} not found in the current directory.")

    with open(PRIVATE_KEY_PATH, 'r') as f:
        private_key = f.read()

    config = Configuration(host=host)
    config.api_key_id = API_KEY_ID
    config.private_key_pem = private_key
    
    return KalshiClient(config)

def get_portfolio_data(client):
    """Fetches total balance and current climate positions value."""
    balance_resp = client.get_balance()
    balance = balance_resp.balance
    
    positions_resp = client.get_portfolio_positions()
    positions = positions_resp.positions
    
    # Filter for climate series and calculate value
    climate_positions = [pos for pos in positions if "KXHIGH" in pos.ticker and pos.count > 0]
    climate_value = sum(pos.market_value for pos in climate_positions)
    
    # Identify the current active ticker if we have one
    current_ticker = climate_positions[0].ticker if climate_positions else None
    
    return balance, climate_value, current_ticker

def place_order(client, ticker, action, side, count, price):
    """Places a limit order using the unified client."""
    if count <= 0: return None
    order_params = CreateOrderRequest(
        ticker=ticker,
        action=action,
        side=side,
        count=count,
        type="limit",
        price=price,
        client_order_id=str(uuid.uuid4())
    )
    try:
        resp = client.create_order(order_params)
        print(f"ORDER SUCCESS: {action.upper()} {count} contracts on {ticker} at {price}c")
        return resp
    except Exception as e:
        print(f"Order failed for {ticker}: {e}")
        return None

def run_aim_strategy():
    client = get_client()
    balance, market_value, active_ticker = get_portfolio_data(client)
    total_equity = balance + market_value

    # Update state with current active ticker from the exchange
    aim_state["active_ticker"] = active_ticker

    # 1. INITIALIZATION / NEW TRADE SELECTION
    # Only look for a new trade if we have NO active positions
    if market_value == 0:
        print(f"Searching across climate series for a single {TARGET_MIN_PROB}-{TARGET_MAX_PROB}% entry...")
        aim_state["portfolio_control"] = 0 # Reset control for the new trade
        
        for series in CLIMATE_SERIES:
            try:
                markets_resp = client.get_markets(status="open", series_ticker=series)
                markets = markets_resp.markets
                
                for m in markets:
                    if TARGET_MIN_PROB <= m.yes_ask <= TARGET_MAX_PROB:
                        # Logic to enter exactly 1 trade
                        investment_goal = total_equity * CASH_RESERVE_TARGET
                        qty = int(investment_goal / m.yes_ask)
                        
                        if qty > 0:
                            print(f"Selected {m.ticker} as active trade.")
                            place_order(client, m.ticker, "buy", "yes", qty, m.yes_ask)
                            
                            # Wait a moment for the order to process then set control
                            time.sleep(2)
                            _, new_market_value, new_ticker = get_portfolio_data(client)
                            aim_state["portfolio_control"] = new_market_value
                            aim_state["active_ticker"] = new_ticker
                            print(f"AIM Initialized for {new_ticker}. Control: {new_market_value}c")
                            return # EXIT: We have our 1 trade.
            except Exception as e:
                print(f"Could not fetch {series}: {e}")

    # 2. MONITORING & TRADING (The AIM Cycle for the SINGLE active trade)
    elif aim_state["active_ticker"]:
        print(f"Managing active trade: {aim_state['active_ticker']}")
        
        # BUY LOGIC (Buy the dip)
        buy_threshold = aim_state["portfolio_control"] * (1 - SAFE_NON_TRADE_ZONE)
        if market_value < buy_threshold:
            transfer_amount = buy_threshold - market_value
            print(f"AIM BUY SIGNAL on {aim_state['active_ticker']}: Value ({market_value}c) < Threshold ({buy_threshold}c)")
            
            # Fetch specific market data to get current ask
            m_data = client.get_market(aim_state["active_ticker"]).market
            qty = int(transfer_amount / m_data.yes_ask)
            
            if qty > 0 and balance > (qty * m_data.yes_ask):
                place_order(client, m_data.ticker, "buy", "yes", qty, m_data.yes_ask)
                aim_state["portfolio_control"] += (qty * m_data.yes_ask) / 2

        # SELL LOGIC (Capture profit)
        sell_threshold = aim_state["portfolio_control"] * (1 + SAFE_NON_TRADE_ZONE)
        if market_value > sell_threshold:
            profit_to_capture = market_value - sell_threshold
            print(f"AIM SELL SIGNAL on {aim_state['active_ticker']}: Value ({market_value}c) > Threshold ({sell_threshold}c)")
            
            # Fetch current bid to sell into
            m_data = client.get_market(aim_state["active_ticker"]).market
            qty_to_sell = int(profit_to_capture / m_data.yes_bid)
            
            # Ensure we don't sell more than the position size
            positions = client.get_portfolio_positions().positions
            current_pos = next((p for p in positions if p.ticker == aim_state["active_ticker"]), None)
            if current_pos:
                qty_to_sell = min(qty_to_sell, current_pos.count)
                if qty_to_sell > 0:
                    place_order(client, m_data.ticker, "sell", "yes", qty_to_sell, m_data.yes_bid)

    print(f"Status | Ticker: {aim_state['active_ticker']} | Equity: ${total_equity/100:.2f} | Assets: ${market_value/100:.2f} | Control: ${aim_state['portfolio_control']/100:.2f}")

if __name__ == "__main__":
    print(f"Bot Live: Scan {TARGET_MIN_PROB}-{TARGET_MAX_PROB}% / Single Trade Limit / AIM Logic.")
    while True:
        try:
            run_aim_strategy()
        except Exception as e:
            print(f"Loop Error: {e}")
        
        print(f"Waiting 1 hour for next scan...")
        time.sleep(SAFE_IDLE_TIME)

Reply

Avatar

or to participate

Keep Reading