import { z } from "npm:zod";
const paramsSchema = z.object({
slug: z.coerce.string(),
estimatedProb: z.coerce.number().min(0).max(1),
bankroll: z.coerce.number().min(0),
deferenceFactor: z.coerce.number().min(0).max(1).optional().default(0.5),
});
function calculateNaiveKellyBet({
marketProb,
estimatedProb,
deferenceFactor,
bankroll,
}: { marketProb: number; estimatedProb: number; deferenceFactor: number; bankroll: number }): {
amount: number;
outcome: "YES" | "NO";
} {
const outcome = estimatedProb > marketProb ? "YES" : "NO";
const marketWinProb = outcome === "YES" ? marketProb : 1 - marketProb;
const fraction = deferenceFactor
* (Math.abs(estimatedProb - marketProb) / (1 - marketWinProb));
const clampedFraction = Math.min(Math.max(fraction, 0), 1);
const amount = bankroll * clampedFraction;
return {
amount,
outcome,
};
}
async function getMarket(slug: string) {
const res = await fetch(`https://api.manifold.markets/v0/slug/${slug}`);
if (!res.ok) {
const body = await res.text();
throw new Error(body ?? "Error fetching market");
}
return res.json();
}
export default async function(req: Request): Promise<Response> {
const searchParams = new URL(req.url).searchParams;
const params = paramsSchema.parse(Object.fromEntries(searchParams.entries())) as z.infer<typeof paramsSchema>;
const market = await getMarket(params.slug);
const kelly = calculateNaiveKellyBet({
marketProb: market.probability,
estimatedProb: params.estimatedProb,
deferenceFactor: params.deferenceFactor,
bankroll: params.bankroll,
});
return Response.json(kelly);
}