<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shashvat Singham on Medium]]></title>
        <description><![CDATA[Stories by Shashvat Singham on Medium]]></description>
        <link>https://medium.com/@shashvatsingham2001?source=rss-c98c1ad6e24a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*a5cjOY2lgFx0les-</url>
            <title>Stories by Shashvat Singham on Medium</title>
            <link>https://medium.com/@shashvatsingham2001?source=rss-c98c1ad6e24a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:55:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shashvatsingham2001/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Smart Contract I Never Deployed]]></title>
            <link>https://medium.com/@shashvatsingham2001/the-smart-contract-i-never-deployed-e0129d1eee28?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0129d1eee28</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 19:23:19 GMT</pubDate>
            <atom:updated>2026-08-28T19:23:19.549Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How an </em><em>eth_call state override let one Solidity file read Uniswap v3 across three chains � with no gas, no private key, and nothing on-chain to maintain.</em></p><p>There is a contract at the heart of my Uniswap v3 analytics dashboard, <a href="https://onchain-lens.vercel.app/">Onchain Lens</a>, that has never existed on any blockchain. It has no address you can look up on Etherscan, no deployment transaction, no verified source page. And yet it runs against Ethereum mainnet, Base, and Arbitrum on every page load.</p><p>This post is about the trick that makes that possible � and about the three bugs it took to make it production-safe, one of which involves a precompile from 2015 silently answering a Uniswap function call.</p><h3>The problem: reading a pool is a dozen round trips</h3><p>Reading the state of a single Uniswap v3 pool honestly takes a lot of calls: token0() and token1(), then each token&#39;s symbol() and decimals(), then fee(), tickSpacing(), liquidity(), slot0() for the current price and tick, and an observe() for the TWAP. That&#39;s roughly a dozen round trips per pool, and a dashboard wants a dozen pools.</p><p>The standard answer is Multicall3: batch the calls into one request. But Multicall batches the <em>calls</em>, not the <em>logic</em>. You still stitch the results together off-chain, and you still special-case every token that answers symbol() wrongly (more on that later). What I actually wanted was a single function:</p><pre>function snapshot(address[] calldata pools, uint32 twapWindow)<br>    external view returns (PoolSnapshot[] memory);</pre><p>…where PoolSnapshot carries everything � tokens, decimals, symbols, fee, tick, price, liquidity, TWAP � already assembled. That function has to live in a contract. And deploying a contract means gas, a funded key, an audit trail, and doing it three times because I support three chains, then keeping all three deployments in sync forever.</p><p>Unless you never deploy it.</p><h3>The trick: eth_call state overrides</h3><p>eth_call � the JSON-RPC method behind every read-only contract call � accepts an optional third parameter that most people never touch: a <strong>state override set</strong>. It lets the caller say to the node: <em>&quot;before you run this call, pretend the state looked like this.&quot;</em> You can override an account&#39;s balance, its storage� or its <strong>code</strong>.</p><p>So the flow becomes:</p><ol><li>Compile PoolLens.sol locally. Keep the deployed bytecode as a build artifact.</li><li>Pick a throwaway address � I use 0x�dEaD, which has no code, keys, or history on any chain.</li><li>Send one eth_call: <em>to</em> that address, with the pool-reading calldata, and a state override that injects the lens bytecode at that address.</li><li>The node runs the contract in a disposable copy of state, returns the fully-stitched answer, and throws the whole thing away.</li></ol><p>With <a href="https://viem.sh/">viem</a> this is almost embarrassingly small:</p><pre>const { data } = await client.call({<br>  to: LENS_ADDRESS, // 0x�dEaD � a sentinel, not a deployment<br>  data: encodeFunctionData({ abi: LENS_ABI, functionName, args }),<br>  stateOverride: [{ address: LENS_ADDRESS, code: LENS_CODE }],<br>});</pre><p>A dozen storage reads plus all the assembly logic collapse into <strong>one round trip</strong>. There is no deployment to fund, verify, or upgrade. And because the bytecode travels with the request, the <em>same artifact</em> runs unchanged against Ethereum, Base, and Arbitrum. A read-only analytics surface could not ask for a better shape.</p><p>One practical caveat: not every RPC endpoint supports state overrides. In my testing, publicnode.com and 1rpc.io handle them fine; some other popular public endpoints either refuse the parameter without an API key or fall over entirely. If you try this, test your fallback list � an endpoint that ignores the override will call empty code and return nothing.</p><h3>Bug #1: the precompile that answered a Uniswap call</h3><p>Here is the bug that taught me the most, and it’s the reason I’d call this pattern <em>deceptively</em> simple.</p><p>My snapshot() takes arbitrary pool addresses. Early on, a bad address found its way into a batch: 0x�0001. On Ethereum, that is not a dead address � it is the <strong>ecrecover precompile</strong>, part of the protocol since genesis. And precompiles have a fun property: they don&#39;t check what function you&#39;re calling. Call slot0() on ecrecover and it <em>succeeds</em> � returning zero bytes.</p><p>My code did what most Solidity code does:</p><pre>try IUniswapV3Pool(pool).slot0() returns (...) { ... } catch { ... }</pre><p>And here is the thing almost nobody internalizes about try/catch in Solidity: <strong>it only catches reverts. It does not catch a failure to decode the return data.</strong> The call to the precompile succeeded, the ABI decoder tried to read seven words out of zero bytes, and the resulting revert was uncatchable � it took down not just that entry but the <em>entire batch</em>. One garbage address, twelve dead pools on the dashboard.</p><p>The fix is to never let the decoder touch unmeasured bytes. Every external read in the lens is now a low-level staticcall whose returndata length is checked <em>before</em> anything is decoded:</p><pre>(bool success, bytes memory ret) = target.staticcall(data);<br>if (!success || ret.length &lt; n * 32) return (false, words);</pre><p>slot0() returns seven values, so a real v3 pool must answer with at least seven words. A precompile or an unrelated contract won&#39;t. With the length check, the ecrecover incident becomes a single ok = false row and the rest of the batch survives � which is the only acceptable failure mode when one dead pool must not kill the dashboard.</p><h3>Bug #2: tokens that lie about their own symbols</h3><p>symbol() and decimals() are conventions, not guarantees. The ERC-20 standard technically marks them optional, and the wild is full of tokens that interpret them creatively:</p><ul><li><strong>MKR</strong> returns its symbol as a bytes32, not a string � 32 bytes of right-padded text instead of ABI-encoded offset/length/data.</li><li>Arbitrum’s bridged USDT answers USD?0 � multi-byte UTF-8 inside the string.</li><li>Some tokens omit the functions entirely.</li></ul><p>The lens decodes symbols by hand: a 32-byte answer is treated as padded text, a well-formed ABI string (= 96 bytes) is bounds-checked and copied, and anything else becomes &quot;?&quot;. A token that hides its decimals() gets the ERC-20 default of 18, and anything claiming more than 36 decimals is treated as noise. A weird token gets a placeholder; it never gets to take the snapshot down.</p><h3>Bug #3: “Stack too deep,” the rite of passage</h3><p>One pool&#39;s snapshot needs a lot of live values at once: the reads, their ok flags, and the struct being assembled. Inlined into the batch loop, that blew past the EVM&#39;s sixteen stack slots and the compiler refused with Solidity&#39;s most famous error. Splitting the single-pool logic into its own snapshotOne() function gave it a fresh frame and the problem vanished. Old advice, still true.</p><h3>Keeping the on-chain and off-chain math honest</h3><p>The dashboard also simulates concentrated-liquidity positions, which means the position math (sqrtRatioAtTick, amounts-for-liquidity) exists twice: once in Solidity for the lens, once in TypeScript for the frontend. Two implementations of the same math is a bug factory, so the test suite runs both against live pools and holds them to <strong>wei-exact agreement</strong> � 14 differential tests, and it was this suite that caught both the precompile bug and a nasty unit-convention bug in how I was denominating position sizes.</p><p>That second one deserves a sentence, because it&#39;s a good trap: a v3 pool&#39;s token1 is just whichever token sorted higher <em>by address</em>. On the deepest pool on Ethereum, that happens to be WETH � so a &quot;default position size of 100,000&quot; quietly meant 100,000 <em>ether</em>, roughly five times the pool&#39;s entire liquidity. Everything is now denominated in the token the pair is actually quoted in. Sorting pools by their raw liquidity value has the same flavor of wrongness (it&#39;s denominated in v(token0�token1) at the pool&#39;s own decimals, so it isn&#39;t comparable across pairs), and the fix was the same: stop trusting fields that look comparable but aren&#39;t.</p><h3>When you should (and shouldn&#39;t) do this</h3><p>State-override lenses are a great fit when:</p><ul><li>the logic is <strong>read-only</strong> � you&#39;re aggregating views, not changing state;</li><li>you want <strong>one artifact across many chains</strong> with zero deployment ops;</li><li>the inputs are <strong>untrusted</strong> and you&#39;re willing to write defensive staticcall-and-measure code.</li></ul><p>They are the wrong tool when other contracts need to call your logic on-chain, when you need events, or when your RPC layer can&#39;t guarantee override support.</p><p>But for an analytics surface, the economics are hard to argue with: no gas, no keys, no verification, no upgrade path to maintain � and the contract can&#39;t be exploited, because there is nothing on-chain to exploit.</p><p>The dashboard is live at <a href="https://onchain-lens.vercel.app/">onchain-lens.vercel.app</a> and the code � the lens, the viem plumbing, and the differential test suite � is public at <a href="https://github.com/shashvat-singham/onchain-lens">github.com/shashvat-singham/onchain-lens</a>.</p><p>The best contract, it turns out, is sometimes the one you never deploy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0129d1eee28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eleven Standard Deviations of Noise]]></title>
            <link>https://medium.com/@shashvatsingham2001/eleven-standard-deviations-of-noise-8b2667a1915c?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b2667a1915c</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 19:23:07 GMT</pubDate>
            <atom:updated>2026-08-28T19:23:07.505Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a live SVI implied-volatility surface from Deribit’s free options feed — and the two undocumented conventions that each cost me a day and taught me more than the model did.</em></p><p>There is a page at <a href="https://svi-surface.vercel.app/">svi-surface.vercel.app</a> that pulls the entire BTC or ETH option board from Deribit’s public API — no key, no account — inverts every quote to implied volatility, fits an arbitrage-aware smile to each expiry, and then audits its own fit for the three ways a volatility surface can be quietly wrong. It refreshes on every load. The whole quant core is TypeScript, tested offline against captured boards, and runs in a Vercel serverless function.</p><p>This post is about the two data-handling decisions that mattered more than any modelling choice: figuring out what a Deribit premium <em>actually is</em>, and learning that the coordinate you trim your data in can double your fit error all by itself.</p><h3>Why anyone fits a volatility surface</h3><p>The Black-76 formula maps a volatility to an option price. Traders run it backwards: given the market’s price, what volatility does it imply? Do that for every strike and expiry on a board and you get the <em>implied volatility surface</em> — a 2-D function of strike and maturity that is, in a real sense, the market’s probability distribution over the future, written in the only units options traders agree on.</p><p>Quants care because everything downstream reads off this surface: pricing anything exotic, marking positions between quoted strikes, computing risk, spotting quotes that sit rich or cheap against their neighbours. But the raw board is a scatter of noisy dots, not a function. You need a smooth fit — and a fit that is smooth but wrong is worse than no fit, because a smile with the wrong shape implies <strong>negative probabilities</strong>, and a negative probability is a butterfly spread with negative value: free money for whoever trades against your marks.</p><p>So the fit has obligations. It must interpolate the quotes, extrapolate past them without inventing arbitrage, and tell you when it can’t.</p><h3>SVI: five parameters, linear wings</h3><p>The industry-standard slice model is Gatheral’s <em>stochastic volatility inspired</em> (SVI) parameterisation. Per expiry, in log-moneyness k = ln(K/F) and total implied variance w = σ²τ:</p><pre>w(k) = a + b·( ρ(k − m) + √((k − m)² + σ²) )</pre><p>Five parameters: a level a, a wing angle b, a skew ρ, a horizontal shift m, and a vertex curvature σ. In code it is one line:</p><pre>export const sviTotalVariance = (k: number, p: SviParams): number =&gt;<br>  p.a + p.b * (p.rho * (k - p.m) + Math.hypot(k - p.m, p.sigma));</pre><p>Why this shape and not, say, a polynomial? Because as k → ±∞ it becomes linear, with wing slopes ψ₊ = b(1+ρ) and ψ₋ = b(1−ρ) — and Roger Lee&#39;s moment formula says total implied variance on any arbitrage-free surface may not grow faster than 2|k|. Linear wings are not a modelling convenience; they are the shape no-arbitrage <em>forces</em>. A quadratic&#39;s wings grow like k², so it violates Lee&#39;s bound at every sufficiently large strike. SVI can be made arbitrage-free; a polynomial can only be checked and hoped for.</p><p>Fitting it is its own trap — a direct five-parameter least squares wanders a flat valley where b and σ trade off against each other. I use Zeliade&#39;s quasi-explicit method: fix (m, σ), substitute y = (k−m)/σ, and the model becomes <em>linear</em> in three transformed parameters, so the inner problem is a small convex QP solved exactly, and the outer problem is a two-dimensional Nelder–Mead over (m, ln σ) from several starts. Five parameters, but only two of them ever see a nonlinear optimiser.</p><p>None of which helps if the numbers going in are wrong. Which brings me to the traps.</p><h3>Trap #1: what is a Deribit premium, exactly?</h3><p>Deribit quotes option premiums in the base currency — a BTC option’s mark_price might read 0.0415. Zero point zero four one five <em>of what</em>?</p><p>The obvious reading is “0.0415 BTC, valued at the spot index”. The docs do not settle it plainly, and the difference matters: the inversion divides the premium by the wrong number and every implied vol on the board shifts. I could have picked a convention and moved on. Instead I measured it, because Deribit publishes its own mark_iv alongside every price — which means the convention can be recovered from the exchange&#39;s own data: take their IV, price the option under each candidate convention, and see which one reproduces their quoted premium.</p><p>The answer: <strong>the quoted premium is the forward-normalised Black-76 price</strong> — P/F, with the rate set to zero and the per-expiry forward taken from the instrument&#39;s underlying_price field. Under that reading, repricing every quote from Deribit&#39;s own mark IV lands within <strong>0.03%</strong> of the quoted premium. Under the premium-over-spot-index reading, the error is <strong>0.50%</strong> — seventeen times worse, and far too large to be rounding. Case closed, empirically.</p><p>The payoff is a dramatically simpler pipeline. Because the premium is already normalised by the forward, mark_price feeds the inversion directly — no index conversion, no interest rate, no discount factor anywhere in the code. The Black-76 pricer works entirely in (k, w):</p><pre>export function blackPrice(k: number, w: number, type: OptionType): number {<br>  if (w &lt;= 0) return type === &quot;call&quot; ? Math.max(1 - Math.exp(k), 0) : Math.max(Math.exp(k) - 1, 0);<br>  const [d1, d2] = dPair(k, w);<br>  return type === &quot;call&quot;<br>    ? normCdf(d1) - Math.exp(k) * normCdf(d2)<br>    : Math.exp(k) * normCdf(-d2) - normCdf(-d1);<br>}</pre><p>Two details in that snippet earned their place the hard way. Each side is priced from its own formula rather than deriving the put from the call by parity — pricing a far-OTM put as call − 1 + eᵏ subtracts two numbers near one to reach one near 10⁻²⁰, catastrophic cancellation returns exactly zero, and the inversion then has nothing to invert. And the inversion&#39;s convergence tolerance is <em>relative to the quote</em>: a wing option worth 10⁻¹⁰ of the forward satisfies any absolute price tolerance at almost any variance, so an absolute test reports &quot;converged&quot; while handing back a meaningless volatility.</p><p>How do I know the inversion is right? Same trick as the convention hunt: check it against the exchange. Across a representative BTC board, my Newton-in-total-variance inversion agrees with Deribit’s own mark IV to <strong>0.013 vol points on average, 0.019 at the 95th percentile</strong>. When your data source publishes the answer key, use it.</p><h3>Trap #2: cut your wings in sigma, not in k</h3><p>Every vol-fitting pipeline throws away far-from-the-money quotes, because deep wings are one-sided books and tick noise. The natural filter — the one I wrote first — is a band in log-moneyness: keep |k| ≤ 1.2, say.</p><p>Here is why that filter is broken, and it is obvious only in hindsight. The statistical width of an expiry’s distribution is σ_atm·√τ — it <em>shrinks with maturity</em>. At crypto-typical vols, |k| = 1.2 on a <strong>four-day</strong> expiry is roughly <strong>eleven standard deviations</strong> from the forward; on a <strong>one-year</strong> expiry the same band is barely <strong>three</strong>. A fixed band in k is a completely different filter at every maturity: on short expiries it admits strikes so absurdly far out that no probability mass will ever reach them, where the quotes are pure quote-grid noise — and then the optimiser dutifully bends the wings of the smile through that noise.</p><p>The fix is to cut in standard deviations: |k| ≤ 3.5·σ_atm√τ, the same <em>statistical</em> window at every maturity.</p><pre>const atm = quotes.reduce((best, q) =&gt; (Math.abs(q.k) &lt; Math.abs(best.k) ? q : best));<br>const scale = atm.vol * Math.sqrt(tau);</pre><pre>return quotes.filter(q =&gt; {<br>  if (Math.abs(q.k) &gt; maxAbsZ * scale) return false;                          // 3.5σ, every expiry<br>  if (Number.isFinite(q.volSpread) &amp;&amp; q.volSpread &gt; maxHalfSpread) return false;<br>  return true;<br>});</pre><p>(The ATM vol defining the standard deviation comes from the quote nearest the forward — circular in principle, harmless in practice, since the cut only has to be right to within a fraction of a sigma.)</p><p>The effect was not subtle. On the BTC board, switching the cut from k-space to sigma-space took the <strong>worst slice RMSE from 4.1 to 1.9 volatility points</strong>. No model change, no optimiser change — the single largest accuracy improvement in the project came from choosing the right coordinate to throw data away in.</p><h3>The audit, and an unflattering result</h3><p>A fit you cannot falsify is decoration, so every slice is audited: Durrleman’s g(k) — the risk-neutral density up to a positive factor — is scanned over |k| ≤ 3, far outside the quoted strikes, because that is where fits break first; Lee&#39;s bound ψ± ≤ 2 is checked on every wing; and calendar monotonicity of w(k, τ) is <em>measured between independently fitted slices</em>, not imposed, with violations reported rather than smoothed away. On a representative nine-expiry BTC board: all nine slices butterfly-free, seven of eight adjacent pairs calendar-monotone, slice RMSEs from 0.11 to 1.86 vol points. The fitted ATM skew decays with maturity at exponent <strong>α = 0.474 ± 0.024</strong> (HC0 errors, R² = 0.98) — steeper than a one-factor stochastic vol model predicts, and tight enough to be an estimate rather than an artefact.</p><p>And the honest number: held out of sample, a plain three-parameter weighted quadratic beats SVI on <strong>most expiries</strong> over the strike range the exchange actually quotes. SVI’s value is not interpolation — it is that you can extrapolate it past the last quote without inventing arbitrage, which the quadratic’s k² wings make impossible. The page says exactly that, because a portfolio piece that hides its baseline comparison is advertising, not research.</p><h3>Closing</h3><p>The surface is live at <a href="https://svi-surface.vercel.app/">svi-surface.vercel.app</a>, and the code — the inversion, the quasi-explicit calibration, the audits, and 43 offline tests against real captured boards — is public at <a href="https://github.com/shashvat-singham/vol-surface">github.com/shashvat-singham/vol-surface</a>.</p><p>The model came from a paper. The results came from reading the data’s fine print — and when the fine print wasn’t written, measuring it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b2667a1915c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eleven Standard Deviations of Noise]]></title>
            <link>https://medium.com/@shashvatsingham2001/eleven-standard-deviations-of-noise-111f52dcc8f4?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/111f52dcc8f4</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 21:29:56 GMT</pubDate>
            <atom:updated>2026-08-25T21:29:56.720Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a live SVI implied-volatility surface from Deribit’s free options feed — and the two undocumented conventions that each cost me a day and taught me more than the model did.</em></p><p>There is a page at <a href="https://svi-surface.vercel.app/">svi-surface.vercel.app</a> that pulls the entire BTC or ETH option board from Deribit’s public API — no key, no account — inverts every quote to implied volatility, fits an arbitrage-aware smile to each expiry, and then audits its own fit for the three ways a volatility surface can be quietly wrong. It refreshes on every load. The whole quant core is TypeScript, tested offline against captured boards, and runs in a Vercel serverless function.</p><p>This post is about the two data-handling decisions that mattered more than any modelling choice: figuring out what a Deribit premium <em>actually is</em>, and learning that the coordinate you trim your data in can double your fit error all by itself.</p><h3>Why anyone fits a volatility surface</h3><p>The Black-76 formula maps a volatility to an option price. Traders run it backwards: given the market’s price, what volatility does it imply? Do that for every strike and expiry on a board and you get the <em>implied volatility surface</em> — a 2-D function of strike and maturity that is, in a real sense, the market’s probability distribution over the future, written in the only units options traders agree on.</p><p>Quants care because everything downstream reads off this surface: pricing anything exotic, marking positions between quoted strikes, computing risk, spotting quotes that sit rich or cheap against their neighbours. But the raw board is a scatter of noisy dots, not a function. You need a smooth fit — and a fit that is smooth but wrong is worse than no fit, because a smile with the wrong shape implies <strong>negative probabilities</strong>, and a negative probability is a butterfly spread with negative value: free money for whoever trades against your marks.</p><p>So the fit has obligations. It must interpolate the quotes, extrapolate past them without inventing arbitrage, and tell you when it can’t.</p><h3>SVI: five parameters, linear wings</h3><p>The industry-standard slice model is Gatheral’s <em>stochastic volatility inspired</em> (SVI) parameterisation. Per expiry, in log-moneyness k = ln(K/F) and total implied variance w = σ²τ:</p><pre>w(k) = a + b·( ρ(k − m) + √((k − m)² + σ²) )</pre><p>Five parameters: a level a, a wing angle b, a skew ρ, a horizontal shift m, and a vertex curvature σ. In code it is one line:</p><pre>export const sviTotalVariance = (k: number, p: SviParams): number =&gt;<br>  p.a + p.b * (p.rho * (k - p.m) + Math.hypot(k - p.m, p.sigma));</pre><p>Why this shape and not, say, a polynomial? Because as k → ±∞ it becomes linear, with wing slopes ψ₊ = b(1+ρ) and ψ₋ = b(1−ρ) — and Roger Lee&#39;s moment formula says total implied variance on any arbitrage-free surface may not grow faster than 2|k|. Linear wings are not a modelling convenience; they are the shape no-arbitrage <em>forces</em>. A quadratic&#39;s wings grow like k², so it violates Lee&#39;s bound at every sufficiently large strike. SVI can be made arbitrage-free; a polynomial can only be checked and hoped for.</p><p>Fitting it is its own trap — a direct five-parameter least squares wanders a flat valley where b and σ trade off against each other. I use Zeliade&#39;s quasi-explicit method: fix (m, σ), substitute y = (k−m)/σ, and the model becomes <em>linear</em> in three transformed parameters, so the inner problem is a small convex QP solved exactly, and the outer problem is a two-dimensional Nelder–Mead over (m, ln σ) from several starts. Five parameters, but only two of them ever see a nonlinear optimiser.</p><p>None of which helps if the numbers going in are wrong. Which brings me to the traps.</p><h3>Trap #1: what is a Deribit premium, exactly?</h3><p>Deribit quotes option premiums in the base currency — a BTC option’s mark_price might read 0.0415. Zero point zero four one five <em>of what</em>?</p><p>The obvious reading is “0.0415 BTC, valued at the spot index”. The docs do not settle it plainly, and the difference matters: the inversion divides the premium by the wrong number and every implied vol on the board shifts. I could have picked a convention and moved on. Instead I measured it, because Deribit publishes its own mark_iv alongside every price — which means the convention can be recovered from the exchange&#39;s own data: take their IV, price the option under each candidate convention, and see which one reproduces their quoted premium.</p><p>The answer: <strong>the quoted premium is the forward-normalised Black-76 price</strong> — P/F, with the rate set to zero and the per-expiry forward taken from the instrument&#39;s underlying_price field. Under that reading, repricing every quote from Deribit&#39;s own mark IV lands within <strong>0.03%</strong> of the quoted premium. Under the premium-over-spot-index reading, the error is <strong>0.50%</strong> — seventeen times worse, and far too large to be rounding. Case closed, empirically.</p><p>The payoff is a dramatically simpler pipeline. Because the premium is already normalised by the forward, mark_price feeds the inversion directly — no index conversion, no interest rate, no discount factor anywhere in the code. The Black-76 pricer works entirely in (k, w):</p><pre>export function blackPrice(k: number, w: number, type: OptionType): number {<br>  if (w &lt;= 0) return type === &quot;call&quot; ? Math.max(1 - Math.exp(k), 0) : Math.max(Math.exp(k) - 1, 0);<br>  const [d1, d2] = dPair(k, w);<br>  return type === &quot;call&quot;<br>    ? normCdf(d1) - Math.exp(k) * normCdf(d2)<br>    : Math.exp(k) * normCdf(-d2) - normCdf(-d1);<br>}</pre><p>Two details in that snippet earned their place the hard way. Each side is priced from its own formula rather than deriving the put from the call by parity — pricing a far-OTM put as call − 1 + eᵏ subtracts two numbers near one to reach one near 10⁻²⁰, catastrophic cancellation returns exactly zero, and the inversion then has nothing to invert. And the inversion&#39;s convergence tolerance is <em>relative to the quote</em>: a wing option worth 10⁻¹⁰ of the forward satisfies any absolute price tolerance at almost any variance, so an absolute test reports &quot;converged&quot; while handing back a meaningless volatility.</p><p>How do I know the inversion is right? Same trick as the convention hunt: check it against the exchange. Across a representative BTC board, my Newton-in-total-variance inversion agrees with Deribit’s own mark IV to <strong>0.013 vol points on average, 0.019 at the 95th percentile</strong>. When your data source publishes the answer key, use it.</p><h3>Trap #2: cut your wings in sigma, not in k</h3><p>Every vol-fitting pipeline throws away far-from-the-money quotes, because deep wings are one-sided books and tick noise. The natural filter — the one I wrote first — is a band in log-moneyness: keep |k| ≤ 1.2, say.</p><p>Here is why that filter is broken, and it is obvious only in hindsight. The statistical width of an expiry’s distribution is σ_atm·√τ — it <em>shrinks with maturity</em>. At crypto-typical vols, |k| = 1.2 on a <strong>four-day</strong> expiry is roughly <strong>eleven standard deviations</strong> from the forward; on a <strong>one-year</strong> expiry the same band is barely <strong>three</strong>. A fixed band in k is a completely different filter at every maturity: on short expiries it admits strikes so absurdly far out that no probability mass will ever reach them, where the quotes are pure quote-grid noise — and then the optimiser dutifully bends the wings of the smile through that noise.</p><p>The fix is to cut in standard deviations: |k| ≤ 3.5·σ_atm√τ, the same <em>statistical</em> window at every maturity.</p><pre>const atm = quotes.reduce((best, q) =&gt; (Math.abs(q.k) &lt; Math.abs(best.k) ? q : best));<br>const scale = atm.vol * Math.sqrt(tau);</pre><pre>return quotes.filter(q =&gt; {<br>  if (Math.abs(q.k) &gt; maxAbsZ * scale) return false;                          // 3.5σ, every expiry<br>  if (Number.isFinite(q.volSpread) &amp;&amp; q.volSpread &gt; maxHalfSpread) return false;<br>  return true;<br>});</pre><p>(The ATM vol defining the standard deviation comes from the quote nearest the forward — circular in principle, harmless in practice, since the cut only has to be right to within a fraction of a sigma.)</p><p>The effect was not subtle. On the BTC board, switching the cut from k-space to sigma-space took the <strong>worst slice RMSE from 4.1 to 1.9 volatility points</strong>. No model change, no optimiser change — the single largest accuracy improvement in the project came from choosing the right coordinate to throw data away in.</p><h3>The audit, and an unflattering result</h3><p>A fit you cannot falsify is decoration, so every slice is audited: Durrleman’s g(k) — the risk-neutral density up to a positive factor — is scanned over |k| ≤ 3, far outside the quoted strikes, because that is where fits break first; Lee&#39;s bound ψ± ≤ 2 is checked on every wing; and calendar monotonicity of w(k, τ) is <em>measured between independently fitted slices</em>, not imposed, with violations reported rather than smoothed away. On a representative nine-expiry BTC board: all nine slices butterfly-free, seven of eight adjacent pairs calendar-monotone, slice RMSEs from 0.11 to 1.86 vol points. The fitted ATM skew decays with maturity at exponent <strong>α = 0.474 ± 0.024</strong> (HC0 errors, R² = 0.98) — steeper than a one-factor stochastic vol model predicts, and tight enough to be an estimate rather than an artefact.</p><p>And the honest number: held out of sample, a plain three-parameter weighted quadratic beats SVI on <strong>most expiries</strong> over the strike range the exchange actually quotes. SVI’s value is not interpolation — it is that you can extrapolate it past the last quote without inventing arbitrage, which the quadratic’s k² wings make impossible. The page says exactly that, because a portfolio piece that hides its baseline comparison is advertising, not research.</p><h3>Closing</h3><p>The surface is live at <a href="https://svi-surface.vercel.app/">svi-surface.vercel.app</a>, and the code — the inversion, the quasi-explicit calibration, the audits, and 43 offline tests against real captured boards — is public at <a href="https://github.com/shashvat-singham/vol-surface">github.com/shashvat-singham/vol-surface</a>.</p><p>The model came from a paper. The results came from reading the data’s fine print — and when the fine print wasn’t written, measuring it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=111f52dcc8f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Optimal Schedule That Lost to a Market Order]]></title>
            <link>https://medium.com/@shashvatsingham2001/the-optimal-schedule-that-lost-to-a-market-order-d353a4ffa866?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d353a4ffa866</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 21:29:45 GMT</pubDate>
            <atom:updated>2026-08-25T21:29:45.447Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I built a limit order book, ran Almgren–Chriss execution schedules through it, and watched half of the theory survive perfectly — while the other half lost to just sweeping the book once.</em></p><p>Almgren–Chriss is the closest thing optimal execution has to a founding theorem. It says that when you have a large order to work, trading fast pays market impact and trading slowly pays volatility, and it hands you the schedule that balances the two in closed form. Every execution desk descends from it. It’s the frontier everyone draws.</p><p>So when I built <a href="https://orderbook-lab.vercel.app/">Order Book Lab</a> — a matching engine plus an execution simulator that runs in the browser — I did the obvious experiment: instead of scoring Almgren–Chriss schedules with the cost formula that produced them, I ran them through an actual order book. One with depth that a child order genuinely consumes, and that refills at a finite rate.</p><p>Half the theory came through untouched. The other half broke in a way the model literally cannot express. This post is about both halves, plus the one engineering trick in the matching engine that I’d defend in an interview: generation-tagged order handles.</p><h3>Microstructure in three paragraphs</h3><p>A limit order book is two queues of resting intentions. Bids on one side, asks on the other, each at a price level, each level ordered by arrival time — price–time priority. When a marketable order arrives, it <em>takes</em>: it walks the opposite side from the best price outward, consuming resting orders until it’s filled or its limit stops it.</p><p>The consequence that matters for execution: <strong>the book has finite depth</strong>. A 12,000-share buy doesn’t fill at the best ask; it eats the best ask, then the next level, and the next, paying a worse price at each. That’s market impact — not a coefficient in a formula, but the arithmetic of levels being gone after you take them.</p><p>The second consequence: <strong>the book has memory</strong>. Market makers replenish swept levels, but not instantly. If you come back for a second slice two seconds after your first, you’re trading against a book that has only partly recovered. This is the Obizhaeva–Wang picture of resilience, and it turns out to be the detail that breaks the theory.</p><h3>Building the engine</h3><p>The engine is a price–time priority book written for the hot path. Orders live in a struct-of-arrays pool — every field is a slot in a typed array, freed slots go on a free list, so nothing allocates once the pool is warm. Price levels are a flat array indexed by tick: a price <em>is</em> an index, no tree, no hash. Each level is an intrusive doubly-linked FIFO, so resting an order is two pointer writes at the tail and cancelling is four in the middle, with no search for the order being cancelled.</p><p>That last point is the design center. Cancels outnumber trades roughly nine to one on a real tape, so O(1) cancel — not O(1) match — is the number that matters.</p><p>The correctness story is a differential test: 4,500 random operations per seed — quotes, takes, sweeps, cancels, amends — replayed against a deliberately naive reference implementation, requiring the identical fill sequence and identical resting book after <em>every single operation</em>, across five seeds. The performance story survived being measured, barely: the same workload against 1,000 and 120,000 resting orders shows throughput sliding from about 1.25M to 0.56M ops/s. The book grows 120-fold and throughput falls about 2× — that’s the working set outgrowing the cache, not a hidden search. A search-based cancel would have cost a factor of 120, not 2. “Flat throughput” would have been the nicer sentence, and it did not survive contact with the benchmark.</p><h3>The bug that justified the design: generation-tagged handles</h3><p>Here’s the trap in any slot-recycling pool. You hand out order ids. An order fills; its slot goes back on the free list; the next order takes that slot. Meanwhile the client’s cancel for the <em>old</em> order — sent while it was still resting, the completely ordinary cancel/fill race — arrives and lands on whoever inherited the slot. You just cancelled a stranger’s order, silently.</p><p>This isn’t hypothetical. It’s what made my fuzz test diverge from the reference book, and the fix is the most interesting fifteen lines in the engine. An order id is not a slot number — it’s a handle that packs a generation counter above the slot bits:</p><pre>const SLOT_BITS = 17;<br>const SLOT_MASK = (1 &lt;&lt; SLOT_BITS) - 1;<br>const handleOf = (slot: number, generation: number) =&gt;<br>  generation * (1 &lt;&lt; SLOT_BITS) + slot;<br>const slotOf = (handle: number) =&gt; handle &amp; SLOT_MASK;</pre><p>Every time a slot is freed, its generation bumps:</p><pre>private release(slot: number): void {<br>  // Bumping the generation is what invalidates every handle still pointing here.<br>  this.orderGeneration[slot] = (this.orderGeneration[slot] + 1) &gt;&gt;&gt; 0;<br>  this.orderNext[slot] = this.freeHead;<br>  this.freeHead = slot;<br>}</pre><p>A cancel checks that the handle’s generation still matches the slot’s. A stale cancel now fails to match and is <em>rejected</em> — the correct answer — instead of cross-cancelling a stranger. There’s a test that forces exactly this: fill an order, recycle its slot through two new submissions, verify the recycled handle has the same slot bits but a different value, then fire the stale cancel and assert the new resting order is untouched.</p><p>If you’ve done graphics or game-engine work, you’ll recognize this as a generational arena. It shows up anywhere handles outlive the memory they point at — which is to say, anywhere with a wire between the client and the state.</p><h3>The experiment: theory versus a book that refills</h3><p>The Almgren–Chriss closed form, as implemented in the lab:</p><pre>x(t) = X · sinh(κ(T − t)) / sinh(κT),    κ = √(λσ²/η̃),    η̃ = η − γτ/2</pre><p>Risk aversion λ and volatility σ enter only through the product λσ² — doubling volatility is identical to quadrupling risk aversion, which is asserted as a test, not left as a remark. And as κ → 0 the sinh ratio degenerates to (T − t)/T: TWAP isn’t a heuristic, it’s the risk-neutral solution.</p><p>The model’s impact term is linear in the trading rate and has no memory. That’s the assumption I wanted to stress. So the simulator builds a book with exponentially decaying depth away from the mid, refills each swept level toward its target at a fixed resilience fraction per step, and lets fair value follow an arithmetic random walk. Impact isn’t assumed — it <em>happens</em>, when a child order eats the levels that were there.</p><p>Then: 12,000 shares, 12 slices, 100 Monte Carlo paths per schedule, sweeping λ from 0 (TWAP) through 20, plus “immediate” — the whole order as one sweep.</p><h3>The result: half the theory survives exactly</h3><p>λ first slice mean shortfall (bps) stdev (bps) 0 (TWAP) 8.3% 36.65 3.94 0.5 12.6% 36.71 3.43 1 16.0% 38.74 3.08 2 21.1% 43.91 2.70 5 31.0% 45.23 2.21 20 51.8% 44.64 1.64 immediate 100% 42.56 0.00</p><p><strong>The variance half holds without qualification.</strong> The standard deviation of shortfall falls monotonically in λ — 3.94 bps at TWAP down to 1.64 at λ = 20 and exactly zero for immediate execution. Hold less inventory for less time, take less of the random walk. The simulation agrees with the derivation completely.</p><p><strong>The cost half breaks.</strong> The theory says expected cost rises smoothly as you trade faster, with immediate execution as the expensive endpoint. The book disagrees: past λ ≈ 1, the front-loaded schedules cost <em>more than trading everything at once</em>. λ = 5 pays 45.23 bps; the single sweep pays 42.56.</p><p>The model cannot express this outcome. Its impact is linear in rate and memoryless, so a fast schedule is costly but can never be worse than one sweep. A resilient book has memory: a front-loaded schedule keeps returning to levels that have only partly refilled, paying a degraded book several times over, while the single sweep pays a full book exactly once. Between λ = 1 and λ = 20 you&#39;re in the worst of both worlds — impatient enough to keep hitting a wounded book, patient enough to do it repeatedly.</p><p>The efficient frontier is still a shape worth reasoning about. It stops being a price the moment the book is allowed to remember you.</p><h3>The calibration has the same disease</h3><p>There&#39;s a companion result that pins down <em>why</em>. The standard way to calibrate the model&#39;s temporary-impact coefficient η is from the empirical square-root law — cost scales with √(order size / daily volume). Equating the linear model&#39;s cost at constant rate with the square-root law&#39;s gives η = Y·σ·T / √(X·V). Substitute back, and the calibrated total cost comes out <strong>independent of the horizon T</strong>.</p><p>Every trader knows working an order more slowly is cheaper. The calibration cannot say so — because the square-root law, as usually quoted, prices a metaorder by its size relative to daily volume and contains no horizon at all. I pinned this with a test rather than leaving it to be rediscovered, because it looks like a bug until you trace the algebra and realize it&#39;s a property.</p><h3>What I&#39;d want you to take away</h3><p>Not &quot;Almgren–Chriss is wrong.&quot; It&#39;s a quadratic program with a beautiful closed form, and the risk half of it survived a hostile simulation exactly as derived. The takeaway is narrower and more useful: <strong>the model&#39;s cost ranking is only as good as its impact term, and a memoryless linear impact term misranks schedules against any book that replenishes at a finite rate.</strong> If your execution logic trusts the formula&#39;s ordering near the aggressive end of the frontier, you&#39;re trusting the one assumption the market most visibly violates.</p><p>And on the engineering side: if your system hands out ids for things that get recycled, tag them with a generation. The race you&#39;re preventing is not exotic — it&#39;s a cancel and a fill crossing on the wire, the single most common race in live trading.</p><p>The whole thing runs in the browser — the book, the benchmark, the Monte Carlo — at <a href="https://orderbook-lab.vercel.app/">orderbook-lab.vercel.app</a>, and the code, including the differential tests and the slot-recycle test, is at <a href="https://github.com/shashvat-singham/orderbook-lab">github.com/shashvat-singham/orderbook-lab</a>.</p><p>The theory told me slower is cheaper. The book told me it depends who remembers you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d353a4ffa866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Auction That Never Sorts]]></title>
            <link>https://medium.com/@shashvatsingham2001/the-auction-that-never-sorts-79220fb4e7f2?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/79220fb4e7f2</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 08:23:40 GMT</pubDate>
            <atom:updated>2026-08-17T08:23:40.292Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How a uniform clearing price kills the value of being first, how two Fenwick-tree queries settle a whole order book in O(log n), and why my Vercel serverless route runs a real EVM on every request.</em></p><p>There is a settlement function at the heart of my on-chain batch auction, <a href="https://batch-auction.vercel.app/">Batch Auction</a>, that finds the market-clearing price of an arbitrary order book without ever looking at more than two numbers. It doesn’t sort the bids. It doesn’t loop over them. It costs the same gas whether four bids arrived or forty — 77,238, measured on a real EVM, in both cases.</p><p>This post is about the design that makes that possible, and about the strangest piece of plumbing in the project: an entire throwaway Ethereum that boots inside a Vercel serverless function so the website can prove its charts against the compiled Solidity instead of against its own arithmetic.</p><h3>The problem: being first is worth money</h3><p>A continuous market — an order book, an AMM, anything that fills trades as they arrive — fills whoever gets there first, at whatever price they named. That makes the <em>right to be first</em> a sellable asset, and someone will always pay a block builder for it. Every sandwich attack, every back-run, every priority-gas auction is that right being sold.</p><p>A batch auction removes the asset instead of policing the sale. Bids are collected for a window, and every bid settles at a single uniform clearing price. Where your transaction sits inside the block — first, last, sandwiched between two searchers — changes nothing about what you pay. There is no first place, so there is nothing to buy.</p><p>My TypeScript engine keeps a sequential-fill simulator around purely as the control for this claim: reorder the bids and the sequential fill changes — earlier bids eat the supply at their own limit price, which is exactly the advantage a searcher pays for. Reorder the bids and the batch settlement returns the identical result.</p><p>So why isn’t every on-chain market a batch auction? Settlement cost. Finding the clearing price naively means sorting the book — O(n log n), unbounded in gas, and a denial-of-service surface the moment the book gets large. Most implementations respond by moving settlement off-chain to a solver and asking you to trust it.</p><h3>Verify, don’t compute</h3><p>The trick is that the contract never needs to <em>find</em> the clearing price. It only needs to <em>check</em> one.</p><p>Write D(t) for the total quantity bid at or above tick t. Raising the price can only lose bids, so D is non-increasing in t. The clearing tick is the highest price the book still covers, and because demand is monotone, exactly two facts pin it down:</p><pre>D(t)   &gt;= supply     this tick is covered<br>D(t+1) &lt;  supply     and nothing above it is</pre><p>Any proposed tick that fails either check is wrong; any tick that passes both is <em>the</em> answer, because a monotone function crosses a threshold exactly once. Verification here is not a weaker substitute for computing the answer — it is the same answer, reached for a fraction of the gas.</p><p>That single observation restructures the whole protocol. A solver (anyone — a bot, the seller, the website) computes the clearing tick off-chain, where compute is free, and proposes it. The contract runs the two checks:</p><pre>uint256 above = demandAtOrAbove(proposedTick);<br>uint256 aboveNext = proposedTick == maxTick ? 0 : demandAtOrAbove(proposedTick + 1);<br><br>// Too low: some higher tick also clears the supply.<br>if (aboveNext &gt;= supply) revert BadTick();<br>// Too high: this tick is not covered, and only the reserve may clear uncovered.<br>if (above &lt; supply &amp;&amp; proposedTick != reserveTick) revert BadTick();</pre><p>A wrong proposal cannot be accepted, so the solver needs no permission and deserves no trust. settle() is callable by anybody, and only the true clearing tick goes through. The fuzz suite leans on this hard: it builds random books, walks the entire price grid the slow way to find the true tick, demands the contract agree — and then proposes random <em>wrong</em> ticks and requires every single one to revert.</p><h3>The Fenwick tree makes the checks cheap</h3><p>The two checks are prefix sums over the price grid — “how much quantity sits at or above tick t?” A plain array of per-tick totals answers that in O(n), which defeats the point. A Fenwick tree (binary indexed tree) answers it in O(log n), with one SLOAD per set bit in the index. The whole library is about thirty lines:</p><pre>function add(mapping(uint256 =&gt; uint256) storage tree, uint256 size, uint256 tick, uint256 delta) internal {<br>    require(tick &gt;= 1 &amp;&amp; tick &lt;= size, &quot;FW: tick&quot;);<br>    unchecked {<br>        for (uint256 i = tick; i &lt;= size; i += i &amp; (~i + 1)) {<br>            tree[i] += delta;<br>        }<br>    }<br>}</pre><p>Two details matter on-chain. First, the tree lives in a storage <em>mapping</em>, not an array, so it is sparse by construction: only the O(log n) nodes on a bid’s update path are ever written, and declaring a grid of a million ticks costs nothing. Second, each bid() pays the O(log n) insertion cost itself, spread across the people creating the work — settlement inherits a pre-aggregated book for free.</p><p>There is also a read-side bonus. The solver doesn’t have to page the whole book over RPC to find the tick to propose: previewClearingTick() descends the Fenwick tree from the top, taking the largest jump whose cumulative demand still leaves the supply covered — O(log n) again, one cheap eth_call.</p><p>The result is the number I opened with. The test suite deploys two auctions, puts 4 bids in one and a much fatter book in the other, and measures settle() on both. Four bids: 77,238 gas. Forty bids: 77,238 gas. Not &quot;roughly flat&quot; — the same number, because the settlement path touches the tree and a handful of storage slots, and the tree&#39;s depth depends on the grid, not the book.</p><p>One Foundry lesson from testing that library: vm.expectRevert cannot catch a require inside a library, because library calls are inlined — there is no deeper call frame to revert out of. I had to wrap the library in a throwaway contract just to test its own guards. File that one away.</p><h3>Escrow makes settlement a pure accounting step</h3><p>A uniform-price auction has a pleasant solvency property if you set it up right. Bidders escrow their full limit cost when they bid. The clearing price can only be at or below a bid’s own limit, and its fill can only be at or below its own size — so the escrow always covers the bill, and settlement can never discover a shortfall. Escrow and payment go through the <em>same</em> round-up function, so a rounding step can never leave a bid a wei short.</p><p>Bids above the clearing tick fill in full — at the clearing price, never at the price they bid. Bids at the clearing tick share whatever supply the fills above left behind, pro rata by size. Bids below get their escrow back whole. An invariant suite drives bids, settlement, claims and withdrawals in random order across 128,000 calls and re-weighs both token balances after every single one. Money is conserved or the run fails.</p><h3>The website runs the actual bytecode</h3><p>Here is my favorite part. The interface needs to price a book on every keystroke, so there is a second implementation of the clearing rules in TypeScript. Two implementations of one set of rules is a classic bug factory — I learned that lesson painfully on my last project — so the question is how to hold them together.</p><p>The answer this time: don’t mock anything. Load the exact runtime bytecode forge build produced into @ethereumjs/evm, an EVM interpreter that runs in-process in Node, and play the entire auction against it — deploy, fund, bid, settle, claim, withdraw. No testnet, no faucet, no deployed address, no wallet:</p><pre>const result = await evm.runCall({<br>  caller, to,<br>  data: hexToBytes(calldata),<br>  gasLimit: 60_000_000n,<br>  block: blockAt(settleTime) // a header stub — moves block.timestamp past the window<br>});</pre><p>That block parameter is the quiet workhorse: settle() refuses to run while bidding is open, and there is no vm.warp outside Foundry — but a stubbed header with a chosen timestamp moves block.timestamp wherever the scenario needs it.</p><p>The vitest suite replays random books through this sandbox and holds the TypeScript engine to <strong>wei-exact</strong> agreement with the contract — every fill, every payment, every refund. Not “close”, not screenshot-similar. Exact. It’s the same discipline the contract’s own arithmetic gets: two independent implementations, held to agreement rather than to vibes.</p><p>And then the trick escalates: the same sandbox <em>is</em> the live demo. The page at batch-auction.vercel.app has an “Execute the bytecode” button that POSTs the book to a Next.js API route, and the route boots a fresh EVM inside the request, runs the compiled contract, and reports the gas the interpreter actually charged. Two production notes if you try this. The @ethereumjs/* packages ship ESM with their own wasm and crypto shims, and letting Next bundle them into the serverless function is where that goes wrong — they must be listed in serverExternalPackages. And an EVM is cheap but not free, so the route caps the book at 60 bids, because the endpoint is open to the internet.</p><h3>What I’m not claiming</h3><p>Honesty section, because auction designs attract overclaiming.</p><p><strong>Bids are not sealed.</strong> A batch removes the value of being <em>first</em>, not the value of <em>seeing</em> the book — the window is public while open, so a late bidder can price against what’s already there. Commit–reveal would close that, at the cost of a second transaction per bid and a griefing surface when reveals are withheld. It is not implemented.</p><p><strong>Pro-rata flooring leaves dust.</strong> At most one wei of base per bid resting on the marginal tick stays in the contract forever. The alternative — letting the seller sweep it — creates a path where the seller can move base an unclaimed bidder is still owed. The dust stays.</p><p><strong>No audit.</strong> Fuzzed and invariant-tested, not audited.</p><h3>Where to poke at it</h3><p>The demo is live at <a href="https://batch-auction.vercel.app/">batch-auction.vercel.app</a> — set a book, drag the supply, press <em>Execute the bytecode</em> and watch a real EVM settle it inside the request. The code — the contract, the Fenwick tree, the fuzz and invariant suites, and the TypeScript-vs-bytecode differential tests — is public at <a href="https://github.com/shashvat-singham/batch-auction">github.com/shashvat-singham/batch-auction</a>.</p><p>The cheapest computation, it turns out, is the one you only have to check.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79220fb4e7f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Smart Contract I Never Deployed]]></title>
            <link>https://medium.com/@shashvatsingham2001/the-smart-contract-i-never-deployed-9341e7aa7cc1?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9341e7aa7cc1</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 08:02:03 GMT</pubDate>
            <atom:updated>2026-08-17T08:02:03.399Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How an </em><em>eth_call state override let one Solidity file read Uniswap v3 across three chains — with no gas, no private key, and nothing on-chain to maintain.</em></p><p>There is a contract at the heart of my Uniswap v3 analytics dashboard, <a href="https://onchain-lens.vercel.app/">Onchain Lens</a>, that has never existed on any blockchain. It has no address you can look up on Etherscan, no deployment transaction, no verified source page. And yet it runs against Ethereum mainnet, Base, and Arbitrum on every page load.</p><p>This post is about the trick that makes that possible — and about the three bugs it took to make it production-safe, one of which involves a precompile from 2015 silently answering a Uniswap function call.</p><h3>The problem: reading a pool is a dozen round trips</h3><p>Reading the state of a single Uniswap v3 pool honestly takes a lot of calls: token0() and token1(), then each token&#39;s symbol() and decimals(), then fee(), tickSpacing(), liquidity(), slot0() for the current price and tick, and an observe() for the TWAP. That&#39;s roughly a dozen round trips per pool, and a dashboard wants a dozen pools.</p><p>The standard answer is Multicall3: batch the calls into one request. But Multicall batches the <em>calls</em>, not the <em>logic</em>. You still stitch the results together off-chain, and you still special-case every token that answers symbol() wrongly (more on that later). What I actually wanted was a single function:</p><pre>function snapshot(address[] calldata pools, uint32 twapWindow)<br>    external view returns (PoolSnapshot[] memory);</pre><p>…where PoolSnapshot carries everything — tokens, decimals, symbols, fee, tick, price, liquidity, TWAP — already assembled. That function has to live in a contract. And deploying a contract means gas, a funded key, an audit trail, and doing it three times because I support three chains, then keeping all three deployments in sync forever.</p><p>Unless you never deploy it.</p><h3>The trick: eth_call state overrides</h3><p>eth_call — the JSON-RPC method behind every read-only contract call — accepts an optional third parameter that most people never touch: a <strong>state override set</strong>. It lets the caller say to the node: <em>&quot;before you run this call, pretend the state looked like this.&quot;</em> You can override an account&#39;s balance, its storage… or its <strong>code</strong>.</p><p>So the flow becomes:</p><ol><li>Compile PoolLens.sol locally. Keep the deployed bytecode as a build artifact.</li><li>Pick a throwaway address — I use 0x…dEaD, which has no code, keys, or history on any chain.</li><li>Send one eth_call: <em>to</em> that address, with the pool-reading calldata, and a state override that injects the lens bytecode at that address.</li><li>The node runs the contract in a disposable copy of state, returns the fully-stitched answer, and throws the whole thing away.</li></ol><p>With <a href="https://viem.sh/">viem</a> this is almost embarrassingly small:</p><pre>const { data } = await client.call({<br>  to: LENS_ADDRESS, // 0x…dEaD — a sentinel, not a deployment<br>  data: encodeFunctionData({ abi: LENS_ABI, functionName, args }),<br>  stateOverride: [{ address: LENS_ADDRESS, code: LENS_CODE }],<br>});</pre><p>A dozen storage reads plus all the assembly logic collapse into <strong>one round trip</strong>. There is no deployment to fund, verify, or upgrade. And because the bytecode travels with the request, the <em>same artifact</em> runs unchanged against Ethereum, Base, and Arbitrum. A read-only analytics surface could not ask for a better shape.</p><p>One practical caveat: not every RPC endpoint supports state overrides. In my testing, publicnode.com and 1rpc.io handle them fine; some other popular public endpoints either refuse the parameter without an API key or fall over entirely. If you try this, test your fallback list — an endpoint that ignores the override will call empty code and return nothing.</p><h3>Bug #1: the precompile that answered a Uniswap call</h3><p>Here is the bug that taught me the most, and it’s the reason I’d call this pattern <em>deceptively</em> simple.</p><p>My snapshot() takes arbitrary pool addresses. Early on, a bad address found its way into a batch: 0x…0001. On Ethereum, that is not a dead address — it is the <strong>ecrecover precompile</strong>, part of the protocol since genesis. And precompiles have a fun property: they don&#39;t check what function you&#39;re calling. Call slot0() on ecrecover and it <em>succeeds</em> — returning zero bytes.</p><p>My code did what most Solidity code does:</p><pre>try IUniswapV3Pool(pool).slot0() returns (...) { ... } catch { ... }</pre><p>And here is the thing almost nobody internalizes about try/catch in Solidity: <strong>it only catches reverts. It does not catch a failure to decode the return data.</strong> The call to the precompile succeeded, the ABI decoder tried to read seven words out of zero bytes, and the resulting revert was uncatchable — it took down not just that entry but the <em>entire batch</em>. One garbage address, twelve dead pools on the dashboard.</p><p>The fix is to never let the decoder touch unmeasured bytes. Every external read in the lens is now a low-level staticcall whose returndata length is checked <em>before</em> anything is decoded:</p><pre>(bool success, bytes memory ret) = target.staticcall(data);<br>if (!success || ret.length &lt; n * 32) return (false, words);</pre><p>slot0() returns seven values, so a real v3 pool must answer with at least seven words. A precompile or an unrelated contract won&#39;t. With the length check, the ecrecover incident becomes a single ok = false row and the rest of the batch survives — which is the only acceptable failure mode when one dead pool must not kill the dashboard.</p><h3>Bug #2: tokens that lie about their own symbols</h3><p>symbol() and decimals() are conventions, not guarantees. The ERC-20 standard technically marks them optional, and the wild is full of tokens that interpret them creatively:</p><ul><li><strong>MKR</strong> returns its symbol as a bytes32, not a string — 32 bytes of right-padded text instead of ABI-encoded offset/length/data.</li><li>Arbitrum’s bridged USDT answers USD₮0 — multi-byte UTF-8 inside the string.</li><li>Some tokens omit the functions entirely.</li></ul><p>The lens decodes symbols by hand: a 32-byte answer is treated as padded text, a well-formed ABI string (≥ 96 bytes) is bounds-checked and copied, and anything else becomes &quot;?&quot;. A token that hides its decimals() gets the ERC-20 default of 18, and anything claiming more than 36 decimals is treated as noise. A weird token gets a placeholder; it never gets to take the snapshot down.</p><h3>Bug #3: “Stack too deep,” the rite of passage</h3><p>One pool&#39;s snapshot needs a lot of live values at once: the reads, their ok flags, and the struct being assembled. Inlined into the batch loop, that blew past the EVM&#39;s sixteen stack slots and the compiler refused with Solidity&#39;s most famous error. Splitting the single-pool logic into its own snapshotOne() function gave it a fresh frame and the problem vanished. Old advice, still true.</p><h3>Keeping the on-chain and off-chain math honest</h3><p>The dashboard also simulates concentrated-liquidity positions, which means the position math (sqrtRatioAtTick, amounts-for-liquidity) exists twice: once in Solidity for the lens, once in TypeScript for the frontend. Two implementations of the same math is a bug factory, so the test suite runs both against live pools and holds them to <strong>wei-exact agreement</strong> — 14 differential tests, and it was this suite that caught both the precompile bug and a nasty unit-convention bug in how I was denominating position sizes.</p><p>That second one deserves a sentence, because it&#39;s a good trap: a v3 pool&#39;s token1 is just whichever token sorted higher <em>by address</em>. On the deepest pool on Ethereum, that happens to be WETH — so a &quot;default position size of 100,000&quot; quietly meant 100,000 <em>ether</em>, roughly five times the pool&#39;s entire liquidity. Everything is now denominated in the token the pair is actually quoted in. Sorting pools by their raw liquidity value has the same flavor of wrongness (it&#39;s denominated in √(token0·token1) at the pool&#39;s own decimals, so it isn&#39;t comparable across pairs), and the fix was the same: stop trusting fields that look comparable but aren&#39;t.</p><h3>When you should (and shouldn&#39;t) do this</h3><p>State-override lenses are a great fit when:</p><ul><li>the logic is <strong>read-only</strong> — you&#39;re aggregating views, not changing state;</li><li>you want <strong>one artifact across many chains</strong> with zero deployment ops;</li><li>the inputs are <strong>untrusted</strong> and you&#39;re willing to write defensive staticcall-and-measure code.</li></ul><p>They are the wrong tool when other contracts need to call your logic on-chain, when you need events, or when your RPC layer can&#39;t guarantee override support.</p><p>But for an analytics surface, the economics are hard to argue with: no gas, no keys, no verification, no upgrade path to maintain — and the contract can&#39;t be exploited, because there is nothing on-chain to exploit.</p><p>The dashboard is live at <a href="https://onchain-lens.vercel.app/">onchain-lens.vercel.app</a> and the code — the lens, the viem plumbing, and the differential test suite — is public at <a href="https://github.com/shashvat-singham/onchain-lens">github.com/shashvat-singham/onchain-lens</a>.</p><p>The best contract, it turns out, is sometimes the one you never deploy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9341e7aa7cc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Trading Bot Lost 16%. Publishing That Is the Result.]]></title>
            <link>https://medium.com/@shashvatsingham2001/my-trading-bot-lost-16-publishing-that-is-the-result-918a598005a2?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/918a598005a2</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 19:28:35 GMT</pubDate>
            <atom:updated>2026-08-14T19:28:35.326Z</atom:updated>
            <content:encoded><![CDATA[<h3>What a real negative result looks like — matched random-walk nulls, information coefficients, and the fee arithmetic that decides everything before your model does</h3><p>Most quant write-ups have the same shape. Someone describes a signal, shows an equity curve that goes up and to the right, and stops. The interesting question — <em>would this have survived an honest test?</em> — never gets asked, because asking it usually kills the article.</p><p>So here is the other kind of post. I built a full trading system for Delta Exchange India perpetuals: about 4,600 lines of Python, four independent signal families, a backtest engine, 43 passing tests on the estimators. Then I measured it against the only benchmark that matters, and it failed.</p><p>Here are the two numbers that matter, from the run artifacts rather than from memory:</p><pre>dev      return -15.56%  fees $764  trades 9,632  hit 45.1%  PF 0.908  Sharpe -2.01<br>holdout  return -16.11%  fees $804  trades 6,868  hit 45.0%  PF 0.902  Sharpe -2.45</pre><p>Two windows, fitted and tested separately, losing at almost exactly the same rate.</p><p>That similarity is the most informative thing in the chart.</p><p>Overfitting looks like a great development curve and a bad holdout one. This is a strategy that is <em>reliably</em> bad, which points at something structural.</p><p>This failure reproduces with one command, and it was far more useful to me than a curve that goes up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=918a598005a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Markov Chain Monte Carlo (MCMC): Unveiling the Magic of Sampling Complex Distributions]]></title>
            <link>https://medium.com/@shashvatsingham2001/markov-chain-monte-carlo-mcmc-unveiling-the-magic-of-sampling-complex-distributions-7ab9c7d176c5?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab9c7d176c5</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 17:00:04 GMT</pubDate>
            <atom:updated>2023-09-12T17:00:04.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monte Carlo Simulations: Predicting the Future with Randomness</h3><p><em>Exploring the Power of Monte Carlo Methods in Numerical Simulation</em></p><h3>Introduction</h3><p>In the world of computational physics, there’s a powerful tool that stands out for its ability to predict complex outcomes by embracing randomness: Monte Carlo simulations. Named after the iconic Monte Carlo Casino in Monaco, these simulations have become indispensable in fields as diverse as physics, finance, engineering, and more. In this 3000-word blog post, we will embark on a journey to understand the core concepts, applications, and practical implementation of Monte Carlo simulations using Python.</p><h3>Table of Contents</h3><ol><li><strong>Understanding Monte Carlo Simulations</strong></li></ol><ul><li>1.1 What Are Monte Carlo Simulations?</li><li>1.2 Why Use Monte Carlo Simulations?</li><li>1.3 The Mathematics Behind Monte Carlo</li></ul><p>2. <strong>Applications of Monte Carlo Simulations</strong></p><ul><li>2.1 Estimating π (Pi) with Randomness</li><li>2.2 Simulating the Ising Model in Statistical Mechanics</li><li>2.3 Monte Carlo Methods in Finance</li></ul><p>3. <strong>Implementing Monte Carlo Simulations in Python</strong></p><ul><li>3.1 Random Number Generation</li><li>3.2 Estimating π Using Monte Carlo</li><li>3.3 Simulating the Ising Model</li><li>3.4 Monte Carlo Option Pricing</li></ul><p>4. <strong>Advanced Techniques and Considerations</strong></p><ul><li>4.1 Markov Chain Monte Carlo (MCMC)</li><li>4.2 Importance Sampling</li><li>4.3 Parallelizing Monte Carlo Simulations</li></ul><p>5. <strong>Challenges and Limitations</strong></p><ul><li>5.1 Sources of Error</li><li>5.2 Convergence Issues</li><li>5.3 High-Dimensional Problems</li></ul><p>6.<strong> Conclusion</strong></p><ul><li>6.1 Recap of Key Takeaways</li><li>6.2 The Ongoing Impact of Monte Carlo Simulations</li></ul><h3>1. Understanding Monte Carlo Simulations</h3><h3>1.1 What Are Monte Carlo Simulations?</h3><p>Monte Carlo simulations are a computational technique used to estimate complex quantities through random sampling. They are particularly valuable when analytical solutions are challenging or impossible to obtain. At the heart of Monte Carlo simulations is the idea of using randomness to explore the solution space of a problem.</p><p>The core concept behind Monte Carlo simulations is random sampling. By generating a large number of random samples from a known probability distribution, we can approximate the behavior of a system or estimate quantities of interest.</p><h3>1.2 Why Use Monte Carlo Simulations?</h3><p>Monte Carlo simulations offer several advantages, including their ability to handle:</p><ul><li>Complex Systems: Monte Carlo simulations can model intricate systems with many variables and interactions.</li><li>Uncertainty: They are ideal for problems involving uncertainty and probabilistic outcomes.</li><li>Integration and Optimization: Monte Carlo methods are used for numerical integration and optimization tasks.</li><li>Parallelization: These simulations can be parallelized to leverage modern computing resources effectively.</li></ul><h3>1.3 The Mathematics Behind Monte Carlo</h3><p>Monte Carlo simulations rely on mathematical principles to estimate quantities. A fundamental concept is the Law of Large Numbers, which states that as the number of random samples increases, the sample mean converges to the true mean. This forms the basis for many Monte Carlo algorithms.</p><p>The Monte Carlo Estimation formula is a key equation used in these simulations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*Le2Ni9J9KQ9Ag4LXLwr7zA.png" /></figure><p>Where:</p><ul><li><em>I</em> is the estimated quantity.</li><li><em>N</em> is the number of random samples.</li><li><em>f</em>(<em>xi</em>​) is the function to be evaluated for each sample <em>xi</em>​.</li></ul><p>Next, we’ll explore practical applications of Monte Carlo simulations.</p><h3>2. Applications of Monte Carlo Simulations</h3><h3>2.1 Estimating π (Pi) with Randomness</h3><p>One of the most famous applications of Monte Carlo simulations is estimating the value of π (pi). This is achieved by simulating random points within a unit square and counting the fraction of points that fall inside a quarter-circle inscribed within the square.</p><p>Let’s implement this estimation in Python:</p><pre>import numpy as np<br><br># Number of random points<br>N = 10000<br><br># Generate random points within the unit square<br>x = np.random.uniform(0, 1, N)<br>y = np.random.uniform(0, 1, N)<br><br># Calculate the distance from the origin for each point<br>distance = np.sqrt(x**2 + y**2)<br><br># Count the points inside the unit circle<br>inside_circle = np.sum(distance &lt;= 1)<br><br># Estimate pi<br>pi_estimate = 4 * inside_circle / N<br><br>print(&quot;Monte Carlo estimate of pi:&quot;, pi_estimate)</pre><p>This simulation effectively approximates π using randomness.</p><h3>2.2 Simulating the Ising Model in Statistical Mechanics</h3><p>Monte Carlo simulations are widely used in statistical mechanics to simulate the behavior of physical systems. The Ising model, which describes the behavior of magnetic spins, is a classic example. By randomly flipping spins according to a probabilistic rule, we can simulate phase transitions in materials.</p><p>Let’s outline the Ising model simulation in Python:</p><pre>import numpy as np<br><br># Initialize a 2D grid of spins<br>L = 10  # Grid size<br>spins = np.random.choice([-1, 1], size=(L, L))<br><br># Define parameters (e.g., temperature)<br>T = 2.0<br><br># Perform Metropolis-Hastings updates<br>for _ in range(N):<br>    i, j = np.random.randint(0, L, 2)  # Randomly select a spin<br>    dE = 2 * spins[i, j] * (spins[(i+1)%L, j] + spins[(i-1)%L, j] + spins[i, (j+1)%L] + spins[i, (j-1)%L])<br>    if dE &lt; 0 or np.random.rand() &lt; np.exp(-dE / T):<br>        spins[i, j] *= -1  # Flip the spin<br><br># Analyze the resulting spin configuration</pre><p>This code outlines the simulation of the Ising model using the Metropolis-Hastings algorithm.</p><h3>2.3 Monte Carlo Methods in Finance</h3><p>Monte Carlo simulations are indispensable in financial modeling and risk assessment. They are used to simulate the behavior of financial instruments, price options, and estimate portfolio risk.</p><p>For instance, Monte Carlo simulations can be used to simulate the future price of a stock under different scenarios, helping investors make informed decisions.</p><p>In the next section, we’ll dive into the practical implementation of Monte Carlo simulations in Python.</p><h3>3. Implementing Monte Carlo Simulations in Python</h3><h3>3.1 Random Number Generation</h3><p>Random number generation is a fundamental aspect of Monte Carlo simulations. In Python, the numpy library provides efficient functions for generating random numbers.</p><pre>import numpy as np<br><br># Generate a random float between 0 and 1<br>random_float = np.random.rand()<br><br># Generate a random integer between 1 and 10<br>random_int = np.random.randint(1, 11)<br><br># Generate an array of random floats<br>random_array = np.random.uniform(0, 1, size=10)<br><br># Generate random samples from a normal distribution<br>mean = 0<br>std_dev = 1<br>random_samples = np.random.normal(mean, std_dev, size=1000)</pre><p>These functions allow you to create random samples necessary for Monte Carlo simulations.</p><h3>3.2 Estimating π Using Monte Carlo</h3><p>We’ve previously seen how to estimate π using Monte Carlo simulations. Here’s the Python code again:</p><pre>import numpy as np<br><br># Number of random points<br>N = 10000<br><br># Generate random points within the unit square<br>x = np.random.uniform(0, 1, N)<br>y = np.random.uniform(0, 1, N)<br><br># Calculate the distance from the origin for each point<br>distance = np.sqrt(x**2 + y**2)<br><br># Count the points inside the unit circle<br>inside_circle = np.sum(distance &lt;= 1)<br><br># Estimate pi<br>pi_estimate = 4 * inside_circle / N<br><br>print(&quot;Monte Carlo estimate of pi:&quot;, pi_estimate)</pre><p>This code demonstrates how randomness can be used to approximate π.</p><h3>3.3 Simulating the Ising Model</h3><p>Continuing from the previous Ising model example, we can further elaborate on the simulation in Python:</p><pre>import numpy as np<br><br># Initialize a 2D grid of spins<br>L = 10  # Grid size<br>spins = np.random.choice([-1, 1], size=(L, L))<br><br># Define parameters (e.g., temperature)<br>T = 2.0<br><br># Perform Metropolis-Hastings updates<br>for _ in range(N):<br>    i, j = np.random.randint(0, L, 2)  # Randomly select a spin<br>    dE = 2 * spins[i, j] * (spins[(i+1)%L, j] + spins[(i-1)%L, j] + spins[i, (j+1)%L] + spins[i, (j-1)%L])<br>    if dE &lt; 0 or np.random.rand() &lt; np.exp(-dE / T):<br>        spins[i, j] *= -1  # Flip the spin<br><br># Analyze the resulting spin configuration</pre><p>This Python code outlines the simulation of the Ising model using Monte Carlo methods.</p><h3>3.4 Monte Carlo Option Pricing</h3><p>Monte Carlo simulations are widely used in finance for option pricing. Let’s outline a basic Monte Carlo option pricing model in Python:</p><pre>import numpy as np<br><br># Define parameters<br>S0 = 100  # Initial stock price<br>K = 110   # Strike price<br>r = 0.05  # Risk-free interest rate<br>sigma = 0.2  # Volatility<br>T = 1.0   # Time to maturity<br>N = 10000 # Number of simulations<br><br># Generate random samples from a normal distribution<br>z = np.random.normal(0, 1, N)<br><br># Calculate the stock price at maturity<br>ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * z)<br><br># Calculate the option payoff<br>payoff = np.maximum(ST - K, 0)<br><br># Estimate the option price<br>option_price = np.exp(-r * T) * np.mean(payoff)<br><br>print(&quot;Monte Carlo estimate of option price:&quot;, option_price)</pre><p>This code outlines a Monte Carlo simulation for option pricing.</p><h3>4. Advanced Techniques and Considerations</h3><h3>4.1 Markov Chain Monte Carlo (MCMC)</h3><p>Markov Chain Monte Carlo (MCMC) is an advanced technique that extends the power of Monte Carlo simulations. It is particularly useful for sampling complex probability distributions. One of the most well-known MCMC algorithms is the Metropolis-Hastings algorithm, which we used in the Ising model simulation.</p><h3>4.2 Importance Sampling</h3><p>Importance sampling is a variance reduction technique used to improve the efficiency of Monte Carlo simulations. It involves sampling from a different, more suitable probability distribution to reduce the variance of estimates.</p><h3>4.3 Parallelizing Monte Carlo Simulations</h3><p>Monte Carlo simulations can be computationally intensive, especially for large-scale problems. Parallelization techniques, such as using multi-core processors or distributed computing, can significantly speed up simulations.</p><h3>5. Challenges and Limitations</h3><h3>5.1 Sources of Error</h3><p>Monte Carlo simulations are subject to various sources of error, including statistical error due to finite sample sizes and systematic error due to modeling assumptions.</p><h3>5.2 Convergence Issues</h3><p>In some cases, Monte Carlo simulations may converge slowly, requiring a large number of samples for accurate estimates. Techniques like stratified sampling can help improve convergence.</p><h3>5.3 High-Dimensional Problems</h3><p>Simulating high-dimensional systems can be challenging due to the “curse of dimensionality.” More advanced techniques, such as Markov Chain Monte Carlo (MCMC), are often required for such problems.</p><h3>6. Conclusion</h3><h3>6.1 Recap of Key Takeaways</h3><p>Monte Carlo simulations are a versatile and powerful tool in computational physics and beyond. They harness randomness to estimate complex quantities, model systems, and make predictions in various fields.</p><h3>6.2 The Ongoing Impact of Monte Carlo Simulations</h3><p>As computational resources continue to advance, Monte Carlo simulations are poised to play an even more significant role in scientific research, engineering, finance, and beyond. The ability to predict the future with randomness has profound implications for understanding complex systems and making informed decisions.</p><p>In this blog post, we’ve covered the fundamental concepts, practical applications, and Python implementation of Monte Carlo simulations. Armed with this knowledge, you can explore and apply Monte Carlo methods in your own research and projects, unlocking the power of randomness to predict the future.</p><p>Stay curious, keep experimenting, and embrace the power of Monte Carlo simulations in your computational journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab9c7d176c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Entanglement, Quantum Field Theory, and Their Computational Implications]]></title>
            <link>https://medium.com/@shashvatsingham2001/quantum-entanglement-quantum-field-theory-and-their-computational-implications-507f675de220?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/507f675de220</guid>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 14:51:52 GMT</pubDate>
            <atom:updated>2023-09-10T14:51:52.106Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In the ever-advancing realm of quantum computing and cryptography, two fundamental concepts — quantum entanglement and Quantum Field Theory (QFT) — unite to forge a future of unparalleled computational power and security. Join us on this journey as we explore their practical applications, backed by code and real-world insights.</em></p><h3>The Quantum Dance of Entanglement</h3><p>Quantum entanglement, often referred to as “spooky action at a distance,” lies at the heart of quantum mechanics. To truly grasp its significance in computer science, let’s explore a quantum key distribution example with code.</p><p>Quantum Key Distribution (QKD) with Entanglement: Below is a simplified Python example using Qiskit, IBM’s quantum computing framework, to demonstrate the creation of an entangled quantum key.</p><pre>from qiskit import QuantumCircuit, Aer, execute<br><br># Create an entangled pair of qubits<br>circuit = QuantumCircuit(2, 2)<br>circuit.h(0)  # Apply a Hadamard gate to the first qubit<br>circuit.cx(0, 1)  # Entangle the qubits using a controlled-X (CNOT) gate<br><br># Measure the qubits<br>circuit.measure([0, 1], [0, 1])<br><br># Simulate the circuit<br>simulator = Aer.get_backend(&#39;qasm_simulator&#39;)<br>result = execute(circuit, simulator, shots=1).result()<br>key = int(list(result.get_counts().keys())[0], 2)<br><br>print(f&quot;Generated Quantum Key: {key}&quot;)</pre><p>In this code, we create an entangled pair of qubits and measure them to generate a quantum key. The remarkable aspect is that any eavesdropping attempt will disturb the entanglement, alerting us to potential security breaches.</p><h3>Quantum Field Theory in Quantum Computing</h3><p>Quantum Field Theory, while traditionally associated with particle physics, is a vital component of quantum computing and simulation. Let’s look at a practical example related to quantum simulation.</p><p>Quantum Simulation of Molecular Energies: Quantum computers can simulate the energy levels of molecules, revolutionizing drug discovery and materials science. Below is a simplified Python code using IBM’s Qiskit Aqua to estimate the energy of a molecule.</p><pre>from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver<br>from qiskit.aqua.components.optimizers import SLSQP<br>from qiskit.chemistry import FermionicOperator<br>from qiskit.chemistry.drivers import PySCFDriver<br><br># Define the molecule and driver<br>driver = PySCFDriver(atom=&quot;H .0 .0 .0; H .0 .0 0.74&quot;, unit=UnitsType.ANGSTROM,<br>                     charge=0, spin=0, basis=&#39;sto3g&#39;)<br><br># Generate the second-quantized operators<br>fer_op = FermionicOperator(driver)<br><br># Define the quantum backend and algorithm<br>backend = Aer.get_backend(&#39;statevector_simulator&#39;)<br>optimizer = SLSQP(maxiter=1000)<br>vqe = VQE(fer_op, optimizer)<br><br># Calculate the energy<br>result = vqe.run(backend)<br>energy = result[&#39;energy&#39;]<br><br>print(f&quot;Estimated Energy: {energy} Hartrees&quot;)</pre><p>In this example, we use Qiskit Aqua to simulate the energy levels of a hydrogen molecule. Quantum computers enable us to perform such simulations much faster than classical computers, opening doors to breakthroughs in chemistry and material science.</p><h3>The Quantum Future Beckons</h3><p>As we delve deeper into the 21st century, the marriage of quantum entanglement and QFT illuminates a path toward computing and cryptography advancements hitherto unimagined. Quantum key distribution and molecular simulations are just the tip of the quantum iceberg.</p><p><em>In this quantum revolution, where code melds with quantum reality, computer scientists stand at the threshold of a future where classical constraints fade into the quantum unknown.</em></p><p><em>Embrace the quantum wave; the journey is bound to be both exhilarating and transformative.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=507f675de220" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Cryptography: Secure Communication with Unbreakable Codes]]></title>
            <link>https://medium.com/@shashvatsingham2001/quantum-cryptography-secure-communication-with-unbreakable-codes-650f451c83b4?source=rss-c98c1ad6e24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/650f451c83b4</guid>
            <category><![CDATA[quantum-cryptography]]></category>
            <dc:creator><![CDATA[Shashvat Singham]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 14:38:55 GMT</pubDate>
            <atom:updated>2023-09-10T14:38:55.110Z</atom:updated>
            <content:encoded><![CDATA[<p>In a world where information travels at the speed of light and security breaches are a constant threat, the quest for unbreakable codes has led us to the fascinating realm of quantum cryptography. Welcome to the future of secure communication, where the fundamental principles of quantum mechanics are harnessed to protect our most sensitive data.</p><h3>The Age of Quantum Cryptography</h3><p>In the age of the internet, data security is paramount. From online banking to government communications, the need for encryption methods that can withstand the relentless advance of computing power is more critical than ever. Enter quantum cryptography.</p><h3>The Quantum Advantage</h3><p>At the heart of quantum cryptography is the unique advantage offered by quantum mechanics. Unlike classical computers, which rely on bits that can be either 0 or 1, quantum computers use qubits. These qubits can exist in multiple states simultaneously thanks to a phenomenon known as superposition. This property allows quantum computers to perform certain calculations at exponentially faster rates than their classical counterparts.</p><h3>Quantum Key Distribution (QKD)</h3><p>One of the cornerstones of quantum cryptography is Quantum Key Distribution (QKD). This process uses the properties of quantum particles, such as photons, to create an unbreakable key for encrypting and decrypting messages.</p><p>Here’s how it works, illustrated with Python code:</p><pre># Quantum Key Generation<br>from qiskit import QuantumCircuit, Aer, execute<br><br># Create a quantum circuit<br>qc = QuantumCircuit(1, 1)<br><br># Generate a random key (Alice&#39;s side)<br>qc.h(0)  # Apply a Hadamard gate<br>qc.measure(0, 0)  # Measure the qubit<br><br># Simulate the quantum circuit<br>simulator = Aer.get_backend(&#39;qasm_simulator&#39;)<br>result = execute(qc, simulator, shots=1).result()<br>key_bit = int(list(result.get_counts().keys())[0])<br><br># Key Comparison (Bob&#39;s side)<br>received_key_bit = # Bob receives Alice&#39;s key bit securely<br><br># Check for discrepancies<br>if key_bit == received_key_bit:<br>    print(&quot;Key exchange successful. Secure communication can begin.&quot;)<br>else:<br>    print(&quot;Security compromised. The key exchange has been tampered with.&quot;)</pre><h3>Challenges and Real-World Applications</h3><p>While quantum cryptography holds immense promise, it’s not without challenges. The need for specialized equipment and the vulnerability of qubits to environmental factors are among the hurdles that researchers are working to overcome.</p><p>However, quantum cryptography is already making its mark in various fields:</p><ul><li>Financial Security: Banks and financial institutions are exploring quantum cryptography to protect transactions and sensitive customer data.</li><li>Government Communications: Governments around the world are considering quantum cryptography to safeguard classified information.</li><li>Healthcare: Secure transmission of patient data and medical records is crucial in the healthcare industry.</li></ul><h3>The Future of Quantum Cryptography</h3><p>As quantum computing technology continues to advance, the importance of quantum cryptography will only grow. Researchers are working on developing more practical and robust quantum cryptographic systems, making this exciting field one to watch in the coming years.</p><h3>In Conclusion</h3><p>Quantum cryptography represents a groundbreaking approach to secure communication in an age where data breaches are a constant threat. By leveraging the mysterious properties of quantum mechanics and incorporating the code examples provided, we are on the verge of achieving unbreakable codes and a new era of digital security.</p><p>In the ever-evolving landscape of cybersecurity, quantum cryptography shines as a beacon of hope, promising a future where our most sensitive information remains safe from prying eyes.</p><p><em>Stay tuned for more exciting developments in the world of quantum cryptography as we continue to unravel the mysteries of the quantum realm.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650f451c83b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>