\section{Game Theory component:}

\textbf{\underline{Players:}}
\begin{itemize}
    \item Ambulance
    \item Hospital A
    \item Hospital B
\end{itemize}

\noindent
\textbf{\underline{Strategies of players:}}
\begin{itemize}
    \item Hospital i:
    \begin{enumerate}
        \item Close doors at \(\hat{c_i} = 1\)
        \item Close doors at \(\hat{c_i} = 2\)
        \item \dots
        \item Close doors at \(\hat{c_i} = C_i\)
    \end{enumerate}
    \item Ambulance:
    \begin{enumerate}
        \item Choose \(p_1 \in [0,1]\)
    \end{enumerate}
\end{itemize}

\noindent
\textbf{\underline{Cost Functions:}} Waiting times + the distance to each hospital.


\documentclass{article}
\usepackage{amsmath, amssymb, bm}

\newcommand{\ba}{\bm{a}}
\newcommand{\bx}{\bm{x}}
\newcommand{\by}{\bm{y}}
\newcommand{\bb}{\bm{b}}
\newcommand{\fs}{\frac{1}{\sigma_n^2}}

\begin{document}

Derivation of exact marginal likelihood.

\section{Model 1a: linear generative (Gaussian prior)}

$L$ is the dimension of $\ba$; $M$ is the dimension of $\bx$; $\Phi$ is a fixed $M \times L$ matrix.
\begin{eqnarray}
  p(\ba) &=& \mathcal{N}(0, I_L) \\
  p(\bx|\ba) &=& \mathcal{N}(\Phi \ba, \sigma_n^2 I_M)
\end{eqnarray}

\subsection{Complicated derivation}

\emph{See Section~\ref{sec:alt1a} for a simpler derivation!}

Defining $\Sigma = (I_L + \fs \Phi^T\Phi)^{-1}$ (the posterior covariance of $\ba$) and working with
logarithms our joint density is
\begin{eqnarray}
  \log p(\bx, \ba)
    &=& \log p(\ba) + \log p(\bx|\ba) \\
    &=& - \log Z_{\ba}
        - \log Z_{\bx |\ba}
        - \frac{1}{2}\big[\ba^T\ba + \fs(\bx-\Phi\ba)^T(x-\Phi\ba)\big] \\
    &=& - \log Z_{\ba}
        - \log Z_{\bx |\ba}
        - \frac{1}{2}\big[\ba^T \Sigma^{-1} \ba - \frac{2}{\sigma_n^2}\bx^T\Phi\ba + \fs \bx^T \bx \big] \\
    &=& - \log Z_{\ba}
        - \log Z_{\bx |\ba} \nonumber \\
    &&  - \frac{1}{2}\big[(\ba - \fs \Sigma \Phi^T \bx)^T \Sigma^{-1} (\ba - \fs \Sigma \Phi^T \bx) \nonumber \\
    && \qquad             - \frac{1}{\sigma_n^4}\bx^T\Phi\Sigma\Phi^T\bx + \fs \bx^T \bx \big]
\end{eqnarray}
where $Z_{\ba}$ and $Z_{\bx |\ba}$ are the normalising constants for $p(\ba)$ and $p(\bx|\ba)$ respectively:
\begin{eqnarray}
  Z_{\ba} &=& (2 \pi)^{\frac{L}{2}} \\
  Z_{\bx |\ba} &=& (2 \pi)^{\frac{M}{2}} \sigma_n^M
\end{eqnarray}
Now to calculate the marginal likelihood we just need to marginalise over (integrate out) $\ba$
\begin{eqnarray}
  \log p(x)
    &=& - \log Z_{\ba}
        - \log Z_{\bx |\ba}
        + \log Z_{\ba |\bx} \nonumber \\
    && \qquad
        + \frac{1}{2 \sigma_n^2}\big[\fs\bx^T\Phi\Sigma\Phi^T\bx - \bx^T \bx \big]
\end{eqnarray}
where $Z_{\ba |\bx}$ is the normalising constant for the posterior of $\ba$
\begin{eqnarray}
  Z_{\ba |\bx} &=& |2 \pi \Sigma|^\frac{1}{2}
\end{eqnarray}

\subsection{Alternative derivation}
\label{sec:alt1a}

Note that if $\bb = \Phi \ba$ then $\bb \sim \mathcal{N}(0, \Phi \Phi^T)$. Now given $\by \sim \mathcal{N}(0, \sigma_n^2 I_M)$
then $\bx$ and $\bb + \by$ have the same distribution. But $\mathbb{E}[\bb + \by] = 0$ and
$\mathbb{V}[\bb + \by] = \mathbb{V}[\bb] + \mathbb{V}[\by] = \Phi \Phi^T + \sigma_n^2 I_M$. Also note
$\bb + \by$ has a a Gaussian distribution. Hence
\begin{eqnarray}
  p(x) = \mathcal{N}(0, \Phi \Phi^T + \sigma_n^2 I_M)
\end{eqnarray}

\end{document}


\documentclass[12pt]{article}
\usepackage[left=2cm, right=2cm, top=2cm, bottom=2cm]{geometry}
\usepackage{graphicx}
\usepackage{float}
\usepackage{adjustbox}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{commath}
\usepackage{wasysym}
\usepackage{pdfpages}

\title{CTA200 Project}
\author{Sinthushan Sivakumar}
\date{May $14^{th}$, 2021}

\begin{document}

\maketitle

\section{Introduction}
In this project the evolution of the Earth-Moon system was integrated back into the past, from present day configuration, using python 3 in a jupyter notebook.

