<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dream</title>
    <description>The latest articles on DEV Community by Dream (@quant001).</description>
    <link>https://dev.to/quant001</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3732259%2Fd089f60c-f2a4-4ba4-a84d-6c79ada78de3.png</url>
      <title>DEV Community: Dream</title>
      <link>https://dev.to/quant001</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/quant001"/>
    <language>en</language>
    <item>
      <title>The ANT Spread: Don't Just Wait for Convergence—Trade the Swings</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Thu, 19 Nov 2026 03:29:14 +0000</pubDate>
      <link>https://dev.to/quant001/the-ant-spread-dont-just-wait-for-convergence-trade-the-swings-30pe</link>
      <guid>https://dev.to/quant001/the-ant-spread-dont-just-wait-for-convergence-trade-the-swings-30pe</guid>
      <description>&lt;p&gt;The ANT spread between Binance and trade.xyz has attracted plenty of discussion over the past few days.&lt;/p&gt;

&lt;p&gt;Both Binance and trade.xyz list a pre-IPO contract linked to Anthropic. In the November 2–5 sample discussed here, converting the quotes to a per-share price using an assumed 12.7 billion shares consistently made Binance the more expensive venue. If the final share count and the exchanges' rebasing rules match that assumption, the two quotes could move onto a common share-count basis, allowing us to assess convergence on that basis.&lt;/p&gt;

&lt;p&gt;With the quantities on both venues matched using this assumption, the position is short Binance and long xyz, waiting for the spread to narrow.&lt;/p&gt;

&lt;p&gt;During these live trading sessions, the spread narrowed sharply several times, then widened again. Holding the position throughout would have meant giving back the unrealized gains along the way. I split the position into several paired tranches, reducing one when the spread narrowed and adding it back after the spread widened, to see whether those swings could produce a return.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. What the Spread Did Over Those Few Days
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fonuwxsglbhxodheb3nja.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fonuwxsglbhxodheb3nja.png" alt=" " width="800" height="413"&gt;&lt;/a&gt;&lt;br&gt;
On November 2 and 3, the spread hovered around 20%, reaching a high of 22.2% on the morning of the 3rd.&lt;/p&gt;

&lt;p&gt;Around noon on the 4th, Silicon Bird (@limxn6) published a post about an arbitrage spread “written into the rules.” It broke down the prospectus item by item and estimated that the exchanges would rebase using roughly 12.7 billion shares. The post drew more than 60,000 views.&lt;/p&gt;

&lt;p&gt;That afternoon, the spread fell from 14% to 4% in five hours.&lt;/p&gt;

&lt;p&gt;The decline did not last. The spread rebounded to 7% that evening and was back above 9% by the afternoon of November 5.&lt;/p&gt;

&lt;p&gt;If you had jumped in at 4% late on the 4th, thinking convergence had begun, the spread would have moved 590 bps against you over the next day.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What Else Matters When Holding This Pair
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The share count used for conversion was still uncertain.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The same prospectus supported two different ways of counting:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;12.7 billion: the estimated shares outstanding at the IPO. Exchanges have used an outstanding-share basis for rebasing, including for SpaceX.&lt;/li&gt;
&lt;li&gt;16.6–16.9 billion: a fully diluted estimate, including options, unvested RSUs, and the portion of Amazon's convertible notes above the ownership cap. This estimate was derived from the prospectus. Entropy uses a fully diluted share-count basis after an IPO.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Finkaif2fe029jbem2cfv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Finkaif2fe029jbem2cfv.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;br&gt;
The two estimates differ by roughly 4 billion shares, which changes the relative prices after conversion:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwgownat6ng0pr9dz9gxa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwgownat6ng0pr9dz9gxa.png" alt=" " width="800" height="373"&gt;&lt;/a&gt;&lt;br&gt;
Using prices from the same moment, Binance was 8.6% more expensive under a 12.7 billion-share assumption. At 14 billion shares, Binance was instead 1.5% cheaper.&lt;/p&gt;

&lt;p&gt;The calculations in this historical analysis use 12.7 billion shares. If that number changes, both the relative prices and the matched quantities need to be recalculated. A grid cannot resolve this uncertainty.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Margin must be monitored separately on each venue.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The two legs sit on different exchanges, with separate margin accounts. When the spread widens, the combined position may show only a small loss while one leg is already under pressure. Unrealized gains on the other venue do not automatically move across to support it. Insufficient margin could force a reduction before the trade has time to play out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Both legs tie up capital while the position is open.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At the time, trade.xyz displayed November 20 as the expected IPO date. If the plan were simply to wait for the final convergence, capital would remain committed on both venues throughout the holding period. The spread might swing up and down dozens of times along the way, and the position would just ride through them.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Splitting the Position and Trading It in Tranches
&lt;/h2&gt;

&lt;p&gt;A closer look at the spread over those few days showed that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The median spread range within a 10-minute window was &lt;strong&gt;34 bps&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Half of the observations were between &lt;strong&gt;21 and 63 bps&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Taker fees for the four fills needed to open and close both legs totaled approximately &lt;strong&gt;10 bps&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Moves of several dozen basis points were common in this sample. But 10 bps covered only commissions at the fee rates used at the time. Bid-ask spreads, slippage, the timing difference between the two legs, and funding still needed to be accounted for separately.&lt;/p&gt;

&lt;p&gt;Execution matters too. The 34 bps figure was an observed range, not an amount a strategy could necessarily capture. After bid-ask spreads, execution differences, and fees, the remaining room would be smaller.&lt;/p&gt;

&lt;p&gt;The direction of the pair stays the same: short Binance and long xyz. The position is split into tranches, each reduced and replenished when its conditions are met.&lt;/p&gt;

&lt;p&gt;When the spread narrows enough to meet a tranche's reduction conditions, both legs of that tranche are closed. If the spread widens again and conditions are suitable, a paired tranche is reopened in the same direction. Its new execution level is recorded, ready for the next narrowing move.&lt;/p&gt;

&lt;p&gt;Here is a simulation of the two approaches using the same historical market data and the same starting position:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffh3kzaulidi4e74nqu7c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffh3kzaulidi4e74nqu7c.png" alt=" " width="799" height="506"&gt;&lt;/a&gt;&lt;br&gt;
From 20:00 on November 4 to 17:00 on November 5, the spread moved from 7% to 10% and then back to 8%. It did not converge, but it kept moving.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Hold throughout&lt;/strong&gt;: −0.29 U, after spending a considerable stretch near −2 U.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Trade the swings while waiting&lt;/strong&gt;: +0.99 U including unrealized P&amp;amp;L, with 2.05 U realized in the simulation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Several rounds of trading were completed in this simulation even though final convergence had not yet occurred. However, realized results and the unrealized P&amp;amp;L on the remaining position must be considered together. Looking only at the gains already realized would give an incomplete picture.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Using Two Timeframes for Position Sizing and Grid Spacing
&lt;/h2&gt;

&lt;p&gt;The first version divided the distance from the entry spread to the take-profit line into equal steps when the position was opened. Each step was 115 bps, and that spacing stayed fixed.&lt;/p&gt;

&lt;p&gt;The spread then swung back and forth for more than three hours, moving 40–50 bps at a time. Not a single tranche was sold, while the position showed an unrealized loss of 2.1 U. The strategy simply watched those swings go by.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9asyvgbv0drq3uu61w0q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9asyvgbv0drq3uu61w0q.png" alt=" " width="799" height="439"&gt;&lt;/a&gt;&lt;br&gt;
The 115 bps spacing did not adjust to the subsequent volatility, so several 40–50 bps swings never reached the next level. The revised approach uses two timeframes: the longer timeframe determines the initial position for each cycle, and the shorter timeframe calculates the trading intervals while the position is open.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;First, use the longer timeframe to determine the initial position.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By default, the strategy examines the past 24 hours of spread data. The area between the 10th and 90th percentiles indicates where the spread has mainly been trading. The most extreme observations at either end are excluded from the normal range, but that does not mean the spread cannot move beyond it.&lt;/p&gt;

&lt;p&gt;The initial position depends on three things together: where the current spread sits within that range, the actual available balance on each venue, and the room for further narrowing after allowing for costs and budgeted funding.&lt;/p&gt;

&lt;p&gt;A higher position within the range can support a larger initial position. Near the lower edge, there may not be enough room for another grid tranche even if cash remains available. When capacity allows, some allocation is reserved for later additions—approximately one quarter by default. If capacity is sufficient for only one tranche, there is no room to set aside another full tranche.&lt;/p&gt;

&lt;p&gt;At startup, the strategy first loads closed historical bars matched to the same minute on both venues. If the history is insufficient, contains too many gaps, or is stale, it waits. It does not open a position using an arbitrary default range.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Second, use the shorter timeframe to calculate trading intervals.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By default, the strategy looks at the past 30 minutes and again uses the central trading range to estimate the spread's amplitude. Under the current default settings, the intervals for both reductions and additions are approximately one third of that range, subject to a cost floor: the larger of the two values is used.&lt;/p&gt;

&lt;p&gt;The reduction and addition coefficients can be configured separately, although their defaults are the same. The longer timeframe determines position size only at the start of a cycle. During the cycle, the shorter timeframe updates the grid spacing.&lt;/p&gt;

&lt;p&gt;Immediately after a tranche is reduced, the next refill uses the current reduction interval, measured from the last actual execution spread. Once the tranche is reopened, the reference point is updated again for the next action.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Third, update the execution reference while retaining each tranche's cost basis.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Each tranche retains the average entry price of both legs. Subsequent trades update the grid reference point, while the original entry costs remain available for checking that tranche's reduction conditions.&lt;/p&gt;

&lt;p&gt;Before reducing a tranche, the strategy checks both the previous execution level and that tranche's entry costs. It then estimates the net result of closing it using the actual average prices and quantities of both legs, the configured fees, and the funding budget accumulated over that tranche's holding period. A normal grid reduction is allowed only if the estimated result meets the minimum net-profit requirement.&lt;/p&gt;

&lt;p&gt;Even if the initial tranches have similar entry costs, they are handled one at a time. Selling one updates the reference point, so the spread must narrow further before the next one can be sold. Touching a single level does not trigger the sale of the entire initial position.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fourth, include execution costs in the minimum grid spacing.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The revised minimum spacing includes more than the fees for four fills. It also allows for slippage on both legs and a minimum net-profit margin.&lt;/p&gt;

&lt;p&gt;With the current default settings, the fee budget is 10 bps, the combined slippage budget for both legs is another 10 bps, and the minimum net-profit allowance is 5 bps. That produces a minimum spacing of 25 bps. These are configured budgets, not a claim that every trade incurs exactly those costs.&lt;/p&gt;

&lt;p&gt;When volatility decreases, the calculated spacing can tighten; when volatility increases, it widens. The earlier rules that compressed spacing as waiting time grew, or widened it based on recent trade results, have been removed. If there is not enough room, the strategy lets that small swing pass.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Fifth, recheck trading conditions before every addition.&lt;br&gt;
*&lt;/em&gt;&lt;br&gt;
Before adding a tranche, the strategy rechecks both balances, effective leverage, the cycle's total capacity, and the remaining profit potential. It also checks order-book depth and the current grid range.&lt;/p&gt;

&lt;p&gt;If the spread suddenly jumps above the grid's current upper boundary, the strategy waits for the range to update instead of chasing the move. It also holds off on the next order if quotes from the two venues are out of sync, account data is not ready, or the outcome of the preceding order remains unresolved.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sixth, settle a completed cycle and plan the next one.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;All initial tranches participate in the grid; no fixed portion is held back solely for final convergence. Once the final tranche has been closed, both legs are flat, and no orders remain unresolved, the cycle is settled.&lt;/p&gt;

&lt;p&gt;The strategy then reassesses the longer-term range, current balances, and available room to plan the next cycle. It does not carry forward the previous cycle's cost basis, reference points, or initial tranche count. It no longer waits for a rebound using an old reference point, and the spread does not have to narrow to 1% for a cycle to end. By default, there is no additional waiting period between cycles, although the new plan still has to pass the ongoing confirmation checks.&lt;/p&gt;

&lt;p&gt;An additional spread protection threshold can be configured separately; it is disabled by default. If contract units or rules change, the strategy first stops opening new positions and adding to existing ones. Conversion assumptions and actual holdings must then be checked before deciding what to do next. An announcement alone is not treated as an automatic instruction to close everything.&lt;/p&gt;

&lt;p&gt;Here are the execution points for fixed spacing and volatility-adjusted spacing over the same historical period:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fx6um1j22vhdg3fypo9p0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fx6um1j22vhdg3fypo9p0.png" alt=" " width="800" height="533"&gt;&lt;/a&gt;&lt;br&gt;
The fixed grid made 1 buy and 1 sell. The dynamic grid made 19 buys and 24 sells.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Live Trading on the Afternoon of November 5
&lt;/h2&gt;

&lt;p&gt;Looking back at that afternoon's session, a paired position was opened at 15:31. Each account held roughly 70 U, and the position was split into 8 tranches of 15 U each.&lt;/p&gt;

&lt;p&gt;The entry spread at 15:31 was 888 bps. Over the next hour and a half, the spread fluctuated between 850 and 950 bps, and the strategy made six sales.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fo3tjzm7n8dwgcyugwu74.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fo3tjzm7n8dwgcyugwu74.png" alt=" " width="800" height="413"&gt;&lt;/a&gt;&lt;br&gt;
Around 16:44, there were four consecutive reductions and additions.&lt;/p&gt;

&lt;p&gt;Within a single minute, the spread dropped from 893 to 763 bps, then rebounded to 943 bps. That spike is not visible in a line plotted from one-minute closes.&lt;/p&gt;

&lt;p&gt;The grid sold one tranche at 778.8 bps, capturing 114 bps of spread movement—more than the previous four sales combined. As the spread rebounded, it reopened a tranche at 839.7 bps, added another at 942.9 bps, and sold again when the spread fell back to 925 bps.&lt;/p&gt;

&lt;p&gt;With fixed spacing, the next sell level for that cycle would have been 757 bps. The spike bottomed at 763 bps before rebounding, missing the level by 6 bps. No tranche would have been sold.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. What Still Needs Monitoring
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Directional risk remains&lt;/strong&gt;. The grid does not change the 12.7 billion-share assumption underlying this historical trade. The S-1/A amendment filed on November 10, 2026 already includes an indicative IPO price range and updated capitalization information. Any continued trading must recheck the latest filings and the exchanges' conversion rules. If the underlying assumption no longer holds, stop and reassess.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Monitor margin separately on both venues&lt;/strong&gt;. A profitable combined position does not mean both accounts are safe. Keep leverage modest. If either leg approaches its margin limit, reduce both legs together.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The number of tranches depends on actual conditions on both venues&lt;/strong&gt;. Available balances, minimum order sizes, and the quantities needed to match the two legs all constrain the tranche count. The initial position in each cycle also depends on the longer-term range and remaining profit potential. It is not always a full eight-tranche position.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Commissions are only part of the cost&lt;/strong&gt;. The minimum grid spacing must also allow for slippage on both legs and a minimum net-profit margin, while funding over the holding period must be considered. The strategy's cycle-level net result is still an estimate based on configured fee rates and funding budgets. The exchanges' actual settlement figures are what ultimately count.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keep monitoring the contract window and conversion rules&lt;/strong&gt;. An expected date is not a final execution schedule. If units or rules change, the relative prices, hedge quantities, and existing positions all need to be checked again.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While waiting for the final rules, holding the position unchanged is not the only option. The longer timeframe determines how each cycle begins; the shorter timeframe handles the swings while the position is open. Once a cycle ends, the next one is planned around the new conditions.&lt;/p&gt;

&lt;p&gt;The next things I want to track are the pressure on positions when the spread keeps widening, and whether actual execution costs leave enough room for these small trades to generate a net return.&lt;/p&gt;

&lt;p&gt;The live trading shown here is mainly intended to explore whether this approach is workable. Both the capital involved and the observation period are limited. At larger sizes, order-book depth, market impact, and execution differences between the two legs become more important. You can also build on this approach with AI assistance to improve liquidity constraints, order splitting, and execution methods, then test those changes against your own capital size and trading conditions.&lt;/p&gt;

&lt;p&gt;DYOR. This article is a record of my own trading, not investment advice.&lt;/p&gt;

</description>
      <category>cryptoarbitrage</category>
      <category>quantcrypto</category>
      <category>fmzquant</category>
      <category>spreadtrading</category>
    </item>
    <item>
      <title>Bringing Cybernetics On-Chain: An LP Bot That Selects Tokens and Opens Positions on Its Own</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Thu, 19 Nov 2026 03:18:36 +0000</pubDate>
      <link>https://dev.to/quant001/bringing-cybernetics-on-chain-an-lp-bot-that-selects-tokens-and-opens-positions-on-its-own-4j76</link>
      <guid>https://dev.to/quant001/bringing-cybernetics-on-chain-an-lp-bot-that-selects-tokens-and-opens-positions-on-its-own-4j76</guid>
      <description>&lt;p&gt;LP stands for Liquidity Provider. When we talk about “doing LP,” we mean depositing assets into a decentralized exchange's liquidity pool so that others can swap against them, earning a share of trading fees in return. This project uses concentrated liquidity, which lets you choose the price range in which to provide liquidity and concentrate your capital around a particular set of prices. While the price stays in that range, you have an opportunity to keep collecting fees. Once it moves outside, that liquidity no longer participates in trades at the current price. In a pool consisting of a token and a quote token, a prolonged decline in the token's price leaves the position holding more and more of that token. By the time the price breaks below the lower bound, the position may consist entirely of it. LP has been around for a long time, but the recent surge in on-chain trading has made things lively, and I have had a chance to try it a few times. When Robinhood Chain was booming in September, you could enter almost any pool and immediately receive an unexpectedly large amount of fee income. As the saying goes, even pigs can fly with a strong enough tailwind. I made quite a bit, but I lost quite a bit too—I just could not keep my hands off the trade button.&lt;/p&gt;

&lt;p&gt;Later, on-chain activity gradually cooled, and the broader financial markets were subdued as well. That gave me a chance to organize what I had been doing. Manually selecting tokens, opening liquidity positions, collecting income, and taking profits or cutting losses could all be handled by a program with FMZ's new DEX functions. After burning through a great many tokens, I started working on an LP strategy that selects tokens automatically and manages positions adaptively.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Pitfalls of Starting with the Rankings
&lt;/h2&gt;

&lt;p&gt;There were detours along the way, of course. I followed my old approach: find the hottest tokens at the top of the rankings and let the program open positions. Quite a few turned out to be scams. Within minutes of entering, the price would plunge before I could get out, drop straight through the pool's lower bound, and leave me the proud owner of millions of worthless tokens.&lt;/p&gt;

&lt;p&gt;That is especially painful for an LP. If you buy a token directly, at least you still hold the same number of tokens when its price falls. With concentrated liquidity, the pool keeps converting your quote token into the falling token along the way. I had hoped to collect fees while waiting for the price to fluctuate. Instead, I collected a little in fees and a very large inventory. Those impressive volume figures on the trending list looked rather different once they reached my own wallet.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnkcv21ctloz9asaxxjl0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnkcv21ctloz9asaxxjl0.png" alt=" " width="799" height="444"&gt;&lt;/a&gt;&lt;br&gt;
In my earlier quantitative strategies, I would normally select an asset and an indicator, enter when certain conditions were met, and exit when others were met. That already amounted to a small systematic implementation. This time, however, the program had to select the asset itself. After entry, it also had to deal with the range, capital allocation, changing fee income, and on-chain execution. Changing a single token-selection indicator could not solve the problems across the whole process. That led me to cybernetics.&lt;/p&gt;
&lt;h2&gt;
  
  
  Organizing the LP Process Around Feedback
&lt;/h2&gt;

&lt;p&gt;Cybernetics studies how systems can be regulated through feedback. Think of an air conditioner with a target temperature: a sensor continuously reads the room temperature, and the controller adjusts cooling power according to the difference. As the actual environment changes, the control action changes with it. A common PID controller divides this adjustment into three parts:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;u(t) = Kp·e(t) + Ki·∫e(t)dt + Kd·de(t)/dt&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here, e(t) is the difference between the target and the current value, and u(t) is the action output by the controller. P is the proportional term, which responds to the current error. I is the integral term, which accounts for error accumulated over time. D is the derivative term, which responds to how quickly the error is changing. The three coefficients determine how strongly each term influences the control action.&lt;/p&gt;

&lt;p&gt;Trading, of course, is not as obedient as an air conditioner. Setting a target return does not make the market deliver the money. This strategy adopts the idea of feedback control: model the changes in LP assets and fee income, simulate the possible outcomes of different actions, and then use actual operating data to correct the model. PID offers an intuitive way to understand feedback; the program's ranges and position sizes are calculated by return and risk models.&lt;/p&gt;

&lt;p&gt;The first step is to use a consistent return objective. Fees collected from LP are only part of the trade's income. Changes in the value of the assets held, swap costs, and gas must all be included. The system makes decisions around net returns after accounting for these effects, with boundaries for capital usage and losses. An opportunity that looks worthwhile at token selection must still pass the test of actual costs when opening a position, and the test of real outcomes after entry.&lt;/p&gt;

&lt;p&gt;Following this approach, I divided the process into five layers: token selection, pool selection, position opening, monitoring, and exit.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F56wujsipxi1d2icseevk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F56wujsipxi1d2icseevk.png" alt=" " width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Layer 1: Token Selection
&lt;/h2&gt;

&lt;p&gt;Token selection first determines which tokens are worth considering for LP.&lt;/p&gt;

&lt;p&gt;Trending rankings are still useful because they provide a continually updated set of candidates. After those sharp drops, though, I no longer wanted ranking to determine entry directly. Active trading is only a starting point. Token safety, trading history, and price stability also matter when deciding whether that activity is worth participating in. For LP, a token that rallies sharply over a short period is not necessarily a better choice than one with sustained trading and relatively steady price fluctuations.&lt;/p&gt;

&lt;p&gt;This layer compares expected fee income with inventory losses caused by price fluctuations. High fees provide a source of income, but excessive volatility can consume that income very quickly. Token selection narrows a large candidate set down to the assets more suitable for deploying capital, passing them to the next stage for calculation. Scan results and rejection reasons are also recorded. The status panel shows what the program is investigating in the current round and which tokens have been filtered out.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu7ys6xom9h96y3si8xmr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu7ys6xom9h96y3si8xmr.png" alt=" " width="800" height="307"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Actual token-selection scan: even actively traded tokens may be rejected because fees do not cover the model's estimated losses, trading history is insufficient, or the short-term drawdown is too large.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Layer 2: Pool Selection
&lt;/h2&gt;

&lt;p&gt;A token often has pools with different trading pairs and fee tiers. Choosing the token does not yet answer where to put the capital.&lt;/p&gt;

&lt;p&gt;One easy mistake is to estimate your fee income directly from the token's total trading volume. Most trading may be happening in a different pool. Even if you choose the pool with the largest volume, substantial liquidity may already be sharing those fees. The fee tier, pool volume, and competing capital need to be considered together.&lt;/p&gt;

&lt;p&gt;FMZ's DEX interface can list candidate pools directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var pools = exchange.IO("lp.pools", BASE, QUOTE);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The program then compares the pools one by one. For concentrated liquidity, it also needs to consider the active liquidity near the current price that is actually participating in trades. The total amount of money in a pool and the amount sharing in the current trade are not the same number. That distinction affects the estimate of our fee share and how much capital we should deploy next.&lt;/p&gt;

&lt;p&gt;Pool selection therefore establishes the specific trading environment for the model. If a token that passed the previous stage has no suitable pool, the strategy will not proceed to open a position. Separating the token and pool decisions keeps “this token is popular” from being confused with “this pool is worth funding.”&lt;/p&gt;

&lt;h2&gt;
  
  
  Layer 3: Opening Positions
&lt;/h2&gt;

&lt;p&gt;Position opening is where the LP simulation does most of its work. When operating manually, it is easy to choose a range by feel. A narrower range concentrates capital and may earn a larger fee share, but a small price move can take it out of range. A wider range accommodates larger fluctuations, at the cost of lower capital efficiency. The amount invested also affects the outcome: fixed gas costs can eat into a small position, while a larger position may increase swap impact, and its share of fees will not always grow in direct proportion to the principal.&lt;/p&gt;

&lt;p&gt;I put these trade-offs into a single model. Using recent price data, the program generates multiple possible price paths and simulates how the assets in the position would change, how much fee income they could earn, and what it would cost to exit under different ranges and investment amounts. The result is a set of possible outcomes that can be compared for return and risk before selecting the range and position size.&lt;/p&gt;

&lt;p&gt;The simulation models how LP actually works. Where the price goes, how much of each asset remains, and how long the capital stays within an active range all affect the final return. If you simulate only the token price and then add a fixed amount of fee income, many of concentrated liquidity's defining features are lost.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9el4rdhxjfu6l6ntpxyu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9el4rdhxjfu6l6ntpxyu.png" alt=" " width="799" height="444"&gt;&lt;/a&gt;&lt;br&gt;
Once the model selects a configuration, the DEX functions generate and execute the position-opening plan:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var plan = exchange.IO("lp.plan", {
    symbol: SYMBOL,
    budget: budget,
    range: {pct: rg.pct},
    shape: "spot",
    layers: LAYERS,
    pool: pool.id,
    slippage: LP_SLIPPAGE
});

var opened = exchange.IO("lp.add", plan);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;lp.plan turns the capital budget, range, and pool into a position-opening plan, and lp.add executes it. This is where the strategy model connects with on-chain operations: the earlier calculations must become an actual position before subsequent feedback has something to measure.&lt;/p&gt;

&lt;p&gt;For tokens with little measured history, the program starts with a smaller allocation and adjusts later investments as data accumulates. Costs must be recalculated after reducing the position size. Otherwise, a theoretical plan may look attractive, but the small amount actually invested may fail to earn enough fees to cover entry and exit costs. These calculations appear in the entry assessment so that the basis for the range and amount can be checked.&lt;/p&gt;

&lt;h2&gt;
  
  
  Layer 4: Monitoring
&lt;/h2&gt;

&lt;p&gt;Once a position is open, feedback control begins to work continuously. The fee data used before entry inevitably involves some extrapolation. Heavy trading in the recent past does not guarantee the same activity ahead. Other investors adding capital to the pool also changes our share. The program must continually read the actual position and compare fees received with the original forecast.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var positions = exchange.IO("lp.positions", SYMBOL);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If actual fees consistently fall short of expectations, the model lowers its subsequent estimates. As measured records accumulate for that token, the experience-based estimates borrowed at entry gradually give way to its actual performance. These records are retained for later decisions. When the same token becomes a candidate again, the program already has experience from its previous participation.&lt;/p&gt;

&lt;p&gt;Monitoring also includes reassessing the current range. After the price moves, the program must use the latest state to calculate whether the original range still makes sense, whether continuing to hold compensates for the risk, and whether switching to another range justifies the cost of trading again. It compares holding, changing the range, and exiting, but does not act immediately on every brief change. On-chain adjustments cost money. Excessively frequent control actions can easily consume the fees that would otherwise have been retained.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftz8rwtml6ktwjaacsv38.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftz8rwtml6ktwjaacsv38.png" alt=" " width="799" height="444"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Layer 5: Exit
&lt;/h2&gt;

&lt;p&gt;The exit layer brings an LP cycle to a real conclusion. Normal exits follow a change in the return assessment: trading activity may have cooled enough that holding is no longer attractive, or the price may have left the range and opening a new position is not worthwhile. These exits can allow time for confirmation to reduce the cost of repeated entries and exits. If a contract anomaly occurs, pool liquidity drops sharply, or losses reach a limit, the outer risk controls intervene directly instead of waiting for the return assessment to confirm slowly.&lt;/p&gt;

&lt;p&gt;In execution, withdrawing liquidity and selling the token must be handled together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var closed = exchange.IO("lp.remove", ids, 1, true);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This requests withdrawal of all liquidity and conversion back into the quote token. On-chain operations may involve several transactions, however. After liquidity has been withdrawn successfully, the wallet must still be checked to confirm that the token has been sold. Any remaining balance needs further handling; if it cannot be sold, the program raises an alert. Having already experienced what it feels like to hold millions of worthless tokens, I naturally take this step seriously.&lt;/p&gt;

&lt;p&gt;Exit results also feed back into the system. Each cycle records the fees actually earned, profit or loss from asset-value changes, and transaction costs. Historical cycles and token records then become useful: they can reveal whether a type of opportunity is persistently overestimated and whether frequent range changes are worthwhile. The next round of token selection and position opening continues to draw on those actual outcomes.&lt;/p&gt;

&lt;p&gt;With the five layers connected, the program can handle everything from discovering candidates to withdrawing the capital. Market changes enter the model, the model generates actions, and on-chain execution produces new position and return data that feeds into the next calculation. FMZ's new DEX functions save a substantial amount of work on basic operations, letting more effort go into this decision and feedback process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Impressions from the Last Two Days
&lt;/h2&gt;

&lt;p&gt;The most immediate difference in use is that the work of repeatedly browsing rankings, checking pools, and calculating returns can now be monitored from the status panel and logs. The status panel shows the current stage, capital, and positions, while the logs record specific decisions over time. There is a record of the entire strategy process, from token and pool selection to entry, adjustments while holding, and the final exit.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F34pz2hum5ckpn7cnto9u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F34pz2hum5ckpn7cnto9u.png" alt=" " width="799" height="266"&gt;&lt;/a&gt;&lt;br&gt;
In this example, CRCL passed token screening and the program compared its pools. But after recalculating for the actual position size, the risk-adjusted return did not meet the entry requirement, so no position was opened. Reading the related log entries together makes it clear where the process stopped. Those same records can help locate the reasons when adjusting the model later.&lt;/p&gt;

&lt;p&gt;After these two days of testing, this version can select relatively stable tokens from the candidates and open positions suited to the pool and market conditions. While on-chain activity is quieter, I plan to keep refining the process. Hopefully, by the next burst of on-chain activity, I will have a useful tool ready to go.&lt;/p&gt;

</description>
      <category>web3quant</category>
      <category>defistrategy</category>
      <category>fmzquant</category>
      <category>cryptobot</category>
    </item>
    <item>
      <title>Missed Another Crypto Opportunity, So I Asked Codex to Design a Tool for Next Time</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Thu, 19 Nov 2026 03:10:52 +0000</pubDate>
      <link>https://dev.to/quant001/missed-another-crypto-opportunity-so-i-asked-codex-to-design-a-tool-for-next-time-1chn</link>
      <guid>https://dev.to/quant001/missed-another-crypto-opportunity-so-i-asked-codex-to-design-a-tool-for-next-time-1chn</guid>
      <description>&lt;h2&gt;
  
  
  Why Does Everyone Else Catch the Opportunity While I Read the Postmortem?
&lt;/h2&gt;

&lt;p&gt;There has been another security incident in crypto.&lt;/p&gt;

&lt;p&gt;I came across an on-chain postmortem. Its author estimated that someone had made about $3.47 million from ETH price differences amid the turmoil. Staring at that figure, I had the same familiar thought:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does everyone else catch the opportunity while I read the postmortem afterward?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This time, I had to look into it. I wanted a script to keep watch for me. Even a small share of the opportunity would be something!&lt;/p&gt;

&lt;p&gt;But further down, another line in the post stood out: according to the author, the address that made the most had already deposited 37 million USDC in Aave beforehand. The $3.47 million figure was also the author's estimate, before on-chain transaction fees.&lt;/p&gt;

&lt;p&gt;That cooled my enthusiasm a little. Their capital was already in place. I had not even worked out how the opportunity arose or what I should be watching.&lt;/p&gt;

&lt;p&gt;So that was where I would start.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fa9yue3z8mzggon1niikx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fa9yue3z8mzggon1niikx.png" alt=" " width="799" height="329"&gt;&lt;/a&gt;&lt;br&gt;
I gave the original post and my ideas to my Codex agent:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Help me design a tool to run on FMZ. First, monitor price differences for me and investigate the conditions when you find a lead. I will confirm when to borrow and sell tokens, decide whether to add collateral and continue borrowing and selling, and finally buy back and repay in batches.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In this article, I will follow the original post's reasoning and work through that process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Someone Is in a Hurry to Buy ETH. Can I Sell It to Them?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv8x0nx9qbgfqpmrd6rcy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv8x0nx9qbgfqpmrd6rcy.png" alt=" " width="799" height="450"&gt;&lt;/a&gt;&lt;br&gt;
According to the original author, someone was urgently converting assets such as USDT into ETH. Those large purchases pushed up prices in particular on-chain markets. Exchanges had suspended withdrawals, so cheaper ETH could not immediately be moved on-chain.&lt;/p&gt;

&lt;p&gt;From another perspective, the trade is straightforward: &lt;strong&gt;the buyer is willing to pay more in stablecoins to get ETH quickly. Anyone who can supply ETH at that moment has a chance to sell at a favorable price&lt;/strong&gt;. The phrase "selling stablecoins cheaply" refers to accepting a worse exchange rate when converting them into ETH.&lt;/p&gt;

&lt;p&gt;Arbitrageurs sell ETH into those expensive markets, economically supplying what the buyer needs and taking the other side of the trade. Transactions typically take place through DEX pools; the two people do not have to be matched directly. The opportunity comes from the premium paid by that urgent buying demand. How Uniswap works&lt;/p&gt;

&lt;p&gt;But what if I do not have any ETH?&lt;/p&gt;

&lt;p&gt;Then I can post collateral, borrow ETH, and sell the borrowed tokens. No inventory? Borrow against collateral and sell short. Aave provides a way to borrow on-chain spot assets. Whether the trade makes money still depends on the cost of buying them back and repaying later.&lt;/p&gt;

&lt;p&gt;The next line in the original post turns this operation into a loop:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Deposit the stablecoin proceeds back in, then keep borrowing and selling.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Add the sale proceeds as collateral and, if borrowing limits, liquidity, and other conditions permit, borrow another batch of ETH and sell again. &lt;strong&gt;Borrowing and selling can continue in successive rounds, but the ETH debt accumulates too. The position is not fully closed until the tokens are bought back and the debt is repaid&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Consider a hypothetical example, assuming sufficient collateral is already in place and the borrowing conditions permit it. First, borrow 1 ETH and sell it for 2,600 USDC. Add the proceeds as collateral, then borrow another 1 ETH and sell that for 2,600 USDC as well. Total sale proceeds are now 5,200 USDC, and the debt is 2 ETH plus interest.&lt;/p&gt;

