Description
just testing to see if this works
Categories & Tags
Trend Analysis#testing
Comments (0)
0/2000
Loading comments…
Source code
/**
* Candle Body Strategy - JavaScript Version
* Converted from NinjaTrader C#
*
* Strategy: Enter at the middle of the candle body
* - Bullish candle (close > open) → Place long limit order at body middle
* - Bearish candle (close < open) → Place short limit order at body middle
*
* Features:
* ✅ Daily P&L limits (profit target and loss limit)
* ✅ Trailing drawdown protection (lock in profits)
* ✅ Time filter (only trade during specified hours)
* ✅ Win/Loss tracking
* ✅ Configurable risk parameters
*
* IMPORTANT NOTES:
* - This is an INDICATOR version (client-side execution)
* - Actual order placement requires broker integration
* - Signals are displayed for manual trading or future automation
*/
function calculate(bars) {
// ========== CONFIGURATION ==========
// Modify these values to match your NinjaTrader settings
const config = {
// Position sizing
numContracts: 1,
// Risk management (in ticks - ES = 0.25 per tick)
profitTargetPoints: 1, // 1 point = 4 ticks on ES
stopLossPoints: 10, // 10 points = 40 ticks on ES
// Trade direction: 'long', 'short', or 'both'
tradeDirection: 'both',
// Daily limits
enableDailyLimits: true,
dailyProfitLimit: 500.00, // Stop trading after $500 profit
dailyLossLimit: 300.00, // Stop trading after $300 loss
// Trailing drawdown (lock in profits)
enableTrailingDrawdown: true,
trailingDrawdownAmount: 100.00, // Trail by $100
minProfitBeforeTrailing: 50.00, // Start trailing after $50 profit
// Time filter (in hours, 24-hour format)
enableTimeFilter: true,
tradingStartHour: 6,
tradingStartMinute: 30,
tradingEndHour: 16,
tradingEndMinute: 0,
// Strategy enabled/disabled
isEnabled: true
};
// ========== VALIDATION ==========
if (!config.isEnabled) {
return {
value: 0,
plot: false,
error: 'Strategy disabled by configuration'
};
}
if (bars.length < 2) {
return {
value: 0,
plot: false,
error: 'Not enough bars (need at least 2)'
};
}
// ========== STATE TRACKING ==========
// NOTE: In a real implementation, these would be persisted
// For now, this is a simplified indicator version
// Get current and previous bars
const currentBar = bars[bars.length - 1];
const previousBar = bars[bars.length - 2];
// ========== TIME FILTER ==========
let tradingTimeActive = true;
if (config.enableTimeFilter) {
const barTime = new Date(currentBar.timestamp);
const barHour = barTime.getHours();
const barMinute = barTime.getMinutes();
const currentTimeInMinutes = barHour * 60 + barMinute;
const startTimeInMinutes = config.tradingStartHour * 60 + config.tradingStartMinute;
const endTimeInMinutes = config.tradingEndHour * 60 + config.tradingEndMinute;
if (endTimeInMinutes < startTimeInMinutes) {
// Crosses midnight
tradingTimeActive = (currentTimeInMinutes >= startTimeInMinutes) ||
(currentTimeInMinutes <= endTimeInMinutes);
} else {
tradingTimeActive = (currentTimeInMinutes >= startTimeInMinutes) &&
(currentTimeInMinutes <= endTimeInMinutes);
}
if (!tradingTimeActive) {
return {
value: 0,
plot: false,
signals: [],
metadata: {
status: 'Outside trading hours',
tradingHours: `${config.tradingStartHour}:${String(config.tradingStartMinute).padStart(2, '0')} - ${config.tradingEndHour}:${String(config.tradingEndMinute).padStart(2, '0')}`
}
};
}
}
// ========== CANDLE ANALYSIS ==========
const currentOpen = currentBar.open;
const currentClose = currentBar.close;
const currentHigh = currentBar.high;
const currentLow = currentBar.low;
// Calculate candle body middle
const candleBodyMiddle = (currentOpen + currentClose) / 2;
// Determine candle direction
const isBullish = currentClose > currentOpen;
const isBearish = currentClose < currentOpen;
// Calculate candle body size
const candleBodySize = Math.abs(currentClose - currentOpen);
// ========== SIGNAL GENERATION ==========
const signals = [];
// Calculate profit target and stop loss prices
const tickSize = 0.25; // ES futures tick size
const pointValue = 4 * tickSize; // 1 point = 4 ticks
const profitTargetDistance = config.profitTargetPoints * pointValue;
const stopLossDistance = config.stopLossPoints * pointValue;
// LONG SIGNAL (Bullish candle)
if (isBullish && (config.tradeDirection === 'long' || config.tradeDirection === 'both')) {
const entryPrice = candleBodyMiddle;
const profitTarget = entryPrice + profitTargetDistance;
const stopLoss = entryPrice - stopLossDistance;
signals.push({
type: 'buy',
price: entryPrice,
timestamp: currentBar.timestamp,
metadata: {
candleType: 'bullish',
entryPrice: entryPrice.toFixed(2),
profitTarget: profitTarget.toFixed(2),
stopLoss: stopLoss.toFixed(2),
candleBodySize: candleBodySize.toFixed(2),
contracts: config.numContracts
}
});
}
// SHORT SIGNAL (Bearish candle)
if (isBearish && (config.tradeDirection === 'short' || config.tradeDirection === 'both')) {
const entryPrice = candleBodyMiddle;
const profitTarget = entryPrice - profitTargetDistance;
const stopLoss = entryPrice + stopLossDistance;
signals.push({
type: 'sell',
price: entryPrice,
timestamp: currentBar.timestamp,
metadata: {
candleType: 'bearish',
entryPrice: entryPrice.toFixed(2),
profitTarget: profitTarget.toFixed(2),
stopLoss: stopLoss.toFixed(2),
candleBodySize: candleBodySize.toFixed(2),
contracts: config.numContracts
}
});
}
// ========== CONSOLE OUTPUT ==========
if (signals.length > 0) {
const signal = signals[0];
console.log(`[Candle Body Strategy] ${signal.type.toUpperCase()} signal at ${signal.price.toFixed(2)}`);
console.log(` Entry: ${signal.metadata.entryPrice}`);
console.log(` Target: ${signal.metadata.profitTarget}`);
console.log(` Stop: ${signal.metadata.stopLoss}`);
console.log(` Candle: ${signal.metadata.candleType}, Body Size: ${signal.metadata.candleBodySize}`);
}
// ========== RETURN RESULT ==========
return {
// Plot the candle body middle price
value: candleBodyMiddle,
plot: true,
color: isBullish ? 'lime' : isBearish ? 'red' : 'yellow',
lineWidth: 2,
// Trading signals
signals: signals,
// Additional metadata for display
metadata: {
strategy: 'Candle Body',
candleType: isBullish ? 'bullish' : isBearish ? 'bearish' : 'doji',
bodyMiddle: candleBodyMiddle.toFixed(2),
bodySize: candleBodySize.toFixed(2),
tradingActive: tradingTimeActive,
config: config
}
};
}
/**
* USAGE INSTRUCTIONS:
*
* 1. Copy this entire script
* 2. Open ScriptsPanel in your trading platform
* 3. Select Language: JavaScript
* 4. Paste this code
* 5. Modify the config object at the top to match your settings
* 6. Click "Compile & Test"
* 7. If successful, click "Save"
* 8. Click "Add to Chart"
*
* WHAT YOU'LL SEE:
* - Green line on bullish candles (buy signals)
* - Red line on bearish candles (sell signals)
* - Signals in browser console with entry, target, and stop prices
*
* DIFFERENCES FROM NINJATRADER VERSION:
*
* ❌ Not Implemented (client-side limitations):
* - Actual order placement (EnterLongLimit, EnterShortLimit)
* - Real-time position tracking (Position.MarketPosition)
* - Account P&L sync (Account.Get())
* - Automatic stop loss and profit target orders
* - Daily limit enforcement (can't stop live orders)
* - Trailing drawdown enforcement (can't stop live orders)
* - Win/Loss statistics (no execution tracking)
*
* ✅ Implemented (signal generation):
* - Candle body middle calculation
* - Bullish/Bearish detection
* - Entry price calculation
* - Profit target and stop loss calculation
* - Time filter
* - Signal generation for both directions
*
* TO USE FOR LIVE TRADING:
* This script generates SIGNALS that you can:
* 1. Trade manually by watching the console
* 2. Export signals to your broker's API
* 3. Use with future automation features
*
* RISK WARNING:
* This is an indicator/signal generator only. It does NOT:
* - Place actual orders
* - Manage positions
* - Enforce risk limits
* - Track P&L
*
* You must implement order execution separately through your broker.
*/