Ocean tides are caused by the gravitational attraction of the Moon, and to a lesser extent, the Sun. Lunar tides are known to increase both the length of day and the length of the Lunar month; the Lunar torque $-T_{\leftmoon}$ produced by the Moon’s gravity acting on the tidal bulge in the oceans and solid body of Earth reduces the spin angular momentum $S_{\oplus}$ of the rotating Earth, and adds the same amount to the orbital angular momentum $L_{\leftmoon}$ of the Moon, with no change in the sum $L_{EM} = S_{\oplus} + L_{\leftmoon}$. The solar torque $T_{\odot}$ associated with the solar tide increases both the length of day and the length of the year; it also reduces, very slightly, $L_{EM}$, increasing the orbital angular momentum $L_{\oplus}$ of Earth by the same amount:
\begin{align}
    \frac{dL_{\oplus}}{dt} &= T_{\odot}, \\
    \frac{dS_{\oplus}}{dt} &= -T_{\odot} - T_{\leftmoon}, \\
    \frac{dL_{\leftmoon}}{dt} &= T_{\leftmoon}.
\end{align}
In this project a simple tidal model was used, where the Lunar Tidal torque was expressed as,
\begin{equation}
    T_{\leftmoon} = \frac{3}{2} \frac{Gm_{\leftmoon}^{2}}{a_{\leftmoon}} \left(\frac{R_{\oplus}}{a_{\leftmoon}}\right)^{5} \frac{k_{2}}{Q_{\leftmoon}}
\end{equation}
In this expression, $G=6.67 \times 10^{-8} g^{-1}cm^{3}s^{-2}$ is Newton’s gravitational constant, $m_{\leftmoon}=7.349 \times 10^{25} g$ is the lunar mass, $R_{\oplus}=6371 km$ is the radius of the Earth, $a_{\leftmoon}$ is the semimajor axis of the lunar orbit. The dimensionless quantity $k_{2} = 0.298$ is the Lover number of Earth; it expresses the rigidity of Earth. The dimensionless tidal quality factor $Q_{\leftmoon}$ is the inverse of the fraction of the tidal energy that is dissipated per tidal cycle. For this project $Q_{\leftmoon}$ was assume to be $11.5$.

The Solar Tidal torque $T_{\odot}$ was expressed as,
\begin{equation}
    T_{\odot} = \frac{1}{4.7} \left( \frac{a_{\leftmoon}}{a_{\leftmoon}(0)}\right)^{6}
\end{equation}
The factor $\frac{1}{4.7}$ is the present day ration of $\frac{T_{\odot}}{T_{\leftmoon}}$ and $a_{\leftmoon}(0)$ is the present day value  of the Lunar semimajoraxis.

To solve this system, ode from scipy.integrate was used. Since this was an initial value problem, the present day values for $L_{\oplus}, S_{\oplus}, L_{\leftmoon}$ were used.
\begin{align}
    L_{\oplus} &= M_{\oplus} \sqrt{G(M_{\odot} + M_{\oplus})a_{\oplus}} \\
    S_{\oplus} &= I\Omega_{\oplus} \\
    L_{\leftmoon} &= m_{\leftmoon} \sqrt{G(M_{\oplus} + m_{\leftmoon})a_{\leftmoon}}
\end{align}
The mass of the sun is $M_{\odot}=1.98 \times 10^{33}g$, mass of the Earth is $M_{\oplus}=5.97 \times 10^{27}g$, the semimajor axis of the Earth is $a_{\oplus}=1.49 \times 10^{8}km$, Earth's moment of inertia is $I=0.3299M_{\oplus}R_{\oplus}^{2}$. The angular velocity of Earth is given by $\Omega_{\oplus}=\frac{2\pi}{lod}$ where $lod$ is the length
of the sidereal day, 86164 seconds.

\section{Method}
First the values for $L_{\oplus_{0}}, S_{\oplus_{0}}, L_{\leftmoon_{0}}$ were calculated in the cgs unit system using python. These values were found to be $L_{\oplus_{0}}=2.65 \times 10^{47} gcm^{2}s^{-1}, S_{\oplus_{0}}=5.83 \times 10^{40} gcm^{2}s^{-1}, L_{\leftmoon_{0}}=2.89 \times 10^{41} gcm^{2}s^{-1}$. Next the present day Lunar tidal torque $T_{\leftmoon}$ and the Solar Tidal torque $T_{\odot}$ were determined by using equations 4 and 5. Using python these torques were found to be $T_{\leftmoon}=4.58 \times 10^{23} gcm^{2}s^{-2}$ and $T_{\odot}=9.75 \times 10^{22} gcm^{2}s^{-2}$. Now, the timescales associated with equations 1 to 3 were found. These timescales were determined by taking the initial conditions and dividing by the associated torques.
\begin{align}
    \tau_{L_{\oplus}} &= \frac{L_{\oplus_{0}}}{T_{\odot}} = 2.72 \times 10^{24} s \\
    \tau_{S_{\oplus}} &= \frac{S_{\oplus_{0}}}{T_{\odot}+T_{\leftmoon}} = 1.05 \times 10^{17} s \\
    \tau_{L_{\leftmoon}} &= \frac{L_{\leftmoon_{0}}}{T_{\leftmoon}} = 6.31 \times 10^{17} s
\end{align}

In order to model the system on python, functions for $T_{\odot}$, $T_{\leftmoon}$ and the system of differential equations was made. Then using ode from scipy.integrate, the system was integrated $2$ billion years into the past. From the tidal model, it was found that the Moon was formed 1.54 billion years ago.

\section{Analysis}
\begin{figure}[H]
\centering
\includegraphics[scale=0.80]{plot1.pdf}
\caption{Plot of Semimajor axis vs. Time for time going back 2 billion years into the past}
\end{figure}

