The Algorithm class is the abstract base class for all trading algorithms in the Lambda Investing framework. It serves
as the central component that receives market data, sends orders, processes execution reports, and manages positions and
P&L. This class implements a comprehensive event-driven architecture for algorithmic trading.
MarketDataListener: Processes market data events (depth, trades, commands)ExecutionReportListener: Handles order execution updatesCandleListener: Processes candle/bar data updates
constructorForAbstract(): Base initialization of internal structuresinit(): Registers with market data and trading engine connectorssetParameters(): Configures algorithm parameters
start(): Activates the algorithm to begin processing events and tradingstop(): Deactivates the algorithm, cancels all ordersresetAlgorithm(): Resets internal state for a fresh start
algorithmState: Tracks algorithm state (NOT_INITIALIZED, INITIALIZING, INITIALIZED, STARTING, STARTED, STOPPING, STOPPED)checkOperationalTime(): Manages trading hours based on firstHourOperatingIncluded and lastHourOperatingIncluded
onDepthUpdate(Depth): Processes order book updatesonTradeUpdate(Trade): Processes market trade updatesonCommandUpdate(Command): Handles system commands (start, stop)onCandleUpdate(Candle): Processes time-based candle/bar data
- Maintains last depth and trade for each instrument
- Updates internal time service based on message timestamps
- Filters out stale or duplicate updates
- Notifies registered observers of market data events
createLimitOrderRequest(): Creates limit orderscreateMarketOrderRequest(): Creates market orderscreateCancel(): Creates cancel requestsgenerateClientOrderId(): Generates unique order IDs
sendOrderRequest(OrderRequest): Validates and sends orderscheckOrderRequest(OrderRequest): Validates order parameterssendQuoteRequest(QuoteRequest): Sends quotes for market making
updateAllActiveOrders(ExecutionReport): Updates internal order statecancelAll(Instrument): Cancels all active orders for an instrumentcancelAllVerb(Instrument, Verb): Cancels all buy or sell ordersclientOrderIdToCancelWhenActive: Queue for canceling orders when they become active
addPosition(ExecutionReport): Updates position on fillsgetPosition(Instrument): Gets current position for an instrumentgetAlgorithmPosition(Instrument): Gets algorithm-specific positiononPosition(Map<String, Double>): Updates positions from external sourcerequestUpdatePosition(boolean): Requests position update from broker
portfolioManager: Manages portfolio and P&L calculationsaddToPersist(ExecutionReport): Adds trades to P&L calculationgetLastPnlSnapshot(String): Gets latest P&L snapshotprintSummaryResults(): Outputs trading results
hedgeManager: Manages hedging operationssetHedgeManager(HedgeManager): Sets custom hedge manager
isBacktest: Flag for backtest modesaveBacktestOutputTrades: Controls saving trade outputsprintSummaryBacktest: Controls printing summaryonFinishedBacktest(): Handles backtest completionplotBacktestResults(): Plots backtest resultssaveBacktestTrades(): Saves backtest trades to file
timeService: Provides current time (real or simulated)getCurrentTime(),getCurrentTimestamp(): Gets current time
LOG_LEVEL: Controls logging verbositystatistics: Tracks general statisticslatencyStatistics: Tracks order latencyslippageStatistics: Tracks execution slippage
algorithmObservers: List of observersregister(AlgorithmObserver): Registers new observeralgorithmNotifier: Notifies observers of events
uiEnabled: Flag for UI activationstartUI(): Starts user interfacesetTheme(): Sets UI theme
To create a new algorithm:
- Extend the
Algorithmclass - Override abstract methods like
printAlgo() - Implement trading logic in market data handlers
- Use
sendOrderRequest()to place orders - Configure parameters via
setParameters()
- Thread safety is maintained through synchronization on critical operations
- Orders should be validated before sending
- Position and P&L are automatically tracked
- Market data events drive algorithm execution
- Time management differs between live trading and backtesting
Example implementations include:
- Market making algorithms
- Factor investing algorithms
- Reinforcement learning algorithms (
SingleInstrumentRLAlgorithm)