# Optimization Problems

Optimization problems involve finding the best set of parameters or conditions that maximize or minimize a particular objective function, subject to a set of constraints.

***

## The Main Underlying Goal

Consider an executed user order `s`, where `S` represents its executed `sell` amount and `B` is its executed `buy` amount. Then:

$$
f\_{\texttt{surplus}}(s) = \texttt{order surplus} = B - \frac{S}{\pi(s)}
$$

where

$$
\pi(s) = \texttt{order's limit price} = \frac{\texttt{sell amount}}{\texttt{buy amount}}
$$

The order can be executed only if:

$$
\pi(s) \geq \frac{S}{B}
$$

Moreover, if the order is executed, we must have:

$$
S \leq \texttt{sell amount}
$$

In the case of a fill-or-kill order, the inequality must be satisfied with equality:

$$
S = \texttt{sell amount}
$$

Given the above definitions, the goal when matching a user order against liquidity sources is to **maximize the surplus of the user order**:

$$
\Omega\_{surplus} = \max \left(f\_{\texttt{surplus}}(s)\right)
$$

***

## The Utility Function (Ω)

As seen above, the utility (or objective) function encodes what is desired to maximize under given constraints.

Another example is that in the context of optimal arbitrage, the utility function could encode the goal of finding the best net trade that is entirely nonnegative.

Yet another example is swapping token `PHI` for token `MU`, aiming to maximize the output of token `MU` given a fixed input of token `PHI` (with arbitrage opportunities captured as part of the swap).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.urani.trade/urani-protocol/technical-considerations/optimization.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