\begin{figure}[H]
\centering
\includegraphics[scale=0.80]{plot2.pdf}
\caption{Plot of the Length of Day on Earth vs.Time for time going back 2 billion years into the past}
\end{figure}

 It is believed that the Moon formed just outside the Roche radius. Assuming this is true, the length of day on Earth at the time of the Moon's formation was found to be $8.5$ hours long.

 Using estimates from NASA's website, the age of the Earth is $4.54$ billion years old and the Moon is $4.51$ billion years old. These values are much older than values obtained from the tidal model.

 The disagreement between the tidal model and the estimates from NASA maybe due to the tidal model not incorporating the effects of other celestial objects, like gravity from other planets. Although the effects of the other celestial objects are small due to the large scales in distance, these small effects compound when integrating over billions of years. For this model the dimensionless tidal quality factor $Q_{\leftmoon}$ was assumed to be constant through time, however, one would expect this quantity to increase as the Earth and Moon got closer, since the gravitational attraction would increase as the distance between the Earth and Moon decreased. Also, changes in eccentricities were not taken into account in the system, for example, when the Earth and Moon are closer together the orbital eccentricity of their orbits would be exaggerated due to greater gravitation attraction between them this can greatly effect the angular momentum and spin angular momentum. Assuming the great impact hypothesis is true, right after the collision there was Earth and a disk of debris orbit Earth as a result of the collision. The Tidal model does not consider how this disk of debris may have formed into the Moon. This model assumes the Earth and Moon being tidally locked from the moment of impact. This assumption would not be correct when utilizing the great impact hypothesis. The process of becoming tidally locked would have rearranged the angular momentum in the Earth-Moon system.

 Additionally, this model only takes into account the angular momentum of the Earth and Moon and spin angular momentum of the Earth. The energy of the system is considered. For example, energy being converted to heat in oceans due to friction can accumulate to loss of angular momentum over billions of years.
\end{document}


\documentclass{exam}
\setlength{\parskip}{0pt}
\setlength{\parindent}{0pt}
\setlength{\voffset}{-15pt}
\usepackage[onehalfspacing]{setspace} % Sets Spacing to 1.5
\usepackage[utf8]{inputenc} % Use UTF-8 encoding
\usepackage{float} % Improved interface for floating objects
\usepackage[colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref} % For hyperlinks in the PDF
\usepackage{graphicx, multicol} % Enhanced support for graphics
\usepackage{amsmath}
\usepackage{framed, caption}
\usepackage{array}
\usepackage{float}
\usepackage{amsmath}
\usepackage{bbm}
\newcommand\tab[1][0.2cm]{\hspace*{#1}}
\usepackage{multicol}
%----------------------------------------------------------------------------------------
\begin{document}

\begin{minipage}{0.295\textwidth} % Left side of title section
\raggedright
SIL765 - Net. \& Sys. Security\\ % Your lecture or course
\footnotesize % Authors text size
CSE, IIT Delhi (SEM2, 2020-21) % Department
\medskip\hrule
\end{minipage}
\begin{minipage}{0.4\textwidth} % Center of title section
\centering
\large % Title text size
\textbf{Assignment 1}\\ % Assignment number
\normalsize % Subtitle text size
 % Assignment subtitle
\end{minipage}
\begin{minipage}{0.295\textwidth} % Right side of title section
\raggedleft
2018CS10388\\ % Entry Number
\footnotesize
Sharique Shamim % Name
\medskip\hrule
\end{minipage}
\vspace{0.1in}
\section{Cracking RSA}
To run the script do: (Note here python2 has been used)
\begin{center}
    \texttt{cd problem-3},
    \texttt{python2 crack.py n}
\end{center}
RSA Algorithm is an asymmetric cryptography algorithm. The algorithm makes use of Public Key and Private Key. Messages encrypted through public key can only be correctly decrypted through private key. As the name describes the public key is given to everyone and the private key is kept private. \vspace{0.05in} \\
\textbf{Idea of RSA Algorithm}: \vspace{0.05in} \\
RSA algorithm is based on the fact that it is very difficult to factorize large integers. The public key consists of two numbers where one number is multiplication of two large prime numbers. And private key is also derived from the same two prime numbers. So if somebody can factorize the large number, the private key is compromised. Therefore encryption strength totally lies on the key size and if we double or triple the key size, the strength of encryption increases exponentially. RSA keys can be typically 1024 or 2048 bits long, but experts believe that 1024 bit keys could be broken in the near future. But till now it seems to be an infeasible task. \vspace{0.05in} \\
\textbf{RSA Algorithm}:
\begin{itemize}
    \item Factorize $n$ \vspace{0.05in} \\
    \tab if $ n \le 10^{20}$ then use Pollard-Rho to factorize n otherwise use ECM to factorize n
    \item Key Setup \vspace{0.05in} \\
    \tab Obtain the prime factors $p$, $q$ such that $n = p \cdot q$ \vspace{0.05in} \\
    \tab Compute $\phi = (p - 1) \cdot (q - 1)$ \vspace{0.05in} \\
    \tab Choose an integer $e$ such that gcd($e, phi$) = $1$ \vspace{0.05in} \\
    \tab Choose an integer $d$ such that $(d \cdot e)$ mod $\phi = 1$ \vspace{0.05in} \\
    \tab Publish the public key $\{e, n\}$ \vspace{0.05in} \\
    \tab Keep the private key $\{d, n\}$
    \item Encryption \vspace{0.05in} \\
    \tab Convert the characters of the plain text to numbers. \vspace{0.05in} \\
    \tab Use the public key $K$ and compute the cipher text as $C = M^e$ mod $n$ \vspace{0.05in} \\
    \tab Convert the numbers of cipher text to characters.
    \item Decryption \vspace{0.05in} \\
    \tab Convert the characters of the cipher text to numbers. \vspace{0.05in} \\
    \tab Use the private key $K$ and compute the plain text as $M = C^d$ mod $n$ \vspace{0.05in}
\end{itemize}
\section{Time to factorize vs number of digits in n}
\begin{figure}[h]
\centering
\includegraphics[scale=0.8]{rsa_plot.png}
\end{figure}
\textbf{Observations}:
In the given file 'nlist.txt' there are several numbers which are square of a prime numbers. But for RSA algorithm to decrypt the cipher text correctly both p and q should be distinct. The following are such numbers in the given file: \\
$2605796209$, $3678058609$, $3694086841$, $4303234442515849$, $961801438520428081$, $11651738070536913351684889$, $840859136266769099141989302482624329$, $1316872907073608066468826571215294289$ \vspace{0.05in} \\
\textbf{Configuration of laptop used}: Intel i5 \vspace{0.05in} \\
\textbf{Largest n cracked within 5 minutes}: All the numbers in the file are cracked within 5 minutes. Largest number of digits in the file is $37$. \vspace{0.05in} \\
\textbf{Conclusion}: The time required to factorize is very low but increases slowly when the number of digits in n increases.
\end{document}


\chapter{Introduction}
\label{chap-introduction}

In 1964, Rado~\cite{rado:universal-graph:} introduced the concept of a \emph{universal} graph, which he defined as a countably infinite graph that contained all finite graphs as induced subgraphs. Later that same year, Moon~\cite{moon:on-minimal-n-un:} studied finite graphs that contain all finite graphs on $m$ vertices, a property that he called $m$-universality, initiating a line of research that continues to enjoy scholarly attention. In this work, we provide a brief survey of universality for various combinatorial structures---words, integer partitions, compositions, graphs, and permutations---under induced containment orders.

We say that the structure $\sigma$ is \emph{$m$-universal} if it contains all structures of size $m$ of the same kind. More generally, if $S$ is a family of structures, we say that $\sigma$ is \emph{$S_m$-universal} if it contains every structure in $S$ of size $m$.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Words over a Finite Alphabet}
\label{sec-words}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

As a simple example that will be prove to be a useful reference, consider the collection of words over a $k$-letter alphabet, where we say a word $u$ is contained in the word $v$ if $u$ is a subsequence of of $v$, and the \emph{size} of a word is its number of letters.
\begin{proposition}
\label{prop-word-universal}
	Let $\W$ denote the collection of words over a $k$-letter alphabet under the subword order. The smallest $\W_m$-universal words have size $km$.
\end{proposition}
\begin{proof}
	To begin, observe that any $\W_m$-universal word must have at least $m$ occurrences of each letter, as for each letter $\ell$, it must contain the word $\ell^m$, ie. the letter $\ell$ repeated $m$ times. Thus any $\W_m$-universal word must have at least $km$ letters.

	To show that this lower bound is tight, we recursively construct a $\W_m$-universal word of size $km$. Let our alphabet be $\{1, 2, \dots, k\}$. If $v$ is a $\W_{m-1}$-universal word, then the concatenation $v 12\cdots k$ is $\W_m$-universal, as the first $m-1$ letters of an abritrary word $u$ of size $m$ embed into $v$, and the final letter embeds into $12\cdots k$. This fact, together with the $\W_0$-universal empty word, shows that the word $(12 \cdots k)^m$ of size $km$ is $\W_m$-universal, completing the proof.
\end{proof}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Keeping it in the Family: Proper Universal Structures}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Not all kinds of structures admit $m$-universal structures for all $m$. Consider, for example, the family $\C = \{\varepsilon, \worda, \wordb, \worda\worda, \wordb\wordb, \cdots\}$ of constant words over the two-letter alphabet $\{\worda, \wordb\}$. No word in $\C$ contains both $\worda$ and $\wordb$, so no word in $\C$ is $\C_m$-universal for any $m \ge 1$. Nevertheless, one may still seek universal words for $\C$ in the collection of all words over $\{\worda, \wordb\}$.

