Strategy Reference

Strategies are the decision-making engine behind every YorN agent. This reference covers the full strategy lifecycle, signal generation, position sizing, risk management, and how the AI generates custom strategies from your plain English descriptions.

Strategy Lifecycle

Every strategy follows a four-phase lifecycle on each evaluation cycle. The agent engine calls these hooks in order, and any phase can halt execution for the current cycle.

1

evaluate()

Analyze market data and generate a Signal with action and confidence.

2

position_size()

Calculate the number of contracts based on signal confidence and balance.

3

risk_check()

Validate the proposed trade against risk limits and portfolio constraints.

4

on_fill()

Callback after trade execution. Update internal state and log results.

Lifecycle Hooks

The following hooks are available for override in your Strategy subclass:

Lifecycle Hooks Python
class MyStrategy(Strategy): async def on_start(self): """Called once when the agent starts.""" self.trade_count = 0 async def evaluate(self, market_data): """Called on each market data update. Returns Signal or None.""" pass def position_size(self, signal, balance): """Returns int: number of contracts.""" return int(balance * 0.02) def risk_check(self, signal, portfolio): """Returns bool: True to approve trade.""" return True async def on_fill(self, fill): """Called after an order fills.""" self.trade_count += 1 async def on_stop(self): """Called when the agent stops.""" pass

Signal Generation

The evaluate method is the core of every strategy. It receives market data and returns a Signal object (or None to skip). Signals encode the trading decision with enough metadata for the executor and risk manager to process.

Signal Fields

Signal Constructor Python
Signal( action="buy", # "buy" | "sell" | "hold" side="yes", # "yes" | "no" confidence=0.85, # Float 0.0-1.0 reason="Momentum shift detected", limit_price=0.55, # Optional: limit order price ttl=300, # Signal expires after N seconds metadata={ # Optional: custom data "indicator": "rsi_oversold", "source_price": 0.42 } )

Confidence Thresholds

The agent engine applies a minimum confidence threshold before passing signals to the executor. By default, the threshold is 0.6 but can be configured per agent:

Confidence Configuration
# In agent config { "min_confidence": 0.7, # Only execute signals >= 0.7 "high_confidence": 0.9, # Doubles position size above this } # Confidence ranges: # 0.0 - 0.5 Signal ignored (below threshold) # 0.5 - 0.7 Low confidence, small position # 0.7 - 0.9 Standard confidence, normal position # 0.9 - 1.0 High confidence, boosted position

Position Sizing

The position_size method determines how many contracts to buy or sell for a given signal. Position sizing is critical for risk management and should scale with confidence and available balance.

Built-in Sizing Methods

Fixed Percentage Python
def position_size(self, signal, balance): # Risk 2% of balance per trade risk_amount = balance * 0.02 contracts = int(risk_amount / signal.limit_price) return min(contracts, self.config.max_position)
Kelly Criterion Python
def position_size(self, signal, balance): # Kelly: f* = (bp - q) / b # b = payout odds, p = win probability, q = 1-p p = signal.confidence q = 1.0 - p b = (1.0 / signal.limit_price) - 1.0 # implied odds kelly = (b * p - q) / b fraction = max(0, kelly * 0.5) # Half-Kelly return int(balance * fraction / signal.limit_price)
Scaled by Confidence Python
def position_size(self, signal, balance): # Scale position with confidence base = balance * 0.01 # 1% base allocation multiplier = signal.confidence ** 2 # Quadratic scaling return int(base * multiplier * 3)

Risk Rules

The risk_check method is the final gate before trade execution. It validates the proposed trade against portfolio-level constraints. If it returns False, the trade is rejected and logged.

Daily Loss Limit

Maximum total loss per day across all trades. Agent pauses when breached. Config: daily_loss_limit

Max Position Size

Maximum number of contracts in a single trade. Hard cap regardless of sizing method. Config: max_position

Trade Cooldown

Minimum time between consecutive trades to prevent overtrading. Config: cooldown (seconds)

Max Open Positions

Limits concurrent open positions to control exposure. Config: max_open_positions

Comprehensive Risk Check Python
def risk_check(self, signal, portfolio): # Check daily loss limit if portfolio.daily_pnl < -self.config.daily_loss_limit: return False # Check max open positions if len(portfolio.open_positions) >= 5: return False # Check per-market concentration market = signal.metadata.get("market_ticker") market_exposure = portfolio.exposure_by_market.get(market, 0) if market_exposure > portfolio.balance * 0.1: return False # Check cooldown if portfolio.seconds_since_last_trade < self.config.cooldown: return False return True

AI-Generated Strategies

YorN generates custom strategies from your plain English descriptions. Describe what you want your agent to do, and the AI produces a complete strategy with signal generation logic, position sizing, and risk rules tailored to your market category.

Category Example Description What the AI Generates
Sports "Trade NBA games where the home team has won 3+ in a row and the spread is at least 5 points" Signal logic with home court advantage filters, streak detection, and spread thresholds
Economics "Buy FOMC hold contracts when fed funds futures imply >80% probability of no change" Signal logic with futures data integration, probability thresholds, and entry timing windows
Weather "Trade temperature extreme markets when at least 3 ensemble models agree on the forecast" Signal logic with multi-model consensus checks, lead time filters, and confidence scoring
Politics "Trade election markets when polling momentum shifts by more than 2 points in a week" Signal logic with poll aggregation, momentum detection, and trend strength filters

The AI generates a complete strategy based on your description. Every parameter can be tuned after generation, and you can refine the strategy by providing additional instructions in plain English.

Creating an AI-Generated Strategy

Create Agent from Description POST /api/agents
{ "name": "NBA-Home-Edge-v1", "description": "Trade NBA games where the home team has a 3+ game win streak and the spread is at least 5 points. Use a 10-game recency window and require 70% confidence.", "mode": "paper", "max_position": 50 }

Custom Strategies

Pro and Enterprise tier users can write fully custom strategies. Custom strategies give you complete control over the evaluation logic while still benefiting from YorN's execution, risk management, and monitoring infrastructure.

Custom strategies still undergo AST safety validation. All the same restrictions apply: no imports, no I/O, no network calls, no system access.

Full Custom Strategy Example

Mean Reversion Strategy Python
class MeanReversionStrategy(Strategy): """Trades mean reversion when price deviates from its rolling average by more than 2 standard deviations.""" def __init__(self, config): super().__init__(config) self.name = "MeanReversion" self.window = config.get("window", 20) self.threshold = config.get("threshold", 2.0) self.prices = [] async def evaluate(self, market_data): price = market_data["yes_price"] self.prices.append(price) if len(self.prices) < self.window: return None # Calculate rolling mean and std dev window = self.prices[-self.window:] mean = sum(window) / len(window) variance = sum((x - mean)**2 for x in window) / len(window) std = variance ** 0.5 if std == 0: return None z_score = (price - mean) / std if z_score < -self.threshold: return Signal( action="buy", side="yes", confidence=min(0.95, abs(z_score) / 4), reason="Price below mean by " + str(round(z_score, 2)) + " std devs" ) elif z_score > self.threshold: return Signal( action="sell", side="yes", confidence=min(0.95, abs(z_score) / 4), reason="Price above mean by " + str(round(z_score, 2)) + " std devs" ) return None

Next Steps