Skip to content

Trading Strategies

The Hydra uses a pluggable strategy architecture. Each strategy is an independent logic unit that processes market data and reference prices to generate trade intents. These strategies are executed by the Trading Engine and are subject to global risk management constraints.

All trading strategies implement a common interface that allows the Trading Engine to manage them uniformly.

The bot operates on a high-frequency event loop. When a market update or a reference price change is received:

  1. The Trading Engine gathers the current state into a Strategy Context.
  2. The context includes current market snapshots, existing positions, the latest reference prices, and fee models.
  3. Each enabled strategy’s logic is invoked via its tick handler.
  4. The strategy returns a list of trade intents (such as placing an order).
  5. These intents are validated by the Risk Manager before being sent for execution.

Latency Arbitrage is the primary strategy of the bot. It identifies price discrepancies between high-frequency external exchanges (such as Binance) and Polymarket.

Polymarket binary options often lag behind the price movements of the underlying crypto assets on spot exchanges. The latency_arb strategy monitors these spot prices in real-time and calculates a “fair” theoretical probability for the Polymarket outcome. When the market price on Polymarket deviates significantly from this theoretical probability, the bot places a trade to capture the edge.

The strategy uses a mathematical model inspired by Black-Scholes for pricing binary options (digital options).

  1. Asset Mapping: The strategy identifies the underlying asset (BTC, ETH, etc.) and the strike price. For “Up or Down” markets, it uses the captured opening price as the dynamic strike.
  2. Volatility Calculation: It maintains a sliding window of reference price history to calculate annualized historical volatility. This volatility represents the market’s expected price fluctuation.
  3. Theoretical Probability: The fair value is calculated using the Normal Cumulative Distribution Function (CDF). It determines the probability that the spot price will be on the winning side of the strike at the time of expiry, given the current price, remaining time, and volatility.
  4. Edge Detection: The bot compares this theoretical probability against the current executable price (the ask price for buying tokens). A trade is triggered if the difference (the edge) exceeds a configured threshold. This ensures the edge accounts for the actual cost of entry.

The strategy includes comprehensive exit logic to manage risk and lock in profits as the edge decays or reverses. Exit logic is executed before entry logic on every tick.

  • Edge Reversal: If the edge moves significantly against an open position (e.g., you are long “YES” but the edge flips to -1% or lower), the bot will immediately exit the position. This is controlled by reverseEdgeThreshold.
  • Edge Decay: As the market price approaches the theoretical “fair” price, the edge shrinks. The bot will exit when the edge falls below minEdgeToHold.
  • Closeout Flattening: When a market enters its final minutes (controlled by closeoutBufferMs), the strategy can be configured to “flatten” (sell) all positions to avoid settlement risk. This is enabled via flattenOnCloseout.
  • Exit Cooldown: To prevent rapid-fire exit attempts due to orderbook jitter, exitCooldownMs enforces a minimum delay between exit orders for the same position.
  • edgeThreshold: The minimum required difference between theoretical and market probability to trigger a trade.
  • maxPositionSize: The maximum number of contracts allowed for a single market.
  • cooldownMs: The minimum time to wait between consecutive trades on the same market.
  • volatilityWindowMs: The lookback period for calculating historical volatility.
  • minVolatility: A safety floor for volatility; trading is paused if volatility falls below this level.
  • closeoutBufferMs: Time before expiry (in ms) to stop entering new trades and potentially flatten positions.
  • reverseEdgeThreshold: Exit when the edge reverses beyond this threshold (e.g., 0.01 for 1%).
  • minEdgeToHold: Exit when the net edge decays below this level (e.g., 0.005 for 0.5%).
  • flattenOnCloseout: If true, force flatten all positions when entering the closeout buffer.
  • exitCooldownMs: Cooldown (in ms) between exit attempts.

Historical vs Implied Volatility: The strategy uses historical volatility calculated from the lookback window of Binance spot prices. This differs from implied volatility used by options markets, which reflects the market’s forward-looking expectations. During sudden market regime changes (e.g., news events, black swan events), historical volatility may lag behind actual market conditions. Consider widening edge thresholds or reducing position sizes during high-uncertainty periods.