A set of structures forms a \emph{class} if it is closed downward under the induced-substructure order, and a class is called \emph{proper} if it does not contain every structure of the given kind. Given a family of structures $\F$, we say that a structure is \emph{$\F_m$-universal} or \emph{$m$-universal for $\F$} if it contains every structure in $\F_m$. If an $\F_m$-universal structure itself lies in $\F$, we say it is a \emph{proper} $\F_m$-universal structure. The classes that admit proper universal objects of all sizes are precisely those that satisfy the joint-embedding property, where we say that a set $\S$ of structures satisfies the \emph{joint-embedding property} if for any $\rho, \sigma \in \S$, there is some $\tau \in \S$ so that $\rho \le \tau$ and $\sigma \le \tau$.


\documentclass{article}
\usepackage[left=3cm,right=3cm,top=2cm,bottom=2cm]{geometry} % page settings
\usepackage{fourier}
\usepackage{listings}
\usepackage{amsmath} % provides many mathematical environments & tools

\setlength{\parindent}{0mm}

\begin{document}

\title{Perpetual arbitrage}
\author{Vladimir Smelov}
\date{\today}
\maketitle

\section{Abstract}
This article explains how to do direct/inverse perpetual contracts arbitrage keeping portfolio delta-neutral and having exposure in USDT.

\section{PNL and Delta formulas}

For a direct BTCUSDT contract

\begin{align*}
Profit^{BTCUSDT}_{linear} = CurrentPrice^{BTC} - AvgEntryPrice^{BTC}
\end{align*}

So the contract derivatives are

\begin{align*}
& \Delta^{BTCUSDT}_{linear} = \frac{\partial Profit^{USDT}_{linear}}{\partial CurrentPrice^{BTC}} = 1 \\
& \Gamma^{BTCUSDT}_{linear} = \frac{\partial \Delta^{BTCUSDT}_{linear}}{\partial CurrentPrice^{BTC}} = 0
\end{align*}