&lt;p&gt;If the ETH can later be bought back for 2,300 USDC each, buying back the principal costs 4,600 USDC. The difference between sale and purchase prices is 600 USDC, before interest and fees. If the buyback price rises to 3,000 USDC, that difference becomes a loss of 800 USDC, with fees still to be accounted for.&lt;/p&gt;

&lt;p&gt;One distinction matters here: Aave's oracle price is used for valuation and risk calculations; it is not a price at which you can sell tokens. If the oracle values ETH at $2,300, that does not mean I can buy 1 ETH on Aave for $2,300. Aave borrowing guide&lt;/p&gt;

&lt;p&gt;Once that is clear, the script's job becomes concrete: &lt;strong&gt;find where ETH can be sold at a premium, while also tracking how many tokens I owe and how much it would cost to buy them back&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Watch for Me First, Then Tell Me Whether the Trade Is Feasible
&lt;/h2&gt;

&lt;p&gt;If my phone rings in the middle of the night and only says "ETH price difference detected," I still have to get up and check several different pages.&lt;/p&gt;

&lt;p&gt;What I want to save is the time spent finding the right interfaces, checking conditions, and calculating fees on the spot.&lt;/p&gt;

&lt;p&gt;The initial monitoring scope is Binance, OKX, Uniswap on Ethereum, PancakeSwap on BNB Chain, and Aerodrome on Base. I want to watch markets related to both BTC and ETH, but each asset and pool needs to be verified. Different wrapped assets cannot be treated as the same token just because their names look similar. For execution, the first version will focus on borrowing ETH through Aave on Ethereum.&lt;/p&gt;

&lt;p&gt;After detecting a significant deviation, the program should investigate using the quantity I intend to trade: how much the sale would actually return, what the fees would be, whether Aave still allows the collateral and borrowing operations, whether enough tokens are available, and how much my account can borrow.&lt;/p&gt;

&lt;p&gt;CEX quotes serve as references for detecting deviations; DEX quotes determine the terms of actual execution. The program must also check whether the quote stablecoin itself is behaving abnormally. I am looking for ETH that has been bid up in a particular market. The alert should separately show "how much higher the price is than the reference" and "how much it would cost to buy back now," so I can see whether this trade still requires waiting for the price to fall.&lt;/p&gt;

&lt;p&gt;Only after those conditions are clear is it worth waking me up.&lt;/p&gt;

&lt;h2&gt;
  
  
  After the First Sale, I Still Need to Decide Whether to Continue
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fur9e22sycgbtc88zbip7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fur9e22sycgbtc88zbip7.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, the FMZ page should show me a concrete plan: how much ETH to borrow, where to sell it, the minimum proceeds I will accept, the estimated fees, and the cumulative token debt after execution.&lt;/p&gt;

&lt;p&gt;The program should borrow and sell according to that plan only after I confirm. If the market has moved outside the approved price range, it should obtain a fresh quote. FMZ interaction commands can provide an entry point for these operations; the agent still needs to connect the appropriate interfaces to implement them. FMZ interaction commands&lt;/p&gt;

&lt;p&gt;After the first sale, if the premium remains, I can choose to add some of the proceeds as collateral and borrow and sell another batch.&lt;/p&gt;

&lt;p&gt;At that point, the most important figure on the page is "&lt;strong&gt;how much ETH I will owe in total if I continue&lt;/strong&gt;." It should also show the collateral, available wallet funds, and health factor—the remaining margin before the lending position faces liquidation. The amount I am allowed to borrow is not necessarily the amount I want to borrow.&lt;/p&gt;

&lt;p&gt;Every addition of collateral and every further round of borrowing and selling must therefore have a new preview and require my confirmation, subject to preset limits on total debt and the health factor. The amount of stablecoins received from sales and the portion already committed as collateral must also be tracked separately.&lt;/p&gt;

&lt;p&gt;If the ETH is borrowed but the sale fails, the program should stop and deal with that loan. If a transaction is still awaiting confirmation, clicking again must not trigger a duplicate loan.&lt;/p&gt;

&lt;p&gt;I want the tool to handle these details so that every decision to continue comes with a clear account of the position.&lt;/p&gt;

&lt;h2&gt;
  
  
  When It Is Time to Exit, Where Does the Buyback Money Come From?
&lt;/h2&gt;

&lt;p&gt;Following the process through reveals another easy-to-miss question: if all the sale proceeds have been deposited back into Aave, what will I use to buy back the ETH?&lt;/p&gt;

&lt;p&gt;A collateral balance and a wallet balance are not the same thing.&lt;/p&gt;

&lt;p&gt;The design therefore needs to provide for buyback funding. One option is to reserve some stablecoins. Another is to withdraw collateral in batches, when the health factor and pool liquidity permit, and use it to buy tokens for repayment. Each step needs its own feasibility check. The design cannot assume that all collateral can be withdrawn at any time. Aave withdrawal guide&lt;/p&gt;

&lt;p&gt;When I decide to buy back, the page should show where the money for that batch will come from, how much ETH it can buy, and how much debt will remain after repayment. After confirmation, it should execute and update the records. If the exit requires several batches, each batch should be confirmed separately.&lt;/p&gt;

&lt;p&gt;Buyback monitoring also cannot focus only on prices that would make a profit. If ETH continues rising, the buyback cost increases. As the debt valuation rises, the health factor may also fall. The program should alert me to both the cost of buying back and the position's risk, instead of waiting indefinitely for a price decline that may never come. Aave health factor guide&lt;/p&gt;

&lt;p&gt;Finally, buying the ETH back is not the end. It must actually be repaid to Aave, with the principal, interest, and remaining debt reconciled. The final result can be calculated only once this position is settled. Any pre-existing positions must be accounted for separately. Aave repayment guide&lt;/p&gt;

&lt;p&gt;That completes the loop described in the original post:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Detect a premium → verify the conditions → manually confirm borrowing and selling → add collateral and continue borrowing and selling as needed → manually confirm staged buybacks and repayments → reconcile debt and actual cash flows.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Handing This Workflow to My Codex
&lt;/h2&gt;

&lt;p&gt;That is the task I am giving the agent: from identifying a price difference, through each additional round of borrowing and selling, to buying back and repaying, the FMZ page should always show where I am in the process and how many tokens I still owe.&lt;/p&gt;

&lt;p&gt;For now, this is still a requirements design. I will share the code and actual operating results once the work is complete.&lt;/p&gt;

&lt;p&gt;The next time a similar opportunity appears, I hope to have a familiar tool ready: check the conditions, review the accounts, and then decide whether to act.&lt;/p&gt;

&lt;p&gt;Even a small share of an opportunity would be something. First, I need to understand how to sell the tokens I borrow—and how to repay them afterward.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Prompt for Codex
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Please design an FMZ price-monitoring and manual-trading tool that follows the original post's workflow: post stablecoins as collateral → borrow ETH → sell at a premium → manually confirm additional collateral and further borrowing and selling → buy back ETH in batches and repay principal and interest in full. Provide an implementation plan first; do not deploy it for live trading directly.

Original background post:
https://x.com/0xNaiXi/status/2115967318274789609

Strategy objective: capture local ETH premiums created by urgent conversion demand, supplying spot ETH by borrowing against collateral, then seeking to buy back and repay. "No inventory? Borrow against collateral and sell short." Without a hedge, the position remains exposed to rising ETH prices; the current premium must not be treated as locked-in profit.

Monitor Binance and OKX spot markets, along with BTC- and ETH-related markets on Uniswap (Ethereum), PancakeSwap (BNB Chain), and Aerodrome (Base). Verify token contracts, wrapped assets, and differences in quote currencies. For execution, the first version should implement only the ETH/WETH workflow between one explicitly identified Aave market on Ethereum and a DEX, with no automatic cross-chain transfers.

1. Monitor first, then verify. Normalize prices to a common quote currency and distinguish a local ETH premium from an abnormal quote currency. After detecting a lead, obtain executable quotes for the specified quantity and check fees, quote freshness, Aave supply and borrowing restrictions, pool liquidity, and the account's collateral eligibility. Display CEX reference prices, Aave oracle valuations, and executable buy and sell quotes separately. A future buyback price is only an assumption and must not be used to display locked-in profit.

2. Support manually controlled cycles of borrowing and selling. For the initial collateral deposit, borrowing and selling, adding sale proceeds as collateral, and further borrowing and selling, first show the corresponding plan and execute only after my confirmation. Each preview should show quantities, price boundaries, fees, and the resulting cumulative debt and health factor. Expired quotes or conditions outside the approved boundaries require renewed confirmation. Allow the position to be increased before all debt has been repaid, subject to a total-debt cap, a minimum health factor, and reserved buyback funds. Do not run an unlimited automatic loop.

3. Complete the buyback and repayment process. Continuously display the current buyback cost, actual principal and interest due, wallet funds, and withdrawable collateral. Fund buybacks from reserves or eligible collateral withdrawals, checking the health factor and liquidity at each step. Show any funding shortfall when funds are unavailable. After my confirmation, buy back and repay in batches, then query the remaining debt until this position is settled. Adding collateral is not repayment, and buying ETH without actually repaying it to Aave does not settle the position either.

4. Record and handle exceptions. Distinguish pre-existing positions from this tool's operations while assessing risk across the entire account. Record actual cash flows, fees, collateral, and debt without deducting fees twice. Repeated clicks must not trigger duplicate trades. If borrowing succeeds but selling fails, allow me to confirm repayment of the unsold tokens. If the status is unknown, query it first and pause subsequent operations. Restore unfinished records after a restart.

Verify the official FMZ and protocol documentation, then provide a concise interaction design, required interfaces and credentials, execution states, and exception handling. Without confirmation, monitor only. Do not invent interface support, code, tests, or returns.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Beta Strategy Tool
&lt;/h2&gt;

&lt;p&gt;This strategy has not been validated through live trading. It is shared solely for discussion and learning.&lt;/p&gt;

</description>
      <category>defitrading</category>
      <category>cryptoquant</category>
      <category>fmzquant</category>
      <category>agents</category>
    </item>
    <item>
      <title>FMZ's WebSocket Interface Gets a Major Upgrade: Bringing Strategies Closer to Market Changes</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Wed, 18 Nov 2026 03:56:21 +0000</pubDate>
      <link>https://dev.to/quant001/fmzs-websocket-interface-gets-a-major-upgrade-bringing-strategies-closer-to-market-changes-146n</link>
      <guid>https://dev.to/quant001/fmzs-websocket-interface-gets-a-major-upgrade-bringing-strategies-closer-to-market-changes-146n</guid>
      <description>&lt;p&gt;When writing quantitative strategies, we tend to focus on trading logic: the conditions for entering a position, where to exit, and how to control position size. Once a strategy is running, however, another question comes before the signal: how closely does the market the program sees match what is actually happening? For decisions made on minute or hourly timeframes, this issue may not always be obvious. But once you monitor several exchanges and instruments at once, or start studying brief changes in spreads, the way you obtain market data directly affects the strategy's results.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4nfwpjqgy6bmoluub561.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4nfwpjqgy6bmoluub561.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
A spread has just widened, but the polling loop has not reached it yet. Quotes from two exchanges have both returned, but they were sampled at different times. After an order is placed, the program is still querying its status while the other leg has already filled. These problems may not originate in the signal formula, yet they affect whether that formula can translate into actual trades. That is why FMZ's latest WebSocket interface upgrade deserves a closer look.&lt;/p&gt;

&lt;p&gt;The upgraded interface brings market data subscriptions, event consumption, account updates, and asynchronous trading into a more unified set of calls. A strategy can continuously receive market changes through ctx.subscribe(), process events with ctx.poll(), and submit WebSocket trading requests through ctx.submit() on supported accounts. The change goes beyond reducing the wait for a market data query. More significantly, a strategy can organize its work around changes in the market: what to watch under normal conditions, what to focus on when an opportunity appears, and where to direct processing resources once it holds a position.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxnr8m57ku7wh3kjpwulv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxnr8m57ku7wh3kjpwulv.png" alt=" " width="799" height="479"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Markets Do Not Always Move at a Fixed Pace
&lt;/h2&gt;

&lt;p&gt;A traditional REST strategy is easy to understand: the program asks a question, and the exchange returns an answer. Get a quote, make a decision, wait, then query again. This is a clear approach and remains suitable for many tasks. Market information, historical data, and account checks can all be explicitly requested through REST. But observing a continuously changing market at a fixed frequency involves a tradeoff. Query less often and you make fewer requests, but brief changes may slip between two samples. Query more often and you generate more requests, consuming rate-limit capacity and processing resources. The problem becomes more pronounced as the number of instruments grows.&lt;/p&gt;

&lt;p&gt;Markets also do not change at an even pace. Sometimes several seconds pass with no new information worth processing; at other times, a burst of quotes and trades arrives almost instantly. Fixed polling follows a predetermined schedule, whereas WebSocket subscriptions let a program update its state as data actually arrives. When volatility suddenly increases, pushed updates can reduce the wait imposed by polling intervals. For strategies monitoring multiple markets, continuously maintaining each market's latest quote is also easier to organize than querying them individually as needed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqfh4mehn4vt10x9h5t33.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqfh4mehn4vt10x9h5t33.png" alt=" " width="799" height="428"&gt;&lt;/a&gt;&lt;br&gt;
Here, though, we need to distinguish “more timely” from “guaranteed to be faster.” REST can reuse connections, batch requests, and run them concurrently. WebSocket performance also depends on the exchange's update frequency, the network path, and the load on the FMZ Docker. This upgrade provides an interface better suited to continuous monitoring; the actual reduction in latency still needs to be measured in the target environment. &lt;strong&gt;Bringing a strategy closer to the market requires adjusting its data input, decision process, and execution tracking together.&lt;/strong&gt; Replacing just one function may not produce the same effect.&lt;/p&gt;
&lt;h2&gt;
  
  
  What This Upgrade Brings Together
&lt;/h2&gt;

&lt;p&gt;FMZ already supported native WebSocket connections through Dial(). Developers could work directly with exchange protocols, which offered considerable flexibility, but subscription formats, fields, order-book updates, and connection management still had to be adapted for each exchange. The upgraded subscription interface shifts more of that work into the platform's connectors. Strategies can use similar calls to receive tickers, best bid and ask quotes, depth, individual trades, and candlesticks. To broaden their coverage, they can subscribe to market-wide tickers on supported exchanges or pass several instruments at once. For strategy authors, this means more effort can go into deciding what to do with the data, instead of repeatedly handling each exchange's message format.&lt;/p&gt;

