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.
Strategy Interface
Section titled “Strategy Interface”All trading strategies implement a common interface that allows the Trading Engine to manage them uniformly.
Execution Flow
Section titled “Execution Flow”The bot operates on a high-frequency event loop. When a market update or a reference price change is received:
- The Trading Engine gathers the current state into a Strategy Context.
- The context includes current market snapshots, existing positions, the latest reference prices, and fee models.
- Each enabled strategy’s logic is invoked via its tick handler.
- The strategy returns a list of trade intents (such as placing an order).
- These intents are validated by the Risk Manager before being sent for execution.
Latency Arbitrage (latency_arb)
Section titled “Latency Arbitrage (latency_arb)”Latency Arbitrage is the primary strategy of the bot. It identifies price discrepancies between high-frequency external exchanges (such as Binance) and Polymarket.
Concept
Section titled “Concept”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.
Probability Model
Section titled “Probability Model”The strategy uses a mathematical model inspired by Black-Scholes for pricing binary options (digital options).
- 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.
- 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.
- 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.
- 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.
Exit Logic
Section titled “Exit Logic”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 viaflattenOnCloseout. - Exit Cooldown: To prevent rapid-fire exit attempts due to orderbook jitter,
exitCooldownMsenforces a minimum delay between exit orders for the same position.
Configuration Parameters
Section titled “Configuration Parameters”- 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.
Exit Parameters (under exit)
Section titled “Exit Parameters (under exit)”- 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.
Limitations
Section titled “Limitations”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.
Model Uncertainty Buffer
Section titled “Model Uncertainty Buffer”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:
| Condition | Additional Buffer | Rationale |
|---|---|---|
| Base uncertainty | +2% always | Black-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).
Dip Arbitrage (dip_arb)
Section titled “Dip Arbitrage (dip_arb)”The Dip Arbitrage strategy is designed to capture mean-reversion opportunities within a single market.
Concept
Section titled “Concept”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.
Two-Leg Execution
Section titled “Two-Leg Execution”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.
Configuration Parameters
Section titled “Configuration Parameters”- 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 (threshold_farm)
Section titled “Threshold Farm (threshold_farm)”Threshold Farm is a mathematical strategy based on the principle of price convergence in prediction markets.
Concept
Section titled “Concept”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.
Configuration Parameters
Section titled “Configuration Parameters”- 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.
Always Buy (always_buy)
Section titled “Always Buy (always_buy)”The Always Buy strategy is a specialized tool used strictly for debugging and system verification.
Concept
Section titled “Concept”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.
Risk Management Integration
Section titled “Risk Management Integration”Every strategy operates under the supervision of the Risk Manager, which enforces safety limits at two levels:
Pre-Trade Validation (Preventive)
Section titled “Pre-Trade Validation (Preventive)”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
maxPositionSizeUSDCare rejected. - Exposure Limit Check: Orders that would cause total exposure across all positions to exceed
maxTotalExposureUSDCare rejected. - Daily Loss Limit Check: Orders are blocked if the session has reached its configured daily loss limit (
maxDailyLossUSDCormaxDailyLossPercent).
This ensures that trades violating limits are blocked before execution, not just detected after the fact.
Continuous Monitoring (Reactive)
Section titled “Continuous Monitoring (Reactive)”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.
Kill Switch
Section titled “Kill Switch”If any safety limit is breached, a “Kill Switch” is triggered, which:
- Blocks all new orders immediately
- Cancels all pending orders on the exchange
- Neutralizes all positions by selling held tokens
- Requires manual restart to resume trading