For an inverse BTCUSD contract

\begin{align*}
& Profit^{BTC}_{inverse} = \frac{1}{AvgEntryPrice^{BTC}} - \frac{1}{CurrentPrice^{BTC}} \\
& Profit^{USD}_{inverse} = CurrentPrice^{BTC} * Profit^{BTC}_{inverse} \\
& Profit^{USD}_{inverse} = CurrentPrice^{BTC} * (\frac{1}{AvgEntryPrice^{BTC}} - \frac{1}{CurrentPrice^{BTC}}) \\
& Profit^{USD}_{inverse} = \frac{CurrentPrice^{BTC}}{AvgEntryPrice^{BTC}} - 1 \\
\end{align*}

So the contract derivatives are

\begin{align*}
& \Delta^{BTCUSD}_{inverse} = \frac{\partial Profit^{USD}_{inverse}}{\partial CurrentPrice^{BTC}} = \frac{1}{AvgEntryPrice^{BTC}} \\
& \Gamma^{BTCUSD}_{inverse} = 0
\end{align*}

Keep in mind that our profit measured in BTC also has delta by the nature equals to 1.

So total portfolio delta equals to:

\begin{align*}
& \Delta Porfolio = Position^{BTCUSDT}_{linear} * \Delta^{BTCUSDT}_{linear} + Position^{BTCUSD}_{inverse} * \Delta^{BTCUSD}_{inverse} + 1 * Account^{BTC} \\
& \Delta Porfolio = Position^{BTCUSDT}_{linear} + Position^{BTCUSD}_{inverse} * \frac{1}{AvgEntryPrice^{BTC}} + Account^{BTC} \\
\end{align*}

\danger We assuming USDT and USD absolutely aligned, what is not completely true. We should handle this in future.

\section{Trade effect on delta position}

Let's say, our position is
$Position^{BTCUSDT}_{inverse} = s1$ entered for $AvgEntryPrice^{BTC} = p1$ \\

We do a trade with $TradeSize = s2$ and $TradePrice = p2$
\\

What will be the new value of $AvgEntryPrice^{BTC} = x$ \\

Let's say we will close the total position later, when the price will be $p3$ \\

Then PNL of closing (s1+s2)@p3 with $AvgEntryPrice^{BTC} = x$ should be equals to PNL of closing s1@p3 with $AvgEntryPrice^{BTC} = p1$ + closing s2@p3 with $AvgEntryPrice^{BTC} = p2$ \\

\begin{align*}
& s1 * (1/p1 - 1/p3) + s2 * (1/p2 - 1/p3) = (s1+s2) * (1/x - 1/p3) \\
& s1 * 1/p1 + s2 * 1/p2 = (s1+s2) * 1/x \\
& s1 * 1/p1 + s2 * 1/p2 = (s1+s2) * 1/x \\
& x = \frac{p1 p2 (s1 + s2)}{p1 s2 + p2 s1} \\
\end{align*}

Let's note that it's the harmonical average formula. \\

So after a trade our delta position on inverse perpetual will be

\begin{align*}
& \Delta_{NEW} = (s1 + s2) * 1 / x \\
& = (s1 + s2) \frac{p1 s2 + p2 s1}{p1 p2 (s1 + s2)} \\
& = \frac{p1 s2 + p2 s1}{p1 p2} \\
& = \frac{PreviousAverageEntryPrice * TradeSize + TradePrice * PreviousPosition}{PreviousAverageEntryPrice * TradePrice} \\
& = \frac{PreviousPosition}{PreviousAverageEntryPrice} + \frac{TradeSize}{TradePrice} \\
& = \Delta PreviosPosition + \Delta Trade
\end{align*}

so delta-position is additive what is logical :-) \\

\subsection{Long-Short effect on delta position}

What will happen if we, say, long s@p1, then short s@p2 using an inverse perpetual? \\

Our current position is 0. \\

Our BTC profit is $ s * (1/p1-1/p2) $ \\

Our USD profit at the moment of the trade is $ p2 * s * (1/p1-1/p2) = s * (p2/p1 - 1) $ \\

Our USD delta is $ \frac{s}{p1} - \frac{s}{p2} $ \\

How is it turned possible that position is 0, but Delta is not 0? \\

It happens because Long-Short trade generated the BTC profit and it has Delta by itself! \\

In a trading-bot it's better to separate btc-wallet-profit from position and keep AvgEntryPrice for position.

\section{Limit wallet BTC amount}

After we make a lot of successful trades with inverse perpetual, we'll get a lot of BTC as a profit on the account.

The problem is that BTC is very volatile by itself so our profit is volatile.

To avoid this and have exposure in USDT we have two options:

\subsection{withdraw BTC}

Just withdraw BTC manually, exchange it to USDT and send it to linear exchange account :-)

\subsection{cross-exchanges transfer BTC to USDT with trades}

The idea is to use situations when we can trade with total profit = 0, making profit trades with linear perpetual and making equal loss with inverse perpetual. \\

Let's say market prices are distributed around \$1000. \\

Let LinearPrice = \$1100, InversePrice = \$1100, if we do SHORT linear, LONG inverse, and then when prices become normal (near \$1000), we close positions, we'll loose 0.1btc on inverse perpetual, but win \$100 on linear, so this way "cross-exchanges transfering" happen! \\

If we wait for situations when LinearPrice gap even higher than InversePrice we'll even make some total profit. \\

In real situation, for a good model, market prices are distributed around theoretical price. So the logic remains the same. \\

\warning If both prices linear and inverse are higher than theoretical, it may indicate up-trend. Nothing really bad may happen, taking into account that our TotalPosition is delta-neutral and for a good model this should be a rare case (good model makes correct predictions with a higher probability than incorrect). \\

\subsection{BTC wallet limit}