&lt;p&gt;For example, the following read-only example can run with a Binance perpetual futures configuration that supports the relevant channels. It subscribes to two instruments, continuously maintains their latest best bid and ask, and exits after one minute without trading. The array returned by a batch subscription also has an unsubscribe() method, allowing the entire group of subscriptions to be released at once.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function main() {
    var subs = ctx.subscribe(exchange, {
        channel: "bbo",
        symbol: ["BTC_USDT.swap", "ETH_USDT.swap"],
        mode: "latest"
    });
    var quotes = {}, started = Date.now(), lastLog = 0;

    try {
        while (Date.now() - started &amp;lt; 60000) {
            var e = ctx.poll([], 200);
            if (e &amp;amp;&amp;amp; e.kind === "status" &amp;amp;&amp;amp; e.prefillStatus === 2) {
                Log("Subscription failed", e.symbol, e.message);
            } else if (e &amp;amp;&amp;amp; e.kind === "ticker" &amp;amp;&amp;amp;
                       e.channel === "bbo" &amp;amp;&amp;amp;
                       e.bid &amp;gt; 0 &amp;amp;&amp;amp; e.ask &amp;gt;= e.bid) {
                quotes[e.symbol] = {
                    bid: e.bid, ask: e.ask, received: e.ts
                };
            }

            if (Date.now() - lastLog &amp;gt;= 1000) {
                Log("Latest quotes", JSON.stringify(quotes));
                lastLog = Date.now();
            }
        }
    } finally {
        subs.unsubscribe();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, poll([], 200) waits for up to 200 milliseconds and returns sooner if an event arrives. It does not request fresh market data every 200 milliseconds. Once a subscription has been registered, the first poll() call starts the connection and subscription, so receiving a subscription object does not mean valid data has already arrived. Another point must be clear when migrating an older strategy: subscribing through WebSocket does not turn existing queries such as GetTicker() and GetDepth() into cache reads. Those functions still use REST; pushed data must be retrieved through the event interface. To use the new data path, the main loop needs to change accordingly. Official subscription documentation&lt;/p&gt;

&lt;p&gt;The upgraded interface also brings in account state. One private subscription per account receives orders, fills, positions, and balances according to what the exchange actually supports. It covers the entire account, so there is no need to subscribe separately for each instrument. This lets a strategy process market changes and its own trading state in the same flow: reassess an opportunity when a quote changes, update trade records when a fill arrives, and check exposure when a position changes. A unified interface does not mean that every exchange pushes exactly the same content, however. Some fields may be absent, and some account changes may not be pushed in real time. After initialization or reconnection, the strategy needs to wait for the account snapshot to be ready; missing information and historical fills still need to be retrieved through queries.&lt;/p&gt;

&lt;h2&gt;
  
  
  To Adapt to Different Markets, Decide Which Data Must Be Retained
&lt;/h2&gt;

&lt;p&gt;As the volume of market data grows, it is tempting to think: if WebSocket can keep pushing updates, why not subscribe to everything? After running a strategy for a while, it often becomes clear that more data is not necessarily more useful. The real questions are whether the strategy needs to process every update and whether it can keep up with the updates it receives.&lt;/p&gt;

&lt;p&gt;A strategy that evaluates spreads from current quotes usually cares most about the latest best bid and ask. Working through a queue of quotes from two seconds ago before reaching the present can leave its decisions behind the market. mode: "latest" allows new market data to replace older updates and is better suited to this use. Research based on individual trades is different. If you calculate order flow from aggressive buys and sells over a short period, overwriting trades in between changes what the statistics mean. Candlesticks likewise require a distinction between historical bars supplied during initialization, the current unfinished bar, and bars that have actually closed.&lt;/p&gt;

&lt;p&gt;Another benefit of the upgrade is therefore the ability to organize data by purpose, instead of applying one consumption model to every channel. Below are several typical subscription calls. They show how to bring in different types of information; each still needs to be handled separately in the event loop, with subscriptions released at the end.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Order book: after receiving a depth event, read price levels with e.book(n).
var depth = ctx.subscribe(exchange, {
    channel: "depth", symbol: "BTC_USDT.swap", depth: 20
});

// Individual trades: examine trade direction, price, and quantity.
var trades = ctx.subscribe(exchange, {
    channel: "trade", symbol: "BTC_USDT.swap"
});

// The candlestick interval is in seconds; also check closed and prefill when identifying closed bars.
var bars = ctx.subscribe(exchange, {
    channel: "kline", symbol: "BTC_USDT.swap", interval: 60
});

// Private stream for the entire account; do not pass symbol.
var account = ctx.subscribe(exchange, {channel: "private"});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The FMZ Docker maintains the order book, so a strategy does not need to assemble incremental depth updates separately for each exchange. But book() reads the currently maintained book; it should not be understood as a historical snapshot from the moment an older event occurred. The latest received data also needs to be considered in terms of time. An event's ts is the time when the Docker received the data. Subtracting it from the current time reveals internal processing and event-consumption delay, but excludes upstream network transmission. Quotes from different exchanges must also be checked for their individual ages and the time difference between them. Receiving both through WebSocket does not mean they represent the same instant. Event field documentation&lt;/p&gt;

&lt;p&gt;Exploring connection stability over the past couple of days reinforced the same point: having a connection, having received data, and still having usable data are three different states. Restoring updates after a network interruption matters, of course. But if the connection remains open while market updates have gone silent, the strategy still needs its own safeguards. When a target quote becomes stale, the strategy should stop using it to open positions. Once updates resume, it should also reconcile positions and pending orders instead of simply continuing the previous calculation.&lt;/p&gt;

&lt;p&gt;Under high volatility or with many instruments, it is also necessary to monitor the dropped-event, backpressure, buffer-capacity, and dropped-response counters exposed by ctx.connectors(). Logging every market update, redrawing a panel, or running slow queries can all slow down the event loop. A strategy that adapts better to market conditions therefore allocates subscriptions and computing resources according to the task at hand. Use lighter data for broad monitoring, add the necessary detail when focusing on a target, and prioritize the relevant quotes and account state while holding positions. When the market gets busy, the program should know which work comes first.&lt;/p&gt;

&lt;h2&gt;
  
  
  From Seeing a Change to Confirming a Completed Trade
&lt;/h2&gt;

&lt;p&gt;Once market data is pushed, substantial waits can still remain in the overall process if order placement blocks one order at a time and is followed by repeated fill queries. The new ctx.submit() allows accounts that support WebSocket trading to submit order and cancellation requests asynchronously. It returns a local request ID after sending the request, and the result is then received through ctx.poll().&lt;/p&gt;

&lt;p&gt;Below is a function that submits an IOC limit order. Price, quantity, and minimum-order requirements should be checked against the target market's rules before calling it. This illustrates the trading entry point, not a complete order-management system.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sendIOC(ex, symbol, side, price, amount, reduceOnly) {
    var req = {
        op: "order", symbol: symbol, side: side,
        price: price, amount: amount, tif: "ioc"
    };
    if (reduceOnly) req.reduceOnly = true;

    var localId = ctx.submit(ex, req);
    if (localId instanceof Error) {
        throw localId; // The request was not sent, so no corresponding response will arrive.
    }
    return localId;
}

// In the main loop, correlate the three stages using localId:
// ack.reqId      → Request result
// order.clientId → Order state, cumulative filled quantity, and average fill price
// fill.clientId  → Each actual fill and its fee information

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Asynchronous trading lets the program continue processing market data while waiting for reports, and makes it easier to send requests for several legs promptly. For trading across exchanges, this is better aligned with practical needs than waiting for one leg to return before handling the other. But a request being sent, receiving a successful acknowledgment, and the order actually filling are different things. A successful ack does not mean a position has been established. Actual quantities and prices still need to be checked against orders, fills, and positions. If the result is unknown, the original request may already have been accepted. The correct approach is to keep it pending and query by client order ID or wait for confirmation from the private stream, rather than simply submitting the order again.&lt;/p&gt;

&lt;p&gt;ctx.submit() itself uses only WebSocket. If it is unsupported, it returns an error and does not switch automatically to REST. A strategy can implement its own fallback, but it must confirm that the original request was not sent so that it does not send another request while the outcome remains uncertain. ctx.order() and ctx.cancel() use the REST trading path and should not be confused with it. Asynchronous trading documentation&lt;/p&gt;

&lt;p&gt;Batch submissions also require checking each result. Exchanges differ in their batch mechanisms and limits, and a batch may succeed only partially. Across two exchanges, sending requests at the same time certainly does not guarantee that both will fill at the same time. WebSocket improves how execution is organized; the strategy still has to manage unmatched legs, partial fills, and rate limits.&lt;/p&gt;

&lt;h2&gt;
  
  
  A Practical Application
&lt;/h2&gt;

&lt;p&gt;Consider the classic strategy of trading the convergence of spreads across exchanges. A traditional implementation calls each exchange's market data interface separately and compares spreads after the quotes arrive. As the number of instruments grows, a query cycle becomes longer: the first exchange's quote has arrived while the second is still pending, and by the time the comparison begins, the earlier price may have changed again. After placing orders, the strategy usually continues querying them to check how much each leg has filled and whether any orders remain outstanding.&lt;/p&gt;

&lt;p&gt;WebSocket can organize this process differently. At startup, the strategy subscribes to BBO data for the instruments being scanned and uses latest mode to maintain each exchange's latest best bid and ask. As quotes arrive, ctx.poll() updates the corresponding instrument's state, and the strategy checks whether trading conditions are met. It can make decisions as market data arrives, reducing the wait associated with querying instruments one at a time. It must still check the freshness of both quotes to avoid directly comparing prices from different times.&lt;/p&gt;

&lt;p&gt;The scope of monitoring does not have to remain equally broad throughout. Once positions are open, the two legs already carrying exposure deserve more attention. The strategy unsubscribes from unrelated market data, retains only the target quotes, and resumes scanning after it exits. The account's private stream stays subscribed throughout, so order and position reports continue to arrive even as the market data focus changes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1x3bv4ypkgs3ttjq6l83.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1x3bv4ypkgs3ttjq6l83.png" alt=" " width="799" height="428"&gt;&lt;/a&gt;&lt;br&gt;
When it is time to trade, accounts that support WebSocket order placement use ctx.submit() to send requests for both legs promptly, and the program then continues processing events. A new quote may arrive first, or a fill on one leg may arrive first; either way, the corresponding records need to be updated. ack confirms the request result, while order and fill reports establish actual quantities and prices. Positions are then checked to confirm whether the two sides match. Market data continues to enter the same processing flow while the program waits for order results.&lt;/p&gt;

&lt;p&gt;After the two requests have been sent, their respective fills still need to be tracked. If an outcome remains uncertain, retain the pending state and wait for a report or query for confirmation. REST still supports initialization, missing-data retrieval, and necessary account checks. Any fallback for order placement must also begin by establishing whether the original request was sent.&lt;/p&gt;

&lt;p&gt;Following a single trade makes the relationship between these interfaces clear: the program continuously receives quotes, organizes its work around changes, keeps tracking after submitting orders, and reconciles the actual results. This also makes the next questions more specific: how long did a quote wait inside the program, which leg was confirmed first, and how much did the market change in the meantime? These records provide the basis for judging whether the interface changes have improved actual operation.&lt;/p&gt;

</description>
      <category>fmzquant</category>
      <category>quanttrading</category>
      <category>cryptotrading</category>
      <category>tradingbot</category>
    </item>
    <item>
      <title>REA Is Gaining Attention. It Made Me Wonder: Can AI Analyze My Strategy from Its Live Trading Logs?</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Wed, 18 Nov 2026 03:29:33 +0000</pubDate>
      <link>https://dev.to/quant001/rea-is-gaining-attention-it-made-me-wonder-can-ai-analyze-my-strategy-from-its-live-trading-logs-2fci</link>
      <guid>https://dev.to/quant001/rea-is-gaining-attention-it-made-me-wonder-can-ai-analyze-my-strategy-from-its-live-trading-logs-2fci</guid>
      <description>&lt;p&gt;Let me start with the result.&lt;br&gt;
When the first report came back, it looked convincing. The AI had listed the trading timeframe, the Bollinger Band parameters, and the weights for the layered orders, with a complete implementation attached. Looking at that submission alone, it was easy to think: has it figured out this strategy completely?&lt;/p&gt;

&lt;p&gt;I then gave it a link to the original strategy and asked it to compare its work against the source code. That was when things turned out to be more complicated: &lt;strong&gt;some parameters matched, but the trading rules were not entirely the same&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I wanted to understand what it had actually recognized in the records and where it had filled in the gaps with its own guesses. The differences gradually became clearer when I put the analysis process alongside the final source-code comparison.&lt;/p&gt;
&lt;h2&gt;
  
  
  REA Inspired a Strategy-Inference Experiment
&lt;/h2&gt;

&lt;p&gt;REA has been getting attention lately. It provides reverse-engineering tools for agents to analyze programs, applications, and their runtime behavior. That gave me an idea: quantitative strategies leave plenty of records every day, too. Could an AI first observe how a strategy buys and sells, then infer the program behind it? About the REA project&lt;/p&gt;

&lt;p&gt;So I selected a publicly viewable bot and asked a coding agent to examine its runtime records, then submit strategy code that it considered a plausible explanation. Only after it had submitted its work did I provide the link to the original strategy. REA inspired this experiment, but the coding agent did the actual analysis and programming. REA itself was not involved.&lt;/p&gt;

&lt;p&gt;I used Codex for this experiment; the model selected in the screenshots is GPT-6 Astra Ultra. Below, I walk through the analysis, the submission, and the comparison against the source code, in that order.&lt;/p&gt;
&lt;h2&gt;
  
  
  Both the Test Case and the Reference Answer Are Public
&lt;/h2&gt;

&lt;p&gt;I chose bot 674839, named D-Man V3 FMZ Rust on its page. The reference, strategy 546875, also has a public page, where the version is listed as v1.1.1; the full source code is available after signing in. I chose it precisely because there would be an answer to check at the end: I could compare the AI's claims against the code, item by item.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fggfzli7ww4a7os1gyunx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fggfzli7ww4a7os1gyunx.png" alt=" " width="800" height="382"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;This screenshot was saved at the time of the experiment. The figures reflect that moment.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;One detail needs to be made clear upfront: the analysis records mention a simulate flag in the exchange scope. Although the platform labels this a “live trading bot” page, the name alone does not establish whether it was trading real money. What I am examining here is the record of its operation. &lt;strong&gt;The returns shown on the page are not treated as verified real-money performance&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Runtime records are not a ready-made strategy manual, though. If you see three buys, for example, can you conclude that the strategy added to its position three times? It could just be one order filled in three parts. I wanted to see whether the AI could connect these scattered records and explain the order-placement rules behind them.&lt;/p&gt;
&lt;h2&gt;
  
  
  What Did I Ask It to Do in the First Round?
&lt;/h2&gt;

&lt;p&gt;My request was simple: I gave it the bot link and asked it to use only the runtime data on that page, without accessing the original source code or strategy description. After analyzing the data, it was to do more than write a paragraph explaining “roughly what kind of strategy this is.” It also had to deliver candidate code that was as complete as possible.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkp50ba773tknw4qlneqi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkp50ba773tknw4qlneqi.png" alt=" " width="800" height="706"&gt;&lt;/a&gt;&lt;br&gt;
The screenshot above shows the prompt and model selected at the time.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc5nhlnbxswyuulbokanq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc5nhlnbxswyuulbokanq.png" alt=" " width="800" height="268"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  The Clues Went Beyond a Few Buys and Sells
&lt;/h2&gt;

&lt;p&gt;It first reported a set of figures: &lt;strong&gt;9,894 public log entries and 54 profit data points&lt;/strong&gt;. I am keeping the term “profit data points” used during the analysis here. The final report called them “54 cycles,” which is an inconsistent description; they cannot simply be taken as the number of fills or complete trading cycles.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fluume9ops2vo0ljauo2k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fluume9ops2vo0ljauo2k.png" alt=" " width="800" height="508"&gt;&lt;/a&gt;&lt;br&gt;
Reading further, I found that the logs already contained many of the answers. According to the report, the 30-minute timeframe, Bollinger Bands calculated from 100 candlesticks, two standard deviations, four layers of staged orders, and capital weights of 1:1:1.5:2.5 could all be found directly in the logs.&lt;/p&gt;

&lt;p&gt;So when it lists a series of accurate parameters, do not rush to give it full marks. &lt;strong&gt;Reading parameters explicitly stated in the logs means organizing information that is already there; working backward from order quantities to a capital-allocation formula means inferring the rules behind them&lt;/strong&gt;. Both are useful, but they cannot all be counted as “figuring it out from the trading actions alone.”&lt;/p&gt;

&lt;p&gt;The report also claimed that a single formula explained 216 observed order quantities, and it inferred exit multiples, a trailing take-profit rule, and a cooldown of roughly two hours. These were the agent's inferences. I noted them down so that, once the source code was revealed, we could see how many matched.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Submission: What Kind of Strategy Did It Write?
&lt;/h2&gt;

&lt;p&gt;It summarized the strategy as “Bollinger Band reversal entries, four layers of staged orders, and volatility-scaled exits.” In simple terms, it looked for reversal entries when the price reached the edges of the Bollinger Bands, placed orders at four levels, and set exit conditions according to the size of the volatility measure. It then wrote a candidate JavaScript implementation based on that interpretation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8ft7w9fy5pg6md4of56d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8ft7w9fy5pg6md4of56d.png" alt=" " width="800" height="731"&gt;&lt;/a&gt;&lt;br&gt;
The code comments also reveal what it had not resolved: exactly what triggers an entry, how the anchor is set, how the volatility scale is calculated, and where the cooldown boundary lies. It did not present all of these as settled answers. For example, it could not identify an order-expiry rule, so that feature was disabled by default in the code.&lt;/p&gt;

&lt;p&gt;The complete code is included in the appendix for line-by-line inspection. It defaults to PAPER mode, meaning it starts with simulated operation. A simulation default does not mean it has passed a backtest or been verified as a faithful reconstruction.&lt;/p&gt;

&lt;p&gt;Once an interpretation becomes code, some ambiguities can no longer hide. “Buy when it falls, sell when it rises” sounds straightforward, but a program cannot avoid the details: how far must the price fall before buying? How much should it buy? What if there is already a position? What if an order has been placed but remains unfilled? Once these questions have explicit answers in code, they can be compared with the original one by one.&lt;/p&gt;
&lt;h2&gt;
  
  
  Revealing the Source: How Do Two Similar-Sounding Rules Differ?
&lt;/h2&gt;

&lt;p&gt;It was time to check the answer. I provided the original strategy link and asked the agent to compare its newly submitted code against the original, item by item. According to the comparison record, the first-round code was kept unchanged; it was not revised after the source code had been viewed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgf2wb59i09mu0v4moj3c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgf2wb59i09mu0v4moj3c.png" alt=" " width="800" height="500"&gt;&lt;/a&gt;&lt;br&gt;
In the comparison report, the four layer weights, several exit multiples, and the roughly two-hour cooldown all matched. The entry rule was where a difference emerged: &lt;strong&gt;the report said the original strategy required an “initial crossing outside the band,” whereas the candidate code checked whether the price was “currently outside the band&lt;/strong&gt;.” Looking at the candidate code, it checks whether the closing price of the latest completed candlestick touches or moves beyond either Bollinger Band. It does not also check whether the preceding candlestick was inside the bands.&lt;/p&gt;

&lt;p&gt;Those two formulations may sound similar, but a short price sequence makes the difference clear. For this comparison, imagine the lower Bollinger Band as a fixed horizontal line: the price starts above it, falls below it, and then stays below it for two more candlesticks.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;“Initial crossing outside the band” looks for the crossing itself, so it needs to compare the states before and after.&lt;/li&gt;
&lt;li&gt;“Currently outside the band” looks only at the present position, so the next two candlesticks may still satisfy the condition.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here, we are looking only at the &lt;strong&gt;signal condition&lt;/strong&gt;. Even when that condition is met, the program must still check positions, cooldown, and budget before deciding whether to place an order. Each signal therefore cannot be treated as an actual fill. Nevertheless, the entry checks alone already show that these are different rules.&lt;/p&gt;

&lt;p&gt;Some differences were less obvious. The report noted that the original had an equity-based budget cap, entry-order expiry, and a maximum holding period, and that the first-round code had not reproduced equivalent versions of these controls. It is easy to see why: if the budget never reaches its cap during a stretch of trading, orders fill quickly, and positions close quickly, these constraints can be difficult to detect from trading actions.&lt;/p&gt;

&lt;p&gt;As a result, several different sets of rules may all explain the same runtime records. They happen to do similar things in that stretch of the market, and only make different choices when some condition changes.&lt;/p&gt;
&lt;h2&gt;
  
  
  What Can We Conclude from This Experiment?
&lt;/h2&gt;

&lt;p&gt;After the agent finished comparing its work against the source code, the result was somewhat disappointing.&lt;br&gt;
If the goal was to give an AI the link to a bot you liked and receive a strategy that reproduced it completely, this experiment did not achieve that. It recognized the broad approach and correctly identified quite a few parameters, but failed to reconstruct several key details that affect trading. To me, it looked more like taking inspiration from the original, imitating it, and filling in the rest with its own interpretation. &lt;strong&gt;What it wrote was essentially a new strategy&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fduczlltv4rpuslv4wzws.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fduczlltv4rpuslv4wzws.png" alt=" " width="800" height="361"&gt;&lt;/a&gt;&lt;br&gt;
According to the comparison report, &lt;strong&gt;the strategy framework and several parameters were identified correctly, but the first-round code did not reproduce the original strategy's behavior&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Another distinction can easily get blurred here. Some differences may have resulted from the AI overlooking available clues; other rules may not have left any identifiable trace in these records. Both show up as a “failure to reconstruct,” but they call for different improvements. Simply phrasing the question differently cannot guarantee that missing evidence will appear.&lt;/p&gt;

&lt;p&gt;This article presents the agent's source-code comparison results. They do not justify a numerical claim about “what percentage was reconstructed.” Quantifying the behavioral gap would require a trade-by-trade replay and validation against independent market data. This result shows that this candidate code failed to reproduce the original strategy; it does not support a conclusion about all models.&lt;/p&gt;
&lt;h2&gt;
  
  
  What Does It Mean for AI to Learn a Trading Pattern?
&lt;/h2&gt;

&lt;p&gt;Once the source was revealed, the mismatches made the idea of “learning a strategy” more concrete. &lt;strong&gt;Recognizing Bollinger Bands and staged orders is only a starting point; the AI also needs to understand under what conditions the strategy changes its decision&lt;/strong&gt;. The differences in entry conditions and execution constraints brought that question into focus.&lt;/p&gt;

&lt;p&gt;If the price falls below the lower band in two different instances, why does one result in a fill while the other does not? There may already have been a position, the strategy may still have been in cooldown, or an order may have been placed but never filled. Giving the AI these cases together with the market conditions, positions, and order states at the time gives it a chance to distinguish between the possible explanations.&lt;/p&gt;

&lt;p&gt;That makes the choice of examples important, too. A long series of ordinary position entries and exits may reveal few hidden conditions. Cases where an order remains unfilled for a long time, a position stays open for a long time, or the budget approaches its cap deserve a closer look. Asking the AI to list possible explanations for these cases and identify the evidence each would require gives the analysis a concrete focus.&lt;/p&gt;

&lt;p&gt;For people researching strategies, this analysis can help organize the reasons for entering trades, the position sizing, and the exit conditions, then assess which ideas are worth learning from. The candidate code turns that understanding into a program. Whether it will make choices close to the original strategy's in new market conditions still needs to be tested.&lt;/p&gt;

&lt;p&gt;So when an AI says, “I understand this strategy,” I would rather follow up with: &lt;strong&gt;given the same market conditions but a different position or order state, would it make a different choice? Which records support that judgment, and under what circumstances would it fail to hold?&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Appendix
&lt;/h2&gt;

&lt;p&gt;Candidate code generated in the first round of analysis:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*
 * FMZ robot 674839 — behavioural reconstruction, NOT the original source.
 * Evidence: public live logs only (data/all_logs.json). No strategy source or
 * strategy description was consulted. JavaScript implementation for FMZ.
 *
 * Observed: ETH_USDT.swap, 30m BB100/2, price levels [.05,.35,.75,1.25],
 * weights [1,1,1.5,2.5]. 216 published quantities fit
 * floor((10000 * weight / 6) / limitPrice, .01) in FMZ order units.
 * A .1 ETH contract multiplier would make that a 1000 USDT nominal budget.
 * Strong inference: TP=1*v, SL=3*v, trailing activation=.8*v, fixed
 * trailing drawdown=.25*v, where v=scale/anchor. Cooldown is about four bars.
 * UNIDENTIFIED, therefore configurable assumptions: signal=%B outside [0,1],
 * anchor=last closed close, scale=.5*(upper-lower), population BB variance,
 * return reference=actual average entry, cooldown current-bar difference&amp;gt;4.
 * No order TTL was identified: disabled by default.
 *
 * DEFAULT PAPER. This file never creates a robot or configures account mode.
 * LIVE is opt-in and requires valid contract metadata, explicit confirmation,
 * an otherwise unused account/instrument, and preconfigured hedge position mode.
 * PAPER fills only against subsequent observed ticks, not historical bar paths;
 * it is a transparent simulator, not a claimed reconstruction backtest.
 *
 * Runtime interfaces (official technical documentation):
 * https://www.fmz.com/syntax-guide/fun/trade/exchange.createorder
 * https://www.fmz.com/syntax-guide/fun/futures
 * https://www.fmz.com/syntax-guide/struct/market
 * https://www.fmz.com/syntax-guide/struct/account
 * https://www.fmz.com/syntax-guide/fun/storage
 */

var RECON_DEFAULTS = {
    RunMode: "PAPER",
    Symbol: "ETH_USDT.swap",
    PeriodSeconds: 1800,
    BBPeriod: 100,
    BBDeviations: 2,
    BBWidthMultiplier: 0.5, // UNKNOWN original definition: modelling assumption.
    SignalMode: "OUTSIDE_BAND", // UNKNOWN original trigger.
    Levels: [0.05, 0.35, 0.75, 1.25],
    Weights: [1, 1, 1.5, 2.5],
    NominalBudgetUSDT: 1000,
    TakeProfitScale: 1,
    StopLossScale: 3,
    TrailingActivateScale: 0.8,
    TrailingDrawdownScale: 0.25,
    CooldownBars: 4, // Require currentBar - exitCurrentBar &amp;gt; CooldownBars.
    OrderTTLSeconds: 0, // No evidence for expiry; off by default.
    LoopMilliseconds: 2000,
    MaxTickerAgeMilliseconds: 30000,
    MaxClosedBarAgePeriods: 2,
    FlatConfirmations: 3,
    FlatConfirmationIntervalMilliseconds: 1500,
    StateKeyPrefix: "fmz674839_reconstruction_v1",
    AccountScope: "PAPER_DEMO", // Unique account/subaccount LABEL; never put credentials here.
    LiveConfirmation: "", // Set to "I_ACCEPT_INFERRED_RULES" explicitly.
    ExpectedExchangeName: "Futures_OKCoin",
    ExpectedBasePerOrderUnit: 0.1, // Evidence-based candidate; LIVE validates metadata.
    AllowExplicitContractMetadata: false,
    ExplicitContractBasePerUnit: null,
    RequireValidEquityForEntry: true,
    MaxGrossNotionalMultiplier: 1.25,
    MinimumMarginReserveUSDT: 0,
    ReturnToMiddleBand: true, // Inferred: positive return AND mark reaches closed-bar BB middle.
    PaperInitialEquity: 1000,
    PaperBasePerOrderUnit: 0.1,
    PaperTickSize: 0.01,
    PaperAmountStep: 0.01,
    PaperMinQty: 0.01,
    PaperMinNotional: 0,
    PaperTakerFeeRate: 0.0005,
    PaperMakerFeeRate: 0.0002,
    PaperMarketSlippageBps: 2,
    PaperFillFractionPerTick: 1
};

function reconClone(x) { return JSON.parse(JSON.stringify(x)); }
function reconNumber(x) { return typeof x === "number" &amp;amp;&amp;amp; isFinite(x); }
function reconAssert(ok, msg) { if (!ok) { throw new Error(msg); } }
function reconStable(x) {
    if (Array.isArray(x)) { return "[" + x.map(reconStable).join(",") + "]"; }
    if (x &amp;amp;&amp;amp; typeof x === "object") {
        return "{" + Object.keys(x).sort().map(function (k) {
            return JSON.stringify(k) + ":" + reconStable(x[k]);
        }).join(",") + "}";
    }
    return JSON.stringify(x);
}
function reconFingerprint(config) {
    var s = reconStable(config), h = 2166136261;
    for (var i = 0; i &amp;lt; s.length; i++) {
        h ^= s.charCodeAt(i);
        h = Math.imul(h, 16777619) &amp;gt;&amp;gt;&amp;gt; 0;
    }
    return "v1-" + ("00000000" + h.toString(16)).slice(-8);
}
function reconConfig(input) {
    var c = reconClone(RECON_DEFAULTS), k;
    input = input || {};
    for (k in input) {
        reconAssert(Object.prototype.hasOwnProperty.call(c, k), "Unknown configuration: " + k);
        c[k] = reconClone(input[k]);
    }
    reconAssert(c.RunMode === "PAPER" || c.RunMode === "LIVE", "RunMode must be PAPER or LIVE");
    reconAssert(typeof c.AccountScope === "string" &amp;amp;&amp;amp; /^[A-Za-z0-9_.-]{1,80}$/.test(c.AccountScope), "Invalid AccountScope label");
    reconAssert(/^[A-Z0-9]+_USDT\.swap$/.test(c.Symbol), "Only USDT linear perpetual symbols supported");
    ["PeriodSeconds", "BBPeriod", "BBDeviations", "BBWidthMultiplier", "NominalBudgetUSDT",
        "TakeProfitScale", "StopLossScale", "TrailingActivateScale", "TrailingDrawdownScale",
        "LoopMilliseconds", "MaxTickerAgeMilliseconds", "FlatConfirmationIntervalMilliseconds",
        "MaxGrossNotionalMultiplier", "PaperInitialEquity", "PaperBasePerOrderUnit", "PaperTickSize",
        "PaperAmountStep", "PaperMinQty"].forEach(function (name) {
        reconAssert(reconNumber(c[name]) &amp;amp;&amp;amp; c[name] &amp;gt; 0, name + " must be positive");
    });
    ["CooldownBars", "OrderTTLSeconds", "MinimumMarginReserveUSDT", "PaperMinNotional",
        "PaperTakerFeeRate", "PaperMakerFeeRate", "PaperMarketSlippageBps"].forEach(function (name) {
        reconAssert(reconNumber(c[name]) &amp;amp;&amp;amp; c[name] &amp;gt;= 0, name + " must be nonnegative");
    });
    reconAssert(Number.isInteger(c.BBPeriod) &amp;amp;&amp;amp; c.BBPeriod &amp;gt;= 2, "Invalid BB period");
    reconAssert(Number.isInteger(c.PeriodSeconds) &amp;amp;&amp;amp; c.PeriodSeconds &amp;gt;= 60, "Invalid candle period");
    reconAssert(Number.isInteger(c.CooldownBars), "CooldownBars must be integral");
    reconAssert(Number.isInteger(c.FlatConfirmations) &amp;amp;&amp;amp; c.FlatConfirmations &amp;gt;= 3, "At least 3 flat confirmations required");
    reconAssert(c.SignalMode === "OUTSIDE_BAND", "Unsupported signal model");
    ["AllowExplicitContractMetadata", "RequireValidEquityForEntry", "ReturnToMiddleBand"].forEach(function (name) {
        reconAssert(typeof c[name] === "boolean", name + " must be a boolean");
    });
    reconAssert(c.Levels.length === 4 &amp;amp;&amp;amp; c.Weights.length === 4, "Exactly four DCA layers required");
    c.Levels.forEach(function (x, i) {
        reconAssert(reconNumber(x) &amp;amp;&amp;amp; x &amp;gt; 0 &amp;amp;&amp;amp; (!i || x &amp;gt; c.Levels[i - 1]), "Invalid levels");
        reconAssert(reconNumber(c.Weights[i]) &amp;amp;&amp;amp; c.Weights[i] &amp;gt; 0, "Invalid weights");
    });
    reconAssert(c.PaperFillFractionPerTick &amp;gt; 0 &amp;amp;&amp;amp; c.PaperFillFractionPerTick &amp;lt;= 1, "Invalid paper fill fraction");
    return c;
}
function reconRoundStep(value, step, direction) {
    reconAssert(reconNumber(value) &amp;amp;&amp;amp; reconNumber(step) &amp;amp;&amp;amp; step &amp;gt; 0, "Invalid rounding input");
    var units = value / step;
    var rounded = direction === "up" ? Math.ceil(units - 1e-10) : Math.floor(units + 1e-10);
    return Number((rounded * step).toFixed(12));
}
function reconClosedCandles(records, now, periodSeconds) {
    reconAssert(Array.isArray(records), "Candle query failed");
    var result = [], seen = {}, period = periodSeconds * 1000;
    records.forEach(function (r) {
        reconAssert(r &amp;amp;&amp;amp; reconNumber(r.Time) &amp;amp;&amp;amp; reconNumber(r.Close) &amp;amp;&amp;amp; r.Close &amp;gt; 0, "Malformed candle");
        if (r.Time + period &amp;lt;= now) {
            reconAssert(!seen[r.Time], "Duplicate candle timestamp");
            seen[r.Time] = true;
            result.push(r);
        }
    });
    result.sort(function (a, b) { return a.Time - b.Time; });
    return result;
}
function reconBollinger(records, period, deviations) {
    reconAssert(records.length &amp;gt;= period, "Insufficient closed candles");
    var x = records.slice(-period), mean = 0, variance = 0;
    x.forEach(function (r) { mean += r.Close / period; });
    x.forEach(function (r) { variance += Math.pow(r.Close - mean, 2) / period; });
    var sd = Math.sqrt(variance);
    return { middle: mean, upper: mean + deviations * sd, lower: mean - deviations * sd, sd: sd };
}
function reconSignal(records, now, c) {
    var closed = reconClosedCandles(records, now, c.PeriodSeconds);
    if (closed.length &amp;lt; c.BBPeriod) { return null; }
    var recent = closed.slice(-c.BBPeriod), periodMs = c.PeriodSeconds * 1000;
    for (var i = 1; i &amp;lt; recent.length; i++) {
        reconAssert(recent[i].Time - recent[i - 1].Time === periodMs, "Candle gap in BB window");
    }
    var bar = closed[closed.length - 1];
    reconAssert(now - (bar.Time + periodMs) &amp;lt;= c.MaxClosedBarAgePeriods * periodMs, "Closed candles are stale");
    var bb = reconBollinger(closed, c.BBPeriod, c.BBDeviations), width = bb.upper - bb.lower;
    if (!(width &amp;gt; 0)) { return { time: bar.Time, side: null, close: bar.Close, bb: bb }; }
    var percentB = (bar.Close - bb.lower) / width;
    return {
        time: bar.Time, side: percentB &amp;lt;= 0 ? "LONG" : (percentB &amp;gt;= 1 ? "SHORT" : null),
        close: bar.Close, anchor: bar.Close, scale: c.BBWidthMultiplier * width,
        percentB: percentB, bb: bb
    };
}
function reconMarket(raw, c) {
    reconAssert(raw &amp;amp;&amp;amp; typeof raw === "object", "Missing contract market metadata");
    var base = c.Symbol.split("_")[0];
    var multiplier = raw.CtVal, unit = raw.CtValCcy;
    if (!(reconNumber(multiplier) &amp;amp;&amp;amp; multiplier &amp;gt; 0 &amp;amp;&amp;amp; unit === base)) {
        reconAssert(c.AllowExplicitContractMetadata &amp;amp;&amp;amp; reconNumber(c.ExplicitContractBasePerUnit) &amp;amp;&amp;amp;
            c.ExplicitContractBasePerUnit &amp;gt; 0, "Missing/ambiguous CtVal or CtValCcy; refuses guessed LIVE quantity");
        multiplier = c.ExplicitContractBasePerUnit;
    }
    if (c.ExpectedBasePerOrderUnit !== null) {
        reconAssert(reconNumber(c.ExpectedBasePerOrderUnit) &amp;amp;&amp;amp;
            Math.abs(multiplier - c.ExpectedBasePerOrderUnit) &amp;lt; 1e-12, "Contract multiplier does not match configured expectation");
    }
    ["TickSize", "AmountSize", "MinQty"].forEach(function (k) {
        reconAssert(reconNumber(raw[k]) &amp;amp;&amp;amp; raw[k] &amp;gt; 0, "Missing/invalid " + k);
    });
    ["MinNotional", "MaxQty", "MaxNotional"].forEach(function (k) {
        if (raw[k] !== undefined &amp;amp;&amp;amp; raw[k] !== null) {
            reconAssert(reconNumber(raw[k]) &amp;amp;&amp;amp; raw[k] &amp;gt;= 0, "Invalid " + k);
        }
    });
    return { basePerUnit: multiplier, tick: raw.TickSize, step: raw.AmountSize, minQty: raw.MinQty,
        maxQty: raw.MaxQty || Infinity, minNotional: raw.MinNotional || 0,
        maxNotional: raw.MaxNotional || Infinity };
}
function reconBuildLayers(signal, market, c) {
    reconAssert(signal.side === "LONG" || signal.side === "SHORT", "Invalid signal direction");
    reconAssert(signal.anchor &amp;gt; 0 &amp;amp;&amp;amp; signal.scale &amp;gt; 0, "Invalid signal anchor/scale");
    var sum = c.Weights.reduce(function (a, b) { return a + b; }, 0);
    return c.Levels.map(function (distance, i) {
        var p = signal.anchor + (signal.side === "LONG" ? -1 : 1) * signal.scale * distance;
        p = reconRoundStep(p, market.tick, signal.side === "LONG" ? "down" : "up");
        reconAssert(p &amp;gt; 0, "Nonpositive DCA price");
        var q = reconRoundStep(c.NominalBudgetUSDT * c.Weights[i] / sum / (p * market.basePerUnit), market.step, "down");
        var nominal = q * p * market.basePerUnit;
        reconAssert(q &amp;gt;= market.minQty &amp;amp;&amp;amp; q &amp;lt;= market.maxQty &amp;amp;&amp;amp; nominal &amp;gt;= market.minNotional &amp;amp;&amp;amp;
            nominal &amp;lt;= market.maxNotional, "Layer violates exchange min/max limits");
        return { index: i, price: p, quantity: q, nominal: nominal, status: "PLANNED", orderId: null };
    });
}
function reconPosition(positions, symbol, longConstant, shortConstant) {
    reconAssert(Array.isArray(positions), "Position query failed");
    var result = { long: 0, short: 0, longCost: 0, shortCost: 0, frozen: 0 };
    positions.forEach(function (p) {
        reconAssert(p &amp;amp;&amp;amp; typeof p.Symbol === "string", "Position lacks unambiguous symbol");
        if (p.Symbol !== symbol) { return; }
        reconAssert(reconNumber(p.Amount) &amp;amp;&amp;amp; p.Amount &amp;gt;= 0 &amp;amp;&amp;amp; reconNumber(p.Price), "Malformed position");
        if (p.Amount === 0) { return; }
        reconAssert(p.Price &amp;gt; 0, "Position average price unavailable");
        var side = p.Type === longConstant ? "long" : p.Type === shortConstant ? "short" : null;
        reconAssert(side !== null, "Unknown position direction");
        result[side] += p.Amount;
        result[side + "Cost"] += p.Amount * p.Price;
        if (reconNumber(p.FrozenAmount) &amp;amp;&amp;amp; p.FrozenAmount &amp;gt; 0) { result.frozen += p.FrozenAmount; }
    });
    result.longAverage = result.long ? result.longCost / result.long : 0;
    result.shortAverage = result.short ? result.shortCost / result.short : 0;
    return result;
}
function reconExit(cycle, position, price, c) {
    var long = cycle.side === "LONG", amount = long ? position.long : position.short;
    if (!(amount &amp;gt; 0)) { return null; }
    var average = long ? position.longAverage : position.shortAverage;
    var ret = (long ? 1 : -1) * (price - average) / average;
    var v = cycle.scale / cycle.anchor;
    var peak = cycle.peakReturn === null ? ret : Math.max(cycle.peakReturn, ret);
    var reason = null;
    if (ret &amp;lt;= -c.StopLossScale * v) { reason = "STOP_LOSS"; }
    else if (ret &amp;gt;= c.TakeProfitScale * v) { reason = "TAKE_PROFIT"; }
    else if (peak &amp;gt;= c.TrailingActivateScale * v &amp;amp;&amp;amp; peak - ret &amp;gt;= c.TrailingDrawdownScale * v) {
        reason = "TRAILING_STOP";
    }
    return { reason: reason, returnRate: ret, peak: peak, volatilityUnit: v };
}
function reconValidateReceipt(order, intent, market) {
    reconAssert(order &amp;amp;&amp;amp; order.Symbol === intent.symbol &amp;amp;&amp;amp; order.Id !== undefined, "Receipt symbol/ID mismatch");
    reconAssert(reconNumber(order.Amount) &amp;amp;&amp;amp; Math.abs(order.Amount - intent.quantity) &amp;lt;= market.step * 0.01,
        "Receipt quantity mismatch");
    var buy = intent.side === "buy" || intent.side === "closesell";
    reconAssert(order.Type === (buy ? 0 : 1), "Receipt buy/sell direction mismatch");
    reconAssert(order.Offset === (intent.purpose === "CLOSE" ? 1 : 0), "Receipt open/close direction mismatch; hedge mode required");
    reconAssert(reconNumber(order.Price), "Receipt price missing");
    if (intent.price === -1) {
        reconAssert(order.Price === 0 || order.Price === -1, "Receipt is not an identifiable market order");
    } else {
        reconAssert(Math.abs(order.Price - intent.price) &amp;lt;= market.tick * 0.1, "Receipt limit price mismatch");
    }
    if (order.Time !== undefined &amp;amp;&amp;amp; order.Time !== null &amp;amp;&amp;amp; order.Time !== 0) {
        reconAssert(reconNumber(order.Time) &amp;amp;&amp;amp; Math.abs(order.Time - intent.createdAt) &amp;lt;= 120000,
            "Receipt creation time differs from intent by over two minutes");
    }
    return true;
}
function reconInitialState(c, now) {
    return { schema: 1, fingerprint: reconFingerprint(c), config: reconClone(c), mode: c.RunMode,
        symbol: c.Symbol, phase: "BOOT", previousPhase: null, paused: false, reasons: [],
        createdAt: now, updatedAt: now, sequence: 0, lastSignalBar: null, exitCurrentBar: null,
        flatCount: 0, lastFlatAt: 0, cycle: null, orders: {}, intents: {}, completed: 0,
        initialEquity: null, lastEquity: null, lastPnl: null, paper: null, mismatch: false };
}

/* PAPER broker. Orders fill on the NEXT broker tick after creation. */
function ReconPaper(c, state) {
    this.c = c;
    this.s = state || { cash: c.PaperInitialEquity, long: 0, short: 0, longAvg: 0, shortAvg: 0,
        orders: {}, nextId: 1, fees: 0, realized: 0, tick: 0, price: null };
}
ReconPaper.prototype.update = function (price, market) {
    reconAssert(reconNumber(price) &amp;amp;&amp;amp; price &amp;gt; 0, "Invalid PAPER tick");
    var self = this;
    this.s.tick++;
    this.s.price = price;
    Object.keys(this.s.orders).forEach(function (id) {
        var o = self.s.orders[id];
        if (o.Status !== 0 || o.createdTick &amp;gt;= self.s.tick) { return; }
        var buy = o.side === "buy" || o.side === "closesell";
        if (o.Price !== -1 &amp;amp;&amp;amp; !(buy ? price &amp;lt;= o.Price : price &amp;gt;= o.Price)) { return; }
        var remain = Math.max(0, o.Amount - o.DealAmount);
        var q = reconRoundStep(Math.max(market.step, remain * self.c.PaperFillFractionPerTick), market.step, "down");
        q = Math.min(remain, q);
        var close = o.side === "closebuy" || o.side === "closesell";
        var side = o.side === "buy" || o.side === "closebuy" ? "long" : "short";
        if (close) { q = Math.min(q, self.s[side]); }
        if (!(q &amp;gt; 1e-12)) { o.Status = 2; return; }
        var px = o.Price === -1 ? price * (1 + (buy ? 1 : -1) * self.c.PaperMarketSlippageBps / 10000) : o.Price;
        var feeRate = o.Price === -1 ? self.c.PaperTakerFeeRate : self.c.PaperMakerFeeRate;
        var fee = q * market.basePerUnit * px * feeRate;
        if (close) {
            var realized = (side === "long" ? 1 : -1) * q * market.basePerUnit * (px - self.s[side + "Avg"]);
            self.s.cash += realized;
            self.s.realized += realized;
            self.s[side] = Math.max(0, self.s[side] - q);
            if (self.s[side] &amp;lt; market.step * 0.01) { self.s[side] = 0; self.s[side + "Avg"] = 0; }
        } else {
            self.s[side + "Avg"] = (self.s[side] * self.s[side + "Avg"] + q * px) / (self.s[side] + q);
            self.s[side] += q;
        }
        self.s.cash -= fee;
        self.s.fees += fee;
        o.AvgPrice = (o.AvgPrice * o.DealAmount + px * q) / (o.DealAmount + q);
        o.DealAmount += q;
        if (o.DealAmount &amp;gt;= o.Amount - market.step * 0.01) { o.Status = 1; }
    });
};
ReconPaper.prototype.submit = function (symbol, side, price, qty) {
    var id = "PAPER," + this.s.nextId++;
    this.s.orders[id] = { Id: id, Symbol: symbol, side: side, Price: price, Amount: qty,
        DealAmount: 0, AvgPrice: 0, Status: 0, Type: side === "buy" || side === "closesell" ? 0 : 1,
        Offset: side === "closebuy" || side === "closesell" ? 1 : 0, createdTick: this.s.tick };
    return id;
};
ReconPaper.prototype.cancel = function (id) {
    var o = this.s.orders[id];
    if (!o) { return false; }
    if (o.Status === 0) { o.Status = 2; }
    return true;
};
ReconPaper.prototype.getOrder = function (id) { return this.s.orders[id] ? reconClone(this.s.orders[id]) : null; };
ReconPaper.prototype.snapshot = function (market, symbol) {
    var p = [], s = this.s;
    if (s.long &amp;gt; 0) { p.push({ Symbol: symbol, Type: 0, Amount: s.long, Price: s.longAvg, FrozenAmount: 0 }); }
    if (s.short &amp;gt; 0) { p.push({ Symbol: symbol, Type: 1, Amount: s.short, Price: s.shortAvg, FrozenAmount: 0 }); }
    var upnl = market.basePerUnit * (s.long * (s.price - s.longAvg) + s.short * (s.shortAvg - s.price));
    return { positions: p, orders: Object.keys(s.orders).map(function (id) { return reconClone(s.orders[id]); })
        .filter(function (o) { return o.Status === 0; }),
        account: { Balance: s.cash, Equity: s.cash + upnl, UPnL: upnl } };
};

function ReconEngine(config, adapter, io) {
    this.c = reconConfig(config);
    this.a = adapter;
    this.io = io || {};
    this.now = 0;
    this.market = null;
    this.lastSnapshot = null;
    this.lastPosition = null;
    this.lastSnapshotAt = 0;
    this.snapshotHealthy = false;
    this.liveAuthorized = false;
    this.key = this.c.StateKeyPrefix + ":" + this.c.RunMode + ":" + this.c.ExpectedExchangeName +
        ":" + this.c.AccountScope + ":" + this.c.Symbol;
    var stored = this.io.load ? this.io.load(this.key) : null;
    this.s = stored ? reconClone(stored) : reconInitialState(this.c, Date.now());
    reconAssert(this.s.schema === 1 &amp;amp;&amp;amp; this.s.symbol === this.c.Symbol &amp;amp;&amp;amp; this.s.mode === this.c.RunMode,
        "Stored state schema/symbol/mode mismatch; manual migration required");
    this.paper = this.c.RunMode === "PAPER" ? new ReconPaper(this.c, this.s.paper) : null;
    if (this.s.fingerprint !== reconFingerprint(this.c)) {
        this.s.mismatch = true;
        this.freeze("Configuration fingerprint differs from persisted state; manual migration required");
    }
    var self = this;
    Object.keys(this.s.intents).forEach(function (id) {
        if (self.s.intents[id].status === "SUBMITTING") {
            self.s.intents[id].status = "UNKNOWN";
            self.freeze("Interrupted submission intent " + id + "; never auto-resubmit");
        }
    });
}
ReconEngine.prototype.log = function (message, extra) {
    if (this.io.log) { this.io.log(message, extra === undefined ? "" : extra); }
};
ReconEngine.prototype.save = function () {
    this.s.updatedAt = this.now || Date.now();
    if (this.paper) { this.s.paper = reconClone(this.paper.s); }
    if (this.io.save) { this.io.save(this.key, reconClone(this.s)); }
};
ReconEngine.prototype.freeze = function (reason) {
    if (this.s.phase !== "FROZEN") { this.s.previousPhase = this.s.phase; }
    this.s.phase = "FROZEN";
    this.s.paused = true;
    if (this.s.cycle) { this.s.cycle.addingStopped = true; }
    this.s.flatCount = 0;
    if (this.s.reasons[this.s.reasons.length - 1] !== reason) {
        this.s.reasons.push(reason);
        this.s.reasons = this.s.reasons.slice(-30);
        this.log("FROZEN", reason);
    }
    this.save();
};
ReconEngine.prototype.unknown = function () {
    var self = this;
    return Object.keys(this.s.intents).some(function (id) {
        return self.s.intents[id].status === "UNKNOWN" || self.s.intents[id].status === "SUBMITTING";
    });
};
ReconEngine.prototype.queryOrder = function (id) {
    return this.paper ? this.paper.getOrder(id) : this.a.getOrder(id);
};
ReconEngine.prototype.submit = function (side, price, quantity, purpose, layer) {
    reconAssert(this.s.phase !== "FROZEN" &amp;amp;&amp;amp; !this.unknown(), "Order submission prohibited while uncertain");
    reconAssert(!this.s.paused || purpose === "CLOSE", "Opening while paused is prohibited");
    var intentId = "intent-" + (++this.s.sequence);
    var intent = { id: intentId, symbol: this.c.Symbol, side: side, price: price, quantity: quantity,
        purpose: purpose, layer: layer, createdAt: this.now, status: "SUBMITTING", orderId: null };
    this.s.intents[intentId] = intent;
    this.save(); // Durable write BEFORE the external side effect.
    var id;
    try {
        id = this.paper ? this.paper.submit(this.c.Symbol, side, price, quantity) :
            this.a.submit(this.c.Symbol, side, price, quantity);
    } catch (e) {
        intent.status = "UNKNOWN";
        this.freeze("Submit outcome unknown for " + intentId + ": " + String(e));
        return null;
    }
    if (id === null || id === undefined || id === false || id === "") {
        intent.status = "UNKNOWN";
        this.freeze("No reliable order receipt for " + intentId + "; automatic retries disabled");
        return null;
    }
    id = String(id);
    intent.status = "ACKNOWLEDGED";
    intent.orderId = id;
    this.s.orders[id] = { id: id, intentId: intentId, side: side, purpose: purpose, layer: layer,
        quantity: quantity, filled: 0, average: 0, status: 0, terminal: false,
        createdAt: this.now, cancelRequested: false };
    if (purpose === "OPEN") {
        this.s.cycle.layers[layer].status = "SENT";
        this.s.cycle.layers[layer].orderId = id;
    }
    this.save();
    this.log("ORDER_ACK", { id: id, side: side, quantity: quantity, price: price });
    return id;
};
ReconEngine.prototype.cancelOpen = function () {
    // A misspelled/missing LIVE opt-in or wrong account scope must not even
    // cancel orders. Only read requests occur until the LIVE startup checks pass.
    if (!this.paper &amp;amp;&amp;amp; !this.liveAuthorized) { return; }
    var self = this;
    Object.keys(this.s.orders).forEach(function (id) {
        var o = self.s.orders[id];
        if (o.purpose !== "OPEN" || o.terminal) { return; }
        o.cancelRequested = true;
        self.save();
        try {
            var ret = self.paper ? self.paper.cancel(id) : self.a.cancel(id);
            if (ret === null || ret === false || ret === undefined) {
                self.freeze("Cancellation acknowledgement unavailable: " + id);
            }
            // A cancellation ACK is NOT final. Reconcile GetOrder on later tick.
        } catch (e) { self.freeze("Cancellation query failed: " + id + " " + String(e)); }
    });
};
ReconEngine.prototype.reconcile = function (snapshot) {
    reconAssert(snapshot &amp;amp;&amp;amp; Array.isArray(snapshot.orders) &amp;amp;&amp;amp; Array.isArray(snapshot.positions), "Incomplete account snapshot");
    var self = this, liveIds = {};
    snapshot.orders.forEach(function (o) {
        reconAssert(o &amp;amp;&amp;amp; o.Symbol === self.c.Symbol &amp;amp;&amp;amp; o.Id !== undefined, "Unexpected/malformed open order");
        liveIds[String(o.Id)] = true;
        reconAssert(!!self.s.orders[String(o.Id)], "Unowned order on strategy instrument: " + o.Id);
    });
    Object.keys(this.s.orders).forEach(function (id) {
        var tracked = self.s.orders[id];
        if (tracked.terminal &amp;amp;&amp;amp; !liveIds[id]) { return; }
        var o = self.queryOrder(id);
        reconAssert(o &amp;amp;&amp;amp; o.Symbol === self.c.Symbol &amp;amp;&amp;amp; String(o.Id) === id, "Order lookup failed/mismatched: " + id);
        reconValidateReceipt(o, self.s.intents[tracked.intentId], self.market);
        reconAssert(o.Status === 0 || o.Status === 1 || o.Status === 2, "Order status unknown: " + id);
        reconAssert(reconNumber(o.DealAmount) &amp;amp;&amp;amp; o.DealAmount &amp;gt;= tracked.filled - 1e-9 &amp;amp;&amp;amp;
            o.DealAmount &amp;lt;= tracked.quantity + self.market.step * 0.01, "Inconsistent cumulative fill: " + id);
        if (o.Status === 1) {
            reconAssert(Math.abs(o.DealAmount - tracked.quantity) &amp;lt;= self.market.step * 0.01,
                "Filled status lacks full cumulative fill quantity: " + id);
        }
        if (o.DealAmount &amp;gt; 0) {
            reconAssert(reconNumber(o.AvgPrice) &amp;amp;&amp;amp; o.AvgPrice &amp;gt; 0, "Fill average unavailable: " + id);
        }
        tracked.filled = o.DealAmount;
        tracked.average = o.AvgPrice || 0;
        tracked.status = o.Status;
        tracked.terminal = o.Status === 1 || o.Status === 2;
        reconAssert(!(tracked.terminal &amp;amp;&amp;amp; liveIds[id]), "Snapshot races final order; retry requires explicit resume");
        if (tracked.purpose === "OPEN" &amp;amp;&amp;amp; self.s.cycle) {
            self.s.cycle.layers[tracked.layer].status = tracked.terminal ? (tracked.filled &amp;gt; 0 ? "FILLED" : "CANCELED") : "SENT";
        }
    });
    var p = reconPosition(snapshot.positions, this.c.Symbol, this.paper ? 0 : this.a.longType,
        this.paper ? 1 : this.a.shortType);
    if (!this.s.cycle) {
        reconAssert(p.long === 0 &amp;amp;&amp;amp; p.short === 0, "Existing position has no persisted ownership record");
    } else {
        reconAssert(this.s.cycle.side === "LONG" ? p.short === 0 : p.long === 0, "Opposite/unowned position detected");
        var expected = 0;
        Object.keys(this.s.orders).forEach(function (id) {
            var o = self.s.orders[id];
            expected += (o.purpose === "OPEN" ? 1 : -1) * o.filled;
        });
        var actual = this.s.cycle.side === "LONG" ? p.long : p.short;
        // Do not invent ownership or trade while fill and position snapshots disagree.
        reconAssert(Math.abs(expected - actual) &amp;lt;= this.market.step * 0.1, "Fill/position reconciliation mismatch");
    }
    this.lastSnapshot = snapshot;
    this.lastPosition = p;
    this.lastSnapshotAt = this.now;
    this.snapshotHealthy = true;
    var account = snapshot.account;
    if (account &amp;amp;&amp;amp; reconNumber(account.Equity) &amp;amp;&amp;amp; account.Equity &amp;gt; 0) {
        if (this.s.initialEquity === null) { this.s.initialEquity = account.Equity; }
        this.s.lastEquity = account.Equity;
        this.s.lastPnl = account.Equity - this.s.initialEquity;
    } else { this.s.lastEquity = null; this.s.lastPnl = null; }
    this.save();
    return p;
};
ReconEngine.prototype.hasPending = function (purpose) {
    var self = this;
    return Object.keys(this.s.orders).some(function (id) {
        var o = self.s.orders[id];
        return !o.terminal &amp;amp;&amp;amp; (!purpose || o.purpose === purpose);
    });
};
ReconEngine.prototype.beginExit = function (reason) {
    if (!this.s.cycle || this.unknown()) { return; }
    this.s.cycle.exitReason = reason;
    this.s.phase = "EXIT_CANCEL";
    this.s.flatCount = 0;
    this.save();
    this.cancelOpen();
};
ReconEngine.prototype.manageRisk = function (position, ticker) {
    var cycle = this.s.cycle;
    if (!cycle || this.unknown() || this.s.mismatch || !this.snapshotHealthy) { return false; }
    var risk = reconExit(cycle, position, ticker.Last, this.c);
    if (!risk) { return false; }
    cycle.peakReturn = risk.peak;
    cycle.lastReturn = risk.returnRate;
    if (risk.reason) { this.save(); this.beginExit(risk.reason); return true; }
    if ((position.long + position.short) * this.market.basePerUnit * ticker.Last &amp;gt;
            this.c.NominalBudgetUSDT * this.c.MaxGrossNotionalMultiplier) {
        this.beginExit("EXPOSURE_LIMIT"); return true;
    }
    if (this.c.ReturnToMiddleBand) {
        var currentBar = Math.floor(this.now / (this.c.PeriodSeconds * 1000));
        if (cycle.middleBar !== currentBar) {
            try {
                var records = this.a.getRecords(this.c.Symbol, this.c.PeriodSeconds, this.c.BBPeriod + 5);
                var observation = reconSignal(records, this.now, this.c);
                reconAssert(observation &amp;amp;&amp;amp; observation.bb &amp;amp;&amp;amp; reconNumber(observation.bb.middle), "Middle band unavailable");
                cycle.middle = observation.bb.middle;
                cycle.middleBar = currentBar;
            } catch (e) {
                // A K-line outage freezes additions but does not disable the ticker-
                // based stop loss / take profit / trailing checks above or next tick.
                this.freeze("Middle-band data failed: " + String(e));
                this.cancelOpen();
                return false;
            }
        }
        if (risk.returnRate &amp;gt; 0 &amp;amp;&amp;amp; (cycle.side === "LONG" ? ticker.Last &amp;gt;= cycle.middle : ticker.Last &amp;lt;= cycle.middle)) {
            this.beginExit("RETURN_TO_MID_BAND"); return true;
        }
    }
    return false;
};
ReconEngine.prototype.submitPlanned = function () {
    if (!this.s.cycle || this.s.cycle.addingStopped || this.s.paused || this.s.phase !== "ACTIVE") { return; }
    var layers = this.s.cycle.layers;
    for (var i = 0; i &amp;lt; layers.length; i++) {
        if (layers[i].status !== "PLANNED") { continue; }
        if (this.unknown() || this.s.phase !== "ACTIVE" || this.s.cycle.addingStopped) { break; }
        this.submit(this.s.cycle.side === "LONG" ? "buy" : "sell", layers[i].price,
            layers[i].quantity, "OPEN", layers[i].index);
    }
};
ReconEngine.prototype.confirmFlat = function (position, snapshot) {
    var flat = position.long === 0 &amp;amp;&amp;amp; position.short === 0 &amp;amp;&amp;amp; snapshot.orders.length === 0 &amp;amp;&amp;amp;
        !this.hasPending() &amp;amp;&amp;amp; !this.unknown();
    if (!flat) { this.s.flatCount = 0; return false; }
    if (!this.s.lastFlatAt || this.now - this.s.lastFlatAt &amp;gt;= this.c.FlatConfirmationIntervalMilliseconds) {
        this.s.flatCount++;
        this.s.lastFlatAt = this.now;
    }
    return this.s.flatCount &amp;gt;= this.c.FlatConfirmations;
};
ReconEngine.prototype.settle = function () {
    if (this.s.cycle) {
        this.log("CYCLE_SETTLED", { id: this.s.cycle.id, reason: this.s.cycle.exitReason,
            equityChange: this.s.lastEquity !== null &amp;amp;&amp;amp; this.s.cycle.startEquity !== null ?
                this.s.lastEquity - this.s.cycle.startEquity : null,
            note: "Equity change includes fees/funding/deposits; not an isolated realized-trade PnL" });
        this.s.completed++;
        this.s.exitCurrentBar = Math.floor(this.now / (this.c.PeriodSeconds * 1000));
    }
    this.s.cycle = null;
    this.s.orders = {};
    this.s.intents = {};
    this.s.phase = "IDLE";
    this.s.flatCount = 0;
    this.s.lastFlatAt = 0;
    this.save();
};
ReconEngine.prototype.command = function (text) {
    if (!text) { return; }
    var cmd = String(text).trim();
    if (cmd === "status" || cmd === "diagnose") { this.log("DIAGNOSTICS", this.diagnostics()); return; }
    if (cmd === "pause") { this.s.paused = true; this.save(); this.cancelOpen(); return; }
    if (cmd === "close") {
        if (this.unknown() || this.s.mismatch || !this.snapshotHealthy) {
            this.log("Close blocked: resolve unknown intent/fingerprint/unhealthy snapshot first"); return;
        }
        this.s.paused = true;
        this.beginExit("MANUAL_CLOSE"); return;
    }
    if (cmd === "resume") {
        if (this.s.mismatch || this.unknown() || !this.lastSnapshot || !this.lastPosition || !this.snapshotHealthy ||
            this.now - this.lastSnapshotAt &amp;gt; this.c.MaxTickerAgeMilliseconds) {
            this.log("Resume blocked: fingerprint/unknown intent/stale snapshot"); return;
        }
        try { this.reconcile(this.lastSnapshot); } catch (e) { this.freeze(String(e)); return; }
        this.s.paused = false;
        this.s.phase = this.s.cycle ? (this.s.cycle.exitReason ? "EXIT_CANCEL" : "ACTIVE") : "BOOT";
        this.s.reasons = [];
        this.s.flatCount = 0;
        this.save(); return;
    }
    // resolve:intent-N:&amp;lt;full FMZ order ID&amp;gt;; the receipt is verified, not trusted blindly.
    if (cmd.indexOf("resolve:") === 0) {
        var split = cmd.indexOf(":", 8), intentId = cmd.slice(8, split), orderId = cmd.slice(split + 1);
        var intent = this.s.intents[intentId];
        if (split &amp;lt; 0 || !intent || intent.status !== "UNKNOWN") { this.log("No such unknown intent"); return; }
        try {
            var o = this.queryOrder(orderId);
            reconAssert(o &amp;amp;&amp;amp; String(o.Id) === orderId, "Receipt ID differs from supplied ID");
            reconValidateReceipt(o, intent, this.market);
            reconAssert(!this.s.orders[orderId], "Receipt already owned");
            intent.status = "ACKNOWLEDGED"; intent.orderId = orderId;
            this.s.orders[orderId] = { id: orderId, intentId: intentId, side: intent.side,
                purpose: intent.purpose, layer: intent.layer, quantity: intent.quantity,
                filled: 0, average: 0, status: 0, terminal: false, createdAt: intent.createdAt, cancelRequested: false };
            if (intent.purpose === "OPEN") {
                this.s.cycle.layers[intent.layer].orderId = orderId;
                this.s.cycle.layers[intent.layer].status = "SENT";
            }
            this.save(); this.log("Receipt linked; wait for healthy reconciliation, then resume explicitly");
        } catch (e) { this.log("Receipt rejected", String(e)); }
        return;
    }
    this.log("Commands: pause | resume | close | status | diagnose | resolve:intent-N:FULL_ORDER_ID");
};
ReconEngine.prototype.diagnostics = function () {
    return { mode: this.c.RunMode, phase: this.s.phase, paused: this.s.paused,
        fingerprint: this.s.fingerprint, mismatch: this.s.mismatch, reasons: this.s.reasons,
        unknownIntent: this.unknown(), cycle: this.s.cycle, positions: this.lastPosition,
        orders: this.s.orders, intents: this.s.intents, flatConfirmations: this.s.flatCount,
        accountEquity: this.s.lastEquity, equityChangeSinceStart: this.s.lastPnl,
        paperFees: this.paper ? this.paper.s.fees : null,
        warning: "Inferred model; anchor/signal/scale definition are not identified by live logs" };
};
ReconEngine.prototype.step = function (now) {
    this.now = now;
    this.snapshotHealthy = false;
    this.liveAuthorized = false;
    var self = this, ticker, records, snapshot, p, signal;
    try {
        if (this.c.RunMode === "LIVE") {
            reconAssert(this.c.LiveConfirmation === "I_ACCEPT_INFERRED_RULES", "LIVE confirmation is missing");
            reconAssert(this.c.AccountScope !== "PAPER_DEMO", "LIVE needs a unique explicit account/subaccount scope label");
            reconAssert(this.a.name() === this.c.ExpectedExchangeName, "Unexpected LIVE exchange adapter");
            if (this.a.assertScope) { this.a.assertScope(this.c.Symbol); }
            this.liveAuthorized = true;
        }
        if (!this.market) {
            this.market = reconMarket(this.paper ? {
                CtVal: this.c.PaperBasePerOrderUnit, CtValCcy: this.c.Symbol.split("_")[0],
                TickSize: this.c.PaperTickSize, AmountSize: this.c.PaperAmountStep,
                MinQty: this.c.PaperMinQty, MinNotional: this.c.PaperMinNotional
            } : this.a.getMarket(this.c.Symbol), this.c);
        }
        try {
            ticker = this.a.getTicker(this.c.Symbol);
            reconAssert(ticker &amp;amp;&amp;amp; reconNumber(ticker.Last) &amp;amp;&amp;amp; ticker.Last &amp;gt; 0, "Ticker query failed");
            if (ticker.Time !== undefined &amp;amp;&amp;amp; ticker.Time !== null &amp;amp;&amp;amp; ticker.Time !== 0) {
                reconAssert(reconNumber(ticker.Time) &amp;amp;&amp;amp; now - ticker.Time &amp;lt;= this.c.MaxTickerAgeMilliseconds &amp;amp;&amp;amp;
                    ticker.Time &amp;lt;= now + 5000, "Stale/future ticker timestamp");
            }
        } catch (tickerError) {
            // A previously latched LIVE close depends on fresh owned positions/orders,
            // not another price trigger. PAPER still needs a tick to simulate fills.
            var latchedClose = !this.paper &amp;amp;&amp;amp; !this.unknown() &amp;amp;&amp;amp; !this.s.mismatch &amp;amp;&amp;amp;
                (this.s.phase === "VERIFY_FLAT" || (this.s.cycle &amp;amp;&amp;amp; this.s.cycle.exitReason));
            if (!latchedClose) { throw tickerError; }
            ticker = null;
        }
        if (this.paper) { this.paper.update(ticker.Last, this.market); this.save(); }
        snapshot = this.paper ? this.paper.snapshot(this.market, this.c.Symbol) : this.a.snapshot(this.c.Symbol);
        p = this.reconcile(snapshot);
    } catch (e) {
        this.freeze(String(e));
        this.cancelOpen(); // Cancelling known opening orders cannot increase exposure.
        return this.diagnostics();
    }
    if (this.s.phase === "FROZEN") {
        this.cancelOpen();
        // Fresh ownership/fill reconciliation permits risk reduction while the
        // opening circuit breaker stays latched for the rest of this cycle.
        if (!this.unknown() &amp;amp;&amp;amp; !this.s.mismatch &amp;amp;&amp;amp; this.s.cycle &amp;amp;&amp;amp; this.snapshotHealthy) {
            if (this.s.cycle.exitReason) {
                // A partially completed exit remains an exit even if price later
                // recovers; do not abandon its residual position on reconnection.
                this.s.phase = "EXIT_CANCEL";
            } else { this.manageRisk(p, ticker); }
            if (this.s.phase === "FROZEN" &amp;amp;&amp;amp; p.long === 0 &amp;amp;&amp;amp; p.short === 0 &amp;amp;&amp;amp; !this.hasPending()) {
                this.s.cycle.exitReason = this.s.cycle.exitReason || "FROZEN_FLAT";
                this.s.phase = "VERIFY_FLAT"; this.s.flatCount = 0; this.s.lastFlatAt = 0;
            }
        }
        this.save(); return this.diagnostics();
    }
    if (this.s.phase === "BOOT" || this.s.phase === "VERIFY_FLAT") {
        if (this.confirmFlat(p, snapshot)) { this.settle(); }
        this.save(); return this.diagnostics();
    }
    if (this.s.phase === "EXIT_CANCEL") {
        this.cancelOpen();
        if (this.s.phase === "FROZEN") { return this.diagnostics(); }
        if (!this.hasPending("OPEN") &amp;amp;&amp;amp; snapshot.orders.length === 0) {
            this.s.phase = "EXIT_CLOSE"; this.save();
        }
        return this.diagnostics();
    }
    if (this.s.phase === "EXIT_CLOSE") {
        if (this.hasPending("CLOSE")) { return this.diagnostics(); }
        var qty = this.s.cycle.side === "LONG" ? p.long : p.short;
        if (qty === 0) {
            this.s.phase = "VERIFY_FLAT"; this.s.flatCount = 0; this.s.lastFlatAt = 0; this.save();
            return this.diagnostics();
        }
        qty = Math.min(qty, this.market.maxQty);
        if (isFinite(this.market.maxNotional)) {
            if (!ticker) {
                this.freeze("Latched exit needs a fresh price to enforce finite MaxNotional");
                return this.diagnostics();
            }
            qty = Math.min(qty, this.market.maxNotional / (ticker.Last * this.market.basePerUnit));
        }
        qty = reconRoundStep(qty, this.market.step, "down");
        if (qty &amp;lt; this.market.minQty || p.frozen &amp;gt; 0) {
            this.freeze("Residual/frozen position cannot be safely closed automatically"); return this.diagnostics();
        }
        // Explicit closebuy/closesell preserves FMZ close direction. NEVER reverse
        // with an opening sell/buy. Preconfigured hedge mode is required for LIVE.
        this.submit(this.s.cycle.side === "LONG" ? "closebuy" : "closesell", -1, qty, "CLOSE", null);
        return this.diagnostics();
    }
    if (this.s.phase === "ACTIVE") {
        var cycle = this.s.cycle;
        if (this.manageRisk(p, ticker)) { return this.diagnostics(); }
        if (this.s.phase === "FROZEN") { return this.diagnostics(); }
        var gross = (p.long + p.short) * this.market.basePerUnit * ticker.Last;
        if (gross &amp;gt; this.c.NominalBudgetUSDT * this.c.MaxGrossNotionalMultiplier) {
            this.beginExit("EXPOSURE_LIMIT"); return this.diagnostics();
        }
        if (this.c.OrderTTLSeconds &amp;gt; 0 &amp;amp;&amp;amp; now - cycle.startedAt &amp;gt;= this.c.OrderTTLSeconds * 1000) {
            this.beginExit("OPTIONAL_TTL"); return this.diagnostics();
        }
        if (this.s.paused) { this.cancelOpen(); this.save(); return this.diagnostics(); }
        var planned = cycle.layers.filter(function (layer) { return layer.status === "PLANNED"; });
        if (planned.length) {
            this.submitPlanned();
        } else if (!this.hasPending() &amp;amp;&amp;amp; p.long === 0 &amp;amp;&amp;amp; p.short === 0) {
            this.s.phase = "VERIFY_FLAT";
            this.s.flatCount = 0;
            cycle.exitReason = cycle.exitReason || "UNFILLED_OR_EXTERNALLY_FLAT";
        }
        this.save(); return this.diagnostics();
    }
    if (this.s.phase === "IDLE" &amp;amp;&amp;amp; !this.s.paused) {
        try {
            records = this.a.getRecords(this.c.Symbol, this.c.PeriodSeconds, this.c.BBPeriod + 5);
            signal = reconSignal(records, now, this.c);
        } catch (e) { this.freeze(String(e)); return this.diagnostics(); }
        if (!signal || signal.time === this.s.lastSignalBar) { return this.diagnostics(); }
        this.s.lastSignalBar = signal.time; this.save();
        var currentBar = Math.floor(now / (this.c.PeriodSeconds * 1000));
        if (this.s.exitCurrentBar !== null &amp;amp;&amp;amp; currentBar - this.s.exitCurrentBar &amp;lt;= this.c.CooldownBars) {
            this.log("COOLDOWN", { currentBar: currentBar, exitBar: this.s.exitCurrentBar }); return this.diagnostics();
        }
        if (!signal.side) { return this.diagnostics(); }
        if (this.c.RequireValidEquityForEntry &amp;amp;&amp;amp; this.s.lastEquity === null) {
            this.freeze("Cannot establish valid Equity; opening disabled"); return this.diagnostics();
        }
        if (snapshot.account &amp;amp;&amp;amp; this.c.MinimumMarginReserveUSDT &amp;gt; 0 &amp;amp;&amp;amp;
            (!reconNumber(snapshot.account.Balance) || snapshot.account.Balance &amp;lt; this.c.MinimumMarginReserveUSDT)) {
            this.log("Insufficient available margin reserve"); return this.diagnostics();
        }
        try {
            var layers = reconBuildLayers(signal, this.market, this.c);
            this.s.cycle = { id: "cycle-" + (++this.s.sequence), side: signal.side, signalBar: signal.time,
                anchor: signal.anchor, scale: signal.scale, percentB: signal.percentB, bb: signal.bb,
                startedAt: now, startEquity: this.s.lastEquity, peakReturn: null, lastReturn: null,
                exitReason: null, layers: layers, addingStopped: false,
                middle: signal.bb.middle, middleBar: currentBar };
            this.s.phase = "ACTIVE"; this.save();
            this.log("CYCLE_CREATED", this.s.cycle);
            this.submitPlanned();
        } catch (e) { this.freeze(String(e)); }
    }
    return this.diagnostics();
};

/* FMZ adapter: local query context only; no leverage/account-mode changes. */
function reconFMZAdapter(ex) {
    var contextPrepared = false;
    return {
        longType: typeof PD_LONG === "undefined" ? 0 : PD_LONG,
        shortType: typeof PD_SHORT === "undefined" ? 1 : PD_SHORT,
        name: function () { return ex.GetName(); },
        assertScope: function (symbol) {
            // GetAccount has no symbol argument. Initialize this strategy's local
            // FMZ quote/contract context once. These setters do not trade or change
            // the exchange account's leverage, hedge mode or margin mode.
            var pair = symbol.split(".")[0];
            if (!contextPrepared) {
                ex.SetCurrency(pair);
                ex.SetContractType("swap");
                contextPrepared = true;
            }
            reconAssert(ex.GetCurrency() === pair &amp;amp;&amp;amp; ex.GetContractType() === "swap",
                "FMZ account query context changed unexpectedly");
        },
        getMarket: function (symbol) {
            var markets = ex.GetMarkets();
            reconAssert(markets &amp;amp;&amp;amp; markets[symbol], "GetMarkets has no requested instrument");
            return markets[symbol];
        },
        getTicker: function (symbol) { return ex.GetTicker(symbol); },
        getRecords: function (symbol, period, limit) { return ex.GetRecords(symbol, period, limit); },
        snapshot: function (symbol) {
            var positions = ex.GetPositions(symbol), orders = ex.GetOrders(symbol), account = null;
            reconAssert(Array.isArray(positions) &amp;amp;&amp;amp; Array.isArray(orders), "Position/order query failed");
            try { account = ex.GetAccount(); } catch (accountError) { account = null; }
            // Missing equity disables new entries and PnL reporting. It must not
            // disable risk reduction of independently verified owned positions.
            return { positions: positions, orders: orders, account: account };
        },
        getOrder: function (id) { return ex.GetOrder(id); },
        submit: function (symbol, side, price, amount) { return ex.CreateOrder(symbol, side, price, amount); },
        cancel: function (id) { return ex.CancelOrder(id); }
    };
}

var reconRunningEngine = null;
function main() {
    var overrides = {};
    // Optional FMZ string parameter, e.g. {"RunMode":"PAPER"}; also editable
    // RECON_DEFAULTS above. No strategy template or external dependency needed.
    if (typeof ReconstructionConfigJSON !== "undefined" &amp;amp;&amp;amp; ReconstructionConfigJSON) {
        overrides = JSON.parse(ReconstructionConfigJSON);
    }
    if (typeof RunMode !== "undefined") { overrides.RunMode = RunMode; }
    var config = reconConfig(overrides);
    reconRunningEngine = new ReconEngine(config, reconFMZAdapter(exchange), {
        load: function (key) { return _G(key); },
        save: function (key, value) { _G(key, value); },
        log: function (message, detail) { Log(message, detail); }
    });
    Log("Behavioural reconstruction started", { mode: config.RunMode, symbol: config.Symbol,
        fingerprint: reconFingerprint(config), unverified: "signal, anchor and BB scale definition" });
    while (true) {
        var now = Date.now();
        var diagnostics = reconRunningEngine.step(now);
        var command = GetCommand();
        if (command) { reconRunningEngine.command(command); diagnostics = reconRunningEngine.diagnostics(); }
        LogStatus("模式 " + config.RunMode + " | " + diagnostics.phase + " | " + config.Symbol + "\n" +
            "参数指纹 " + diagnostics.fingerprint + "\n" + JSON.stringify(diagnostics));
        if (diagnostics.accountEquity !== null &amp;amp;&amp;amp; typeof LogProfit === "function") {
            LogProfit(diagnostics.equityChangeSinceStart);
        }
        Sleep(config.LoopMilliseconds);
    }
}
function onexit() {
    if (reconRunningEngine) {
        reconRunningEngine.s.paused = true;
        reconRunningEngine.save();
        reconRunningEngine.cancelOpen();
        // A stop callback cannot prove fills/cancels are final. Persist and require
        // the normal reconciliation path on restart; do not claim liquidation.
        reconRunningEngine.save();
    }
}
if (typeof module !== "undefined" &amp;amp;&amp;amp; module.exports) {
    module.exports = {
        defaults: RECON_DEFAULTS, config: reconConfig, fingerprint: reconFingerprint,
        roundStep: reconRoundStep, closedCandles: reconClosedCandles, bollinger: reconBollinger,
        signal: reconSignal, market: reconMarket, buildLayers: reconBuildLayers,
        position: reconPosition, exitDecision: reconExit, initialState: reconInitialState,
        validateReceipt: reconValidateReceipt,
        PaperBroker: ReconPaper, Engine: ReconEngine, fmzAdapter: reconFMZAdapter
    };
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>quanttrading</category>
      <category>agents</category>
      <category>fmzquant</category>
      <category>quantcrypto</category>
    </item>
    <item>
      <title>If You Can't Outrun the Bots, Let Them Do the Work: Lessons and a New Direction from a BSC On-Chain Arbitrage Experiment</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Wed, 18 Nov 2026 03:20:18 +0000</pubDate>
      <link>https://dev.to/quant001/if-you-cant-outrun-the-bots-let-them-do-the-work-lessons-and-a-new-direction-from-a-bsc-on-chain-167g</link>
      <guid>https://dev.to/quant001/if-you-cant-outrun-the-bots-let-them-do-the-work-lessons-and-a-new-direction-from-a-bsc-on-chain-167g</guid>
      <description>&lt;p&gt;The latest bull-market excitement has eased for now, the meme frenzy has temporarily subsided, and the market seems quiet again. But this round of speculation certainly brought on-chain markets to everyone's attention. There is still plenty to explore in the on-chain primary market, so this time we set out to do some research.&lt;/p&gt;

&lt;p&gt;What can you do when the market is quiet? Get back to straightforward arbitrage, of course. Today's subject, however, is not arbitrage between exchanges. &lt;strong&gt;It is arbitrage between an on-chain market and an exchange&lt;/strong&gt;: PancakeSwap on BSC and Binance USDT-margined perpetual futures.&lt;/p&gt;

&lt;p&gt;The idea is familiar: the price of the same token in an on-chain pool sometimes differs from its price on Binance. When it is cheaper on-chain, buy it there and simultaneously open a short on Binance. When the prices converge, close both sides and capture the difference. What follows is a chronological account of the past week's work, the problems we encountered, and the strategy we eventually arrived at.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. The First Strategy: More Than 13 Hours Without a Single Entry
&lt;/h2&gt;

&lt;p&gt;The first version took the most direct approach: "Spot a spread, then rush in and take it." After deployment on FMZ, it ran for more than 13 hours and completed over 43,000 scan cycles, each taking a little over 700 milliseconds. It did not open a single position.&lt;/p&gt;

&lt;p&gt;The logs revealed a strikingly consistent pattern. There were roughly 30 entry signals during that period. When each signal appeared, the on-chain buy quote was 50–147 basis points (bp) below Binance's best bid, comfortably exceeding the entry threshold. But every time the strategy requested a fresh quote just before submitting an order, the spread had shrunk to 0–40 bp, back to the token's usual level. The final check therefore blocked the trade. Around 30 signals, without a single exception.&lt;/p&gt;

&lt;p&gt;The signals were real, and the final checks were correct. The problem lay in the less than one second between the two.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fo2wr2zmwgnqug2o04ry5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fo2wr2zmwgnqug2o04ry5.png" alt=" " width="800" height="474"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Where the Spread Went: A Seller Unloading 369 USDT at a Time and the First Trade in the Next Block
&lt;/h2&gt;

&lt;p&gt;To find out, I pulled ARIA's on-chain trades around 03:51 a.m. and examined them one by one. Within that minute, the logs recorded three almost identical signals: initial spreads of 92.6, 91.1, and 92.8 bp, which fell to 40.9, 41.5, and 42.3 bp at the final check. Each had lost about 51 bp.&lt;/p&gt;

&lt;p&gt;The on-chain records showed a seller unloading ARIA in fixed amounts of 369 USDT. Each sale pushed the pool price from 0.03703 down to around 0.03684, a move of roughly 51 bp. Then, in the very next block, the first or second transaction was invariably a purchase worth a few hundred USDT that brought the price back to its previous level. Three sell-offs, three recoveries, with the timing matching the strategy logs exactly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr7kddfem8wgjl03u22qc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr7kddfem8wgjl03u22qc.png" alt=" " width="799" height="420"&gt;&lt;/a&gt;&lt;br&gt;
These were on-chain backrunning bots. They monitor every block, and when someone sells heavily, they buy the discounted tokens at the very front of the next block, then sell on Binance to hedge. BSC currently produces a block roughly every 0.45 seconds. These bots do not secure their place by paying higher gas prices; their gas price is often the minimum 0.05 gwei. Instead, they transfer a tip of about 0.0006 BNB directly to the block builder to buy a position at the start of the block.&lt;/p&gt;

&lt;p&gt;Our strategy needs at least two or three blocks to scan, fetch Binance order-book depth, check two balances, request a fresh quote, and submit the transaction. The spread it "sees" is therefore already gone before it can act. Every opportunity rejected by the final check had expired.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Scanning the Entire Market: The Money Is Real, but More Than 50 Competitors Are Already Sharing It
&lt;/h2&gt;

&lt;p&gt;One token could have been a coincidence. So I wrote a detector to scan all 867,000 trades over the previous 24 hours across 1,428 pools and 217 tokens that had both a Binance perpetual contract and a PancakeSwap pool. It identified every individual trade that moved the price by at least 30 bp, then checked how quickly the move was reversed and who reversed it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fcm75o40qi0tsj1siurcc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fcm75o40qi0tsj1siurcc.png" alt=" " width="800" height="103"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi927nngjtae1hnhcoybt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi927nngjtae1hnhcoybt.png" alt=" " width="800" height="462"&gt;&lt;/a&gt;&lt;br&gt;
Two conclusions emerged:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;This business does exist. Across the market, it generates roughly one or two thousand USDT in gross profit per day, much of it from sellers like the one in ARIA who unload fixed amounts at regular intervals. On HANA, someone was selling about 2,700 USDT every 42 blocks or so; on AAVE, someone was selling 190 USDT every 90 blocks.&lt;/li&gt;
&lt;li&gt;It is already fully contested. More than 50 recovery bots appeared over the day, with a few leaders consistently taking the first position in the block. The median gross profit per trade was only 0.6 USDT, and in the handful of trades I checked, 30%–50% of that went to the builder as a tip. Few competitors bothered with the slower opportunities, but after pool fees and Binance fees, almost nothing remained.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  4. Four Dead Ends
&lt;/h2&gt;

&lt;p&gt;Over the next day, I tried several different approaches, validating each against the data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Shadow mode&lt;/strong&gt;. The program subscribed to real-time pool trades. Whenever it detected a sell-off, it simulated a recovery trade against the block state after that sale, calculated net profit after fees using Binance's live quotes, and then checked who ultimately won. Detection itself was within our reach: the median delay from block production to receiving the event was 204 milliseconds. But among 89 events over 30 minutes, 14 were already reversed by someone else within the same block, and 18 were captured by traders at the front of the next block. Of the remaining 33 events where others were slow enough to leave us a chance, only 11 were profitable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Seeing large trades in advance&lt;/strong&gt;. We subscribed to pending transactions through public nodes. Of 27 large trades, 21 were visible, but the median time at which we saw them was actually 148 milliseconds after the block had been produced. Those trades went through private channels; public nodes broadcast them only after block production. To see them genuinely early, we would need to buy a professional transaction-flow service and then compete with the existing bots on bids.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Using on-chain activity as a signal to trade on Binance&lt;/strong&gt;. When recovery bots buy on-chain, they need to sell on Binance to hedge, which should theoretically put some downward pressure on Binance prices. We measured Binance price movements 1–60 seconds after 258 on-chain impacts. At 1, 3, and 10 seconds, the median change in the mid-price was zero. Prices followed the direction of the on-chain move only 21%–38% of the time, and entering and exiting as a taker lost money on average. On-chain prices followed Binance, not the other way around.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Holding inventory and waiting&lt;/strong&gt;. Buy on-chain during a sell-off, open a short on Binance, then hold both until someone pushes the on-chain price up and we can sell. Under optimistic assumptions—execution in the very next block—both trades in a one-hour window were profitable. Under conservative assumptions—one block later—we managed to buy just once in roughly 280 sell-offs. Speed was still the bottleneck.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fz0r9n9gvc2pysoqzubx6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fz0r9n9gvc2pysoqzubx6.png" alt=" " width="800" height="476"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  5. The Turning Point: Become the Counterparty the Bots Trade With
&lt;/h2&gt;

&lt;p&gt;The change in perspective came from an article Xiaocao had written for the FMZ column a few years earlier. Looking at one-second STORJ candles on Binance, he had spotted a bot dumping ten or twenty thousand tokens with market orders every few seconds, regardless of cost. Instead of trying to beat it on speed, he placed buy orders in the book ahead of time, passively took the inventory when the bot sold into them, then placed sell orders after the rebound. My takeaway was simple: &lt;strong&gt;an order placed in advance does not need speed&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;On-chain AMMs do not have order books, which was why I originally thought this approach would not work. Concentrating liquidity in a PancakeSwap V3 range just below the current price looks like placing a limit buy order. But when the price recovers, it crosses that same range in reverse and buys the tokens back at the same prices. The recovery bots still capture the spread.&lt;/p&gt;

&lt;p&gt;The breakthrough came with the 1inch Limit Order Protocol. Its orders are signed off-chain and filled on-chain: I sign an order off-chain saying "buy this token at this price with 20 USDT," then submit it to the 1inch order platform. Posting the order requires no on-chain transaction and no gas. Anyone can take that signed order on-chain and fill it, provided they are willing to sell me the tokens at my price.&lt;/p&gt;

&lt;p&gt;That reverses the situation. When a seller pushes the pool price below my buy order's price, a recovery bot sees a risk-free route: buy tokens cheaply from the affected pool, then sell them into my order within the same transaction, keeping the difference. Speed and tips become the bot's concern. I simply wait for a fill, then open a short on Binance once I have received the tokens.&lt;/p&gt;

&lt;p&gt;First, I checked whether anyone was already doing this. Over roughly the previous five hours, about 260 1inch limit orders had been filled on BSC by six recurring bot contracts. Around one-third followed the pattern of swapping on a DEX first and then filling a limit order within the same transaction. The median fill value was around 50 USDT. The bots that could do the work for us were already there.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy3x77gek8hopkm0h4hon.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy3x77gek8hopkm0h4hon.png" alt=" " width="800" height="302"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  6. Strategy Implementation
&lt;/h2&gt;

&lt;p&gt;The strategy is written in JavaScript on FMZ and requires two exchange objects: exchanges[0] for Binance USDT-margined perpetual futures, and exchanges[1] for Web3 on BSC. Here is the overall workflow:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fg897z6b0wki7s5zrxdsk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fg897z6b0wki7s5zrxdsk.png" alt=" " width="800" height="1200"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;1. Token Selection: Focus on Consistent Sellers&lt;/strong&gt;&lt;br&gt;
The profit comes from sellers who repeatedly dump tokens, so those are the only tokens where we place orders. The strategy first identifies tokens in the PancakeSwap token list that also have Binance perpetual contracts. It then uses Multicall to query all their USDT and WBNB pools in the V2 and V3 factories in one batch—about 200 tokens and 1,400 pools.&lt;/p&gt;

&lt;p&gt;After that, it fetches new Swap events with eth_getLogs every 20 seconds and calculates the pool price before and after each trade. A trade worth at least 100 USDT that pushes the price down by at least 40 bp counts as a sell-off. Sell-offs in the same token are then grouped by value, with amounts within 10% treated as belonging to the same bucket. The more events in a bucket, the more likely it is that someone is selling a fixed amount each time:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;s.dumps.forEach(function (u) { var b = Math.round(Math.log(u) / Math.log(1.1)); (bucket[b] = bucket[b] || []).push(u) })
var best = []
Object.keys(bucket).forEach(function (b) { if (bucket[b].length &amp;gt; best.length) best = bucket[b] })
return { sym: k, dumps: s.dumps.length, pumps: s.pumps, repeat: best.length, size: median(best), mv: median(s.mv) }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, tokens are ranked first by the number of fixed-size sell-offs, then by the total number of sell-offs, and the top five are selected. The default lookback is three hours. The table below shows a trial run using real data from the previous hour:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdvfhvi95m3t3wxej2ryg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdvfhvi95m3t3wxej2ryg.png" alt=" " width="800" height="184"&gt;&lt;/a&gt;&lt;br&gt;
DUSK had 12 sell-offs in one hour, nine of them worth about 118 USDT each. HANA still featured the familiar seller unloading around 2,500 USDT at a time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Entry: Sign a 1inch Limit Buy Order&lt;/strong&gt;&lt;br&gt;
The order price is Binance's best bid × (1 − 40 bp), and the order is valid for 15 seconds. 1inch v4 orders use EIP-712 structured signatures, with both the expiration time and permission for partial fills encoded in makerTraits:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function makerTraits(expireTs) { return (BigInt(1) &amp;lt;&amp;lt; BigInt(254)) | (BigInt(expireTs) &amp;lt;&amp;lt; BigInt(80)) }   

var o = {
    salt: String(now()) + String(Math.floor(Math.random() * 1000)), maker: WALLET, receiver: ZERO,
    makerAsset: USDT, takerAsset: t.addr,                       
    makingAmount: usdRaw.toString(), takingAmount: tokRaw.toString(),
    makerTraits: makerTraits(expire).toString(),
}
var hash = orderDigest(o), sg = DEX.IO("sign", "0x" + hash)    
HttpQuery(API_BASE, { method: "POST", body: body, headers: { "Authorization": "Bearer " + P.KEY, "Content-Type": "application/json" } })

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A single incorrect bit in the signature format can cause the platform to reject the order or prevent it from being filled on-chain. At startup, the strategy therefore signs a test order, checks its digest against hashOrder in the 1inch contract, and verifies the signer with the ecrecover precompiled contract. It proceeds only if both checks pass.&lt;/p&gt;

&lt;p&gt;Orders are not posted at fixed intervals. If the previous order has expired, or Binance's best bid has moved by more than 10 bp relative to the quote used when that order was posted, the strategy posts a new order at the updated price. Old orders are not canceled, because on-chain cancellation costs gas; they are simply allowed to expire. Several orders may therefore be valid at the same time. Exposure is capped by requiring "inventory plus unexpired buy orders for any one token ≤ 60 USDT" and "the total across all tokens ≤ 200 USDT":&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var fresh = o &amp;amp;&amp;amp; now() &amp;lt; o.expire &amp;amp;&amp;amp; Math.abs(t.bid / o.ref - 1) * 1e4 &amp;lt; P.DRIFT
if (fresh) return
var buyPx = t.bid * (1 - P.BUY_BPS / 1e4)
var room = Math.min(P.MAX_INV - inv.qty * t.bid - pendingUsd(t), P.MAX_TOTAL - totalUsd())

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is one more calculation before posting an order: assuming it fills, how far below Binance's best ask would the price be if we immediately sold the inventory on-chain? If the gap exceeds 30 bp, the pool is too shallow: buying the tokens would leave us unable to sell them back out effectively. The strategy skips orders for that token for now.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Fills and Hedging&lt;/strong&gt;&lt;br&gt;
In live trading, the strategy checks the wallet's balance of each token once per cycle. An increase means a buy order has been filled, so it immediately opens a market short on Binance for the filled quantity. Any remainder below Binance's minimum order size is accumulated until there is enough to hedge together.&lt;/p&gt;

&lt;p&gt;Simulation mode (DRY_RUN) follows the same process as live trading, but does not submit orders or execute trades. A simulated fill occurs when, during an order's validity period, the price of an on-chain trade crosses the order price by enough to cover the pool fee, leaving a profit for the bot. The entire order is then treated as filled, and the hedge is recorded at Binance's best bid at that moment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (o.side !== "buy" || pxUsd &amp;gt; o.px * (1 - p.fee)) return
o.filled = true
hedge(t, o.qty, o.px, snapAt(t, ts))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Exit: Wait for the Spread to Converge, Then Close Both Sides&lt;/strong&gt;&lt;br&gt;
The original idea was to post a sell order 40 bp above Binance's best ask after acquiring inventory, then wait for a bot to fill it when someone drove the pool price up. But the token-selection data showed that many tokens had large trades in only one direction, so a sell order might wait a very long time. We therefore switched to an active exit: on each cycle, the strategy uses PancakeSwap's Quoter contract to request quotes from all USDT pools for that token, calculates how much selling now would return, and compares the result with Binance's best ask:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var entryBp = (inv.shortCost / inv.short / (inv.cost / inv.qty) - 1) * 1e4   
var exitBp = (best.px / t.ask - 1) * 1e4                                     
var netBp = entryBp + exitBp - 2 * TAKER_FEE * 1e4
if (netBp &amp;lt; P.TP_BPS &amp;amp;&amp;amp; !force) return

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When entry spread + exit spread − Binance fees on both trades ≥ 5 bp, the strategy sells on PancakeSwap and simultaneously closes the short on Binance. With both sides executed together, changes in the token price offset each other, leaving only the spread to capture. If the spread still has not converged after 72 hours, both positions are forcibly closed at the prevailing spread.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Risk Controls&lt;/strong&gt;&lt;br&gt;
With one leg on-chain and the other on an exchange, there are more ways for things to go wrong than with a single-exchange strategy. The risk controls are therefore fairly detailed:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhpkpcdsvibsskir9gwmw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhpkpcdsvibsskir9gwmw.png" alt=" " width="800" height="260"&gt;&lt;/a&gt;&lt;br&gt;
The core logic for handling unmatched legs is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (now() - t.legSince &amp;lt; P.LEG_TIMEOUT * 1000) {
    hedge(t, 0, inv.qty &amp;gt; 0 ? inv.cost / inv.qty : t.bid, { bid: t.bid, ask: t.ask })   
    return
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unrealized profit on the on-chain leg is also calculated using the price at which the inventory could actually be sold on-chain now, rather than substituting the Binance price. That way, if the spread between the two venues widens, the loss appears directly in the status panel instead of being hidden.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Where We Are Now
&lt;/h2&gt;

&lt;p&gt;The token-selection scanner has been successfully tested on real on-chain data, and the strategy is currently running in simulation mode. The next steps are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run the simulation to assess whether token selection and order prices are reasonable, and examine the spread distributions for simulated entries and exits.&lt;/li&gt;
&lt;li&gt;Post one order far from the market price to confirm that the 1inch platform accepts it.&lt;/li&gt;
&lt;li&gt;Start small-scale live trading with 20 USDT per order.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The foreseeable risks are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Being picked off by better-informed traders&lt;/strong&gt;. If Binance prices fall sharply while my buy order is still valid, the order becomes expensive relative to the new market price. The first trader to fill it may then be someone who knows the price is falling, rather than a recovery bot. This is adverse selection. The validity period has been reduced from the originally planned 45 seconds to 15 seconds, with a cooldown triggered when a fill locks in a particularly poor spread. How much protection these measures provide still needs to be measured in live trading.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Unhedged exposure&lt;/strong&gt;. There is a gap of a few seconds between the on-chain fill and the Binance hedge.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;An exit that never arrives&lt;/strong&gt;. The spread may fail to converge for a long time, eventually triggering a forced exit after 72 hours at an unfavorable spread.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The wallet must be left alone&lt;/strong&gt;. Any change in the wallet's token balances will be treated as an order fill and hedged. Do not manually operate this wallet while the strategy is running.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  8. Closing Thoughts
&lt;/h2&gt;

&lt;p&gt;This was an exploration of a framework. The process showed that mature bots already capture on-chain arbitrage spreads extremely efficiently. They compete on speed, private transaction flow, and tips to builders—areas where an ordinary strategy has no advantage.&lt;/p&gt;

&lt;p&gt;Even so, the work was valuable. We learned the rhythm of on-chain recovery trades, identified the behavior of fixed-size sellers, and finally found a route through 1inch limit orders that does not require winning a speed race. Whether it can actually make money remains to be tested with small live trades. Opportunities always exist in the market. The code, data, and lessons from this attempt can serve as a reserve, helping us recognize and act on the next opportunity more quickly.&lt;/p&gt;

&lt;p&gt;Strategy source code: 1inch On-Chain Limit-Order Arbitrage — BSC and Binance&lt;/p&gt;

&lt;p&gt;This article is a personal record of strategy research and does not constitute investment advice. On-chain trading involves risks including smart contracts, private keys, adverse selection, and hedging failures. Simulated results and historical data do not indicate future returns.&lt;/p&gt;

</description>
      <category>web3trading</category>
      <category>defiarbitrage</category>
      <category>cryptoquant</category>
      <category>fmzquant</category>
    </item>
    <item>
      <title>FMZ Completes Its DEX Module: Turn New Token Trading, Market Making, and Cross-Chain Price Comparisons into Strategies</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Tue, 17 Nov 2026 09:38:12 +0000</pubDate>
      <link>https://dev.to/quant001/fmz-completes-its-dex-module-turn-new-token-trading-market-making-and-cross-chain-price-1d4k</link>
      <guid>https://dev.to/quant001/fmz-completes-its-dex-module-turn-new-token-trading-market-making-and-cross-chain-price-1d4k</guid>
      <description>&lt;h2&gt;
  
  
  1. The Wave Sparked by Robinhood Chain
&lt;/h2&gt;

&lt;p&gt;On-chain trading has picked up noticeably since Robinhood Chain went live. New tokens keep launching, pools are being created one after another, and stock tokens, meme coins, and stablecoin pools are all seeing activity. The momentum has not been confined to a single chain: capital and users are moving between Robinhood, Solana, and BSC, bringing more activity to new tokens and liquidity pools on Solana and BSC as well. One active newcomer seems to have stirred up the wider market.&lt;/p&gt;

&lt;p&gt;The main action in this wave is in the primary market: tokens have just launched, pools have just been created, and centralized exchanges have not listed them yet. The opportunities are all on-chain. Users have very specific needs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Buy new tokens on-chain as soon as they become available, and avoid having slippage eat into the proceeds when selling.&lt;/li&gt;
&lt;li&gt;Provide liquidity to new pools and earn trading fees.&lt;/li&gt;
&lt;li&gt;Compare prices and fee income across several chains and pools.&lt;/li&gt;
&lt;li&gt;Ideally, put all of this into strategies with automated execution and consistent accounting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;FMZ has supported Web3 for a long time through a unified interface: exchange.IO connects to nodes and calls contracts. This interface is flexible enough to do almost anything in principle, but the barrier to entry is too high for most users. To make a single swap on Uniswap, you have to look up contract addresses, encode the ABI, handle token approvals, calculate slippage, estimate gas, and wait for transaction confirmation. To provide concentrated liquidity, you also have to convert ticks, calculate the ratio of the two tokens, and manage the position NFT. Each chain and DEX adds its own differences: Uniswap has V2, V3, and V4; PancakeSwap has its own Infinity; Aerodrome has basic pools and Slipstream; and Solana has another ecosystem with Meteora, Raydium, and Orca. Much of the time that should go into writing a strategy ends up being spent dealing with contracts.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What This Update Adds
&lt;/h2&gt;

&lt;p&gt;We have now completed the DEX module as a whole. The idea is to stop making users interact directly with contracts and instead represent each DEX as an exchange object, connecting to it just as they would to a centralized exchange, with dedicated functions for operations unique to on-chain trading.&lt;/p&gt;

&lt;p&gt;Select the chain and wallet when adding an exchange, and the strategy uses familiar calls: GetTicker for prices, GetAssets for balances, and Buy / Sell / CreateOrder to place orders. The platform handles approvals, routing, slippage, gas, and transaction confirmation. When finer control is needed, parameters let you specify the routing version (v2 / v3 / v4), fee tier, and a particular pool. If a token launched only a few hours ago and is not yet in the platform's token list, register it with a single line, exchange.IO("token", name, contractAddress), and trade it like any other pair.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnw2qq0y2k4mn7na1zgxu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnw2qq0y2k4mn7na1zgxu.png" alt=" " width="799" height="178"&gt;&lt;/a&gt;&lt;br&gt;
Check the capability matrix to compare the functions supported by each exchange.&lt;/p&gt;

&lt;p&gt;For primary-market users, the three most immediate changes are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;One set of calls across chains and DEXs.&lt;/strong&gt; The same strategy can use Uniswap on Robinhood, PancakeSwap on BNB Chain, or Jupiter on Solana. The functions and fields stay the same; only the chain and pools change.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Register a new token and start trading immediately&lt;/strong&gt;. There is no need to wait for the platform to list it. With the contract address—or mint address on Solana—you can obtain quotes, place orders, and provide liquidity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dedicated functions for liquidity provision (LP)&lt;/strong&gt;. Finding a pool, setting a range, opening a position, collecting fees, and withdrawing liquidity each have an lp.* function. Tick conversions, token ratios, and approvals that you previously handled yourself are now handled inside these functions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will connect these capabilities through an LP example strategy below. First, let's spend two minutes on how LP works.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Understanding LP in Two Minutes
&lt;/h2&gt;

&lt;p&gt;On a DEX, there are no traditional resting buy and sell orders; trades are made against a pool. A pool holds two tokens, such as CASHCAT and WETH. Someone who wants to buy CASHCAT puts WETH into the pool and takes CASHCAT out, paying a fee along the way (1% for this pool). Liquidity providers supply the tokens in the pool, and the fees are distributed to them in proportion to their shares.&lt;/p&gt;

&lt;p&gt;Uniswap V3 introduced &lt;strong&gt;concentrated liquidity&lt;/strong&gt;: LPs can provide liquidity only within a price range they choose. What a position holds changes with the price:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmf9sta2lhgd7jaklwg9p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmf9sta2lhgd7jaklwg9p.png" alt=" " width="799" height="412"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Price is inside the range&lt;/strong&gt;: The position contains both tokens, and each trade through that range pays you fees.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Price falls&lt;/strong&gt;: As other traders sell the token into the pool, your position keeps buying it. Once the price drops below the lower bound, the position consists entirely of the token.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Price rises&lt;/strong&gt;: The reverse happens: your position keeps selling the token. Once the price rises above the upper bound, the position consists entirely of the quote token.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An LP position can therefore be understood as an automatically executed “buy low, sell high” order that also earns fees as it fills:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The income comes from fees. The more the price moves back and forth within the range, the more fees you collect. A narrower range concentrates your capital and gives you a larger share.&lt;/li&gt;
&lt;li&gt;The risk comes from a sustained move in one direction. If the price falls all the way through the range, you end up holding only the token. If it rises all the way through, you sell all your tokens early. The difference compared with simply holding the original assets is what is commonly called impermanent loss.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Whether LP is profitable ultimately comes down to arithmetic: can fee income exceed the losses caused by price movements?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.1 LP Functions Provided by the Platform&lt;/strong&gt;&lt;br&gt;
The lp.* functions cover the full life cycle of an LP position, from finding a pool to withdrawing liquidity. They are all called through exchange.IO("lp.xxx", ...). The Uniswap family (including PancakeSwap, Aerodrome, and others) and Jupiter (Meteora DLMM, Raydium CLMM, and Orca on Solana) use the same function names and return fields:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdtab4cpbz18zs2osxu5u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdtab4cpbz18zs2osxu5u.png" alt=" " width="800" height="361"&gt;&lt;/a&gt;&lt;br&gt;
Aerodrome / Velodrome also provide lp.stake, lp.unstake, and lp.claim for staking positions and claiming rewards. For full parameter details, see Uniswap · Concentrated Liquidity (LP) and Jupiter.&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Example Strategy: Web3 Liquidity Provision
&lt;/h2&gt;

&lt;p&gt;We used these functions to build a “Web3 Liquidity Provision Example Strategy.” Rather than being a fully automated black box, it breaks one LP cycle into clear steps: &lt;strong&gt;select a pool → configure positions → review the plan and scenario analysis → open positions → collect fees / reduce positions / withdraw liquidity&lt;/strong&gt;. Opening positions, collecting fees, and withdrawing liquidity are triggered manually through status-panel buttons. The strategy handles calculations, display, swaps, and accounting, and writes every step to the log.&lt;/p&gt;

&lt;p&gt;There are only three parameters: the token (enter its name if already listed, or “name,contractAddress” for a new token), the amount to invest each time, and whether to trade live. Leave live trading unchecked to simulate: the strategy only reads on-chain data, accounts for positions locally using Uniswap formulas, and submits no transactions.&lt;/p&gt;

&lt;p&gt;The overall workflow and the functions used at each step are shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9k4njq3bwedpe2j54d3k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9k4njq3bwedpe2j54d3k.png" alt=" " width="800" height="533"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;4.1 Identify the Chain and Register a New Token&lt;/strong&gt;&lt;br&gt;
At startup, the strategy first identifies the chain used by the current exchange and determines the funding token and gas token. It uses USDG on Robinhood, USDT on BNB Chain, and USDC on the remaining chains and Solana. For the Uniswap family, chain information is read through contracts; Jupiter is identified as Solana by its exchange name. The strategy then registers the new token and reads the current price and wallet balances:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var ct = exchange.IO("contracts")                     
exchange.IO("token", "CASHCAT", "0x020bfc650a365f8bb26819deaabf3e21291018b4")   
var ticker = exchange.GetTicker()                     
var assets = exchange.GetAssets()                     

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The startup log records each item clearly: the chain, funding token and gas token, whether the new token was registered successfully, current price, wallet balances, and whether the strategy is in simulation or live mode. In live mode, it immediately flags insufficient balances or a low gas-token balance.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8qzkdys3uivppmm2bqk9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8qzkdys3uivppmm2bqk9.png" alt=" " width="800" height="150"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;4.2 Pool Selection: Every Pool for a Token&lt;/strong&gt;&lt;br&gt;
New tokens in the primary market often have several pools at once: different quote tokens (USDG, WETH, native ETH), different protocol versions, and different fee tiers. When no quote token is supplied, lp.pools lists the token's pools across all quote tokens:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var pools = exchange.IO("lp.pools", "CASHCAT")        
pools.forEach(function (p) {
    if (p.empty) return                               
    p.dailyYield = p.fees24hUsd / p.tvlUsd * 100      
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;LPs earn fees, so the metric to compare is not trading volume but &lt;strong&gt;daily fee yield = 24-hour fees / TVL&lt;/strong&gt;. The strategy lists valid pools on separate pages by quote token, showing the fee tier, current price (also converted into the funding token when quoted in another token), TVL, 24-hour volume and fees, daily fee yield, annualized yield, daily turnover, and “estimated daily income for this investment” based on the default position configuration. Empty pools are excluded separately.&lt;/p&gt;

&lt;p&gt;In the live run, the scan found several valid CASHCAT pools quoted in USDG, WETH, and ETH. The WETH-quoted 1% pool had the deepest TVL, at approximately $2.5 million.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9ff4ibjpat6jydl4ywzq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9ff4ibjpat6jydl4ywzq.png" alt=" " width="800" height="94"&gt;&lt;/a&gt;&lt;br&gt;
A pool can be selected directly even when its quote token differs from the funding token, as with CASHCAT/WETH. When opening positions, the strategy first uses any WETH already in the wallet, then automatically swaps USDG to cover the shortfall. After withdrawing, it swaps WETH back into USDG, keeping all profit and loss accounting in the funding token. Operations across quote tokens that once required several contract calls now take a single Buy / Sell call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.3 Configure Positions and Review the Plan and Scenario Analysis&lt;/strong&gt;&lt;br&gt;
Click “Configure Positions” on a pool and set three things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Liquidity distribution&lt;/strong&gt;: uniform Spot, center-concentrated Curve, or edge-concentrated Bid-Ask.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Range&lt;/strong&gt;: the lower and upper bounds relative to the current price. A negative upper bound places staggered “buy orders” entirely below the current price.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Number of bands&lt;/strong&gt;: with uniform distribution, the range is divided into equal intervals on a logarithmic price scale.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After confirmation, the strategy immediately calls lp.plan to create a plan without submitting a transaction, and displays two tables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var plan = exchange.IO("lp.plan", {
    symbol: "CASHCAT_WETH",
    budget: 0.0041,                
    range: {lower: a, upper: b},   
    shape: "spot",
    pool: pool.id,
    slippage: 0.01
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Position plan&lt;/strong&gt;: Each band's price range, quantities of the two tokens, and equivalent amount in the funding token.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Returns and scenario analysis&lt;/strong&gt;: Estimated daily fees and annualized yield, share of pool liquidity, funding preparation, swaps required to open positions, whether wallet balances are sufficient, &lt;strong&gt;profit and loss and impermanent loss if the price falls to the lower bound or rises to the upper bound&lt;/strong&gt;, and how many days of fees would be needed to recover the loss at the lower bound.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There is a detail to watch when planning multiple bands: pool price boundaries must fall on multiples of the tick spacing (one spacing interval is about 2% in a pool with a 1% fee tier), so lp.plan aligns each band's lower and upper bounds outward. If each band is planned independently, adjacent bands overlap. The strategy therefore &lt;strong&gt;uses the previous band's actual aligned upper bound as the next band's lower bound, keeping them joined end to end. If a band is so narrow that it merges into the previous band&lt;/strong&gt;, the strategy skips it and suggests reducing the number of bands.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F58jgw57jbdlnl75xwbsa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F58jgw57jbdlnl75xwbsa.png" alt=" " width="799" height="266"&gt;&lt;/a&gt;&lt;br&gt;
If the returns look suitable, click “Open Positions” in the scenario-analysis table. Otherwise, configure positions in another pool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.4 Open Positions&lt;/strong&gt;&lt;br&gt;
lp.add executes the plan: it swaps tokens if needed, handles approvals, and then adds liquidity one band at a time. Actual gas costs are read from the receipt (on Solana, transaction fees and non-refundable account rent are used) and included in the cost of the cycle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var r = exchange.IO("lp.add", part)           
var rc = exchange.IO("receipt", r.txHash)     

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On-chain transactions occasionally time out without being included in a block, which is relatively common on Solana. The platform's error message explicitly states whether the transaction has reached the chain. If it is confirmed not to have reached the chain, the strategy replans that band at the latest price and automatically resubmits it, up to two times. If the status is uncertain, it does not retry, avoiding duplicate positions.&lt;/p&gt;

&lt;p&gt;The position-opening log follows four stages: “plan → swap → submit each band on-chain → complete.” Every band's position ID and transaction hash can be found in the log.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.5 Position Management&lt;/strong&gt;&lt;br&gt;
After the positions are opened, the “Position Plan” table becomes a table of actual holdings, refreshed with lp.positions every 10 seconds:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var ps = exchange.IO("lp.positions", "CASHCAT_WETH")
ps.forEach(function (p) {
    // p.priceLower / p.priceUpper / p.amountBase / p.amountQuote / p.value / p.feesValue
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each band shows its price range, status, quantities of both tokens, invested amount, value, uncollected fees, and profit or loss after its allocated gas costs. Summing the individual bands gives exactly the profit or loss for the group. The status column explains what each band is doing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;🟢 In range: shows the distance to the lower and upper bounds.&lt;/li&gt;
&lt;li&gt;⏳ Not yet reached; price must fall x% to enter: currently holds only the quote token and is waiting to buy the token.&lt;/li&gt;
&lt;li&gt;⏳ Not yet reached; price must rise x% to enter: currently holds only the token and is waiting to sell.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F728ud30gs90jjrlciqva.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F728ud30gs90jjrlciqva.png" alt=" " width="799" height="129"&gt;&lt;/a&gt;&lt;br&gt;
Each band and the total row have three buttons:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F64sr6kf8813m1awlbjfe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F64sr6kf8813m1awlbjfe.png" alt=" " width="798" height="106"&gt;&lt;/a&gt;&lt;br&gt;
When withdrawing liquidity, the platform submits transactions for each position in turn. If a transaction times out partway through, the error includes the positions already completed. The strategy first records those completed withdrawals, then automatically retries the remaining ones if they are confirmed not to have reached the chain. Before withdrawing, it also checks which positions still exist on-chain so that withdrawals are not duplicated.&lt;/p&gt;

&lt;p&gt;The metric cards at the top, price and range chart, fee coverage ratio, location within the range, capital and return breakdown, and return attribution (price changes / impermanent loss / fees / gas / quote-token exchange rate) put the arithmetic of “can fees cover the losses from price movements?” in front of you in real time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4g02b5u0ld1a0l4kgpcx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4g02b5u0ld1a0l4kgpcx.png" alt=" " width="799" height="266"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;4.6 One Codebase, Multiple Chains&lt;/strong&gt;&lt;br&gt;
Because DEXs are represented as exchange objects, this strategy can run on several chains without code changes. Only the exchange configuration needs to change:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxwk3oqnqkhirierzzuli.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxwk3oqnqkhirierzzuli.png" alt=" " width="799" height="155"&gt;&lt;/a&gt;&lt;br&gt;
There are two differences on Solana, both already handled by the strategy: token names and mint addresses are case-sensitive, and position IDs carry a protocol prefix, such as orca:address or meteora:address.&lt;/p&gt;
&lt;h2&gt;
  
  
  5. Live Trading Results
&lt;/h2&gt;

&lt;p&gt;We ran one live cycle on Robinhood Chain with 10 USDG, selecting the CASHCAT/WETH 1% pool with three uniform bands and a range of ±6%:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faz8ri2tnl03ii7sh1yyd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faz8ri2tnl03ii7sh1yyd.png" alt=" " width="800" height="152"&gt;&lt;/a&gt;&lt;br&gt;
We also ran a cycle with ORCA on Solana. Opening positions and withdrawing liquidity in the Orca pool both worked normally. A transaction timeout during the process led to the automatic resubmission and partial-completion accounting described in Sections 4.4 and 4.5.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi7npdn9w2evnvqltgldq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi7npdn9w2evnvqltgldq.png" alt=" " width="800" height="315"&gt;&lt;/a&gt;&lt;br&gt;
A single cycle with a small amount of capital does not establish long-term returns. A more measured approach is to run in simulation mode for a few days, checking fee coverage, time in range, and performance against buying and holding over the same period, then move to a small live allocation to confirm actual gas costs and slippage. On Solana, we recommend configuring a private RPC for the Jupiter exchange, as public nodes impose strict rate limits and transactions can easily time out.&lt;/p&gt;
&lt;h2&gt;
  
  
  6. A Side Note: The New Status Panel
&lt;/h2&gt;

&lt;p&gt;The screenshots above use the platform's new status panel. LogStatus now accepts objects directly to render components: metric cards, gauges, progress bars, various charts, calendar heatmaps, tabs, and more. Existing tables and buttons continue to work as before. For example, here are the metric cards at the top of the positions page:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;LogStatus("Liquidity Market Making · CASHCAT", {type: "badge", items: [{text: "Position Active", color: "up"}, {text: "Live Trading", color: "down"}]}, "\n", [
    {type: "alert", level: "success", title: "In Range, Earning Fees", text: "2/3 ranges are active"},
    {type: "grid", cols: 3, items: [
        {type: "kpi", title: "Strategy Equity", value: 9.998, unit: "USDG"},
        {type: "kpi", title: "Fee Income", value: 0, unit: "USDG", color: "up"},
        {type: "progress", title: "Range Position", value: 0.62}
    ]}
])

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdw3scwoerxyi7sjmfkyq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdw3scwoerxyi7sjmfkyq.png" alt=" " width="745" height="293"&gt;&lt;/a&gt;&lt;br&gt;
See the LogStatus documentation for complete component syntax.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. What's Next
&lt;/h2&gt;

&lt;p&gt;With the DEX module complete, several primary-market approaches—buying newly launched tokens, making markets to earn fees, comparing prices across chains and pools, and trading on-chain perpetuals and yields—can all be written into strategies under the same set of APIs. This LP example is just one of them. We will continue developing more on-chain strategies and sharing them with the community. If you have an approach you would like to implement on-chain, or run into problems while using these features, please leave a message in the community.&lt;/p&gt;

</description>
      <category>web3quant</category>
      <category>defiautomation</category>
      <category>fmzquant</category>
      <category>dexmodule</category>
    </item>
    <item>
      <title>Put These Two Features to Work in Quant Trading: Let AI Write Strategies, Run Tests, and Close the Loop</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Tue, 17 Nov 2026 08:28:23 +0000</pubDate>
      <link>https://dev.to/quant001/put-these-two-features-to-work-in-quant-trading-let-ai-write-strategies-run-tests-and-close-the-363a</link>
      <guid>https://dev.to/quant001/put-these-two-features-to-work-in-quant-trading-let-ai-write-strategies-run-tests-and-close-the-363a</guid>
      <description>&lt;p&gt;Recently, a user in the community raised a very practical question: when you use a browser-based AI to modify a strategy, you have to keep copying code between the chat window and the FMZ editor. Once the conversation gets long, you have to explain the background all over again. Switching to a coding tool such as Codex does let you edit a local project directly, but can you still make use of FMZ's candlestick annotations, logs, and profit curves at the same time?&lt;/p&gt;

&lt;p&gt;Yes. Connect your local project, FMZ remote synchronization, and the Extended API, and after changing the code, the AI can go on to read the strategy's runtime records, check its actual behavior, and make the next round of adjustments. The platform's charts remain available, while source code, tests, and review materials accumulate locally.&lt;/p&gt;

&lt;p&gt;Using Codex and a JavaScript strategy as examples, this article introduces the way we actually collaborate with AI in our strategy research. Other AI coding tools that can read and write project files and execute scripts can follow the same workflow.&lt;/p&gt;

&lt;p&gt;It seems that quite a few people don't know these tools can be used together this way, so this article was clearly needed! The examples below use GPT6. A model that is too weak may not be up to the task, so try to use a leading model. Let's get started.&lt;/p&gt;

&lt;p&gt;Quick tip: &amp;gt;_&amp;lt;! If the article feels too long and you don't want to read it all, you can simply hand it to AI. It will explain it clearly and tell you what you need to do.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. First, Define the Roles of Development and Execution
&lt;/h2&gt;

&lt;p&gt;The overall workflow can be organized like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Propose a strategy idea, constraints, and acceptance criteria
              ↓
AI reads the local project → Modifies code → Runs tests
              ↓
FMZ remote synchronization → Verify platform source code and parameters → Load the new version
              ↓
FMZ Docker runs the strategy, producing status information, order records, and profit data
              ↓
Retrieve data through the Extended API → Review locally → Make the next round of changes

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The local project preserves the development process, FMZ Docker executes the strategy, and the FMZ interface continues to provide monitoring and charts. AI performs specific tasks based on the files, tool permissions, and runtime data made available to it.&lt;/p&gt;

&lt;p&gt;Day-to-day trading should still follow explicit rules in the strategy code. The AI in this article is used for development and review. There is no need to call a large language model before every order, nor do you need to put exchange API keys into the chat history.&lt;/p&gt;

&lt;p&gt;There is an important prerequisite here: what AI can analyze depends on which data sources and tools we have actually connected. With only local source code, it cannot know what happened last night. With only a screenshot of the status panel, it cannot reconstruct an entire night's order changes, either.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Create a Local Project That AI Can Pick Up and Continue
&lt;/h2&gt;

&lt;p&gt;In plain English: create a local strategy development directory (folder), set up a series of project directories and files inside it, and then let your installed Codex application work in that strategy development directory.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you are not comfortable setting up Codex CLI, you can also use the Codex desktop app for your operating system, which is quite convenient. The instructions below use Codex CLI.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you already have Node.js and npm installed, you can install Codex CLI in a terminal and then enter your strategy directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @openai/codex
cd "your-strategy-project-directory"
codex

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Follow the prompts to sign in on your first run. Codex can read project files, modify code, and execute local commands, subject to the current permission settings. Refer to the official Codex CLI documentation for installation and sign-in instructions.&lt;/p&gt;

&lt;p&gt;Start by downloading the existing source code from FMZ and exporting the complete strategy configuration as well. A .js file contains only code, whereas the .xml file from a complete strategy export also contains configuration such as parameters. The two are not interchangeable. For the differences, see FMZ's guide to importing and exporting complete strategies.&lt;/p&gt;

&lt;p&gt;A small project can use the following structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my-strategy/
├── AGENTS.md                   # Project rules for AI
├── README.md                   # Current version, how to run it, and outstanding issues
├── strategy-design.md          # Signals, positions, exits, and profit accounting definitions
├── quant.js                    # Source code to synchronize to FMZ
├── complete-strategy-export.xml # Backup of platform configuration: parameters, interactive controls, etc.
├── tests/                      # Tests for key calculations and order scenarios
└── reports/                    # Runtime snapshots, reviews, and version verification records

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A complex strategy can be split into multiple modules and then built into a single release file. In that case, establish a fixed build entry point so that local modules, the release file, and the source code in the web editor do not each end up being edited separately.&lt;/p&gt;

&lt;p&gt;Codex supports reading project guidance from AGENTS.md. We can put frequently repeated requirements in this file, for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Project Rules

- Before making changes, read README.md, strategy-design.md, and the latest review report.
- Use the local source code as the basis for development; if someone edits the code manually in the web interface, pull it back and compare it first.
- When changing order logic, check partial fills, fills during cancellation, and duplicate updates.
- Preserve profit accounting, recording realized P&amp;amp;L, unrealized P&amp;amp;L, trading fees, and funding fees separately.
- Record test results before release; after release, verify the source code and the version running in live trading.
- Read keys from local environment variables or a separate credentials file; do not put them in source code or reports.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For how project rules are loaded, see Codex's AGENTS.md documentation. This file guides collaboration; actual permissions are still controlled by the tools and API permissions.&lt;/p&gt;

&lt;p&gt;At the end of each round, also ask AI to update the README: which version is local, which version is stored on the platform, which version is running live, and what evidence is still needed next. Even if you switch to a new conversation, work can resume from these files without retelling the entire chat history. Use Git alongside the source code to save checkpoints for comparison and rollback.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Connect FMZ's Two Channels
&lt;/h2&gt;

&lt;p&gt;Essential reading: before putting the following into practice, have your Codex Agent thoroughly read the FMZ platform's API documentation. Simply tell the AI to read the FMZ platform documentation first.&lt;/p&gt;

&lt;p&gt;There are two channels to connect: one for uploading code and one for reading runtime data. First, distinguish between the credentials involved:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr8c9gax7m0umya4w912b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr8c9gax7m0umya4w912b.png" alt=" " width="800" height="142"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Strategy synchronization token (strategy synchronization code): open the page for the strategy you want AI to design and work on:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgbuqabzrhxcjpox543m6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgbuqabzrhxcjpox543m6.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdbmnxqloz9373fe2lc78.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdbmnxqloz9373fe2lc78.png" alt=" " width="800" height="388"&gt;&lt;/a&gt;&lt;br&gt;
Once you have the synchronization code, you can give it directly to AI. You can delete the code when you are finished using it, so there will be no security issues.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;FMZ Extended API, on this page: &lt;a href="https://www.fmz.com/m/account#apikey" rel="noopener noreferrer"&gt;https://www.fmz.com/m/account#apikey&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F379wk88l3qzy3ecq1jfk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F379wk88l3qzy3ecq1jfk.png" alt=" " width="800" height="128"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1gwwa6ydbqtlsbe6hstu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1gwwa6ydbqtlsbe6hstu.png" alt=" " width="799" height="164"&gt;&lt;/a&gt;&lt;br&gt;
Once you have the Extended API KEY, you can give it directly to AI. You can also delete it after use, or save it in a file for AI to read when needed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Upload Source Code with Remote Synchronization (AI Can Do This; You Only Need to Understand the Basics Here)&lt;/strong&gt;&lt;br&gt;
Find the remote synchronization option on the target strategy's editing page and obtain the synchronization command provided for that strategy. Using the endpoint employed in our current project as an example, the core operation is to upload source code to &lt;a href="https://www.fmz.com/rsync" rel="noopener noreferrer"&gt;https://www.fmz.com/rsync&lt;/a&gt; with the strategy's Bearer token.&lt;/p&gt;

&lt;p&gt;Here is the Bash version. First, set the FMZ_SYNC_TOKEN environment variable through your local credentials configuration. The file to upload is quant.js in the current directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Exit immediately if the token is missing; do not put the real token in this script.
: "${FMZ_SYNC_TOKEN:?Please configure FMZ_SYNC_TOKEN first}"

printf 'Authorization: Bearer %s\n' "$FMZ_SYNC_TOKEN" |
  curl --fail-with-body --silent --show-error \
    --header @- \
    --upload-file quant.js \
    https://www.fmz.com/rsync

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use the path and token in the command generated by your own strategy editor. After synchronization, check the response and the target strategy, then read the source code back for comparison. An HTTP 200 response alone does not mean the entire release is complete.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Successfully synchronizing the source code does not mean the running live trading instance has loaded the new code.&lt;/strong&gt; In this project's actual synchronization process, after the platform's source code was updated, the original process continued running the old version. The new version would only load on the next start. Release records therefore need to keep both the "synchronized version" and the "currently running version." Use the new startup logs and the version shown in the status panel to establish the latter.&lt;/p&gt;

&lt;p&gt;Source code synchronization is no substitute for parameter migration, either. When code adds or changes parameters, interactive controls, or template references, also verify the platform configuration and the parameter values saved in existing live trading instances. The update plan should explain how existing positions, pending orders, and the persistent ledger will be carried forward.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Read Live Trading Data with the Extended API (AI Can Do This; You Only Need to Understand the Basics Here)&lt;/strong&gt;&lt;br&gt;
Open "API Interface" in your FMZ account settings and create an Extended API Key. For the initial connection, you can enable only GetRobotDetail,GetRobotLogs, which read live trading instance details and runtime records, respectively. FMZ supports configuring permissions by API method name; see the Create ApiKey documentation.&lt;/p&gt;

&lt;p&gt;The following Python 3 example only queries live trading instance details; it does not modify a strategy or start a live trading instance. Before running it, set three environment variables locally: FMZ_ACCESS_KEY, FMZ_SECRET_KEY, and FMZ_ROBOT_ID. The live trading instance ID is not the strategy ID.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import hashlib
import json
import os
import time
from urllib.parse import urlencode
from urllib.request import Request, urlopen

params = {
    "version": "1.0",
    "access_key": os.environ["FMZ_ACCESS_KEY"],
    "method": "GetRobotDetail",
    "args": json.dumps([int(os.environ["FMZ_ROBOT_ID"])]),
    "nonce": str(time.time_ns() // 1_000_000),
}
message = "|".join([
    params["version"], params["method"], params["args"],
    params["nonce"], os.environ["FMZ_SECRET_KEY"],
])
params["sign"] = hashlib.md5(message.encode("utf-8")).hexdigest()

request = Request(
    "https://www.fmz.com/api/v1",
    data=urlencode(params).encode("utf-8"),
    headers={"Content-Type": "application/x-www-form-urlencoded"},
    method="POST",
)
with urlopen(request, timeout=20) as response:
    payload = json.load(response)

data = payload.get("data") or {}
if payload.get("code") != 0 or data.get("error") or not data.get("result"):
    raise RuntimeError("FMZ query failed; check code and data.error in the response")

robot = data["result"]["robot"]
fields = ("id", "status", "strategy_id", "start_time", "refresh", "profit")
print(json.dumps({k: robot.get(k) for k in fields}, ensure_ascii=False, indent=2))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The signature concatenation follows the FMZ Extended API authentication documentation, and the response structure follows the GetRobotDetail documentation. The example retains HTTPS certificate verification and checks for application-level errors returned by the platform.&lt;/p&gt;

&lt;p&gt;This is only a single-query example. When turning it into a reusable tool, also handle timeouts, rate limits, and error logging. Requests using the same Key should centrally manage an increasing nonce to avoid conflicts between concurrently running scripts. See the Extended API interface details for the relevant requirements.&lt;/p&gt;

&lt;p&gt;It is fine if you are unfamiliar with the API. You can give AI the official documentation and the structure above and ask it to generate a query script in your project. Inject credentials through local input or a separate configuration, and let AI call the script. Do not copy real keys into public articles, strategy source code, or version-control repositories.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. How to Keep Using FMZ's Charts and Profit Curves
&lt;/h2&gt;

&lt;p&gt;Editing locally changes where the code is maintained. The strategy still runs on FMZ Docker, and its existing Log, LogStatus, LogProfit, Chart, and other outputs remain available. These display runtime logs, the status panel, the profit curve, and custom charts, respectively. See FMZ's logging and charting function documentation.&lt;/p&gt;

&lt;p&gt;For AI-assisted review, you can retrieve the data behind these displays locally:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fseoqp71jgeoywgcs4414.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fseoqp71jgeoywgcs4414.png" alt=" " width="798" height="189"&gt;&lt;/a&gt;&lt;br&gt;
The GetRobotLogs documentation describes the three groups of records—logs, profit, and charts—as well as the status panel field. Set the number of records requested according to your actual needs, read them in batches, and deduplicate them by record ID. Follow the official GetRobotLogs documentation and the actual responses for the API's response structure and parameters.&lt;/p&gt;

&lt;p&gt;The API returns data stored by the platform, not a screenshot of the entire web page. If existing candlestick annotations are recorded in chart data, they can be parsed alongside the series definitions. If the output consists only of images, those images need to be provided separately. Nor can tick-by-tick order book data that the strategy never saved be reconstructed from a profit curve.&lt;/p&gt;

&lt;p&gt;So, beyond charts, it is best to leave structured records of key actions. For example, for a single order, you should at least be able to trace:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SUBMIT: What side, price, and quantity were submitted?
ACK: Did the exchange accept the order, and what order ID did it return?
FILL: What quantity actually filled, at what price, and with what fees?
CANCEL: Why was the order canceled, and what was the cancellation result?
SETTLED: Have the final filled quantity and position been reconciled?

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Only then can AI distinguish between "a signal occurred," "an order was submitted," and "an order actually filled." A buy log or an order ACK does not mean a purchase has completed. Partial fills may also continue to arrive after a cancellation request has been sent.&lt;/p&gt;

&lt;p&gt;Keep the status panel concise, showing the version, freshness of market and account data, positions, current orders, main reasons preventing action, and net profit. Detailed diagnostics can be output on demand. The following illustrative snippet is intended to be embedded in an existing main loop; diag is maintained by the strategy's own statistics module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Place this in the existing command dispatch logic; if GetCommand is already called, do not consume commands again.
var command = GetCommand();
if (command === "diagnostics") {
    Log("DIAGNOSTICS", JSON.stringify({
        version: diag.version,
        observedAt: Date.now(),
        decisions: diag.decisions,
        signalPassed: diag.signalPassed,
        orderAttempts: diag.orderAttempts,
        blockers: diag.blockers
    }));
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, diagnostics is a command implemented by the strategy itself, not a built-in FMZ diagnostics feature. You can configure an interactive button, or trigger it through the API after separately enabling CommandRobot permission. For the command-receiving mechanism, see FMZ's GetCommand documentation.&lt;/p&gt;

&lt;p&gt;Profit accounting also needs clear definitions. Our project breaks strategy net profit down into realized P&amp;amp;L, unrealized P&amp;amp;L, trading fees, and signed funding fees, with account equity displayed separately. LogProfit only records the value passed to it. It does not automatically account for all costs, nor does it distinguish deposits, other strategies' P&amp;amp;L, and the strategy's own returns on the strategy's behalf.&lt;/p&gt;

&lt;p&gt;To avoid flooding the logs, you can record profit after events such as fills, reconciled position changes, or fees being posted, while continuously updating valuations in the status panel. When reviewing a run, save both the accounting period and the valuation time so that an event-sampled curve is not mistaken for an account equity curve updated every second.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. A Practical Case: Why a Strategy Ran All Night Without Trading
&lt;/h2&gt;

&lt;p&gt;During one iteration of Flow Efficiency Maker, the live trading instance ran for about 15 hours without making a new trade. The status panel at that moment showed the strategy waiting for a signal, but it could not tell us whether that had been the case all night.&lt;/p&gt;

&lt;p&gt;We examined the runtime records, diagnostic snapshots, and the corresponding version of the source code together and established several specific facts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Of about 209,000 decision samples, roughly 189,000 had valid model data. The market data inputs had not been invalid throughout the night.&lt;/li&gt;
&lt;li&gt;Only one sample reached recovery confirmation. That candidate had about 3.35 bp of remaining room to its target, below the strategy's required 5 bp cost buffer.&lt;/li&gt;
&lt;li&gt;The account, limits, and stopping mechanisms were not the main reasons for the lack of trades in this instance.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Further code inspection revealed a conflict between the recovery conditions and cost requirements: the strategy was designed to capture price shocks starting at about 8 bp, but required at least 20% recovery before entering confirmation, with the target set at 80% recovery. Ignoring small differences from the price denominator and rounding, the maximum available room was approximately:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;8bp × (80% − 20%) = 4.8bp

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That was already below the 5 bp cost buffer, and subsequent confirmation could consume still more of the available room. This explained why, even with apparently normal market data and the strategy continuously computing, it struggled to produce executable orders. Decision samples were highly correlated, so the counts above cannot be treated as the number of independent trading opportunities, either.&lt;/p&gt;

&lt;p&gt;Subsequent adjustments used this finding to align recovery timing with the room available to cover costs. We also added event-stage statistics to record whether opportunities disappeared at the identification, confirmation, cost, or execution stage. For validation, we used the same synthetic market data to compare behavior before and after the changes, then checked compatibility with the platform's runtime environment.&lt;/p&gt;

&lt;p&gt;This case illustrates the value of the collaboration workflow: use live trading evidence to locate specific conditions in the code, then use tests to validate the changes. It does not prove that the new version has acquired a profitable edge. Preset fills in synthetic scenarios cannot be treated as a market backtest. Ultimately, we still need to observe price movements after real fills, exit costs, and net profit.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Organize Each Round of Changes as a Verifiable Experiment
&lt;/h2&gt;

&lt;p&gt;After connecting the tools, it is not enough to tell AI simply to "keep optimizing." Each iteration should have a goal whose outcome can be assessed, such as "identify the main reason there have been no trades in the last 12 hours" or "check whether partial fills during cancellation are being counted twice."&lt;/p&gt;

&lt;p&gt;You can describe a task like this:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;First, read the project rules, strategy design, and latest validation report, and establish which versions are present locally, in the platform source code, and in the current live trading instance. Use the Extended API to retrieve the last 12 hours of logs, profit records, and diagnostic information, and save them in reports by time and record ID. Distinguish between signals not triggering, insufficient order amount, insufficient room to cover costs, failed order submissions, and orders canceled without fills, and provide supporting data. Once the cause is confirmed, modify the local code and run the relevant tests, recording the differences in behavior before and after the changes. Carry out source code synchronization and the live trading restart separately, as agreed for this round, and state in the report exactly which steps have actually been completed.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This task description connects the subject of the investigation, the evidence, the changes, and the release status. When first connecting the tools, you can limit the work to queries, then gradually add authorized synchronization and testing operations as you become familiar with the workflow. The Extended API includes both query and control endpoints; there is no need to enable every permission just to read logs.&lt;/p&gt;

&lt;p&gt;Validation should also be separated into levels, so that a single statement such as "tests passed" does not stand in for answers to every question:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F009pbasiud1sbb3oj771.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F009pbasiud1sbb3oj771.png" alt=" " width="800" height="156"&gt;&lt;/a&gt;&lt;br&gt;
For example, for a market-making strategy that relies on individual trades and order book queues, an ordinary candlestick backtest cannot adequately test queue-based fills and adverse selection. The test report needs to describe the data granularity, matching assumptions, sample period, and scenarios not covered. Any uncovered questions should remain on the list of items to validate.&lt;/p&gt;

&lt;p&gt;It is useful for each round to leave four deliverables: the modified source code, test results addressing that round's issue, runtime data and review conclusions, and a clear release status. In the next round, AI can read these files and continue researching the unresolved issues.&lt;/p&gt;

&lt;p&gt;With this approach, developers can devote more attention to strategy hypotheses, trading constraints, and evaluating the evidence: let AI perform repeatable queries, changes, and checks, while FMZ handles strategy execution and result recording. Only when each change has a corresponding version and validation record can we later determine what it actually solved.&lt;/p&gt;

&lt;p&gt;While we're here, let me also share a strategy used in the hands-on work discussed in this article&lt;/p&gt;

</description>
      <category>quanttrading</category>
      <category>aitrading</category>
      <category>algorithmictrading</category>
      <category>cryptobots</category>
    </item>
    <item>
      <title>Let AI Trade with a Different Kind of Candlestick: A Complete Strategy Development and Iteration Loop with Your Own Agent</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Tue, 17 Nov 2026 08:16:33 +0000</pubDate>
      <link>https://dev.to/quant001/let-ai-trade-with-a-different-kind-of-candlestick-a-complete-strategy-development-and-iteration-2f5l</link>
      <guid>https://dev.to/quant001/let-ai-trade-with-a-different-kind-of-candlestick-a-complete-strategy-development-and-iteration-2f5l</guid>
      <description>&lt;p&gt;A quiet fifteen minutes and fifteen minutes of suddenly surging volume each appear as a single fifteen-minute candlestick on a conventional chart. Yet the amount of trading activity within those two periods can be very different.&lt;/p&gt;

&lt;p&gt;What happens if we let trading volume determine when a bar closes, then use those bars to identify price breakouts?&lt;/p&gt;

&lt;p&gt;This time, we will work through a complete example using a “Volume Clock Breakout” strategy: give the idea to our own AI assistant, have it write the program, read backtest results, inspect runtime logs, and then make changes based on the evidence. Along the way, we need to answer a specific question: does observing the market at a different pace actually improve trading?&lt;/p&gt;

&lt;p&gt;In the previous article, we connected this development workflow using the Extended API and a strategy synchronization code. Here, we keep the same framework but switch to FMZ's MCP interface. We will hand tasks to the Agent step by step, working through connection setup, development and testing, and runtime inspections.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. First, Distinguish Who Writes the Code from Who Executes the Trades
&lt;/h2&gt;

&lt;p&gt;An Agent is an AI assistant that can read and write files, call tools, and work through a sequence of tasks. MCP supplies the platform's tools and parameter descriptions, allowing the Agent to understand how to read strategies, save versions, submit backtests, and query results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Propose a trading idea
    ↓
The Agent writes the strategy and tests
    ↓ Via MCP
The platform runs the backtest and returns results and logs
    ↓
The Agent analyzes the evidence, makes changes, and validates again

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After deployment, the strategy program processes market data and calculates signals, while the FMZ Docker runs the program and connects to the exchange. Each trade follows rules written in advance. The Agent handles research, development, and inspection, and can also carry out updates within an explicitly defined scope of operations.&lt;/p&gt;

&lt;p&gt;Periodic inspections also require the client or an external scheduler to wake the Agent. MCP supplies the tools; the scheduler initiates inspections at the specified times. The local project stores the source code, experiment configurations, and records.&lt;/p&gt;

&lt;p&gt;This is what makes it possible to trace an error log to the version that is running, and to associate a backtest with the rules and parameters used at the time.&lt;/p&gt;

&lt;p&gt;In plain language:&lt;br&gt;
The strategy running as a live trading instance on FMZ is the program that does the trading.&lt;br&gt;
The AI Agent handles strategy development, testing, iteration, evaluation, review, and supervision of that instance.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Connect Your Own AI and Complete a Read Operation First
&lt;/h2&gt;

&lt;p&gt;Open the FMZ homepage, find “Put FMZ in the hands of your own AI agent,” and click “Copy setup instructions.”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1duy3gqkcbgyzuc0t764.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1duy3gqkcbgyzuc0t764.png" alt=" " width="799" height="298"&gt;&lt;/a&gt;&lt;br&gt;
Give the instructions to your assistant and specify the scope for this round:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Read https://www.fmz.com/agent/setup.md, then connect to FMZ Quant.

Request all permissions for this round.
After connecting, list the available tools, verify the permissions, and complete one read-only query.
Do not create or start any running instances yet.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Let the Agent learn how to connect, as shown below:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyqcojmlvxmxk9wbwxy3m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyqcojmlvxmxk9wbwxy3m.png" alt=" " width="800" height="731"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Click the authorization link provided by the Agent:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fie7pfjeol5pfun8n5dmr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fie7pfjeol5pfun8n5dmr.png" alt=" " width="800" height="600"&gt;&lt;/a&gt;&lt;br&gt;
According to the official setup guide, the Agent provides a confirmation link after requesting authorization. You sign in through your browser, review the permissions, and authorize access; the Agent then finishes configuring the connection. If you already have a connection, you can first check whether it works.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk3xcdf8dveryu3wxm8m2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk3xcdf8dveryu3wxm8m2.png" alt=" " width="800" height="1032"&gt;&lt;/a&gt;&lt;br&gt;
The tool counts shown in the screenshots are illustrative; use the actual tool list returned after connecting. A successful connection is established by tools returning data successfully, not merely by the assistant saying “Setup is complete.”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ljbddli2iu7722qcgf6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ljbddli2iu7722qcgf6.png" alt=" " width="800" height="600"&gt;&lt;/a&gt;&lt;br&gt;
The read, backtest, and write permissions cover reading, backtesting, and saving changes, respectively. Creating, starting, or stopping instances later requires trade permission, along with explicit identification of the instance, Docker, and exchange object. Exchange API keys are configured on the platform's website; the Agent uses the IDs of objects that have already been configured. Permissions can be adjusted on the API Key management page.&lt;/p&gt;

&lt;p&gt;For this round, create a separate strategy. During connection setup, save a record of one successful query and the available tool scope. All subsequent development will use the same strategy ID.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Turn the Volume Clock into a Reproducible Experiment
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;First, Explain Why the Idea Is Worth Testing&lt;/strong&gt;&lt;br&gt;
A conventional fifteen-minute bar closes when its time is up. A volume bar accumulates trading volume and closes when it reaches a target.&lt;/p&gt;

&lt;p&gt;Suppose a bar has a target of 1,000 volume units: at 50 units traded per minute, it takes twenty minutes to complete; at 250 units per minute, it takes four minutes. This simply illustrates the mechanism. The actual target is calculated from historical data.&lt;/p&gt;

&lt;p&gt;Our hypothesis is that updating the observation interval more quickly when trading activity is concentrated may help identify breakouts sooner. We also need to consider the opposite possibility: the price may already have moved a long way by the time volume surges, faster bar formation may produce more false breakouts, and any additional returns may fall short of covering the costs.&lt;/p&gt;

&lt;p&gt;To evaluate this, the first version uses simple, fixed breakout rules and is compared against a version using conventional fifteen-minute bars.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Define the Rules for the First Version&lt;/strong&gt;&lt;br&gt;
The strategy is called “Volume Clock Breakout,” or VCB for short. The initial study uses ETH_USDT.swap and completed one-minute market data bars.&lt;/p&gt;

&lt;p&gt;Before each new volume bar begins, take the volume from the preceding full twenty-four hours and divide it by 96 to set the target volume for that bar. The number 96 is the number of fifteen-minute intervals in a day. It calibrates the initial scale; it does not mean that exactly 96 bars will form each day.&lt;/p&gt;

&lt;p&gt;The target stays fixed throughout the bar. Aggregate open, high, low, close, and volume minute by minute, completing a bar the first time the target is reached. Even a minute with extremely high volume produces only one bar. Do not invent an intraminute sequence of prices or reuse excess volume.&lt;/p&gt;

&lt;p&gt;This method is called “one-minute approximate volume bars.” Volume units must be consistent: coin quantities, contract counts, and traded notional amounts must not be mixed.&lt;/p&gt;

&lt;p&gt;The trading rules are fixed as follows:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fre9besshwr2esptnevk1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fre9besshwr2esptnevk1.png" alt=" " width="800" height="176"&gt;&lt;/a&gt;&lt;br&gt;
Estimate the order quantity as “account equity × risk fraction ÷ (stop price distance + estimated trading cost per unit).” Then apply the maximum notional limit and round down to the quantity step size. If the quantity or margin is insufficient, display the reason rather than increasing the budget automatically.&lt;/p&gt;

&lt;p&gt;Fix the ATR when the signal is confirmed, set the stop and target from the actual average fill price, and measure the maximum holding time from the first fill. Before trading begins, the twenty-four-hour volume baseline, twenty historical bars, and the data required for ATR must all be ready. Wait if the warm-up is incomplete.&lt;/p&gt;

&lt;p&gt;The channel must exclude the current bar. The core sequence is shown below; a complete program also needs data, order, and risk handling:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let signal = 0;
const prior = completedBars.slice(-20);

if (prior.length === 20) {
    const upper = Math.max(...prior.map(b =&amp;gt; b.High));
    const lower = Math.min(...prior.map(b =&amp;gt; b.Low));
    signal = closedBar.Close &amp;gt; upper ? 1
           : closedBar.Close &amp;lt; lower ? -1 : 0;
}

completedBars.push(closedBar);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read the historical channel first, then add the current bar. If the current bar is included in the highest-high calculation, a strict upward breakout cannot occur.&lt;/p&gt;

&lt;p&gt;After confirming a signal, execute using the next available market data. Do not assume a fill at a closing price that has already passed. Checks for a position's stop, profit target, and holding-time limit run independently, without waiting for the next volume bar to complete.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step One: Give the Requirements to the Agent
&lt;/h2&gt;

&lt;p&gt;Send this article to the Agent as the requirements specification, followed by these development instructions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Create a new VCB strategy in FMZ JavaScript, supporting ETH_USDT.swap.
Implement the volume-bar version according to this article's rules, and provide a fifteen-minute time-bar version for comparison.
Both versions must share the signal, position-sizing, and exit code. Use the backtest configuration below for the initial parameters.

Check the market data interval, volume units, warm-up length, and trading quantity rules.
Process duplicate minutes only once; do not open new positions while a data gap remains unresolved.
After a restart, restore data, order, and position state; do not place catch-up orders for past signals.
If an order's submission result is uncertain, query the order first rather than submitting it again immediately.

Show the breakout channel on the chart. In the status panel, show bar-formation progress, reasons for not trading,
orders and positions, account equity, and the strategy's net profit.

Complete local tests first, and deliver the source code, parameter descriptions, test results, and usage instructions.
After saving to the platform, read the strategy back to verify it, and record the strategy ID and code version.
Do not start a running instance yet.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flf3lwrr70bkstpewdjfa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flf3lwrr70bkstpewdjfa.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
For specific API calls, see the GetRecords documentation. The strategy rules and test conditions are provided in this article; the API documentation explains how to make the calls.&lt;/p&gt;

&lt;p&gt;Local tests should focus on three questions: does the same market data produce the same bars; can the program resume from its previous state after a restart; and can subsequent data rewrite earlier signals? While checking the conditions for opening new positions, continue handling exits for existing positions.&lt;/p&gt;

&lt;p&gt;Partial fills, duplicate reports, and order submission timeouts need separate local tests. FMZ backtesting uses taker execution with full fills, so it cannot cover partial fills. A simulated intraminute price path does not represent the actual sequence of prices either. See the backtest mode explanation.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Agent has designed the strategy on its own from the requirements:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4trfbz35b4mejlsgzu48.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4trfbz35b4mejlsgzu48.png" alt=" " width="800" height="296"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step Two: Check the Program First, Then Compare the Strategies
&lt;/h2&gt;

&lt;p&gt;First, select one week within the development period for a short backtest, and verify the warm-up, bar formation, signals, orders, and profit ledger. If there are no trades, inspect the counts at each stage and use deterministic samples to verify that signals can trigger. Do not relax the actual trading rules just to produce trades.&lt;/p&gt;

&lt;p&gt;Once the program's flow is working correctly, run the formal comparison. The following fixed configuration is suggested for the first round. All settings are research conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Historical period: 2025-10-01 to 2026-10-01, treated as a UTC interval that includes the start and excludes the end.&lt;/li&gt;
&lt;li&gt;Use the first nine months for development; reserve the three months starting on 2026-07-01 for the final check.&lt;/li&gt;
&lt;li&gt;Both versions start with 10,000 USDT in simulated capital, a planned risk fraction of 0.25% per trade, and a maximum notional amount of 1,000 USDT.&lt;/li&gt;
&lt;li&gt;Initially assume, per side, a taker fee of 5 bp and slippage of 2 bp, then add a stress test with both doubled. These are research assumptions; verify the actual fee rates separately.&lt;/li&gt;
&lt;li&gt;Obtain additional warm-up data from before the start date. If the full history is unavailable, report the available coverage first, then establish a new fixed experiment period.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One basis point (1 bp) is one ten-thousandth. Calculate funding fees based on historical positions. If the data is missing, label the results “excluding funding fees”; do not record a missing cost as zero.&lt;/p&gt;

&lt;p&gt;Both versions start from the same one-minute data, with time bars aggregated on UTC fifteen-minute boundaries. The only deliberately changed experimental condition is the bar construction method; position sizing and exits share the same implementation. Actual ATR values, position sizes, holding times, and trading frequency may change as a result, and the report should list these as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Run both versions using the fixed configuration and record each backtest ID.
Complete the development-period tests and cost stress tests first. Freeze the code and parameters before checking the holdout period.

Compare signal counts, actual trade counts, holding times, turnover, gross profit,
trading fees, funding fees, net profit, and maximum drawdown.
List missing data and execution-model assumptions separately. Do not deduct fees already included by the engine a second time.

If the code raises errors, read the logs and fix them, for no more than three rounds. Save each version and retest under the original conditions.
Do not continue tuning parameters based on the holdout results, or automatically select whichever period looks best.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If gross profit rises while net profit falls, examine the costs of the additional trades. If performance improves during development but fails in the holdout period, examine how dependent the results are on market conditions. If the two versions produce unexpectedly identical bars, or the same signal repeatedly submits orders, return to debugging the implementation first.&lt;/p&gt;

&lt;p&gt;Successful testing includes correct program behavior and complete records. Whether the strategy has a trading edge is a separate question, judged by its performance after costs.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Runtime Inspections: Evidence for Anomalies and Verification for Updates
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Observe First, Then Verify Orders and Profit&lt;/strong&gt;&lt;br&gt;
After historical testing, start in observation-only mode to confirm that real-time data, bar formation, and signals work correctly. Then use an explicitly designated simulated-trading exchange object to verify order submission and reconciliation.&lt;/p&gt;

&lt;p&gt;The platform interface uses “live trading instance” as the name for the runtime container. Whether it uses real or simulated funds depends on the connected exchange object. Creating an instance may incur platform fees. The strategy's “Allow order submission” switch does not turn a real exchange into a simulated one either.&lt;/p&gt;

&lt;p&gt;Before starting, fill in the objects and budget in the following task:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Use my designated Docker and simulated-trading exchange object to start the verified VCB version.
First report the object IDs, trading environment, parameters, and the results of the funds and order-quantity checks.
Operate within the scope explicitly defined for this round; do not modify other instances.

After starting, read back the version, data status, orders, positions, and net profit.
Record order submission, exchange acknowledgment, actual fills, and cancellation acknowledgment. Do not treat a request as a fill.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep five categories of information in the status panel: data warm-up, volume progress, signals and blocking reasons, orders and positions, and equity and strategy profit. Keep detailed data in the logs.&lt;/p&gt;

&lt;p&gt;If there are no trades, trace the issue along this path:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;One-minute data → Completed bars → Breakout signals → Execution checks → Order submission → Fills

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If no new bar has formed, the strategy may be waiting for volume. If a bar has formed without a breakout, no signal has appeared. If there is a signal but no order, check quantity, margin, quotes, and orders awaiting confirmation. Count these reasons separately rather than combining them into a single “Conditions not met” message.&lt;/p&gt;

&lt;p&gt;Account separately for realized profit, unrealized profit, trading fees, and funding fees. Exclude deposits, withdrawals, and profit or loss from other strategies. The status panel can refresh unrealized profit and loss; record profit logs when events occur, such as fills, position changes, or funding-fee entries.&lt;/p&gt;

&lt;p&gt;Simulated trading first verifies system behavior. A day without a fill does not establish whether a strategy is effective, and a handful of fills does not demonstrate long-term profitability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Make Inspections into Tasks That Actually Run&lt;/strong&gt;&lt;br&gt;
First, manually perform one read-only inspection to confirm that status information and new logs can be retrieved, then set up a schedule:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Inspect the designated instance every day at 9:00 a.m. Asia/Singapore time.
Verify the running version, parameters, Docker, exchange object, and data status.
Read new records from the previous log cursor, and report counts at each stage,
reasons for not trading, orders and positions, fees, and net profit.

Save the time, evidence, and conclusions to the local project.
This inspection is read-only. Do not automatically change parameters, modify code, or restart the instance.
Return the schedule record after creating it, and retain a record of an actual run after it executes.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If your current assistant does not support scheduling, use an external scheduled task to wake it. Having MCP connected and having a scheduled inspection actually run are two separate things that each need verification.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Work Through the Update Process with One Reproducible Problem&lt;/strong&gt;&lt;br&gt;
When an anomaly appears during testing, give the Agent both the raw data and the logs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Reproduce the problem from this inspection record, and identify the code version associated with the evidence.
Fix only the identified issue, add regression tests, and retest using the original configuration.
Report the changes, test results, and any matters that remain unverified.

If the running instance needs updating, first verify how outstanding orders and positions will be handled.
Then save the version, update, and restart within the scope explicitly defined for this round.
After restarting, read back the startup logs, actual running version, orders and positions, and profit ledger.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If no fault has been found yet, you can deliberately test duplicate minutes, missing minutes, or a restart during a local replay to check whether the program handles them as designed.&lt;/p&gt;

&lt;p&gt;After successfully saving the new source code, you still need to confirm that the running instance is actually using the new version. Retain a code digest, backtest IDs, runtime parameters, logs, and a research conclusion that can be checked, so the next round can build on the existing results.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The live trading instance started and supervised by the Agent, with no human intervention, is shown below:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhqr79kqkav99e9qxibv2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhqr79kqkav99e9qxibv2.png" alt=" " width="800" height="272"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;The Strategy Used in This Study&lt;/strong&gt;&lt;br&gt;
The source code for the strategy researched autonomously by AI through this complete loop is publicly available&lt;/p&gt;

</description>
      <category>quanttrading</category>
      <category>aitradingagent</category>
      <category>fmzquant</category>
      <category>cryptotrading</category>
    </item>
    <item>
      <title>No Explanations, Just Decisions: Plugging Jev into a Perpetual Strategy — Run It First, Talk Later</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Wed, 23 Sep 2026 02:46:37 +0000</pubDate>
      <link>https://dev.to/quant001/no-explanations-just-decisions-plugging-jev-into-a-perpetual-strategy-run-it-first-talk-later-2gep</link>
      <guid>https://dev.to/quant001/no-explanations-just-decisions-plugging-jev-into-a-perpetual-strategy-run-it-first-talk-later-2gep</guid>
      <description>&lt;p&gt;Last year, when Alpha Arena was making the rounds, several AI models were put into live trading environments, and every gain or loss sparked another round of discussion. Quant traders paid especially close attention: after spending so much time researching models and strategies, it was fascinating to see someone simply give the models capital and let them trade.&lt;/p&gt;

&lt;p&gt;This year, Jev arrived. I recently came across an open-source project that connects Jev to Kuru's order book on Monad and makes a trading decision roughly once every 300 milliseconds, in step with Monad's block cadence. Both the code and front end are open source. One widely circulated screenshot was especially eye-catching: on one side, people were impressed by the technology; on the other, it said something along the lines of "ran for 14 hours and lost more than 300%." But the screenshot was marked as a dry run, meaning the fills were simulated, and that percentage also depends on the P&amp;amp;L calculation method. It should not be interpreted as a real account literally losing more than three times its initial capital.&lt;/p&gt;

&lt;p&gt;Alpha Arena coverage · On-chain trading project source code&lt;/p&gt;

&lt;p&gt;After watching all that, I naturally wanted to try it myself. Last year AI trading went viral; this year we have a model designed specifically to make structured judgments. As quant traders, it is hard not to plug something like that into our own strategy and see what happens.&lt;/p&gt;

&lt;p&gt;That led to this Binance USDT-margined perpetual strategy running on FMZ. It is currently being tested live on ONE_USDT. Recently I have mainly used it to observe the kind of high-volatility, fast-moving market conditions traders often call "monster-coin" behavior. In these markets, changes in the order book and short-term price action are easier to see, and it is also easier to spot where the strategy and execution logic fail to cooperate.&lt;/p&gt;

&lt;p&gt;Below, I will walk through how Jev was integrated, why the strategy was modified along the way, and what became visible only after it started running.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let Jev Watch the Order Book, but Keep the Division of Labor Clear
&lt;/h2&gt;

&lt;p&gt;Jev's role can be summarized in one sentence: give it the current state, ask several clearly defined questions, and let it return choices, probabilities, or scores that the program can use downstream. For this experiment, that interface is enough.&lt;/p&gt;

&lt;p&gt;Short-term traders are familiar with situations like these: the bid side looks thick, yet the price refuses to rise; offers keep getting lifted, but new sell orders keep appearing; the market is quiet, then several aggressive buys hit in succession and the price starts stepping higher. Each of these observations can be turned into an indicator on its own. The difficult part is deciding what they mean when several appear at the same time.&lt;/p&gt;

&lt;p&gt;What I wanted to test was whether these clues could be organized into a clean market state and handed to Jev as several specific judgments.&lt;/p&gt;

&lt;p&gt;Official quick start&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffdoob0gaccifin3ovj8j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffdoob0gaccifin3ovj8j.png" alt=" " width="800" height="463"&gt;&lt;/a&gt;&lt;br&gt;
The input sent to Jev mainly includes the order book, recent trades, short-window price changes, and volatility. Missing data is explicitly marked as missing; "we did not receive the data" must not be silently converted into "buying and selling pressure is balanced."&lt;/p&gt;

&lt;p&gt;Account positions, order sizes, and trading restrictions are kept local. That way, when a trade does not happen, we can still determine whether the model failed to produce a strong enough signal or whether the order was blocked by fees, position limits, stale market data, or another execution rule.&lt;/p&gt;

&lt;p&gt;For execution, the strategy uses passive Maker orders in the hope of getting a better fill price. But anyone who has placed Maker orders knows the trade-off: being right does not guarantee a fill, and when you finally do get filled, it may be because the market has already started moving against you. Most of the later changes revolved around this problem.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Most Useful Change Was Splitting "Should I Trade?" into Separate Questions
&lt;/h2&gt;

&lt;p&gt;The easiest first attempt is to put market data, fees, and positions into one request and ask, "Should I buy, sell, or wait?" You get an answer, but if the model keeps saying "wait," it is hard to know why.&lt;/p&gt;

&lt;p&gt;Does it expect the price to fall? Does it think the upside is too small to cover fees? Is it worried about chasing the move? Is the current position affecting the answer?&lt;/p&gt;

&lt;p&gt;After reading How to Use Jev: Three Question Primitives and Layered Thresholds and comparing that approach with the official documentation, the division of labor became much clearer. The most useful idea was to split a large trading decision into several smaller judgments and then combine the answers in code.&lt;/p&gt;

&lt;p&gt;The snippets below are taken from the core strategy logic. Some field descriptions, logs, and surrounding checks are omitted for readability.&lt;/p&gt;

&lt;p&gt;Official design patterns&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9tkkoplp0wmwuq9apskk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9tkkoplp0wmwuq9apskk.png" alt=" " width="800" height="492"&gt;&lt;/a&gt;&lt;br&gt;
First, ask about direction and magnitude with a Choice question. For example: 30 seconds from now, is the return more likely to fall into a large decline, small decline, narrow-range move, small rise, or large rise?&lt;/p&gt;

&lt;p&gt;The program defines these ranges in advance, and the model assigns a probability to each one.&lt;/p&gt;

&lt;p&gt;Why ask about magnitude as well as direction? Because we have all seen trades where the direction was correct but there was almost nothing left after costs. Knowing only up or down is not enough.&lt;/p&gt;

&lt;p&gt;The strategy asks the same type of question over several horizons. The main trading horizon is 30 seconds; the other horizons are kept mainly for comparison.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;forecastHorizons().forEach(function (h) {
    questions["market_" + h] = {
        type: "choice",
        instructions: {
            question: "At " + h / 1000 +
                " seconds after state.timestamp, which interval will " +
                "R = 10000*(future mid price/state.mid - 1) fall into?"
        },
        criteria: criteria  // Five predefined return intervals
    };
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, ask whether getting filled is likely to hurt. This uses a Score question.&lt;/p&gt;

&lt;p&gt;A common Maker-order problem on the buy side is that the order refuses to fill, and then the moment it finally fills, the price drops. On the sell side, the mirror image happens: you finally sell, and the price keeps rallying.&lt;/p&gt;

&lt;p&gt;So I evaluate the two sides separately and ask how severe the adverse-selection risk would be over the next few seconds after a passive fill.&lt;/p&gt;

&lt;p&gt;The score levels should not be vague labels such as "low," "medium," and "high." Each level needs a concrete description: do aggressive trades and price movement point in the same adverse direction? Is there only one warning sign, or are several independent clues pointing the same way?&lt;/p&gt;

&lt;p&gt;In the snippet below, book is the best quote on that side. adverse means a decline for a buy order and a rise for a sell order.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;questions["toxicity_" + side] = {
    type: "score",
    instructions: {
        question: "If an order at " + book + " is filled, how severe is the risk " +
            "that price moves " + adverse + " by more than " +
            bounds.neutral + " bps within 5 seconds?"
    },
    criteria: [
        "Microprice, aggressive trades, and the realized price path do not point " + adverse,
        "Evidence is conflicting, or there are too few trades / too little depth to judge",
        "Microprice shifts toward " + adverse + " and aggressive flow keeps hitting that side",
        "Microprice, aggressive trades, and the realized price path all point " + adverse
    ]
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also need to ask whether the order is likely to fill at all. For that I use Noul.&lt;/p&gt;

&lt;p&gt;Noul returns a number between 0 and 1 representing the model's estimated probability that a yes/no statement is true. A value close to 0.5 means the model has no strong preference between yes and no.&lt;/p&gt;

&lt;p&gt;Here, that estimate is used to filter entry candidates that appear unlikely to fill and also helps determine the quote placement.&lt;/p&gt;

&lt;p&gt;However, the model does not know our true queue position, and a single order-book snapshot cannot reconstruct the full sequence of cancellations and fills. So the number has to be checked against actual order records later rather than treated as ground truth.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;questions["fill_" + side] = {
    type: "noul",
    instructions: {
        question: "If we place at " + book + ", will the order be filled within the next " +
            Math.round(CFG.signalTtlMs / 1000) + " seconds?"
    },
    criteria: {
        "true": "The passive order will be hit by the opposing side",
        "false": "The passive order will remain unfilled"
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Putting these three question types into one request gets much closer to the way a trader actually thinks while watching the book:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What do direction and magnitude look like?&lt;/li&gt;
&lt;li&gt;If I place the order, is it likely to fill?&lt;/li&gt;
&lt;li&gt;If it fills, am I likely to regret the fill immediately?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once the answers come back, the program uses them in different places: whether the directional signal is strong enough to open a position, whether fill probability is too low, and whether higher adverse-selection risk should move the quote to a more favorable price.&lt;/p&gt;

&lt;p&gt;Splitting the decision this way also gives us something concrete to debug. If quoting is too aggressive, inspect the risk score and quote-placement logic. If no orders ever appear, inspect which condition keeps failing.&lt;/p&gt;

&lt;p&gt;The three question primitives&lt;/p&gt;

&lt;h2&gt;
  
  
  When the Market Gets Wild, a Fixed Ruler Stops Working
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fd6js1f5nfsnoxw1vty7u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fd6js1f5nfsnoxw1vty7u.png" alt=" " width="800" height="510"&gt;&lt;/a&gt;&lt;br&gt;
While running the strategy on ONE, one thing became obvious: short-term market features are easier to see. Changes in buying and selling pressure, bursts of trades, sharp rallies, and pullbacks all become visible over relatively short windows.&lt;/p&gt;

&lt;p&gt;But large moves also magnify the weaknesses in passive quoting and exits.&lt;/p&gt;

&lt;p&gt;The first thing that needed to change was the ruler used to define price-move magnitude.&lt;/p&gt;

&lt;p&gt;A move that counts as a meaningful rise in a quiet market may be nothing more than ordinary noise in a token that is moving violently. If every instrument uses the same fixed boundaries, the model may still answer "large rise," "small rise," or "sideways," but those labels correspond to very different market conditions.&lt;/p&gt;

&lt;p&gt;The strategy previously spent long periods doing nothing. After checking the logic, the reason was fairly straightforward: on one hand, we were asking the model to predict a fairly large move over a very short horizon; on the other, we also required the model to be quite confident about it. When those conditions do not match the current volatility regime, waiting for a long time without a trade is perfectly normal.&lt;/p&gt;

&lt;p&gt;The return-interval boundaries were therefore changed to adapt to recent volatility, while preserving a floor based on fees and safety buffers.&lt;/p&gt;

&lt;p&gt;The lines below determine the initial boundary for a "large move." Upper and lower constraints are applied afterward. The volatility scaling is only an approximation, especially in markets with jumps and abrupt reversals; it should not be interpreted as a precise forecast of future move size.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;VOL.sigmaHorizonBps = VOL.sigma1mBps *
    Math.sqrt(CFG.signalHorizonMs / 60000);

var z = inverseNormal(1 - CFG.tailTargetRate);

var outer = Math.max(
    z * VOL.sigmaHorizonBps,
    minimumEdgeBps()
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Cancel-and-requote logic has the same problem. If the strategy cancels every time the price moves slightly, it may look responsive while constantly throwing away queue position.&lt;/p&gt;

&lt;p&gt;So the requote distance also needs to account for volatility and the instrument's minimum tick size.&lt;/p&gt;

&lt;p&gt;I will not go through every parameter one by one. Price precision, quantity precision, and minimum-order requirements should be read from the exchange whenever possible. Distances that can be estimated from live market data should adapt automatically. The human mainly decides what to trade, how much to trade each time, and the maximum allowed position.&lt;/p&gt;

&lt;p&gt;That reduces manual configuration mistakes when switching instruments, although the actual behavior still needs to be evaluated instrument by instrument.&lt;/p&gt;

&lt;h2&gt;
  
  
  A Bearish Model Does Not Automatically Mean "Open a Short Now"
&lt;/h2&gt;

&lt;p&gt;Another useful idea from the reference material is that different actions should have different thresholds.&lt;/p&gt;

&lt;p&gt;Suppose we already hold a long position and the model starts leaning bearish. That evidence may not yet be strong enough to justify opening a new short position, but it may already be strong enough to reduce part of the long.&lt;/p&gt;

&lt;p&gt;The code therefore separates the directional probability threshold for opening a new position from the threshold for reducing an existing position.&lt;/p&gt;

&lt;p&gt;Opening new exposure requires a stronger judgment. The strategy also checks whether the probability distribution is too diffuse and whether the passive fill probability is too low.&lt;/p&gt;

&lt;p&gt;Reducing exposure uses a lower directional threshold.&lt;/p&gt;

&lt;p&gt;The lines below show the core threshold-selection logic. Market-data validity, signal freshness, and the other safeguards still run around this block.&lt;/p&gt;

&lt;p&gt;Official confidence documentation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var required = plan.reducing
    ? CFG.reduceThreshold
    : CFG.openThreshold;

decision.requiredProbability = required;

if (tail &amp;lt; required) {
    decision.reasonCode = "probability";
    return decision;  // Keep the default action: wait
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The dashboard follows the same division of labor.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Signals &amp;amp; Decisions&lt;/strong&gt; panel puts the directional probability, entry and reduction thresholds, fill estimates for both sides, and adverse-selection scores in one place. The final column states why the current decision was made.&lt;/p&gt;

&lt;p&gt;With that table, we can trace a local execution decision back to the model outputs instead of guessing why the system keeps waiting.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Prediction Probabilities by Horizon&lt;/strong&gt; section expands the different time scales so we can compare the model's view over short and slightly longer horizons.&lt;/p&gt;

&lt;p&gt;One distinction matters here: the directional probabilities correspond to specific market events, while confidence measures how concentrated the answer distribution is. Confidence should not be interpreted directly as a trading win rate.&lt;/p&gt;

&lt;p&gt;Likewise, a bullish or bearish prediction still has to pass the local execution checks before it can become an order.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fafnbls93b4gw2h406suu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fafnbls93b4gw2h406suu.png" alt=" " width="800" height="174"&gt;&lt;/a&gt;&lt;br&gt;
Figure 1: Signal section captured from the live strategy dashboard. The upper section checks trading conditions; the lower section compares market judgments across multiple horizons. Values update while the strategy is running.&lt;/p&gt;

&lt;h2&gt;
  
  
  Once It Is Running, You Need to See What It Is Actually Doing
&lt;/h2&gt;

&lt;p&gt;The strategy is already running live, and the dashboard is mainly there to help identify problems.&lt;/p&gt;

&lt;p&gt;For example, when the model makes a prediction, once the forecast horizon has elapsed the strategy records which interval the realized price actually landed in. This appears in the &lt;strong&gt;Prediction Validation&lt;/strong&gt; section.&lt;/p&gt;

&lt;p&gt;For each horizon, it shows the sample count and five-class accuracy. It also includes a simple baseline that always predicts the narrow-range class.&lt;/p&gt;

&lt;p&gt;A Brier score is displayed alongside the accuracy figures to evaluate the error of the full probability distribution. Non-overlapping samples are also tracked to reduce the problem of many consecutive forecasts covering nearly the same market interval.&lt;/p&gt;

&lt;p&gt;Each metric tells us something different. No single number should be used to judge the entire strategy. Looking at them together makes it easier to identify which horizons and which market regimes deserve deeper investigation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm29th53b7ohgr536zct0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm29th53b7ohgr536zct0.png" alt=" " width="799" height="266"&gt;&lt;/a&gt;&lt;br&gt;
Figure 2: Prediction-validation panel. It uses the same return-interval definitions to compare the model's judgments with realized price action, while retaining a simple baseline and non-overlapping samples for later review.&lt;/p&gt;

&lt;p&gt;Passive fill quality needs to be evaluated separately, so the dashboard also contains a Post-Fill Price Performance section.&lt;/p&gt;

&lt;p&gt;It records the price move at several timestamps after a fill is detected. After a buy, a price rise is considered favorable; after a sell, a decline is favorable. The opposite direction is adverse.&lt;/p&gt;

&lt;p&gt;If the market frequently moves against the order immediately after a fill, we can go back and check whether the quote was too aggressive or whether the adverse-selection score actually helped.&lt;/p&gt;

&lt;p&gt;This measurement starts from the time the local program detects the fill. It does not subtract fees. Its purpose is to observe whether passive Maker orders are systematically exposed to adverse selection, not to report the net P&amp;amp;L of each trade.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxkpuvjfds7vuklr66zrg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxkpuvjfds7vuklr66zrg.png" alt=" " width="799" height="266"&gt;&lt;/a&gt;&lt;br&gt;
Figure 3: Post-fill price-performance panel. It keeps the short-term price path after each fill so it can be compared with the earlier risk score and quote-selection logic.&lt;/p&gt;

&lt;p&gt;When debugging, I also compare the &lt;strong&gt;Order Book &amp;amp; Order Flow, Data &amp;amp; Request Health&lt;/strong&gt;, and order-history sections.&lt;/p&gt;

&lt;p&gt;The first tells us what the model was seeing at the time. The health checks tell us whether the data was fresh and whether requests were failing. Position and order records tell us how far the execution actually progressed.&lt;/p&gt;

&lt;p&gt;If there was a signal but no order, first inspect the decision reason and the data state. If an order was placed but never filled, then inspect the quote and the fill-probability estimate.&lt;/p&gt;

&lt;p&gt;Read this way, each dashboard panel maps back to a specific piece of strategy logic described earlier.&lt;/p&gt;

&lt;p&gt;There are still important things missing from the current implementation.&lt;/p&gt;

&lt;p&gt;After a position exceeds its time budget, the strategy attempts to place a Reduce Only Maker order, but placing the order does not mean the position will be closed immediately. A complete hard stop-loss, daily-loss circuit breaker, and liquidation-distance check have not yet been added.&lt;/p&gt;

&lt;p&gt;As I continue running the strategy, what I most want to understand is where Jev provides useful information about order-book states, and how much of that value survives the transition from a model judgment to a real passive order.&lt;/p&gt;

&lt;p&gt;By keeping the input, judgment, execution, and validation records, there is something concrete to review afterward—and a much clearer answer to what should be changed next.&lt;/p&gt;

</description>
      <category>quanttrading</category>
      <category>cryptotrading</category>
      <category>perpetualfutures</category>
      <category>trading</category>
    </item>
    <item>
      <title>FMZ Web3 in Practice: Lessons from New-Pool Pitfalls — Building an Automated V3/V4 LP Strategy</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Wed, 23 Sep 2026 01:54:53 +0000</pubDate>
      <link>https://dev.to/quant001/fmz-web3-in-practice-lessons-from-new-pool-pitfalls-building-an-automated-v3v4-lp-strategy-14l</link>
      <guid>https://dev.to/quant001/fmz-web3-in-practice-lessons-from-new-pool-pitfalls-building-an-automated-v3v4-lp-strategy-14l</guid>
      <description>&lt;p&gt;In the previous article, we connected FMZ to Robinhood Chain and built a Uniswap V4 new-pool radar. Once a new pool appeared, the program could quickly capture information such as the trading pair, fee tier, and liquidity. That part went smoothly. With the pools now discoverable, the next question was obvious: could we provide liquidity when trading activity is high and earn some fees?&lt;/p&gt;

&lt;p&gt;So I continued modifying the code, adding simulated entries, position valuation, and exit logic. The first results looked quite good—the simulated equity curve climbed almost all the way up. That was tempting enough that I went on to add approvals, token purchases, liquidity provision, liquidity removal, and token selling, completing the live-trading workflow.&lt;/p&gt;

&lt;p&gt;After launching the bot, I was excited to watch the returns keep rising. Instead, I quickly learned that there are bad actors out there.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Three Tokens, Two Could Not Be Sold
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqcmn02tnr0bjoxc2a01v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqcmn02tnr0bjoxc2a01v.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
Of the first three tokens I tried, two became impossible to sell after the purchase. I had barely used ETH to buy the target token when the liquidity on the other side was removed. It almost felt as if someone had been waiting specifically for my order. I had entered the pool hoping to earn trading fees, but before earning anything, I was already left holding tokens in the wallet.&lt;/p&gt;

&lt;p&gt;My first reaction was that I had run into a honeypot token. But after checking the on-chain transactions, the causes still needed to be separated clearly. A token contract that restricts selling and a pool whose liquidity has been drained can both make a token effectively unsellable, but they are not the same problem.&lt;/p&gt;

&lt;p&gt;The perp case was especially obvious. Roughly two seconds after the purchase, the original LP removed its liquidity. Our own LP position had not even been established yet. I later tried reducing the sell amount, but the quote still reported insufficient liquidity. Increasing slippage and repeating approvals did not help—the counterparty liquidity required for the swap was simply no longer there.&lt;/p&gt;

&lt;p&gt;Looking back at the simulation curve at that point made it clear that I had celebrated too early. A simulation can value assets using the pool price, but whether that price is actually executable and whether sufficient liquidity will still exist at exit must be validated separately. Appreciation in the target token also cannot simply be counted as LP fee income. There is a full execution process between seeing a profit on paper and actually getting the capital back.&lt;/p&gt;

&lt;p&gt;So I first changed the accounting model. Estimated income, position valuation, realized LP fees, and final cash flows are now recorded separately. If the token has not yet been sold or the transaction has not been confirmed, the round cannot be considered successfully completed and profitable.&lt;/p&gt;

&lt;p&gt;For incomplete transactions, the program also preserves execution progress. After a restart, it first checks previously submitted transactions so that a temporarily missing receipt is not misclassified as a failure and the same purchase is not sent again.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Stop Racing into Brand-New Pools and Look for Pools That Can Keep Trading
&lt;/h2&gt;

&lt;p&gt;After taking that loss, I changed direction. A newly created pool has very little history, and its liquidity can disappear at any moment. No matter how carefully we check before buying, there is no guarantee that the state will not change one second later.&lt;/p&gt;

&lt;p&gt;Since the goal is to earn trading fees continuously, it makes more sense to start with pools that have already been operating for some time and still have ongoing trading activity. At least then, the main challenge is no longer fighting for the first few seconds after a pool is created.&lt;/p&gt;

&lt;p&gt;The first version of the filter, however, was too strict: the pool had to be at least seven days old, TVL had to be at least $500,000, the fee tier could not exceed 0.3%, and additional volume and price conditions were layered on top. Each rule made sense individually, but after combining them, very few V4 pools survived the filter. The bot was certainly cautious—it just rarely opened a position.&lt;/p&gt;

&lt;p&gt;After breaking the problem down, I found that some pools were excluded because the thresholds were too strict, some were never discovered by the program, and some belonged to protocols that were not yet supported.&lt;/p&gt;

&lt;p&gt;So while loosening the pool-age, liquidity, and short-term volume thresholds, I also added V3 support. In practice, V3 contained more pools worth further review. Focusing only on V4 unnecessarily narrowed the candidate universe.&lt;/p&gt;

&lt;p&gt;Adding V3 did not simply mean inserting pool addresses into a list. The V3 workflow also required identity verification, quoting, approval, entry, position creation, and exit logic.&lt;/p&gt;

&lt;p&gt;Here, a “stable pool” means a pool whose trading activity and liquidity are relatively stable. It does not mean that we only trade stablecoin pairs. What matters is whether continuing volume can plausibly support fee income and whether capital can enter and exit under reasonable conditions.&lt;/p&gt;

&lt;p&gt;The current thresholds—such as a minimum pool age of 12 hours and TVL of $20,000—are only research settings for this stage and still need to be calibrated against live operating data.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. The Pool Is Clearly Visible on the Website, but the Program Cannot Find It
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkqmhq6phpl2ag3qz8787.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkqmhq6phpl2ag3qz8787.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
After expanding the search scope, another frustrating problem appeared: some pools were clearly visible when opened manually in the browser, yet the program never placed them into the candidate list. MOO was one example.&lt;/p&gt;

&lt;p&gt;Early on, when we queried related pools through the ETH, WETH, and USDG token addresses, each API call returned only a limited number of results, and MOO was not among them. When we queried using the MOO token address itself, however, the pool appeared immediately.&lt;/p&gt;

&lt;p&gt;The problem was simple: it had never entered our pool directory in the first place. No matter how sophisticated the downstream filtering logic was, the pool could never reach that stage.&lt;/p&gt;

&lt;p&gt;We later added a hot-pool list and also tried reconstructing the historical directory from V3 and V4 pool-creation events. Technically, this works. But the node plan we were using allowed each eth_getLogs request to cover only ten blocks, making a historical backfill expensive in both request count and waiting time.&lt;/p&gt;

&lt;p&gt;For a new-pool radar, following the latest events forward is a good fit. But once the goal becomes finding already-active pools, rebuilding the full directory from historical blocks turns into a separate infrastructure project.&lt;/p&gt;

&lt;p&gt;After going around in circles, we eventually adopted the &lt;strong&gt;KyberSwap Earn pool-directory API&lt;/strong&gt;. Without specifying MOO by name or address, the pool appeared in ordinary pagination.&lt;/p&gt;

&lt;p&gt;From that point on, we separated pool discovery, market statistics, and on-chain verification:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flualy8fpi9jpth3y8g25.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flualy8fpi9jpth3y8g25.png" alt=" " width="695" height="148"&gt;&lt;/a&gt;&lt;br&gt;
Each directory page retrieves 100 pools. After completing one full pass, the program waits 30 minutes and then paginates again, merging and refreshing the results.&lt;/p&gt;

&lt;p&gt;Market statistics come directly from the available API fields, while on-chain requests are concentrated on candidate verification and position management. This way, the bot does not need to spend its first hour accumulating its own market history after startup, nor does it need to repeatedly scan historical blocks just to filter existing pools.&lt;/p&gt;

&lt;p&gt;Pagination itself also caused problems. The API sorts pools by real-time TVL, so the order can change while the program is moving through pages. As a result, the number of unique pools after deduplication may not exactly match the total reported by the API.&lt;/p&gt;

&lt;p&gt;If the program rigidly requires those numbers to match, it may keep restarting from page one forever. We therefore retained discrepancy logging, retry handling, and periodic refreshes, while separating the idea of “this pagination pass has finished” from “the entire chain has been covered completely.”&lt;/p&gt;

&lt;p&gt;The API provides a much broader candidate universe, but indexing delays and omissions can still occur, so continued rechecking is necessary.&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Testing with Only 3U — So How Did Gas Reach 2.33U?
&lt;/h2&gt;

&lt;p&gt;Once the pools could be discovered reliably, the next step was to measure costs seriously.&lt;/p&gt;

&lt;p&gt;During simulation, gas was mostly treated as an estimate. In live execution, however, one LP cycle can involve wrapping ETH, approvals, swaps, adding liquidity, removing liquidity and collecting fees, selling back, and unwrapping. V3 and V4 also use different approval paths, so it is not accurate to estimate both with a rough fixed number of transactions.&lt;/p&gt;

&lt;p&gt;We therefore wrote a standalone fee-measurement script. Using a principal budget of roughly 3U (~$3), it performed short-duration entry and exit cycles in pools pairing USDG with ETH/WETH.&lt;/p&gt;

&lt;p&gt;The tests were designed to answer two questions first: can the entire workflow complete successfully, and how much does each individual step actually cost?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu7zwh7pejk5r0fnsx9f2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu7zwh7pejk5r0fnsx9f2.png" alt=" " width="800" height="219"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Gas is calculated from the actual usage and gas price recorded in the transaction receipt rather than from the configured estimate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Actual gas expenditure, in wei
var gasWei =
    BigInt(receipt.gasUsed) *
    BigInt(receipt.effectiveGasPrice);

totalGasWei += gasWei;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0onyjhibg0xrr2unuiet.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0onyjhibg0xrr2unuiet.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
In the tests, the first complete V3 cycle consumed about 0.326U in gas, while a later V3 cycle reached approximately 2.33U. That result was surprising: with just a little over three dollars in principal, how had gas suddenly climbed above two dollars?&lt;/p&gt;

&lt;p&gt;Comparing the transactions showed that the later round required more approval steps and also ran during a period of significantly higher gas prices.&lt;/p&gt;

&lt;p&gt;In both rounds, wrapping ETH used exactly 57,647 gas, yet the actual cost was approximately 0.0139U in one round and 0.1545U in the other.&lt;/p&gt;

&lt;p&gt;Even the same operation can cost very different amounts. We cannot simply reuse the previous result as the next transaction's expected cost.&lt;/p&gt;

&lt;p&gt;A subsequent standalone V4 test consumed about 0.226U for the full cycle. Again, that number is only a cost sample from that particular execution.&lt;/p&gt;

&lt;p&gt;With these measurements available, the production code was changed to reserve gas separately for each operation—wrapping, approval, swapping, LP creation, and liquidity removal—while also considering the current gas price and a safety buffer.&lt;/p&gt;

&lt;p&gt;For token operations that have not yet been measured in live conditions, the program still keeps a relatively conservative fallback budget. What we are calibrating here is the budgeting model. Actual expenditure is still calculated from receipts, rather than hard-coding one historical test result into the strategy.&lt;/p&gt;

&lt;p&gt;The accounting scope also needs to be clear. In the standalone fee-measurement script, the roughly 3U principal was tracked separately from gas. In the production strategy, the current 3U budget per position already includes entry gas and execution reserves.&lt;/p&gt;

&lt;p&gt;The net change over a full cycle also mixes swap loss, price movement, and LP income. The amount remaining after subtracting gas cannot simply be labeled “swap fees.”&lt;/p&gt;

&lt;p&gt;These rounds successfully validated the V3 and V4 capital-in/capital-out workflow and fee accounting, but they were not long-term profitability tests.&lt;/p&gt;

&lt;p&gt;With such a small position, fixed execution costs represent a very large percentage of capital. Increasing the principal may dilute those fixed costs, but it will also change price impact, the strategy's share of liquidity, and the amount of capital at risk. Those effects still need to be evaluated separately.&lt;/p&gt;
&lt;h2&gt;
  
  
  5. Estimate What This Position Can Earn Before Deciding Whether to Open It
&lt;/h2&gt;

&lt;p&gt;A pool can have a lot of trading activity without necessarily generating much fee income for our position.&lt;/p&gt;

&lt;p&gt;For a concentrated-liquidity position, revenue also depends on the selected price range, current active liquidity, and the positions of other LPs. The current model therefore estimates our share of active liquidity before estimating fee income instead of directly using the APR displayed on a webpage.&lt;/p&gt;

&lt;p&gt;For volume, the model uses the smaller of the one-hour trading volume and the six-hour average hourly trading volume. This avoids making an overly optimistic decision based only on a recent one-hour spike.&lt;/p&gt;

&lt;p&gt;After combining the fee tier, the share of fees distributable to LPs, and the position's expected liquidity share, the estimated fee income is compared with the full round-trip cost. The core logic can be simplified as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Revenue and costs are normalized to ETH
var hourlyVolumeUSD = Math.min(volume1hUSD, volume6hUSD / 6);
var share = myLiquidity / (poolLiquidity + myLiquidity);

var expectedFeesETH = hourlyVolumeUSD / ethUSD
    * feeRate * lpFeeShare * share * 0.5;

var totalCostETH =
    quoteLossETH + slippageReserveETH + gasBudgetETH;

var requiredFeesETH =
    totalCostETH * 1.5 + principalETH * 0.01;

var incomeConditionMet = expectedFeesETH &amp;gt;= requiredFeesETH;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The revenue side applies a &lt;strong&gt;50% discount factor&lt;/strong&gt;. On the cost side, expected fees must cover &lt;strong&gt;1.5× the total cost&lt;/strong&gt;, with an additional &lt;strong&gt;1% of principal&lt;/strong&gt; reserved for inventory risk.&lt;/p&gt;

&lt;p&gt;Even after that condition is met, the position must still pass capital and execution checks.&lt;/p&gt;

&lt;p&gt;These coefficients are still model assumptions and are not supported by a sufficiently large sample of profitable trades. The discount factor and buffers are used to leave room between historical trading activity and future realized income—not to guarantee that a position will cover its costs after entry.&lt;/p&gt;

&lt;p&gt;After a position is opened, we also need to check whether the original assumptions are actually being realized. Price deviation, net loss, and declining liquidity can all trigger an exit. Once a position has been held for ten minutes, the strategy begins checking whether actual fee accumulation is materially lagging behind expectations.&lt;/p&gt;

&lt;p&gt;At entry, we rely on estimates. Once the position is live, actual data is available, so that data should be used to continue validating the thesis.&lt;/p&gt;

&lt;p&gt;The earlier design of forcing an exit after a fixed 30 minutes was removed. If pool conditions have not changed, repeatedly entering and exiting simply because a timer expired adds unnecessary costs. If conditions have already deteriorated, the strategy should not wait for the timer either.&lt;/p&gt;

&lt;p&gt;One hour is still used as the revenue-evaluation window, but it is no longer treated as a mandatory holding period.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. What to Optimize Next After Completing This Version
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fifytd7reizo3oaifl34d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fifytd7reizo3oaifl34d.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
At this point, the complete strategy workflow is in place: the API supplies candidates, V3 and V4 use separate execution paths, expected revenue and costs are evaluated before entry, positions are continuously checked while open, and exits are settled using actual cash flows.&lt;/p&gt;

&lt;p&gt;Unconfirmed transactions and unresolved assets remain in the ledger. After a restart, the strategy first resumes existing workflows so that an interruption does not leave behind an untracked position.&lt;/p&gt;

&lt;p&gt;In addition to small-scale full-cycle live tests, code checks now cover directory-pagination anomalies, pool-identity mismatches, quote failures, insufficient budgets, delayed transaction receipts, and restart recovery.&lt;/p&gt;

&lt;p&gt;The priority is to make sure the program stops opening new positions when conditions are not satisfied and, when transaction state is unclear, verifies already-submitted transactions before sending anything again.&lt;/p&gt;

&lt;p&gt;Only after the execution process is sufficiently robust does it make sense to evaluate the real effectiveness of pool selection and the revenue model.&lt;/p&gt;

&lt;p&gt;Future adjustments will therefore revolve around actual operating data. In particular, we need to avoid a common trap: lowering thresholds simply because the strategy is not opening positions, then immediately tightening them after a loss, until the system is just oscillating between parameter sets.&lt;/p&gt;

&lt;p&gt;Every change should correspond to a specific problem and have a measurable comparison metric:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3wgs60ip1nifvdh4fx7l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3wgs60ip1nifvdh4fx7l.png" alt=" " width="800" height="177"&gt;&lt;/a&gt;&lt;br&gt;
Looking back, the main value of this experiment was that it forced us to fill in the parts that simulations easily gloss over: where the pool comes from, how capital actually enters, how costs are calculated, and whether the exit is truly completed.&lt;/p&gt;

&lt;p&gt;With those pieces now represented explicitly in the strategy, later optimization can build on a stable foundation instead of redesigning the entire system every time a new problem appears.&lt;/p&gt;

</description>
      <category>web3trading</category>
      <category>strategy</category>
      <category>cryptobot</category>
      <category>fmz</category>
    </item>
    <item>
      <title>Put Factors Under Continuous Evaluation: Implementing the APFF Multi-Asset Perpetual Strategy on FMZ</title>
      <dc:creator>Dream</dc:creator>
      <pubDate>Wed, 09 Sep 2026 09:15:16 +0000</pubDate>
      <link>https://dev.to/quant001/put-factors-under-continuous-evaluation-implementing-the-apff-multi-asset-perpetual-strategy-on-fmz-2hnn</link>
      <guid>https://dev.to/quant001/put-factors-under-continuous-evaluation-implementing-the-apff-multi-asset-perpetual-strategy-on-fmz-2hnn</guid>
      <description>&lt;p&gt;Writing a momentum factor is not difficult. Writing a mean-reversion factor is not difficult either. The real hesitation begins when two factors give opposite opinions today: which one should the capital listen to? If a factor performs poorly for a while, should its weight be reduced, should it be temporarily disabled, or should its direction be reversed? And why should a newly discovered formula be allowed to control real positions at all?&lt;/p&gt;

&lt;p&gt;These questions are difficult to solve simply by adding more indicators. The more factors a system has, the more it needs a unified set of rules for evaluating and using them.&lt;/p&gt;

&lt;p&gt;APFF stands for Adaptive Perpetual Factor Factory. It is a multi-asset adaptive factor-factory strategy for perpetual futures. The system compares relative strength across a group of perpetual contracts, combines a small number of interpretable factors into a long-short portfolio, continuously records each factor's forward performance, gradually adjusts factor weights, and requires new candidates to pass through observation and small-weight trials before they can receive meaningful capital.&lt;/p&gt;

&lt;p&gt;This article is based on the repaired and runnable FMZ JavaScript implementation. It walks through the full process from data and factors to actual orders. The corresponding version is v0.1.0, build 20260905-05, research-definition version 2. Current live-running and simulation tests have validated the main engineering workflow, while long-term return performance still requires further out-of-sample evidence.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. First Turn the Trading Problem Into “Who Is Relatively Stronger?”
&lt;/h2&gt;

&lt;p&gt;At every decision point, APFF works with a cross-section: a group of different contracts observed at the same time.&lt;/p&gt;

&lt;p&gt;Suppose two baskets each start with 3,000 USDT of notional exposure. One basket is long and the other is short. Ignoring fees, funding, and rebalancing for the moment, if the long basket rises 4% while the short basket rises 1%, the price PnL is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Long-basket profit = 3,000 × 4% = 120 USDT
Short-basket loss  = 3,000 × 1% =  30 USDT
Total PnL          = 120 - 30   =  90 USDT

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the long basket falls 2% while the short basket falls 5%, the price PnL can still be positive when both sides have the same notional size. The point is that a long-short portfolio cares about the return spread between two groups of assets.&lt;/p&gt;

&lt;p&gt;But similar long and short notionals do not eliminate market risk. If the long side is concentrated in high-volatility assets while the short side is concentrated in low-volatility assets, a sudden market decline can still produce a severe imbalance between the two sides. For that reason, APFF adds volatility scaling, per-symbol caps, and a limited BTC beta hedge on top of relative-strength ranking.&lt;/p&gt;

&lt;p&gt;The system operates on several different time scales:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqszqd40ceue6gnjnv0t9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqszqd40ceue6gnjnv0t9.png" alt=" " width="800" height="202"&gt;&lt;/a&gt;&lt;br&gt;
Market data needs to be timely, but factor weights should move more slowly. Recomputing weights every time the order book ticks would turn a medium/low-frequency portfolio into a noise-chasing rebalancing system.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. The Trading Universe Determines What the Factors Are Comparing
&lt;/h2&gt;

&lt;p&gt;The current version supports only &lt;strong&gt;Binance USDⓈ-M USDT linear perpetual futures, with a default universe size of 30 symbols&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The program reads contract specifications through GetMarkets, while GetTickers and live market data are used to maintain volume, price, and spread information. The base filters include contract trading status, valid quotes, spread limits, and a 90-day listing-age requirement when listing time is available. Eligible contracts are then ranked by current 24-hour trading volume.&lt;/p&gt;

&lt;p&gt;A ranking buffer is used to reduce unnecessary membership turnover. By default, an existing member is preferentially retained as long as it remains within the top 40 eligible contracts. The remaining slots are filled with the highest-ranked alternatives. This prevents two contracts with similar volume from repeatedly entering and leaving the portfolio merely because they swap daily ranking positions.&lt;/p&gt;

&lt;p&gt;BTC is treated separately as the market benchmark and hedging instrument. Even if it is included in the trading universe, it is excluded from the ordinary alpha ranking. Actual portfolio decisions also require at least 15 non-BTC symbols that pass the data checks. The configured universe size and the number of symbols that are actually usable must therefore be treated as separate quantities.&lt;/p&gt;

&lt;p&gt;This implementation has clear boundaries. The current version uses 24-hour trading volume and basic filters. The reference design's 30-day average volume, historical point-in-time universes, continuous-data completeness filters, and order-book-depth filters have not yet been fully implemented. If listing time is missing, the code also cannot independently prove that a contract has been listed for at least 90 days. These differences should be kept in mind when evaluating strategy results.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Five Seed Factors, Each Representing a Testable Hypothesis
&lt;/h2&gt;

&lt;p&gt;The first set of seed factors comes from five families: momentum, reversal, funding, premium, and open interest.&lt;/p&gt;

&lt;p&gt;In the table below, RET denotes &lt;strong&gt;log price return&lt;/strong&gt;; RV denotes the sample standard deviation of 4-hour log returns within the corresponding window, not annualized volatility; and Z_TS denotes a time-series z-score computed separately for each symbol.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk2mcwoyl02dshegsygt8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk2mcwoyl02dshegsygt8.png" alt=" " width="798" height="190"&gt;&lt;/a&gt;&lt;br&gt;
The price-direction term in the OI factor is +1 when the 24-hour return is non-negative and -1 when it is negative. These interpretations are research hypotheses; whether they hold must be answered by mature samples. For example, “high funding” does not mean price must fall immediately. Crowded trades can persist for a long time.&lt;/p&gt;

&lt;p&gt;The core of the momentum factor can be seen directly in the source code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var full = returnBars(prices, p.longBars)
var recent = returnBars(prices, p.skipBars)
var rv = realizedVol(prices, p.longBars)
return finite(full) &amp;amp;&amp;amp; finite(recent) &amp;amp;&amp;amp; rv &amp;gt; 0
    ? direction * (full - recent) / rv
    : NaN

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The seed parameters use 42 four-hour candles to represent seven days and skip the most recent candle. Invalid data returns NaN and is then excluded from the valid-value set.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Funding Must First Be Put on a Common Time Scale&lt;/strong&gt;&lt;br&gt;
Funding settlement intervals can differ across records. The current implementation uses the observed settlement interval to normalize funding rates to a common 8-hour scale before computing time-series z-scores. The seed factor uses roughly 30 days of history and also checks whether historical coverage is sufficient and whether the most recent record is fresh enough.&lt;/p&gt;

&lt;p&gt;The current-period funding rate and historical settled funding rates must also be kept separate. FMZ's GetFundings provides funding-rate data for the current period. APFF stores it as current-period information, while research returns and settlement accounting use separate historical records. See the FMZ GetFundings documentation.&lt;/p&gt;

&lt;p&gt;Binance's /fapi/v1/fundingRate history endpoint provides fundingTime, fundingRate, and the markPrice associated with each funding settlement. This is the basis used by the current implementation to calculate historical funding cash flows. See the Binance USDⓈ-M Futures market-data documentation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Premium and OI Require Careful Attention to Data Sources&lt;/strong&gt;&lt;br&gt;
In production, the Premium factor uses historical Premium Index Klines from the exchange. In simulation, the system gradually accumulates a proxy snapshot series based on Mark / Index - 1. The two series are not defined identically, so factor performance observed in the simulated environment cannot be directly treated as evidence for production performance.&lt;/p&gt;

&lt;p&gt;Production OI history only accepts the quote-currency notional-value definition. Simulated snapshots are accumulated from available open-interest quantity and price data, then stored in 4-hour time buckets. This avoids accidentally treating six minute-level snapshots as six independent 4-hour observations.&lt;/p&gt;

&lt;p&gt;If auxiliary history is insufficient, the corresponding factor can remain unavailable temporarily. For a system designed to run for a long time, explicitly knowing that “this factor does not yet have enough data” is more meaningful than forcing the program to produce a number.&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Put Every Factor on a Common Ranking Scale So They Can Vote Together
&lt;/h2&gt;

&lt;p&gt;The five raw factors have different units and cannot be added directly. APFF processes each factor cross-sectionally: invalid values are filtered out, the remaining values are winsorized at the 5th and 95th percentiles, and ranks are then mapped to [-1, +1].&lt;/p&gt;

&lt;p&gt;If ranks start at 0, the mapping is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Normalized score = 2 × rank / (number of valid symbols - 1) - 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The highest score represents the symbol most favored by the factor, while the lowest score represents the least favored one. Equal raw values receive the average rank. If the entire cross-section has no meaningful variation, the factor is treated as invalid so that array ordering cannot manufacture a signal out of nothing.&lt;/p&gt;

&lt;p&gt;A single factor must cover at least 80% of the symbols in the current round. When the combined alpha score is formed, each individual symbol must also have coverage from at least 80% of the currently valid factor weight. These two checks separately control whether a factor has enough cross-sectional information and whether a particular symbol has enough combined information.&lt;/p&gt;

&lt;p&gt;For a symbol that passes the checks, the combined score is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Alpha_i = Σ(available factor weight_j × normalized score_ij)
          / Σ(available factor weight_j for symbol i)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This score determines relative ranking. How much capital the portfolio is allowed to use depends on another quantity: the amount of factor budget that is actually available.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. If Two Factors Are Missing, Why Should Total Exposure Shrink Too?
&lt;/h2&gt;

&lt;p&gt;The five initial seed factors each receive a 20% budget. Suppose momentum, reversal, and funding are available, while Premium and OI have not yet accumulated enough history. The effective factor budget is then:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;20% + 20% + 20% = 60%

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the remaining three factors are rescaled to 33.33% each, their weights sum back to 100%, but the same portfolio is now supported by less information and each factor is implicitly carrying more risk.&lt;/p&gt;

&lt;p&gt;APFF preserves the original budget meaning of each factor and leaves the unallocated portion idle. The initial gross notional budget is calculated as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Gross notional budget = account equity
                      × configured gross-exposure ratio
                      × selector confidence factor
                      × sum of effective factor budgets
                      × drawdown scaling factor

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Consider an example used only to explain the arithmetic. Account equity is 10,000 USDT, configured gross exposure is 60%, the sum of effective factor budgets is 60%, and both the confidence factor and drawdown factor are 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Gross notional budget = 10,000 × 60% × 1 × 60% × 1
                      = 3,600 USDT
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Initially, roughly 1,800 USDT is allocated to each side. Per-symbol constraints, hedging constraints, and turnover constraints are applied afterward. This number does not mean that the final orders are guaranteed to fill to the full amount, nor does it represent margin utilization.&lt;/p&gt;

&lt;p&gt;Current effective weights are also subject to these caps:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0sd8rz87ras2bfwk0b99.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0sd8rz87ras2bfwk0b99.png" alt=" " width="259" height="184"&gt;&lt;/a&gt;&lt;br&gt;
These percentages constrain &lt;strong&gt;factor budgets&lt;/strong&gt;. They further affect portfolio notional exposure and should not be interpreted directly as the percentage of account equity allocated to a particular coin.&lt;/p&gt;

&lt;p&gt;The corresponding code is split into two steps. effectiveWeights extracts ACTIVE and TRIAL factors that have valid scores in the current round, then calls the budget-constraint function. The following excerpts show the connection between the two pieces; the second excerpt sits inside the factor loop of normalizeWeightTargets:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function effectiveWeights(matrix) {
    var raw = {}
    factorIdsByStatus(["ACTIVE", "TRIAL"]).forEach(function(id) {
        if (Object.keys(matrix[id] || {}).length)
            raw[id] = Math.max(0, num(G.registry[id].weight, 0))
    })
    return normalizeWeightTargets(raw, G.registry, true)
}

// Per-factor cap inside normalizeWeightTargets
var cap = factor.status === "TRIAL"
    ? FIXED.trialFactorCap : FIXED.activeFactorCap
result[id] = Math.min(
    cap,
    Math.max(0, num(raw[id], 0))
        / (preserveBudget ? Math.max(1, total) : total)
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key is the final true, which corresponds to preserveBudget. Suppose the sum of valid weights, total, is only 0.6. The denominator becomes Math.max(1, 0.6), so each 0.2 stays 0.2. If the code divided directly by 0.6, each factor would be inflated to approximately 0.3333. If total budget exceeds 1, the same denominator mechanism compresses it back into the total budget range. Later checks also enforce family caps and total trial-factor caps. Any budget clipped by these constraints is not redistributed to the other factors.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Save Today's Decision First, Then Wait for Tomorrow's Answer
&lt;/h2&gt;

&lt;p&gt;One of the easiest mistakes in an adaptive system is to change the question while evaluating the answer.&lt;/p&gt;

&lt;p&gt;Whenever APFF generates a new decision round, it stores the universe version, entry reference prices, factor scores, and coverage observed at that time, then creates a research sample that matures eight hours later. Factor performance is updated only after that sample matures.&lt;/p&gt;

&lt;p&gt;After the first startup, seeing “valid samples: 0” in the status panel can be completely normal. Having enough historical candles to calculate momentum and having accumulated complete forward evaluation samples are two different conditions. The five seed factors being marked ACTIVE describes their initial operating status; it does not mean they have already passed a statistical test.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Freeze Sample Membership and Maturity Time&lt;/strong&gt;&lt;br&gt;
At entry, each factor's research portfolio uses the scores available at that moment to select approximately the top 20% of symbols for the long side and the bottom 20% for the short side. Half of the notional budget is allocated to each side, with equal weights within each side. Tied symbols on a quantile boundary are included together and side-level weights are then redistributed.&lt;/p&gt;

&lt;p&gt;At maturity, a symbol cannot simply be removed because its terminal price is missing, followed by reranking and replacement with another symbol. Otherwise, a losing position that happens to have missing data could disappear from the statistics.&lt;/p&gt;

&lt;p&gt;The current implementation allows at most a 60-second terminal-price collection window. Once a terminal price has been fixed, it is not replaced by a later price even if funding history arrives late. Funding history may be awaited until five minutes after the original maturity time; if the required data is still incomplete, the entire sample is invalidated.&lt;/p&gt;

&lt;p&gt;This puts an explicit bound on timing error, but the label is still a mid-price research approximation. It cannot be treated as the realized return of a passive limit order in a real exchange queue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Price Features and Trading Returns Use Different Return Definitions&lt;/strong&gt;&lt;br&gt;
Log returns are suitable for momentum and volatility features. For a fixed-quantity linear perpetual position, however, PnL should be calculated using simple price returns plus funding cash flows.&lt;/p&gt;

&lt;p&gt;Let the entry reference price be P0, the terminal price be P1, the k-th funding settlement rate be f_k, and its settlement mark price be M_k. The long-side research return per unit of initial notional is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;r_long = P1 / P0 - 1 - Σ(f_k × M_k / P0)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When historical mark prices are available, the code uses this definition. If mark price is unavailable, the funding impact is approximated against the initial notional. Trading fees are not deducted at this stage.&lt;/p&gt;

&lt;p&gt;The factor's long-short research portfolio then aggregates returns using signed weights and subtracts estimated turnover costs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Turnover   = Σ |new weight_i - old weight_i|
Net return = Σ(new weight_i × r_long_i) - Turnover × one-way cost

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example, if a symbol moves from a +5% long weight to a -5% short weight, the absolute weight change is already 10%, which includes both closing the long and opening the short. Multiplying by 2 again would double-count the cost.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Make New Factors Pass Through Observation, Trial, and Exit
&lt;/h2&gt;

&lt;p&gt;The current “factor factory” generates candidates from a finite set of templates. The templates cover momentum, reversal, Funding, Premium, OI, price-volume relationships, low-volatility ideas, and multiple lookback horizons.&lt;/p&gt;

&lt;p&gt;Each batch can add at most 12 candidates that have not already been registered. Formula type, parameters, and direction together define a fixed identity used for deduplication. Once the template space is exhausted, later batches may generate no new candidates. The current version does not call a large language model online to generate trading code, nor does it perform open-ended formula search.&lt;/p&gt;

&lt;p&gt;The main candidate lifecycle is:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2tyu80v2fnnomkh91ifq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2tyu80v2fnnomkh91ifq.png" alt=" " width="798" height="206"&gt;&lt;/a&gt;&lt;br&gt;
The observation stage requires at least 180 valid 8-hour samples, which is about 60 days under ideal continuous conditions. After entering TRIAL, the candidate must independently accumulate at least another 90 valid samples, or roughly 30 days. Missing samples and weekly screening cadence can make the actual calendar time longer.&lt;/p&gt;

&lt;p&gt;Trial-stage performance is recorded separately. Good performance accumulated during OBSERVING cannot be carried over to satisfy the TRIAL threshold.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Does the Evaluation Look At?&lt;/strong&gt;&lt;br&gt;
The current evaluation mainly examines &lt;strong&gt;Rank IC, cost-adjusted long-short returns, subperiod stability, bucket monotonicity, turnover, and data coverage&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Rank IC measures whether the ranking of entry scores agrees with the ranking of subsequent returns. To reduce small-sample optimism, the mean IC is shrunk:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Shrunk mean IC = n / (n + 60) × mean IC

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Stability divides the available return series into four time segments and measures how many segments have positive average net returns. This is a four-segment check; it should not be interpreted as having already survived four real calendar quarters or four complete market regimes.&lt;/p&gt;

&lt;p&gt;Candidates must not only have positive shrunk IC but also pass a stricter cost test. The base net return has already deducted one estimated cost charge; promotion testing subtracts the same cost once more to check whether the factor remains positive under doubled costs.&lt;/p&gt;

&lt;p&gt;The system also uses block bootstrap resampling to examine result stability. Separately, it estimates a tail probability under a zero-mean null and then applies a dependence-adjusted multiple-testing threshold. These two statistics must not be confused. The bootstrap positive-return frequency shown in the status panel describes the resampling results; it is not a “probability of future profitability.”&lt;/p&gt;

&lt;p&gt;These rules are intended to reduce the influence of small samples, repeated screening, and accidental winners. Fixed block length, a finite number of resamples, and continuous online screening still introduce approximations and selection bias. The system therefore cannot claim that all false discoveries have been rigorously controlled.&lt;/p&gt;

&lt;p&gt;In addition, if the absolute correlation between a candidate's contemporaneous research returns and those of existing portfolio factors exceeds 0.85, it is treated as highly redundant. At most two candidates from each batch can enter TRIAL, and at most one from the same family can do so. No more than two factors can be in TRIAL simultaneously, and no more than six factors can be ACTIVE.&lt;/p&gt;

&lt;p&gt;The basic admission function used during screening is shown below. The original logic is preserved; only line breaks and comments are made clearer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function factorPasses(factor, minimumSamples) {
    var s = summarizeFactor(factor)
    return s.samples &amp;gt;= minimumSamples
        &amp;amp;&amp;amp; s.shrunkIc &amp;gt; 0
        // meanNet already includes the base cost deduction.
        // Subtract the same cost once more to test doubled costs.
        &amp;amp;&amp;amp; s.meanNet - num(s.turnover, 0)
            * G.cfg.oneWayCostBps / 10000 &amp;gt; 0
        &amp;amp;&amp;amp; s.stability &amp;gt;= 0.75
        &amp;amp;&amp;amp; s.pPositive &amp;gt;= 0.90
        &amp;amp;&amp;amp; s.coverage &amp;gt;= 0.98
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All conditions must be satisfied simultaneously. stability &amp;gt;= 0.75 requires at least three of the four time segments to have positive average net returns. coverage &amp;gt;= 0.98 checks the average factor coverage across evaluation samples, which is stricter than the 80% threshold used for participation in a single round. During the observation stage, the function is called with a 180-sample threshold. During the trial stage, it uses independent trialMetrics and a 90-sample threshold. Even after this function returns true, the caller still checks the relevant multiple-testing criteria, correlation limits, and slot limits. A single true does not mean the factor has automatically been promoted.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Adaptive Reweighting Should Respond to Evidence With Restraint
&lt;/h2&gt;

&lt;p&gt;When there are not enough samples, the system uses equal budgets for the seed factors. Only after the adaptive-sample requirements are met are target weights derived from each factor's evaluation results.&lt;/p&gt;

&lt;p&gt;The implementation's evidence score combines scaled IC, net-return score, stability, and monotonicity, then subtracts turnover and missing-data penalties. It is an internal composite score, &lt;strong&gt;not a calibrated probability&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Target weights also take the volatility of factor research returns into account. The old and new target weights are then smoothed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Smoothed weight = 70% × old weight + 30% × new target weight

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;During ordinary weekly reweighting, the change in any single factor is limited to 5 percentage points, after which all budget caps are applied again. Factor dormancy and hard constraints can reduce a weight faster, so this smoothing rule should not be interpreted as saying that exposure can only decrease slowly under all circumstances.&lt;/p&gt;

&lt;p&gt;Once an ACTIVE factor has accumulated at least 180 valid samples, it enters DORMANT status and its weight is set to zero if both the mean IC and mean net return over the most recent 90 samples are negative. The current logic reduces or disables a factor; it does not automatically reverse the trading direction merely because recent performance has been poor.&lt;/p&gt;

&lt;p&gt;Reversing direction is itself a new hypothesis and should be evaluated from scratch. Otherwise, the system can easily end up chasing noise back and forth across the positive and negative sides of a signal that has simply stopped working.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. From Combined Scores to Executable Target Positions
&lt;/h2&gt;

&lt;p&gt;The live portfolio differs from the equal-weight research baskets used earlier to evaluate individual factors.&lt;/p&gt;

&lt;p&gt;The actual portfolio selects assets from both tails of the combined-score ranking. New targets are chosen from roughly the top and bottom 20%, with at most six symbols on each side. Existing targets are preferentially retained as long as they remain within roughly the corresponding 35% region of the ranking, reducing repeated turnover around the selection boundary.&lt;/p&gt;

&lt;p&gt;The raw weight within each side is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;raw weight_i ∝ max(0.05, |Alpha_i|) / RV_7D_i

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Stronger relative scores receive larger raw weights, while higher historical volatility reduces allocation. A per-symbol cap is then applied, with the default absolute target notional limited to 8% of account equity.&lt;/p&gt;

&lt;p&gt;The BTC hedge estimates beta from aligned 4-hour returns. If the absolute estimated beta exposure of the portfolio exceeds 2% of equity, the program attempts to offset it with BTC. The hedge itself is capped and remains subject to per-symbol and total-portfolio exposure limits. Some residual beta can remain after clipping, so this is intentionally a &lt;strong&gt;limited hedge&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Turnover is handled last. Under normal target rebalancing, the notional amount changed in one decision is softly capped at 20% of account equity. If the desired adjustment exceeds that level, the portfolio moves proportionally toward the new target. However, if the current target already violates a hard risk limit, required deleveraging takes priority; excessive risk is not preserved merely to satisfy the turnover limit.&lt;/p&gt;

&lt;p&gt;After all hedge and turnover adjustments, the program performs another check of per-symbol and total exposure. A target that passed earlier checks can become invalid again after subsequent transformations, so this final validation must occur before the executable target is finalized.&lt;/p&gt;

&lt;p&gt;Because the actual portfolio uses volatility weighting, ranking buffers, BTC hedging, and turnover controls, individual factor research returns cannot simply be added together and treated as strategy-level account returns. The research layer evaluates ranking information; the execution layer must additionally determine whether that information can be converted into positions at a reasonable cost.&lt;/p&gt;

&lt;h2&gt;
  
  
  10. After an Order Fills, the Position Still Has to Give the Same Answer
&lt;/h2&gt;

&lt;p&gt;Once a multi-asset strategy runs asynchronously, market data, order responses, fills, and position snapshots can arrive in different orders.&lt;/p&gt;

&lt;p&gt;FMZ's exchange.Go can call trading interfaces asynchronously and retrieve results through the returned object's wait method. APFF uses this mechanism to stagger data and account queries. The current maximum number of concurrent tasks is 8. See the FMZ exchange.Go documentation.&lt;/p&gt;

&lt;p&gt;Asynchronous execution creates another question that must be answered explicitly: &lt;strong&gt;did this request actually take effect on the exchange?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Save the Intent Before Sending the Order&lt;/strong&gt;&lt;br&gt;
Before every order is sent, the program first generates a client order ID and records the symbol, side, quantity, current position, and corresponding target, then persists that intent. If persistence fails, the order is not sent.&lt;/p&gt;

&lt;p&gt;At most one active intent is allowed per symbol, and at most four can exist globally at the same time. When reversing direction, the program closes the original side before considering a new position on the opposite side. Normal execution uses &lt;strong&gt;GTX passive limit orders&lt;/strong&gt;. New targets have a default execution window of 15 minutes. After that window expires, the strategy stops adding new risk, while required risk reduction and reconciliation continue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If a Request Times Out, Verify the Result First&lt;/strong&gt;&lt;br&gt;
A definite rejection and an unknown result must be treated differently. Insufficient balance, precision errors, and similar responses can be handled as explicit rejections. A timeout, broken connection, or unknown response may occur &lt;strong&gt;after&lt;/strong&gt; the exchange has already accepted the order.&lt;/p&gt;

&lt;p&gt;The current implementation continuously reconciles by order ID or client order ID against order details, open orders, and historical orders. It does not release an unknown intent and submit the order again merely because “the open-order list is empty” or “tens of seconds have passed.”&lt;/p&gt;

&lt;p&gt;After the Order Reaches a Terminal State, Confirm the Position Too&lt;br&gt;
Suppose the original position is 100 contracts and a closing sell order accumulates 30 contracts of fills. The next position snapshot should confirm that roughly 70 contracts remain. This query must be initiated after the order reaches its terminal state; a late response from an older request cannot be used as confirmation. If the snapshot still reports 100 contracts, the program shows WAIT_POSITION, continues querying, and keeps the symbol locked.&lt;/p&gt;

&lt;p&gt;The expected position is calculated as “initial position + signed cumulative filled quantity” and stored as barrier.expected. After a position response arrives, applyPositions checks whether the reconciliation lock can be released. The following excerpt shows the core order path in the current version, omitting diagnostic logs and legacy state-migration branches. positions is the already-parsed position map:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var snapshotAt = num(requestedAt, nowMs())
Object.keys(G.execution.positionBarriers || {}).forEach(function(symbol) {
    var barrier = G.execution.positionBarriers[symbol]
    // The query must have been initiated after the terminal state.
    // A symbol with simultaneous long and short positions cannot be unlocked.
    if (snapshotAt &amp;lt;= barrier.at || (G.actual.hedgedSymbols || {})[symbol])
        return

    var spec = G.universe.markets[symbol]
    var tolerance = Math.max(1e-12, num(spec &amp;amp;&amp;amp; spec.step, 0) / 2)
    if (finite(barrier.expected)
        &amp;amp;&amp;amp; Math.abs(num(positions[symbol], 0) - barrier.expected) &amp;gt; tolerance)
        return

    delete G.execution.positionBarriers[symbol]
    clearIssue("POSITION_RECONCILE_" + symbol)
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;snapshotAt uses the request-initiation time to determine ordering. Quantity comparison allows an error of half the order-size step and also applies a tiny numerical-error floor. If any check fails, the function returns early, the symbol lock remains in place, and the execution layer continues blocking new orders for that symbol. Only after all checks pass is positionBarriers[symbol] deleted. This avoids the classic duplicate-trading failure mode of “the order has filled, the position endpoint has not updated yet, so the strategy sends the same trade again.”&lt;/p&gt;

&lt;p&gt;One Binance simulation test provides a concrete example. A TAC position-reduction order accumulated &lt;strong&gt;17,990 contracts&lt;/strong&gt; of fills, reducing the position from &lt;strong&gt;37,062&lt;/strong&gt; to &lt;strong&gt;19,072&lt;/strong&gt; contracts. During the process, a cancel request raced with the fill and produced one -2011 response. Subsequent order queries confirmed the remaining execution within about &lt;strong&gt;2.17 seconds&lt;/strong&gt;, completing reconciliation.&lt;/p&gt;

&lt;p&gt;This test record shows how that particular race condition was recovered. The error message itself cannot prove that the order filled, nor can it prove that cancellation succeeded. Final confirmation still requires the terminal order state and the position quantity to agree with each other.&lt;/p&gt;

&lt;h2&gt;
  
  
  11. Risk Controls Must Work While the Program Is Still Running
&lt;/h2&gt;

&lt;p&gt;APFF scales target budget according to drawdown from the historical equity peak:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fuqgjj517oxxk4x0tf8hf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fuqgjj517oxxk4x0tf8hf.png" alt=" " width="464" height="181"&gt;&lt;/a&gt;&lt;br&gt;
The 4% and 7% tiers take effect on the current target immediately; the system does not wait for the next 8-hour decision. The zero-target state continues to prevent new exposure, while the execution layer reduces positions after it obtains the required market and account state. These controls constrain the program's targets and execution behavior; they do not guarantee that maximum loss in an extreme market will stop exactly at 10%.&lt;/p&gt;

&lt;p&gt;The interactive controls distinguish three actions: PAUSE_NEW pauses new risk, RESUME resumes portfolio execution, and REDUCE_TO_ZERO cancels this strategy's orders, completes reconciliation, and then closes the positions managed by this strategy.&lt;/p&gt;

&lt;p&gt;The strategy uses its own position-ownership markers to determine what it manages. If a target symbol already has a position that is not attributed to this strategy, or if simultaneous long and short positions are detected in the same symbol, automatic trading for that symbol is blocked.&lt;/p&gt;

&lt;p&gt;Stopping the process does not automatically liquidate positions. If the intention is to flatten the portfolio, the flattening workflow should be allowed to complete and its result should be verified. Simply stopping the robot leaves positions in place. For a multi-asset portfolio, this distinction directly determines how much risk remains in the account after shutdown.&lt;/p&gt;

&lt;h2&gt;
  
  
  12. How to Interpret Run Modes and the Status Panel on FMZ
&lt;/h2&gt;

&lt;p&gt;The current version provides three run modes:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2l70zjvcp0o2l9ujmm1v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2l70zjvcp0o2l9ujmm1v.png" alt=" " width="800" height="121"&gt;&lt;/a&gt;&lt;br&gt;
LIVE uses the trading interface. If the exchange object is configured for the Binance simulated environment, orders are matched in the exchange's simulation environment. Only when the strategy is connected to a real-money account does LIVE correspond to real-money trading. Both the run-mode name and the account environment must be checked.&lt;/p&gt;

&lt;p&gt;The current program depends on live WebSocket data and blocks entry into FMZ's historical backtest environment during initialization. Therefore, PAPER must accumulate forward results through real-time running. It is not a mode where one can simply select a historical date range and backtest it.&lt;/p&gt;

&lt;p&gt;After importing the complete strategy file and adding a corresponding Binance futures exchange object, the main parameters are:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1j2kyfurdzzb1hd8cg5x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1j2kyfurdzzb1hd8cg5x.png" alt=" " width="798" height="254"&gt;&lt;/a&gt;&lt;br&gt;
These values are program defaults and have &lt;strong&gt;not&lt;/strong&gt; been certified as return-optimal parameters. Cost parameters in particular must be interpreted according to the run mode. The research layer deducts estimated cost from reference-price returns. In PAPER, buys use the Ask and sells use the Bid, so bid-ask spread is already reflected; the configured cost parameter is then charged additionally as a fee estimate. Cost calibration should avoid counting the same cost component twice.&lt;/p&gt;

&lt;p&gt;When observing the strategy, the status panel can be read in this order:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Market data and data gates&lt;/strong&gt;: Are both market-data connections updating continuously, and are enough tradable symbols available?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Research samples and maturity&lt;/strong&gt;: Is the system merely warmed up on data, or has it already accumulated valid forward samples?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Configured weights and effective target weights&lt;/strong&gt;: Which factors are actually participating in this round?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Targets and positions&lt;/strong&gt;: Are deviations caused by the execution window, minimum order notional, exchange limits, or fills that are still awaiting confirmation?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Order intents and position-confirmation locks&lt;/strong&gt;: Are UNKNOWN or WAIT_POSITION states persisting, and are the related reconciliation queries still progressing?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The PAPER ledger separates realized PnL, unrealized PnL, funding, and estimated fees. Funding is posted against the historical position that existed at settlement time; late-arriving funding records are not simply applied to the current position.&lt;/p&gt;

&lt;p&gt;LIVE currently displays performance mainly as the difference between account equity and baseline account equity. It does not yet fully exclude deposits, withdrawals, or the effect of other strategies, and it does not fully separate actual realized PnL, unrealized PnL, and funding. Items that are not separately accounted for are shown as -; they must not be interpreted as zero.&lt;/p&gt;

&lt;h2&gt;
  
  
  13. What Has Been Validated So Far?
&lt;/h2&gt;

&lt;p&gt;As of the build used in this article, the project has completed base logic checks, 23 order-regression checks, and 34 dedicated audit tests. The dedicated tests include 36 accelerated decision cycles and 500 randomized weight-constraint checks.&lt;/p&gt;

&lt;p&gt;It is important to state what these numbers do and do not mean. The 36 cycles use synthetic data and a controlled clock to validate sampling, maturity, accounting, and recovery workflows; they are not a 12-day historical return backtest. The randomized constraint checks validate budget caps; they do not validate the predictive power of the factors.&lt;/p&gt;

&lt;p&gt;Runtime retesting in the Binance simulated environment covers actual simulated matching, restart recovery, cancel/fill races, explicit order rejection, and position reconciliation. These results are enough to justify continuing to accumulate forward evidence, but they are not sufficient to report conclusions about annualized return, Sharpe ratio, or long-term win rate.&lt;/p&gt;

&lt;p&gt;The highest-priority next steps are to add point-in-time historical data and independent rolling out-of-sample validation, calibrate execution costs by symbol and market regime, add correlation-cluster position limits, and introduce an entry threshold requiring expected return to cover trading costs. These directions already exist in the research design, but they have not all been fully implemented in the current code.&lt;/p&gt;

&lt;p&gt;APFF has already encoded the lifecycle of a factor—from creation and performance recording, to receiving budget, participating in orders, and eventually leaving the portfolio—into a running program. The most valuable data from here will be the decision recorded at each point in time and the answer obtained eight hours later under the same rules: which signals remain effective, which work only in certain market regimes, and how much of their apparent edge survives actual execution.&lt;/p&gt;

</description>
      <category>apff</category>
      <category>crypto</category>
      <category>momentumtrading</category>
      <category>fmzquant</category>
    </item>
  </channel>
</rss>
