-- Fixed wager in sats, with a session guard and stop(reason)
-- The starting balance comes from Settings, not from the script: at the top level `balance`
-- IS the session bankroll. This template reads it in satoshis, refuses to start when it is
-- too small, bets a fixed number of sats, and ends the run with a reason you can read in
-- the result strip and the console. 1 sat = 0.00000001 of the selected coin.

chance  = 49.5
bethigh = false

local WAGER_SATS    = params.wagersats or 100       -- fixed bet, in satoshis
local MIN_BAL_SATS  = params.minbalsats or 100000   -- need at least 0.001 of the coin to start
local TARGET_SATS   = params.targetsats or 10000    -- stop once the session is up this much
local MAX_LOSS_SATS = params.maxlosssats or 20000   -- stop once the session is down this much

local startSats = Units.ToSats(balance)
print(string.format("session balance %.0f sats (%.8f %s), wager %d sats", startSats, balance, currency, WAGER_SATS))

if startSats < MIN_BAL_SATS then
  -- Stops before the first roll: zero rolls, nothing wagered, balance and nonce untouched.
  stop(string.format("needs at least %d sats, this session has %.0f", MIN_BAL_SATS, startSats))
end

nextbet = Units.FromSats(WAGER_SATS)
basebet = nextbet

function dobet()
  nextbet = basebet
  local pnl = math.floor(Units.ToSats(profit) + 0.5)   -- whole sats (float noise would miss "== 10000")
  if pnl >= TARGET_SATS then
    stop(string.format("target reached: +%.0f sats after %d bets", pnl, bets))
  elseif pnl <= -MAX_LOSS_SATS then
    stop(string.format("loss limit: %.0f sats after %d bets", pnl, bets))
  end
end