When we see that WalletInverseBTC is high enough (and before we resolve it with one of the methods above), we disable trades which tend to increase InverseProfit. \\

IF WalletInverseBTC > Max: \\
DO NOT LONG when TheoPriceInverse > MarketPriceInverse \\
DO NOT SHORT when TheoPriceInverse < MarketPriceInverse \\

\section{Arbitrage algorithm idea}

Let's say, we have a good model which gives predictions of TheoPrice perpetual value. \\

Let's make an algorithm to trade using the simple criteria: \\

CRITERA = (MarketPriceLinear - TheoPriceLinear) - (MarketPriceInverse - TheoPriceInverse)

\danger different exchanges may have different funding mechanisms, different involved risk and different fees, this may affect theoprice.

IF CRITERIA > SENSITIVITY: SHORT linear, LONG inverse \\
IF CRITERIA < -SENSITIVITY: LONG linear, SHORT inverse \\

After we do trades, we always hedge WalletBTC with short/long linear perpetual, so PortfoiloDelta is always 0.

If WalletBTC is high we disable further increasing of BTC (see "BTC wallet limit"), and transfer BTC to USDT account with the method described in "cross-exchanges transfer BTC to USDT with trades".

\section{Arbitrage algorithm example}

Let's say market prices are normally distributed around \$1000.

Let SENSITIVITY=1.

\begin{lstlisting}
for i in range(20):
    print(f'time={i}, linear={int(random.gauss(1000, 10))}, inverse={int(random.gauss(1000, 10))}')

time=0, linear=1005, inverse=994
# CRITERA = (1005-1000) - (994-1000) = 11 -> SHORT linear, LONG inverse
# short 1btc@1005, long 994usdt@994

time=1, linear=1004, inverse=1011
# CRITERA = -6 -> LONG linear, SHORT inverse
# long linear 1btc@1004, short inverse -994usdt@1011,
# linear profit = -1usdt
# inverse profit = 994*(1/994-1/1011) = 0.017btc
# short linear -0.017btc@1004 to hedge

time=2, linear=989, inverse=995
# CRITERA = -6 -> LONG linear, SHORT inverse
# opportunity to "cross-exchange-transfer BTC" with making money on linear
# short inverse -995usdt@995
# long linear 1btc@989, so linear position is +1-0.017=0.983 with
# linear profit -0.017*(989-1004)=0.255usdt
# so linear position 0.983btc@989, inverse position -995usdt@995, inverse profit = 0.017btc, linear profit=-1+0.255=-0.745usdt

time=3, linear=1002, inverse=1000
# CRITERA = 2 -> SHORT linear, LONG inverse
# short linear -0.983btc@1002, linear profit += 0.983*(1002-989)=12.779usdt
# long inverse 995usdt@1000, inverse profit += -995*(1/995-1/1000) = -0.005btc
# note, that total usd profit 12.779-0.005*1000=7.779 > 0
# we could do trades on time=2 for even bigger size and decrease BTC wallet even more
# linear profit = -0.745+12.779 = 12usdt, inverse profit = 0.017-0.005 = 0.012btc
# to hedge we do short -0.012btc@1002 <- linear position
# and inverse position = 0usdt

time=4, linear=987, inverse=1002
# CRITERIA = -15 -> DO short inverse, long linear

time=5, linear=998, inverse=1005
# CRITERIA = -7, do not do anything, wait to close position

time=5, linear=1000, inverse=1003
# CRITERIA = -3, do not do anything, wait to close position

time=6, linear=993, inverse=999
# CRITERIA = -6, do not do anything, wait to close position

time=7, linear=1010, inverse=1004
# CRITERIA = 6, DO long inverse, short linear
# make money on closing the position
# hedge WalletBTC delta with linear perpetual

time=8, linear=1012, inverse=1011
# if WalletBTC is big enough we can decrease it \\
# using "cross-exchange-transfer BTC" method (see above)

...
\end{lstlisting}

\section{Appendix}
Exchanges with perpetual contracts:

\begin{itemize}
\item DueDEX (BTCUSDT linear)
\item BitMEX (BTCUSD inverse)
\item Deribit (BTCUSD inverse)
\item OceanEX (both)
\item ByBit (both)
\item Poloniex(BTCUSDT linear)
\item CoinBene (various direct PPT)
\item ...
\end{itemize}

Open questions:
\begin{itemize}
\item Why exactly there are no linear USD perpetuals? Is there some specific law or something?
\end{itemize}

\section{References}
\begin{itemize}
\item https://duedex.zendesk.com/hc/en-us/articles/360046896273-DueDEX-USDT-Perpetual-Contract-FAQ
\item https://blockonomi.com/perpetual-contracts-bitcoin/
\item https://forklog.com/likvidatsiya-marzha-i-usdt-kontrakty-torguem-na-bybit/
\item https://www.bitmex.com/app/pnlGuide
\item https://help.bybit.com/hc/en-us/articles/900000306086
\end{itemize}

\end{document}


% !TEX root = report.tex
\section{The Experiment}
\label{sec:experiment}

\subsection{Experiment set-up}

In this section, we evaluate how well our proposed Alloy verification framework performs on various \textsc{drc} database queries. Below are the list of database tables in the schema.

\newrobustcmd\Employee{\rel{Employee}}
\newrobustcmd\Supervisor{\rel{Supervisor}}
\newrobustcmd\Reviewer{\rel{Reviewer}}

\begin{itemize}[topsep=0.5pc,itemsep=0.25pc]
    \item  $\Employee(\field{id}, \field{security-level})$:\; each employer ID and their security levels; and
    \item  $\Supervisor(\field{employee-id},\field{boss-id})$:\; stores employee--boss pairs
    \item  $\Reviewer(\field{employee-id},\field{year},\field{reviewer-id})$:\; stores the employee ID of the performance reviewer for each employee in each year
