### JBookTrader Shell Script Example Source: https://context7.com/mkoistinen/jbooktrader/llms.txt A sample shell script to launch JBookTrader. It sets the maximum heap size and specifies the path to the JBookTrader JAR file. ```bash #!/bin/bash cd /path/to/jbooktrader java -Xmx512m -jar JBookTrader.jar . ``` -------------------------------- ### JBookTrader Application Constants and Startup in Java Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Access application constants like name, version, and copyright from the JBookTrader class. The application can be launched from the command line, and operating modes are managed via the Dispatcher. ```java import com.jbooktrader.platform.startup.JBookTrader; import com.jbooktrader.platform.model.Dispatcher; import com.jbooktrader.platform.model.Mode; // Application constants String appName = JBookTrader.APP_NAME; // "JBookTrader" String version = JBookTrader.VERSION; // "9.01" String releaseDate = JBookTrader.RELEASE_DATE; // "July 8, 2013" String license = JBookTrader.COPYRIGHT; // "Open Source, BSD license" // Launch from command line: // java -jar jbooktrader.jar /path/to/jbooktrader/home // Operating modes (set via Dispatcher) Dispatcher dispatcher = Dispatcher.getInstance(); // Mode.Trade - Live trading with real orders // Mode.ForwardTest - Paper trading with simulated fills // Mode.BackTest - Historical backtesting // Mode.Optimization - Parameter optimization // Mode.ForceClose - Emergency position close ``` -------------------------------- ### Implement Balance Indicators and Strategy Logic Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Use balance indicators to analyze order book pressure and integrate them into strategy execution methods. ```java import com.jbooktrader.indicator.balance.*; // Balance Velocity - rate of change in order book imbalance BalanceVelocity balVel = new BalanceVelocity(5, 50); // fast period, slow period double velocityValue = balVel.getValue(); // Balance EMA - smoothed order book balance BalanceEMA balEMA = new BalanceEMA(20); double balanceEMA = balEMA.getValue(); // Balance Acceleration BalanceAcceleration balAccel = new BalanceAcceleration(5, 20, 50); double acceleration = balAccel.getValue(); // Balance Volatility BalanceVolatility balVol = new BalanceVolatility(20); double volatility = balVol.getValue(); // Using balance indicators in strategy logic @Override public void onBookSnapshot() { double balanceVelocity = balanceVelocityInd.getValue(); double priceVelocity = priceVelocityInd.getValue(); // Combine order flow and price momentum double force = balanceVelocity - 16 * priceVelocity; if (force >= 92 && balanceVelocity > 0 && priceVelocity < 0) { goLong(); // Strong buying pressure with price pullback } else if (force <= 21) { goFlat(); // Exit condition } } ``` -------------------------------- ### Evaluate Strategy Performance with PerformanceManager Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Access comprehensive trade statistics, risk metrics, and performance ratios for strategy evaluation. ```java import com.jbooktrader.platform.performance.PerformanceManager; // Access performance metrics in strategy PerformanceManager pm = getPerformanceManager(); // Trade statistics int totalTrades = pm.getTrades(); double winRate = pm.getPercentProfitableTrades(); // Percentage double avgProfit = pm.getAverageProfitPerTrade(); // Risk metrics double maxDrawdown = pm.getMaxDrawdown(); double maxSingleLoss = pm.getMaxSingleLoss(); // Performance ratios double profitFactor = pm.getProfitFactor(); // Gross profit / Gross loss double performanceIndex = pm.getPerformanceIndex(); // Risk-adjusted return double kellyCriterion = pm.getKellyCriterion(); // Optimal bet sizing double cpi = pm.getCPI(); // Combined Performance Index // Portfolio metrics double netProfit = pm.getNetProfit(); double avgDuration = pm.getAveDuration(); // Minutes per trade double bias = pm.getBias(); // Long vs Short bias (%) // Trade-level data double lastTradeProfit = pm.getTradeProfit(); double lastCommission = pm.getTradeCommission(); boolean isCompletedTrade = pm.getIsCompletedTrade(); Commission commissionStructure = pm.getCommission(); ``` -------------------------------- ### Initialize Price Indicators Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Instantiate and retrieve values from built-in price-based technical indicators like EMA, RSI, and Bollinger Bands. ```java import com.jbooktrader.indicator.price.*; // Exponential Moving Average of price PriceEMA ema20 = new PriceEMA(20); double emaValue = ema20.getValue(); // Price Velocity (rate of change using fast/slow EMAs) PriceVelocity velocity = new PriceVelocity(5, 20); // fast period, slow period double velocityValue = velocity.getValue(); // Relative Strength Index PriceRSI rsi14 = new PriceRSI(14); double rsiValue = rsi14.getValue(); // Returns 0-100 // Bollinger Bands PriceBollinger bollinger = new PriceBollinger(20, 2); // period, multiple double stdDev = bollinger.getValue(); // Standard deviation double midpoint = bollinger.getMidpoint(); // SMA (middle band) double upper = bollinger.getUpperBand(); // Upper band double lower = bollinger.getLowerBand(); // Lower band double width = bollinger.getWidth(); // Band width // Price Acceleration PriceAcceleration accel = new PriceAcceleration(5, 20, 50); // 3 periods double acceleration = accel.getValue(); // Price Volatility PriceVolatility vol = new PriceVolatility(20); double volatility = vol.getValue(); ``` -------------------------------- ### Access Market Data and Snapshots Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Retrieve market history, current snapshots, and order depth information within a strategy. ```java import com.jbooktrader.platform.marketbook.MarketBook; import com.jbooktrader.platform.marketbook.MarketSnapshot; import com.jbooktrader.platform.marketdepth.MarketDepth; // Accessing market data in strategy @Override public void onBookSnapshot() { MarketBook marketBook = getMarketBook(); // Get current snapshot MarketSnapshot snapshot = marketBook.getSnapshot(); // Snapshot data long timestamp = snapshot.getTime(); // Time in milliseconds double price = snapshot.getPrice(); // Mid-price double balance = snapshot.getBalance(); // Order book imbalance (-1 to +1) int volume = snapshot.getVolume(); // Current volume // Check market state boolean isEmpty = marketBook.isEmpty(); boolean isOpen = marketBook.isExchangeOpen(); // Access market depth (order book) MarketDepth depth = marketBook.getMarketDepth(); // Detect gaps in data (for handling overnight sessions) MarketSnapshot nextSnapshot = /* from data feed */; boolean isGapping = marketBook.isGapping(nextSnapshot); // Gap > 1 hour } // MarketSnapshot creation (for backtesting/data recording) MarketSnapshot snapshot = new MarketSnapshot( System.currentTimeMillis(), // time 0.25, // balance (-1 to +1) 1250.50, // mid-price 1500 // volume ); ``` -------------------------------- ### Define Strategy Parameters in Java Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Use the addParam method within the setParams() method to define optimizable parameters for a trading strategy. Parameters include name, min, max, step, and default value. ```java import com.jbooktrader.platform.optimizer.StrategyParams; import com.jbooktrader.platform.optimizer.StrategyParam; // Parameters are defined in strategy's setParams() method @Override protected void setParams() { // addParam(name, min, max, step, defaultValue) addParam("Period", 10, 100, 5, 50); // Range: 10-100, step 5 addParam("Threshold", 50, 200, 10, 100); // Range: 50-200, step 10 addParam("Scale", 1, 20, 1, 10); // Range: 1-20, step 1 } ``` -------------------------------- ### Define Trading Schedules with TradingSchedule Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Defines active trading hours and optional exclusion periods for strategies. ```java import com.jbooktrader.platform.schedule.TradingSchedule; import com.jbooktrader.platform.model.JBookTraderException; // Basic trading schedule: 9:35 AM to 3:45 PM Eastern TradingSchedule schedule = new TradingSchedule("9:35", "15:45", "America/New_York"); // Trading schedule with lunch break exclusion TradingSchedule scheduleWithExclusion = new TradingSchedule("9:35", "15:45", "America/New_York"); scheduleWithExclusion.setExclusion("12:00", "13:00"); // Result: Trading 9:35-12:00, positions closed at 12:00, resume at 13:00, close at 15:45 // Check if current time is within trading hours long currentTime = System.currentTimeMillis(); boolean canTrade = schedule.contains(currentTime); // Get remaining time until trading session ends long remainingMillis = schedule.getRemainingTime(currentTime); // Get the schedule's timezone TimeZone tz = schedule.getTimeZone(); // Schedule string representation String scheduleText = schedule.toString(); // "9:35 to 15:45 (America/New_York)" ``` -------------------------------- ### Create Interactive Brokers Contracts with ContractFactory Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Provides convenience methods for generating stock, futures, forex, and index contracts for Interactive Brokers. ```java import com.ib.client.Contract; import com.jbooktrader.platform.util.contract.ContractFactory; // Create E-mini S&P 500 futures contract Contract esMini = ContractFactory.makeFutureContract("ES", "GLOBEX"); // Create futures contract with currency specification Contract goldFutures = ContractFactory.makeFutureContract("GC", "NYMEX", "USD"); // Create stock contract Contract appleStock = ContractFactory.makeStockContract("AAPL", "SMART", "USD"); // Create stock contract (simplified - exchange only) Contract googleStock = ContractFactory.makeStockContract("GOOG", "SMART"); // Create forex contract (EUR/USD) Contract eurusd = ContractFactory.makeCashContract("EUR", "USD"); // Create index contract Contract spxIndex = ContractFactory.makeIndexContract("SPX", "CBOE"); // Generic contract creation with all parameters Contract customContract = ContractFactory.makeContract( "CL", // symbol "FUT", // security type: STK, FUT, CASH, IND "NYMEX", // exchange "USD" // currency ); ``` -------------------------------- ### Complete E-mini S&P 500 Futures Trading Strategy Source: https://context7.com/mkoistinen/jbooktrader/llms.txt This strategy implements trading logic for E-mini S&P 500 futures. It uses BalanceVelocity and PriceEMA indicators to make trading decisions. Configure trading parameters and contract details in the constructor. ```Java package com.jbooktrader.strategy.base; import com.ib.client.*; import com.jbooktrader.indicator.balance.*; import com.jbooktrader.indicator.price.*; import com.jbooktrader.platform.commission.*; import com.jbooktrader.platform.indicator.*; import com.jbooktrader.platform.model.*; import com.jbooktrader.platform.optimizer.*; import com.jbooktrader.platform.schedule.*; import com.jbooktrader.platform.strategy.*; import com.jbooktrader.platform.util.contract.*; /** * Complete example: E-mini S&P 500 futures trading strategy */ public class MyTradingStrategy extends Strategy { // Technical indicators private Indicator balanceVelocityInd, priceEMAInd; // Strategy parameters private static final String FAST_PERIOD = "FastPeriod"; private static final String SLOW_PERIOD = "SlowPeriod"; private static final String ENTRY_THRESHOLD = "EntryThreshold"; private final int entryThreshold; public MyTradingStrategy(StrategyParams optimizationParams) throws JBookTraderException { super(optimizationParams); // Read parameter values entryThreshold = getParam(ENTRY_THRESHOLD); // Configure trading contract Contract contract = ContractFactory.makeFutureContract("ES", "GLOBEX"); // Define trading schedule (10:05 AM to 3:25 PM Eastern) TradingSchedule tradingSchedule = new TradingSchedule("10:05", "15:25", "America/New_York"); // Contract configuration int multiplier = 50; // E-mini S&P multiplier double bidAskSpread = 0.25; Commission commission = CommissionFactory.getBundledNorthAmericaFutureCommission(); setStrategy(contract, tradingSchedule, multiplier, commission, bidAskSpread); } @Override protected void setParams() { // Define parameter ranges for optimization: name, min, max, step, default addParam(FAST_PERIOD, 10, 100, 5, 50); addParam(SLOW_PERIOD, 100, 500, 10, 200); addParam(ENTRY_THRESHOLD, 50, 150, 5, 100); } @Override public void setIndicators() { // Initialize technical indicators balanceVelocityInd = addIndicator(new BalanceVelocity(getParam(FAST_PERIOD), getParam(SLOW_PERIOD))); priceEMAInd = addIndicator(new PriceEMA(getParam(SLOW_PERIOD))); } @Override public void onBookSnapshot() { // Called on each market book update - implement trading logic here double balanceVelocity = balanceVelocityInd.getValue(); double priceEMA = priceEMAInd.getValue(); double currentPrice = getMarketBook().getSnapshot().getPrice(); // Trading logic: go long when balance velocity exceeds threshold // and price is above EMA if (balanceVelocity > entryThreshold && currentPrice > priceEMA) { goLong(); } else if (balanceVelocity < -entryThreshold) { goFlat(); // Exit position } } } ``` -------------------------------- ### Calculate Trading Commissions Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Define custom commission structures or utilize pre-defined factory methods for common asset classes. ```java import com.jbooktrader.platform.commission.Commission; import com.jbooktrader.platform.commission.CommissionFactory; // Create custom commission structure // Parameters: rate per contract/share, minimum per order, max as % of trade Commission custom = new Commission(1.50, 1.50, 0.01); // $1.50/contract, $1.50 min, 1% max // Calculate commission for a trade int contracts = 5; double price = 1250.00; double commission = custom.getCommission(contracts, price); // Pre-defined commission structures for Interactive Brokers // North American futures (bundled): $2.01 per contract Commission futuresComm = CommissionFactory.getBundledNorthAmericaFutureCommission(); // US stocks (bundled): $0.005/share, $1 min, 0.5% max Commission stockComm = CommissionFactory.getBundledNorthAmericaStockCommission(); // Forex: $0.00002 per unit, $2.50 minimum Commission forexComm = CommissionFactory.getForexCommission(); ``` -------------------------------- ### Access Strategy Parameters in Java Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Retrieve parameter values using getParam() in the setIndicators() method to configure strategy indicators. Parameters can also be accessed and modified directly via the StrategyParams object. ```java // Access parameters in strategy @Override public void setIndicators() { int period = getParam("Period"); int threshold = getParam("Threshold"); int scale = getParam("Scale"); // Use parameters to configure indicators myIndicator = addIndicator(new PriceEMA(period)); } ``` ```java // Working with StrategyParams object directly StrategyParams params = getParams(); int paramCount = params.size(); // Iterate through parameters for (StrategyParam param : params.getAll()) { String name = param.getName(); int min = param.getMin(); int max = param.getMax(); int step = param.getStep(); int value = param.getValue(); // Modify for optimization param.setMin(20); param.setMax(80); param.setStep(10); param.setValue(50); } // Get specific parameter StrategyParam periodParam = params.get("Period"); StrategyParam firstParam = params.get(0); // By index ``` -------------------------------- ### Manage Trading Positions with PositionManager Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Use within a strategy to track current and target positions, execute trades, and access historical position data. ```java import com.jbooktrader.platform.position.PositionManager; // In strategy, use position manager for trade control @Override public void onBookSnapshot() { PositionManager pm = getPositionManager(); // Check current position int currentPos = pm.getCurrentPosition(); // Actual position int targetPos = pm.getTargetPosition(); // Desired position // Get fill prices double avgFill = pm.getAvgFillPrice(); double expectedFill = pm.getExpectedFillPrice(); // Trading decisions use goLong(), goShort(), goFlat() if (/* entry condition */) { goLong(); // Sets target to portfolio-determined size } else if (/* exit condition */) { goFlat(); // Sets target to 0 } // Force close position (used at end of trading day) closePosition(); } // Position history for analysis LinkedList history = pm.getPositionsHistory(); ``` -------------------------------- ### Implement Custom Indicators with Indicator Base Class Source: https://context7.com/mkoistinen/jbooktrader/llms.txt Defines the structure for technical indicators by extending the Indicator class and implementing calculation logic. ```java import com.jbooktrader.platform.indicator.Indicator; import com.jbooktrader.platform.marketbook.MarketBook; /** * Custom indicator example: Simple Moving Average of Price */ public class PriceSMA extends Indicator { private final int period; private final double[] prices; private int index; private double sum; private boolean isFull; public PriceSMA(int period) { super(period); // Pass parameters to generate unique key this.period = period; this.prices = new double[period]; } @Override public void calculate() { double price = marketBook.getSnapshot().getPrice(); if (isFull) { sum -= prices[index]; } prices[index] = price; sum += price; index = (index + 1) % period; if (index == 0) { isFull = true; } int count = isFull ? period : index; value = sum / count; // 'value' is the indicator output } @Override public void reset() { sum = 0; index = 0; isFull = false; java.util.Arrays.fill(prices, 0); } } // Using indicators in a strategy @Override public void setIndicators() { Indicator sma50 = addIndicator(new PriceSMA(50)); Indicator sma200 = addIndicator(new PriceSMA(200)); } @Override public void onBookSnapshot() { double shortMA = sma50.getValue(); double longMA = sma200.getValue(); if (shortMA > longMA) { goLong(); } else if (shortMA < longMA) { goShort(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.