The Black-Scholes model has known limitations in certain scenarios. To account for this, the strategy includes a model uncertainty buffer that dynamically adjusts the edge threshold based on market conditions.

When modelUncertaintyEnabled: true (default), the effective edge threshold increases in scenarios where the model is less reliable:

ConditionAdditional BufferRationale
Base uncertainty+2% alwaysBlack-Scholes is never perfect
Deep ITM/OTM strikes+0-5%Log-normal assumptions break down
Extreme probabilities (<5% or >95%)+0-5%Tail probabilities are least accurate
Long-dated options (>7 days)+1%More time = more uncertainty

Example: A market with 3% probability near a deep OTM strike might require 10%+ edge instead of the base 2%, ensuring the bot only trades when the edge significantly exceeds model uncertainty.

This makes the bot more conservative when the pricing model is least reliable, reducing risk in edge cases where Black-Scholes assumptions break down (extreme strikes, tail probabilities, trending markets).

The Dip Arbitrage strategy is designed to capture mean-reversion opportunities within a single market.

This strategy monitors a moving average of the market’s mid-price over a short sliding window. If the price “dips” significantly below the average, the bot buys the undervalued side, anticipating a return to the mean.

To manage the risk of a price move that does not revert, the strategy includes a timeout mechanism. If the bot buys one side of the market (Leg 1) and the price does not move as expected within a certain timeframe, it will automatically buy the opposing side (Leg 2) to neutralize the position and limit potential losses.

  • slidingWindowMs: The duration of the price history used for the moving average.
  • dipThreshold: The percentage deviation from the moving average required to trigger a trade.
  • leg2TimeoutSeconds: The maximum time to wait before executing the second leg of the arbitrage.

Threshold Farm is a mathematical strategy based on the principle of price convergence in prediction markets.

In a binary market, the sum of the “Yes” and “No” prices should ideally be close to 1.00 (ignoring fees and market friction). If the combined price of both sides falls significantly below 1.00, it represents an opportunity to buy both sides and guarantee a profit upon market settlement.

The strategy monitors the sum of the best ask prices for both outcomes. It calculates the expected profit after accounting for maker and taker fees. If the combined cost is below a target threshold and the profit rate is sufficient, the bot simultaneously buys both sides.

  • sumTarget: The maximum combined price of both outcomes allowed for a trade.
  • minProfitRate: The minimum expected profit margin after fees.
  • maxTimeRemainingMs: Limits the strategy to markets that are close to their expiry time.

The Always Buy strategy is a specialized tool used strictly for debugging and system verification.

This strategy ignores market conditions and reference prices, consistently generating buy intents for a specific side. It is used to test the end-to-end execution pipeline, including order placement, signing, and settlement, without requiring specific market movements.

Every strategy operates under the supervision of the Risk Manager, which enforces safety limits at two levels:

Before any order generated by a strategy reaches the exchange, the execution layer validates it against risk limits. All valuations use executable exit prices (bid for long, ask for short) rather than theoretical mid-prices to ensure conservative risk assessment:

  • Risk Mode Check: Orders are blocked if the kill switch has been triggered or trading is paused.
  • Position Limit Check: Orders that would cause a market position to exceed maxPositionSizeUSDC are rejected.
  • Exposure Limit Check: Orders that would cause total exposure across all positions to exceed maxTotalExposureUSDC are rejected.
  • Daily Loss Limit Check: Orders are blocked if the session has reached its configured daily loss limit (maxDailyLossUSDC or maxDailyLossPercent).

This ensures that trades violating limits are blocked before execution, not just detected after the fact.

The Risk Manager also performs periodic checks:

  • Staleness Protection: If reference price data or market updates are delayed beyond a certain threshold, the Risk Manager halts all strategy execution to prevent trading on outdated information.
  • Drawdown Monitoring: The system tracks peak equity and triggers the kill switch if drawdown exceeds the configured limit.
  • Position Reconciliation: The system periodically verifies that local position state matches the exchange.

If any safety limit is breached, a “Kill Switch” is triggered, which:

  1. Blocks all new orders immediately
  2. Cancels all pending orders on the exchange
  3. Neutralizes all positions by selling held tokens
  4. Requires manual restart to resume trading