\end{itemize}

\newrobustcmd{\empX}{\ensuremath{x}}
\newrobustcmd{\empY}{\ensuremath{y}}
\newrobustcmd{\boss}{\ensuremath{b}}
\newrobustcmd{\level}{\ensuremath{\ell}}
\newrobustcmd{\yearT}{\ensuremath{t}}

\medskip\noindent
We also consider the following \textsc{drc} queries.

\begin{itemize}[topsep=0.5pc,itemsep=0.25pc]
    \item  $\boldsymbol{Q_1}$\hrsp:\;\marginnote{\textsc{safe}}
        Pairs of employees who share the same boss, and at least one of them has the same security level as their boss.
        \begin{align*}
            Q_1 &= \big\{ \empX, \empY \mid
                \exists \boss \hrsp\big[
                    \Supervisor(\empX, \boss) \wedge \Supervisor(\empY, \boss) \\
            & \qquad\qquad\qquad\wedge \exists \level \hrsp[\Employee(\boss, \level) \wedge (\Employee(\empX, \level) \vee \Employee(\empY, \level))]\big]\big\}
        \end{align*}

    \item  $\boldsymbol{Q_2}$\hrsp:\;\marginnote{\textsc{unsafe}}
        Employees without their own bosses.
        \begin{align*}
            Q_2 &= \big\{ \empX \mid
                \neg \exists \boss \hrsp[\Supervisor(\empX, \boss)] \big\}
        \end{align*}

    \item  $\boldsymbol{Q_3}$\hrsp:\;\marginnote{\textsc{unsafe}}
        Pairs of employees, one of which has the same security level as one of their bosses.
        \begin{align*}
            Q_3 &= \big\{ \empX, \empY \mid
                \exists \boss \exists \level \hrsp[\Employee(\boss, \level) \\
            & \qquad\qquad\qquad\qquad\wedge (\Employee(\empX, \level) \wedge \Supervisor(x, b)  \\
            & \qquad\qquad\qquad\qquad\qquad\vee \Employee(\empY, \level) \wedge \Supervisor(y, b))]\big\}
        \end{align*}

    \item  $\boldsymbol{Q_4}$\hrsp:\;\marginnote{\textsc{safe}}
        Pairs of employees who review each other within the same year.
        \begin{align*}
            Q_4 &= \big\{ \empX, \empY \mid
                \exists \yearT \hrsp[\Reviewer(\empX, \yearT, \empY) \wedge \Reviewer(\empY, \yearT, \empX)] \big\}
        \end{align*}

    \item  $\boldsymbol{Q_5}$\hrsp:\;\marginnote{\textsc{unsafe}}
        \emph{Super} employees who (a) has reviewed everyone else at some point (excluding themselves), and (b) is a boss of at least one employee.
        \begin{align*}
            Q_5 &= \big\{ \boss \mid
                \forall \empX \exists \yearT \hrsp[\Reviewer(\empX, \yearT, \boss)]
                \wedge \exists \empY \hrsp[
                \Supervisor(\empY, \boss) \wedge \neg(\empY = \boss)] \big\}
        \end{align*}
\end{itemize}

\begin{lstlisting}[language=alloy,float,basicstyle={\footnotesize\ttfamily},caption={The complete Alloy program which verifies queries {\protect $Q_1$ through $Q_5$} as defined earlier in \sectionref{sec:experiment}. To verify the safety of other query functions, some portions of the code (shown highlighted) needs to be modified.},label={src:experiment},aboveskip=0pc,belowskip=0pc]
/* Scalar values */
sig Superparticle {} {
	Superparticle = Universe.Element
}

/* Domains */
abstract sig Universe { Element: some Superparticle }
one sig UniverseAlpha, UniverseBeta extends Universe {}

/* Common domain */
some sig Particle in Superparticle {} {
	Particle = UniverseAlpha.Element & UniverseBeta.Element
}

/* Database Instance */
one sig Table {
    Employee: Particle -> Particle,
    Supervisor: Particle -> Particle,
    Reviewer: Particle -> Particle -> Particle
}

/* Query functions */
fun query1[u: Universe]: Superparticle -> Superparticle {
    { x, y: u.Element | some b: u.Element |
        (x -> b in Table.Supervisor) and (y -> b in Table.Supervisor) and
        (some l: u.Element | (b -> l in Table.Employee) and
                             ((x -> l in Table.Employee) or (y -> l in Table.Employee))) }
}
fun query2[u: Universe]: set Superparticle {
    { x: u.Element | not some b: u.Element | x -> b in Table.Supervisor }
}
fun query3[u: Universe]: Superparticle -> Superparticle {
    { x, y: u.Element | some b, l: u.Element |
        (b -> l in Table.Employee) and
        ((x -> l in Table.Employee) and (x -> b in Table.Supervisor) or
         (y -> l in Table.Employee) and (y -> b in Table.Supervisor)) }
}
fun query4[u: Universe]: Superparticle -> Superparticle {
    { x, y: u.Element | some t: u.Element |
        (x -> t -> y in Table.Reviewer) or (y -> t -> x in Table.Reviewer) }
}
fun query5[u: Universe]: set Superparticle {
    { b: u.Element |
        (all x: u.Element | some t: u.Element | x -> t -> b in Table.Reviewer) and
        (some y: u.Element | (y -> b in Table.Supervisor) and not (y = b)) }
}

/* Safety assertion */
assert queryIsSafe {
    all u, u': Universe | <|\hll{exp-assert1}|>query1<|\hlr{exp-assert1}|>[u] = <|\hll{exp-assert2}|>query1<|\hlr{exp-assert2}\label{li:replace-assert}|>[u']
}

