-- Dynamic Recovery (calculated drawdown)
-- After a loss, size the next bet so that a single win recovers the whole session
-- drawdown plus one base bet of profit:  bet = (drawdown + basebet) / (payout - 1).
-- Bets grow slower than a doubling martingale at high payouts, and the size is
-- capped as a fraction of balance so a bad run degrades instead of going bust.

chance  = params.chance or 33
bethigh = false

basebet = params.basebet or balance / 20000
nextbet = basebet

local maxBetPct = params.maxbetpct or 0.10   -- never bet more than 10% of balance
local payout    = (100 - houseedge) / chance

local peakProfit = profit

function dobet()
  if profit > peakProfit then
    peakProfit = profit
  end

  local drawdown = peakProfit - profit

  if drawdown <= 0 then
    nextbet = basebet
    return
  end

  local target = (drawdown + basebet) / (payout - 1)
  local cap = balance * maxBetPct
  if target > cap then
    target = cap
  end
  if target < basebet then
    target = basebet
  end
  nextbet = target
end
