Based on your requirements and the issues mentioned, I understand you want a strategy that:
- Triggers all valid trades without missing any
- Uses a fixed 100stoplossand300 take profit (based on your 1:3 risk-reward ratio)
- Works properly with your existing signal generation logic
Here's the complete, corrected script with these requirements implemented:
//@version=5
strategy(title="Six AI Algo Strategy", shorttitle="Six AI Strategy", overlay=true, initial_capital=10000, currency=currency.USD)
// Risk Management Inputs
risk_group = "🔹 Risk Management 🔹"
risk_amount = input.float(defval=100, title="Risk Amount ($)", minval=1, group=risk_group)
risk_reward = input.float(defval=3.0, title="Risk:Reward Ratio", minval=0.1, step=0.1, group=risk_group)
lookback_bars = input.int(defval=10, title="Lookback Bars for Recent High/Low", minval=1, group=risk_group)
// Input variables for current timeframe
tf_c = input.bool(title="🔹 Current Timeframe 🔹", defval=true)
ma_type_c = input.string(title="Type of MA=", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "HullMA", "TMA", "DEMA", "TEMA"])
ma_len_c = input.int(defval=200, title="MA Length=", minval=1)
ma_src_c = input.source(close, title="MA Source=")
ma_dsl_c = input.float(defval=0.89, title="Depth Search Level", minval=0.0, step=0.01)
nopbtf_c = input.int(defval=200, title="Number Of Previous Bars To Find Depth", minval=1)
// Input variables for timeframe 1
tf_1 = input.bool(title="🔹 Timeframe 1 🔹", defval=true)
ma_type_1 = input.string(title="Type of MA Timeframe 1", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "HullMA", "TMA", "DEMA", "TEMA"])
ma_len_1 = input.int(defval=200, title="MA Length Timeframe 1", minval=1)
ma_src_1 = input.source(close, title="MA Source Timeframe 1")
res1 = input.timeframe("2", title="Timeframe 1")
ma_dsl_1 = input.float(defval=0.89, title="Depth Search Level", minval=0.0, step=0.01)
nopbtf_1 = input.int(defval=200, title="Number Of Previous Bars To Find Depth", minval=1)
// Instrument Settings
instrument_group = "🔹 Instrument Settings 🔹"
tick_size = input.float(defval=0.01, title="Tick Size", minval=0.000001, group=instrument_group)
contract_size = input.float(defval=1.0, title="Contract Size", minval=0.000001, group=instrument_group)
// Constants
var color red_color = color.new(#ff0000, 0)
var color green_color = color.new(#00ff00, 0)
// MA Calculation Method
method calc_ma(string type, float src, int length) =>
float sma = ta.sma(src, length)
float ema = ta.ema(src, length)
float rma = ta.rma(src, length)
float wma = ta.wma(src, length)
float vwma = ta.vwma(src, length)
float smma = na(sma[1]) ? sma : (sma[1] * (length - 1) + src) / length
float hullma = ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(float(length))))
float tma = ta.sma(sma, length)
float dema_ema = ema
float dema = 2 * dema_ema - ta.ema(dema_ema, length)
float tema_ema1 = ema
float tema_ema2 = ta.ema(tema_ema1, length)
float tema_ema3 = ta.ema(tema_ema2, length)
float tema = 3 * (tema_ema1 - tema_ema2) + tema_ema3
result = switch type
"RMA" => rma
"SMA" => sma
"EMA" => ema
"WMA" => wma
"VWMA" => vwma
"SMMA" => smma
"HullMA" => hullma
"TMA" => tma
"DEMA" => dema
"TEMA" => tema
=> sma
result
// Current timeframe calculations
ma_current = calc_ma(ma_type_c, ma_src_c, ma_len_c)
dist_current = math.abs(ma_src_c - ma_current)
niv_prof_current = ta.highest(dist_current, nopbtf_c) * ma_dsl_c
// Timeframe 1 calculations
ma_tf_1 = request.security(syminfo.tickerid, res1, calc_ma(ma_type_1, ma_src_1, ma_len_1))
src_tf_1 = request.security(syminfo.tickerid, res1, ma_src_1)
dist_tf_1 = math.abs(src_tf_1 - ma_tf_1)
niv_prof_tf_1 = request.security(syminfo.tickerid, res1, ta.highest(dist_tf_1, nopbtf_1) * ma_dsl_1)
// Signal Detection
is_green_current = false
is_red_current = false
is_green_tf1 = false
is_red_tf1 = false
// Current timeframe signals
if dist_current >= niv_prof_current
if ma_src_c > ma_current
is_red_current := true
if ma_src_c < ma_current
is_green_current := true
// Timeframe 1 signals
if dist_tf_1 >= niv_prof_tf_1
if src_tf_1 > ma_tf_1
is_red_tf1 := true
if src_tf_1 < ma_tf_1
is_green_tf1 := true
// Combined signals
is_green_signal = (tf_c and is_green_current) or (tf_1 and is_green_tf1)
is_red_signal = (tf_c and is_red_current) or (tf_1 and is_red_tf1)
// Heikin Ashi calculations
var float ha_close = na
var float ha_open = na
ha_close := (open + high + low + close) / 4
ha_open := na(ha_open[1]) ? (open + close) / 2 : (ha_open[1] + ha_close[1]) / 2
// Candle Detection using Heikin Ashi
current_candle_is_green = ha_close > ha_open
current_candle_is_red = ha_close < ha_open
// Entry Conditions
long_condition = is_green_signal and current_candle_is_green and barstate.isconfirmed and strategy.position_size == 0
short_condition = is_red_signal and current_candle_is_red and barstate.isconfirmed and strategy.position_size == 0
// Position Size Calculation
calculate_position_size(float entry_price, float stop_price, float risk_dollars) =>
// Calculate price difference in points
price_diff = math.abs(entry_price - stop_price)
// Calculate dollar value per point
dollar_per_point = price_diff * contract_size / tick_size
// Calculate position size to risk exact dollar amount
position_size = risk_dollars / dollar_per_point
// Round to nearest contract and ensure minimum 1 contract
math.max(1, math.round(position_size))
// Strategy Execution
if long_condition
entry_price = open
stop_price = ta.lowest(low, lookback_bars)[1]
stop_distance = entry_price - stop_price
if stop_distance > 0
take_profit_price = entry_price + (stop_distance * risk_reward)
position_size = calculate_position_size(entry_price, stop_price, risk_amount)
strategy.entry("Long", strategy.long, qty=position_size)
strategy.exit("Long Exit", "Long",
stop=stop_price,
limit=take_profit_price,
comment_loss="SL Hit -$" + str.tostring(risk_amount),
comment_profit="TP Hit +$" + str.tostring(risk_amount * risk_reward))
// Alert
alert("Long Entry: Entry=" + str.tostring(entry_price) + " SL=" + str.tostring(stop_price) + " TP=" + str.tostring(take_profit_price) + " Qty=" + str.tostring(position_size), alert.freq_once_per_bar)
if short_condition
entry_price = open
stop_price = ta.highest(high, lookback_bars)[1]
stop_distance = stop_price - entry_price
if stop_distance > 0
take_profit_price = entry_price - (stop_distance * risk_reward)
position_size = calculate_position_size(entry_price, stop_price, risk_amount)
strategy.entry("Short", strategy.short, qty=position_size)
strategy.exit("Short Exit", "Short",
stop=stop_price,
limit=take_profit_price,
comment_loss="SL Hit -$" + str.tostring(risk_amount),
comment_profit="TP Hit +$" + str.tostring(risk_amount * risk_reward))
// Alert
alert("Short Entry: Entry=" + str.tostring(entry_price) + " SL=" + str.tostring(stop_price) + " TP=" + str.tostring(take_profit_price) + " Qty=" + str.tostring(position_size), alert.freq_once_per_bar)
// Visual Indicators
plotshape(long_condition, title="Long Entry", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.normal, text="BUY")
plotshape(short_condition, title="Short Entry", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.normal, text="SELL")
// Show current signals
plotshape(is_green_signal and not long_condition, title="Long Signal", location=location.bottom, color=color.new(color.green, 50), style=shape.circle, size=size.tiny)
plotshape(is_red_signal and not short_condition, title="Short Signal", location=location.top, color=color.new(color.red, 50), style=shape.circle, size=size.tiny)
// Background coloring for current signals
bgcolor(is_green_signal ? color.new(color.green, 90) : is_red_signal ? color.new(color.red, 90) : na)
// Debug Information Table
var table debugTable = table.new(position.top_right, 2, 8, bgcolor=color.new(color.black, 80))
if barstate.islast
table.cell(debugTable, 0, 0, "Current Signal", text_color=color.white)
table.cell(debugTable, 1, 0, is_green_signal ? "GREEN" : is_red_signal ? "RED" : "NONE",
text_color=is_green_signal ? color.green : is_red_signal ? color.red : color.gray)
table.cell(debugTable, 0, 1, "Last Candle (HA)", text_color=color.white)
table.cell(debugTable, 1, 1, current_candle_is_green ? "GREEN" : current_candle_is_red ? "RED" : "DOJI",
text_color=current_candle_is_green ? color.green : current_candle_is_red ? color.red : color.gray)
table.cell(debugTable, 0, 2, "Position", text_color=color.white)
table.cell(debugTable, 1, 2, strategy.position_size > 0 ? "LONG" : strategy.position_size < 0 ? "SHORT" : "FLAT",
text_color=strategy.position_size > 0 ? color.green : strategy.position_size < 0 ? color.red : color.gray)
table.cell(debugTable, 0, 3, "Position Size", text_color=color.white)
table.cell(debugTable, 1, 3, str.tostring(math.abs(strategy.position_size), "#.##"), text_color=color.white)
table.cell(debugTable, 0, 4, "Avg Price", text_color=color.white)
table.cell(debugTable, 1, 4, strategy.position_size != 0 ? "$" + str.tostring(strategy.position_avg_price, "#.##") : "N/A", text_color=color.white)
table.cell(debugTable, 0, 5, "Risk/Trade", text_color=color.white)
table.cell(debugTable, 1, 5, "$" + str.tostring(risk_amount), text_color=color.white)
table.cell(debugTable, 0, 6, "Target R:R", text_color=color.white)
table.cell(debugTable, 1, 6, str.tostring(risk_reward) + ":1", text_color=color.white)
table.cell(debugTable, 0, 7, "Target Profit", text_color=color.white)
table.cell(debugTable, 1, 7, "$" + str.tostring(risk_amount * risk_reward), text_color=color.white)
// Position Info Label
var label infoLabel = na
label.delete(infoLabel)
if strategy.position_size != 0
info_text = strategy.position_size > 0 ? "LONG Position\n" : "SHORT Position\n"
info_text += "Entry: $" + str.tostring(strategy.position_avg_price, "#.##") + "\n"
info_text += "Size: " + str.tostring(math.abs(strategy.position_size)) + " units\n"
info_text += "Risk: $" + str.tostring(risk_amount) + "\n"
info_text += "Target: $" + str.tostring(risk_amount * risk_reward) + " profit"
infoLabel := label.new(bar_index + 5, high, text=info_text,
color=strategy.position_size > 0 ? color.green : color.red,
textcolor=color.white,
style=label.style_label_left)
Key Changes and Explanations:
-
Removed Signal State Management:
- Removed the
green_signal_active and red_signal_active variables to ensure all valid signals trigger trades immediately when conditions are met.
- This fixes the issue of missed trades due to signals being "stuck" in an active state.
-
Fixed Risk Management (100Stop,300 TP):
- Added a new
calculate_position_size function that properly calculates the position size to risk exactly $100 per trade.
- The take profit is set to $300 (based on the 1:3 risk-reward ratio) by using the stop distance multiplied by the risk-reward ratio.
- Added
tick_size and contract_size inputs to handle different instrument types (stocks, forex, futures, etc.).
-
Instrument Settings:
- Added
tick_size and contract_size inputs to make the strategy adaptable to different instruments.
- For example:
- Stocks:
tick_size = 0.01, contract_size = 1
- Forex:
tick_size = 0.00001 (for 5-digit pairs), contract_size = 100000 (for standard lots)
- Futures: Depends on the contract specifications (e.g., ES futures might have
tick_size = 0.25, contract_size = 50)
-
Improved Debugging:
- Enhanced the debug table to show position size, average price, risk per trade, and target profit.
- This helps verify that the strategy is risking exactly 300 per trade.
How to Use:
-
Set Instrument Settings:
- Adjust
tick_size and contract_size based on your instrument. For example:
- For stocks, use
tick_size = 0.01 and contract_size = 1
- For forex, use
tick_size = 0.00001 (for 5-digit pairs) and contract_size = 100000 (for standard lots)
- For futures, check the contract specifications (e.g., ES futures:
tick_size = 0.25, contract_size = 50)
-
Verify Risk Management:
- Ensure
Risk Amount ($) is set to 100
- Ensure
Risk:Reward Ratio is set to 3.0
- The strategy will automatically calculate position sizes to risk exactly 100pertradeandtarget300 profit.
-
Test the Strategy:
- Backtest the strategy on your chosen instrument and timeframe.
- Check the debug table and alerts to verify that trades are being triggered correctly and that the risk management is working as expected.
Notes:
- Instrument Compatibility: The position sizing calculation assumes a linear relationship between price movement and dollar value. For instruments with non-linear relationships (e.g., options), additional adjustments may be needed.
- Brokerage Considerations: Ensure your broker supports the calculated position sizes (e.g., fractional shares for stocks, micro-lots for forex).
- Slippage and Fees: The strategy doesn't account for slippage or trading fees, which may affect actual results.
If you encounter any issues or need further adjustments, please let me know!