/* Results placeholder */
abstract sig Result {
    OneColOutput: set Superparticle,
    TwoColOutput: Superparticle -> Superparticle
}
one sig ResultAlpha, ResultBeta extends Result {} {
    ResultAlpha. <|\hll{exp-alpha-o}\llap{\color{Symbol}@}|>TwoColOutput<|\hlr{exp-alpha-o}|> = <|\hll{exp-alpha}|>query1<|\hlr{exp-alpha}\label{li:replace-alpha}|>[UniverseAlpha]
    ResultBeta. <|\hll{exp-beta-o}\llap{\color{Symbol}@}|>TwoColOutput<|\hlr{exp-beta-o}|> = <|\hll{exp-beta}|>query1<|\hlr{exp-beta}\label{li:replace-beta}|>[UniverseBeta]
}

/* Invoke the verification on the assertion */
check queryIsSafe for 4
\end{lstlisting}

\bigskip
\marginhead{How to verify each specific query}
The Alloy model for these \textsc{drc} queries are shown in \autoref{src:experiment}. By default the Alloy program verifies the query $Q_1$. If we wish to verify other queries, we need to modify some parts of the code (shown highlighted). Specifically,
\begin{itemize}[topsep=0.5pc,itemsep=0.25pc]
    \item  The query function name \alloy{query1} on lines \ref{li:replace-assert}, \ref{li:replace-alpha}, and \ref{li:replace-beta} should be replaced by names of other functions such as \alloy{query2}, \alloy{query3}, etc.
    \item  The result placeholder \alloy{TwoColOutput} may need to be changed to \alloy{OneColOutput} depending of the output signature of the query function.
\end{itemize}

\subsection{Verification result and analysis}

As we expect, Alloy Analyzer has \emph{correctly} determined whether all of these queries are safe. For unsafe queries $Q_2$, $Q_3$, and $Q_5$, Alloy finds the first counterexample in relatively short time (underlined in the output below). The console output for each of these unsafe queries are reproduced here (emphasis added).

\begin{lstlisting}[numbers=none,escapeinside={<|}{|>},xleftmargin=6pc]
<|\llap{\textbf{query2:~~}}|>Executing "Check queryIsSafe for <|\uline{\textbf{10}}|>"
   Solver=sat4j Bitwidth=0 MaxSeq=0 SkolemDepth=1 Symmetry=20
   4658 vars. 1464 primary vars. 6953 clauses. 15ms.
   <|\uline{Counterexample} \uline{found}|>. Assertion is invalid. <|\uline{\textbf{17ms}}|>.
\end{lstlisting}

\begin{lstlisting}[numbers=none,escapeinside={<|}{|>},xleftmargin=6pc]
<|\llap{\textbf{query3:~~}}|>Executing "Check queryIsSafe for <|\uline{\textbf{10}}|>"
    Solver=sat4j Bitwidth=0 MaxSeq=0 SkolemDepth=1 Symmetry=20
    38148 vars. 1464 primary vars. 128213 clauses. 2068ms.
   <|\uline{Counterexample} \uline{found}|>. Assertion is invalid. <|\uline{\textbf{189ms}}|>.
\end{lstlisting}

\newpage
\begin{lstlisting}[numbers=none,escapeinside={<|}{|>},xleftmargin=6pc]
<|\llap{\textbf{query5:~~}}|>Executing "Check queryIsSafe for <|\uline{\textbf{10}}|>"
   Solver=sat4j Bitwidth=0 MaxSeq=0 SkolemDepth=1 Symmetry=20
   9498 vars. 1464 primary vars. 24953 clauses. 58ms.
   <|\uline{Counterexample} \uline{found}|>. Assertion is invalid. <|\uline{\textbf{99ms}}|>.
\end{lstlisting}

\noindent
For safe queries $Q_1$ and $Q_4$, here is the console output (emphasis added).

\begin{lstlisting}[numbers=none,escapeinside={<|}{|>},xleftmargin=6pc]
<|\llap{\textbf{query1:~~}}|>Executing "Check queryIsSafe for <|\uline{\textbf{10}}|>"
   Solver=sat4j Bitwidth=0 MaxSeq=0 SkolemDepth=1 Symmetry=20
   32858 vars. 1464 primary vars. 105823 clauses. 457ms.
   <|\uline{No} \uline{counterexample} \uline{found}|>. Assertion may be valid. <|\uline{\textbf{16593ms}}|>.
\end{lstlisting}

\begin{lstlisting}[numbers=none,escapeinside={<|}{|>},xleftmargin=6pc]
<|\llap{\textbf{query4:~~}}|>Executing "Check queryIsSafe for <|\uline{\textbf{10}}|>"
   Solver=sat4j Bitwidth=0 MaxSeq=0 SkolemDepth=1 Symmetry=20
   7898 vars. 1464 primary vars. 17663 clauses. 39ms.
   <|\uline{No} \uline{counterexample} \uline{found}|>. Assertion may be valid. <|\uline{\textbf{132ms}}|>.
\end{lstlisting}

\begin{note}
    In terms of computational cost,
    \begin{itemize}[topsep=0.5pc,itemsep=0.25pc]
        \item  Queries with more complex syntax tend to take more time to verify (cf.\ \alloy{query1} vs.\ \alloy{query4}) even if the maximum numbers of objects for each type in the search space are the same.
        \item  When comparing queries with similar complexity (such as \alloy{query1} vs.\ \alloy{query3}), unsafe queries take less computation time as it only requires to find one counterexample whereas safe queries need to exhaust the search space.
    \end{itemize}
    In addition, if we choose to vary the maximum number of objects for each model type in Alloy verification task, then undoubtedly, as the number increases, the computational cost also increases. This is a normal Alloy behavior so we would not include the result of such experiment here.
\end{note}