FT Strategy Engine - Template

FuturesTeller · strategy · 1280 行 · 点赞 128 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
 
//@version=6
//@strategy_alert_message {{strategy.order.alert_message}} \nClosePrice = {{strategy.order.price}} \nOrderID = {{strategy.order.id}} \nAction = {{strategy.order.action}} \nMarket Position = {{strategy.market_position}} \nPrevious Market Position = {{strategy.prev_market_position}}
 
 
 
 
// =================================================================================================
//  FT STRATEGY ENGINE — TEMPLATE USER GUIDE (EDIT ONLY THE MARKED AREAS)
// =================================================================================================
//
// This script is a TEMPLATE.
// You do NOT need to touch the order execution engine, risk management engine, session logic,
// max daily trades logic, alerts, or visuals.
//
// ✅ What you MUST customize:
//   A) Add your CONDITION NAMES  (Long/Short logic selector)
//   B) Add your ENTRY LEVEL NAMES (Stop/Limit entry price selector)
//   C) Write the actual boolean conditions + price levels inside the switches.
//
// ❗ IMPORTANT RULES:
//   1) Every name you add to the input `options=[ ... ]` MUST exist as a case inside its `switch`.
//      If a name exists in options but not in switch => the script will NOT compile.
//   2) Condition switches must return TRUE/FALSE.
//   3) Entry-level switches must return a PRICE (float). Use `na` if not applicable.
//   4) If you choose MARKET orders, entry level is ignored automatically.
//   5) This strategy places orders only on bar close (barstate.isconfirmed), so your conditions should
//      be stable at bar close (avoid repainting sources).
//
// =================================================================================================
 
 
 
///////////////////////////////////////
// --------------------------------- //
// INPUTS (EDIT ZONE #1 — CONDITIONS NAMES + ENTRY LEVEL NAMES)
// --------------------------------- //
///////////////////////////////////////
 
// ---------------------------------
// TRADE CONDITIONS
// ---------------------------------
//
// HOW TO ADD YOUR CONDITIONS NAMES:
// 1) Replace the placeholder string "!!! INSERT HERE CONDITION NAMES !!!" inside the inputs "i_LongCondition" and "i_ShortCondition" with your names.
// 2) Keep quotes and comma separation.
// 3) Example:
//      options = ["None", "Breakout", "Reversal", "TrendFilter"]
//
// Then go below to section "LONG & SHORT SETUPS" and add one `switch` case for each name.
 
 
// ---------------------------------
// DIRECTIONS AND ORDERS — ENTRY LEVEL SELECTOR
// ---------------------------------
//
// HOW TO ADD YOUR ENTRY LEVEL NAMES:
// 1) Replace the placeholder string "!!! INSERT HERE ENTRY LEVELS NAMES !!!" with your names.
// 2) Example:
//      options = ["None", "PrevHigh", "PrevLow", "SessionOpen", "VWAP"]
//
// Then go below to section "LONG & SHORT ORDERS LEVELS" and add one switch case for each name.
//
// NOTE:
// - These levels are used ONLY when order type is "stop" or "limit".
// - For MARKET orders, the template automatically sets the level to `na` and ignores it.
// =================================================================================================
 
 
 
///////////////////////////////////////
// --------------------------------- //
// LONG & SHORT SETUPS (EDIT ZONE #2 — WRITE YOUR CONDITIONS)
// --------------------------------- //
///////////////////////////////////////
//
// This is where you DEFINE the actual trading logic.
// The user selects a condition name from the inputs above.
// Then this switch returns TRUE/FALSE for Long and Short.
//
// ✅ You can freely use:
// - indicators (ta.sma, ta.rsi, ta.atr, etc.)
// - price action (close > open, high > high[1], etc.)
// - your PatternLong / PatternShort filters (already computed)
// - session/time/weekday filters (already computed)
//
// IMPORTANT:
// - Keep logic readable and deterministic at bar close.
// - If you want extra filters, combine them with `and`.
//
// Example logic patterns:
//   Breakout: close > high[1]
//   Reversal: close > open and close[1] < open[1]
//   Trend filter: close > ta.sma(close, 200)
//
// LONG
// bool Long_cond = switch i_LongCondition
//     "None" => false
//   Replace the placeholder below with your real condition names.
//   Example:
//      "Breakout"     => close > high[1]
//      "TrendFilter"  => close > ta.sma(close, 200)
//      "Reversal"     => close > open and close[1] < open[1]
 
 
 
// SHORT
// bool Short_cond = switch i_ShortCondition
//    "None" => false
//      Example:
//      "Breakout"     => close < low[1]
//      "TrendFilter"  => close < ta.sma(close, 200)
//      "Reversal"     => close < open and close[1] > open[1]
// =================================================================================================
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// LONG & SHORT ORDERS LEVELS (EDIT ZONE #3 — WRITE YOUR ENTRY PRICES)
// --------------------------------- //
///////////////////////////////////////
//
// This is where you DEFINE the entry price used by STOP/LIMIT orders.
//
// RULES:
// - Return a FLOAT price (example: high, low, close, ta.vwap, etc.)
// - Return `na` when "None" is selected.
// - Long levels are used for Buy stop/limit.
// - Short levels are used for Sell stop/limit.
//
// Examples of entry levels:
//   "High"       => high
//   "Low"        => low
//   "PrevHigh"   => high[1]
//   "PrevLow"    => low[1]
//   "MidBar"     => (high + low) / 2
//
// LONG ORDERS (price for stop/limit long entries)
// float myle_switch = switch myle_level
//     "None" => na
//      Replace the placeholder below with your real level names.
//      Example:
//      "PrevHigh" => high[1]
//      "MidBar"   => (high + low) / 2
 
 
 
// SHORT ORDERS (price for stop/limit short entries)
// float myse_switch = switch myse_level
//      "None" => na
//      Example:
//      "PrevLow"  => low[1]
//      "MidBar"   => (high + low) / 2
 
 
// NOTE: The template automatically ignores myle/myse when order type is MARKET.
// So users can leave the level set to "None" when using market entries.
// =================================================================================================
 
 
 
strategy("FT Strategy Engine - Template", overlay=true, fill_orders_on_standard_ohlc = true, initial_capital = 100000, backtest_fill_limits_assumption = 1, currency = "USD", slippage = 1, commission_type = strategy.commission.cash_per_contract, commission_value = 2.5, margin_long = 5, margin_short = 5, behind_chart = false)
import FuturesTeller/FT_TV_template_lib/1 as FT
 
 
 
///////////////////////////////////////
// --------------------------------- //
// INPUTS
// --------------------------------- //
///////////////////////////////////////
 
//GENERAL INFORMATIVE
Informative = input.bool(false, "I have read the strategy disclosure", display = display.none, tooltip = "FuturesTeller assumes no responsibility for any future results obtained from using this model/strategy. By using this strategy, you acknowledge that you are solely responsible for all consequences resulting from its use.")
 
//SYSTEM'S NAME
System_name = input.string("Strategy N.1", "System's Name", tooltip = "Used in alerts to identify the system that executed the operation", group = "SYSTEM'S NAME")
 
//SESSION TIMES
i_SessionStartTime = input.int(1700, "Session Start Time", tooltip = "Session Start Time expressed as 'HHmm'. \nAlways reference selected time zones.", group = "SESSION TIMES", display = display.none)
i_SessionEndTime = input.int(1600, "Session End Time", tooltip = "Session End Time expressed as 'HHmm'. \nAlways reference selected time zones.", group = "SESSION TIMES", display = display.none)
i_tmzn = input.string("Exchange", "Timezone:", tooltip = "Choose your instrument Time Zone. \nSould match your chart's time zone. \nKeep default setting 'Exchange' to automatically use exchange's time zone.", display = display.none, group = "SESSION TIMES", options = ["Exchange","Africa/Bamako","Africa/Bangui","Africa/Banjul","Africa/Bissau","Africa/Blantyre","Africa/Brazzaville","Africa/Bujumbura","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/Conakry","Africa/Dakar","Africa/Dar_es_Salaam","Africa/Djibouti","Africa/Douala","Africa/El_Aaiun","Africa/Freetown","Africa/Gaborone","Africa/Harare","Africa/Johannesburg","Africa/Juba","Africa/Kampala","Africa/Khartoum","Africa/Kigali","Africa/Kinshasa","Africa/Lagos","Africa/Libreville","Africa/Lome","Africa/Luanda","Africa/Lubumbashi","Africa/Lusaka","Africa/Malabo","Africa/Maputo","Africa/Maseru","Africa/Mbabane","Africa/Mogadishu","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Niamey","Africa/Nouakchott","Africa/Ouagadougou","Africa/Porto-Novo","Africa/Sao_Tome","Africa/Timbuktu","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Anguilla","America/Antigua","America/Araguaina","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/ComodRivadavia","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Aruba","America/Asuncion","America/Atikokan","America/Atka","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Buenos_Aires","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Catamarca","America/Cayenne","America/Cayman","America/Chicago","America/Chihuahua","America/Coral_Harbour","America/Cordoba","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Ensenada","America/Fort_Nelson","America/Fort_Wayne","America/Fortaleza","America/Glace_Bay","America/Godthab","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Indianapolis","America/Inuvik","America/Iqaluit","America/Jamaica","America/Jujuy","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/Knox_IN","America/Kralendijk","America/La_Paz","America/Lima","America/Los_Angeles","America/Louisville","America/Lower_Princes","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Mendoza","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montreal","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Nuuk","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Acre","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Rosario","America/Santa_Isabel","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Shiprock","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Virgin","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/McMurdo","Antarctica/Palmer","Antarctica/Rothera","Antarctica/South_Pole","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Ashkhabad","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Calcutta","Asia/Chita","Asia/Choibalsan","Asia/Chongqing","Asia/Chungking","Asia/Colombo","Asia/Dacca","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Harbin","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Istanbul","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kashgar","Asia/Kathmandu","Asia/Katmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macao","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Rangoon","Asia/Riyadh","Asia/Saigon","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Tel_Aviv","Asia/Thimbu","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ujung_Pandang","Asia/Ulaanbaatar","Asia/Ulan_Bator","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faeroe","Atlantic/Faroe","Atlantic/Jan_Mayen","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/St_Helena","Atlantic/Stanley","Australia/ACT","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Canberra","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/LHI","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/North","Australia/NSW","Australia/Perth","Australia/Queensland","Australia/South","Australia/Sydney","Australia/Tasmania","Australia/Victoria","Australia/West","Australia/Yancowinna","Brazil/Acre","Brazil/DeNoronha","Brazil/East","Brazil/West","Canada/Atlantic","Canada/Central","Canada/Eastern","Canada/Mountain","Canada/Newfoundland","Canada/Pacific","Canada/Saskatchewan","Canada/Yukon","CET","Chile/Continental","Chile/EasterIsland","CST6CDT","Cuba","EET","Egypt","Eire","EST","EST5EDT","Etc/GMT","Etc/GMT+0","Etc/GMT+1","Etc/GMT+10","Etc/GMT+11","Etc/GMT+12","Etc/GMT+2","Etc/GMT+3","Etc/GMT+4","Etc/GMT+5","Etc/GMT+6","Etc/GMT+7","Etc/GMT+8","Etc/GMT+9","Etc/GMT-0","Etc/GMT-1","Etc/GMT-10","Etc/GMT-11","Etc/GMT-12","Etc/GMT-13","Etc/GMT-14","Etc/GMT-2","Etc/GMT-3","Etc/GMT-4","Etc/GMT-5","Etc/GMT-6","Etc/GMT-7","Etc/GMT-8","Etc/GMT-9","Etc/GMT0","Etc/Greenwich","Etc/UCT","Etc/Universal","Etc/UTC","Etc/Zulu","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belfast","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Kyiv","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Nicosia","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Tiraspol","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Factory","GB","GB-Eire","GMT","GMT+0","GMT-0","GMT0","Greenwich","Hongkong","HST","Iceland","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Iran","Israel","Jamaica","Japan","Kwajalein","Libya","MET","Mexico/BajaNorte","Mexico/BajaSur","Mexico/General","MST","MST7MDT","Navajo","NZ","NZ-CHAT","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Johnston","Pacific/Kanton","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Ponape","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Samoa","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Truk","Pacific/Wake","Pacific/Wallis","Pacific/Yap","Poland","Portugal","PRC","PST8PDT","ROC","ROK","Singapore","Turkey","UCT","Universal","US/Alaska","US/Aleutian","US/Arizona","US/Central","US/East-Indiana","US/Eastern","US/Hawaii","US/Indiana-Starke","US/Michigan","US/Mountain","US/Pacific","US/Samoa","UTC","W-SU","WET","Zulu"])
 
 
 
// --------------------------------------------------- //
// #1 -- SET YOUR CONDITION NAMES HERE (OPTIONS PARAMETER)
// --------------------------------------------------- //
 
//TRADE CONDITIONS
i_LongCondition = input.string("None", "Long Condition", options = ["None", "!!! INSERT HERE CONDITION NAMES !!!"], tooltip = "Choose which condition use for Long Trades. \n\nFollow instructions inside the script to understand how to add your conditions.", group = "TRADE CONDITIONS", display = display.none)
i_ShortCondition = input.string("None", "Short Condition", options = ["None", "!!! INSERT HERE CONDITION NAMES !!!"], tooltip = "Choose which condition use for Short Trades. \n\nFollow instructions inside the script to understand how to add your conditions.", group = "TRADE CONDITIONS", display = display.none)
 
// --------------------------------------------------- //
// END OF NEEDED COMPILATION
// --------------------------------------------------- //
 
 
 
 
 
//DIRECTIONS AND ORDERS
i_Trades_direction = input.string("Both Long and Short", "Strategy can Trade:", display = display.none, options = ["Both Long and Short", "Only Long, short is not used", "Only Long, short used to close long positions", "Only Short, long is not used", "Only Short, long used to close short positions"], group ="DIRECTIONS AND ORDERS", tooltip = "Choose whether the strategy can operate in both directions or only in one direction and whether to use the Long/Short entry conditions as closing conditions for trades in the opposite direction")
 
 
 
 
// --------------------------------------------------- //
// #2 -- SET YOUR ENTRY LEVELS NAMES HERE (OPTIONS PARAMETER)
// --------------------------------------------------- //
 
i_myle_level = input.string("None", "Buy Order Level", options = ["None", "!!! INSERT HERE ENTRY LEVELS NAMES !!!"], group = "DIRECTIONS AND ORDERS", display = display.none, tooltip = "Select the Long order levels. \n\nFollow instructions inside the script to understand how to add your entry levels.")
i_myse_level = input.string("None", "Sell Order Level", options = ["None", "!!! INSERT HERE ENTRY LEVELS NAMES !!!"], group = "DIRECTIONS AND ORDERS", display = display.none, tooltip = "Select the Short order levels.  \n\nFollow instructions inside the script to understand how to add your entry levels.")
 
// --------------------------------------------------- //
// END OF NEEDED COMPILATION
// --------------------------------------------------- //
 
 
 
 
 
 
i_Long_Order_type = input.string("market", "Long Order Type", options = ["market", "stop", "limit"], group = "DIRECTIONS AND ORDERS", display = display.none, tooltip = "Select the type of orders the strategy will send for Long trades. \n\nIf you want to use Stop or Limit orders, you must select a value different than 'None' for Buy Order Level.")
i_Short_Order_type = input.string("market", "Short Order Type", options = ["market", "stop", "limit"], group = "DIRECTIONS AND ORDERS", display = display.none, tooltip = "Select the type of orders the strategy will send for Short trades. \n\nIf you want to use Stop or Limit orders, you must select a value different than 'None' for Sell Order Level.")
i_ignore_entry_condition = input.bool(false, "Ignore entry conditions for closing orders", group = "DIRECTIONS AND ORDERS", display = display.none, tooltip = "If the strategy uses Long/Short conditions to only close trades made in the opposite direction, by enabling/disabling this option you can decide whether or not to send the close orders ignoring the conditions for entry orders. \n\n(operational window, pause, weekday filters, max number of daily trades)")
 
//POSITION SIZING
i_posSize_mode = input.string("Fixed Shares/Contracts", "Position Size Calculation:", options = ["Fixed Shares/Contracts", "Fixed Capital", "Strategy Net Profit"], group = "POSITION SIZING", display = display.none, tooltip = "'Fixed Shares/Contracts' = position size is calculated using the fixed amount of shares or contracts specified in the 'Fixed Amount to Trade' input. \n\n'Fixed Capital' =  position size is calculated using the fixed capital value set in 'Fixed Amount to Trade'. \n\n'Strategy Net Profit' = position size is calculated using the strategy net profit. \n\nIf an option different than 'Fixed Shares/Contracts' is selected, then the position size will be equal to the rounded value of: \n\n ((capital * leverage) / close) \n\nwhere: \n'capital' = capital set in 'Fixed Amount to Trade' \n'leverage' = the amount set in 'Leverage' input \n'close' = the instrument's close.")
i_NContracts = input.int(1, "Fixed Amount to Trade:", minval = 1, step=1, group = "POSITION SIZING", display = display.none, tooltip = "Amount of shares/contracts to trade or fixed capital allocated to this strategy for sizing.\n\nUsed only if 'Position Size Calculation' is not set to 'Strategy Equity'.")
i_leverage = input.float(1.0, "Leverage:", step=0.1, minval=0.01, group = "POSITION SIZING", display = display.none, tooltip = "Multiplier applied to the capital used for sizing.\n\nExample: leverage = 2 means the script sizes positions as if it had 2x the capital.\nFor CFDs, leverage depends on broker margin requirements and may differ from TradingView backtest settings.")
i_minQty = input.int(1, "Minimum Quantity:", minval=0, group = "POSITION SIZING", display = display.none, tooltip = "Minimum order quantity (shares/contracts) the strategy is allowed to place.\n\nIf the computed quantity is below this value, it will be raised to this minimum.\n\nSet to 0 to allow 'no trade' when capital is insufficient.")
 
//STRATEGY MONEY MANAGEMENT
i_SL_mode = input.string("points", "Stop Loss:", options = ["points", "percentage", "ATR"], group = "STRATEGY MONEY MANAGEMENT", inline = "Stop Loss", display = display.none)
i_SL = input.float(0.000000, "", minval = 0, tooltip = "Points = distance of SL from entry level as absolute value. \n\nPercentage = distance of SL from entry level as percentage of candle's close price. \n\nATR = distance of SL from entry level as multiple of 50 periods Average True Range. \n\nSet to 0 to disable.", group = "STRATEGY MONEY MANAGEMENT", inline = "Stop Loss", display = display.none)
i_TP_mode = input.string("points", "Take Profit:", options = ["points", "percentage", "ATR"], group = "STRATEGY MONEY MANAGEMENT", inline = "Take Profit", display = display.none)
i_TP = input.float(0.000000, "",  minval = 0, tooltip = "Points = distance of TP from entry level as absolute value. \n\nPercentage = distance of TP from entry level as percentage of candle's close price. \n\nATR = distance of TP from entry level as multiple of 50 periods Average True Range. \n\nSet to 0 to disable.", group = "STRATEGY MONEY MANAGEMENT", inline = "Take Profit", display = display.none)
i_BE_mode = input.string("points", "Break Even:",  options = ["points", "percentage", "ATR"], group = "STRATEGY MONEY MANAGEMENT", inline = "Break Even", display = display.none)
i_BE = input.float(0.000000, "", minval = 0, tooltip =  "Points = distance of BE from entry level as absolute value. \n\nPercentage = distance of BE from entry level as percentage of candle's close price. \n\nATR = distance of BE from entry level as multiple of 50 periods Average True Range. \n\nSet to 0 to disable. \n\nOnce the trade reaches the selected distance, stop loss will be moved to entry level.", group = "STRATEGY MONEY MANAGEMENT", inline = "Break Even", display = display.none)
i_Trail_sma_exit = input.bool(false, "", group = "STRATEGY MONEY MANAGEMENT", inline = "Trail SMA", display = display.none)
i_Trail_sma_exit_length = input.int(30, "SMA Trail Stop length: ", minval = 1, maxval = 1000, group = "STRATEGY MONEY MANAGEMENT", inline = "Trail SMA", tooltip = "SMA Trail Stop length = Set the Simple Moving Average length to use. \nTrades will be closed when in profit and retrace under (for longs) or over (for shorts) the Simple Moving Average. \n\nCheck the box to enable the Simple Moving Average trailing stop.", display = display.none)
i_Trail_sma_exit_plot = input.bool(false, "Plot SMA Trailed stop", tooltip = "Enable to show the SMA used as Trailing Stop", group = "STRATEGY MONEY MANAGEMENT", display = display.none)
 
//STRATEGY PARAMETERS
i_TimeStart = input.int(0, "Trades are permitted from:", tooltip = "Time of the day from when strategy can open trades. \nExpressed as 'HHmm' \nAlways reference selected time zone. \nIf >= 2400 then strategy can operate from Midnight", group = "STRATEGY PARAMETERS", display = display.none)
i_TimeEnd = input.int(2359, "Trades are permitted until:", tooltip = "Time of the day until which the strategy can open trades. \nExpressed as 'HHmm' \nAlways reference selected time zone. \nIf >= 2400 then strategy can operate till 23:59:59", group = "STRATEGY PARAMETERS", display = display.none)
i_PauseStart = input.int(1200, "Pause Start Time:", tooltip = "Time of the day from when strategy can NOT open trades. \nExpressed as 'HHmm' \nAlways reference selected time zone. \nIf Pause Start Time > Pause End Time then Pause is disabled", group = "STRATEGY PARAMETERS", display = display.none)
i_PauseEnd = input.int(1100, "Pause End Time:", tooltip = "Time of the day until which the strategy can NOT open trades. \nExpressed as 'HHmm' \nAlways reference selected time zone. \nIf Pause Start Time > Pause End Time then Pause is disabled", group = "STRATEGY PARAMETERS", display = display.none)
i_MaxDailyTrades = input.int(100, "Max Trades per Day:", minval = 1, tooltip = "Max number of trades that strategy can open in a solar day. \nAlways reference selected time zone.", group = "STRATEGY PARAMETERS", display = display.none)
i_MaxNDaysDuration = input.int(0, "Max Trade Duration", display = display.none, tooltip = "Max number of daily sessions a trade can remain open. \nThe count increments at the start of each new session. When the count equals the set value, the operation is closed at the end of the daily session. \nIf = 0 then is disabled", group = "STRATEGY PARAMETERS")
i_CloseTime = input.int(2500, "Long-lasting trades Closing Time", tooltip = "Once an open trade reaches its Max Trade Duration, it will be closed at the time specified in this input. \nExpressed as 'HHmm'. \nAlways reference selected time zone. \nIf >= 2400 then is disabled", group = "STRATEGY PARAMETERS", display = display.none)
i_NotLongTradingDay_string = input.string("None", "Do not operate LONG On:", options = ["None", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],  tooltip = "Day of the Week during which long trades are not permitted.", group = "STRATEGY PARAMETERS", display = display.none)
i_NotShortTradingDay_string = input.string("None", "Do not operate SHORT On:", options = ["None", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],  tooltip = "Day of the Week during which short trades are not permitted.", group = "STRATEGY PARAMETERS", display = display.none)
 
//LONG & SHORT FILTERS
i_DailyMode = input.string("Session", title = "Calculate OHLC values on:", options = ["Session", "Day"], group = "LONG & SHORT FILTERS", tooltip = "Set to Session to calculate daily candle's OHLC on specified Session Start Time and Session End Time hours. \n\nSet to Day to calculate daily candle's OHLC between 00:00:00 and 23:59:59", display = display.none)
i_showPatternPanel = input.bool(false, "Show OHLC Pattern Panel", group = "LONG & SHORT FILTERS", display = display.none)
i_hlBars = input.bool(false, "Highlight pattern bars", group = "LONG & SHORT FILTERS", display = display.none)
i_uiScale = input.int(3, "Panel size (1..5)", minval=1, maxval=5, group = "LONG & SHORT FILTERS", display = display.none)
i_panelPos = input.string("Bottom Center", "Panel position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Rgiht", "Bottom Left", "Bottom Center", "Bottom Right"], group = "LONG & SHORT FILTERS", display = display.none)
i_ZPtnLS_Y_mu = input.int(34, "Operate IF:", minval = -35, maxval = 35, step = 1, group = "LONG & SHORT FILTERS", tooltip = "Choose the number corresponding to the OHLC pattern the system must met in order to open Long and Short trades. \n\n34/-34 = always true \n35/-35 = always false \n 0 = none specified (do not use) \n\nYou can find the pattern list inside 'FT_template_lib' library under 'ZPattern_MostUsed' function.", display = display.none)
i_ZPtnLS_N_mu = input.int(35, "Operate if NOT:", minval = -35, maxval = 35, step = 1, group = "LONG & SHORT FILTERS", tooltip = "Choose the number corresponding to the OHLC pattern the system must NOT met in order to open Long and Short trades. \n\n34/-34 = always true \n35/-35 = always false \n 0 = none specified (do not use) \n\nYou can find the pattern list inside 'FT_template_lib' library under 'ZPattern_MostUsed' function.", display = display.none)
i_ZPtnLY_1_mu = input.int(34, "Go Long IF (all):", minval = -35, maxval = 35, step = 1, inline = "Long Conditions Most Used", group = "LONG & SHORT FILTERS", display = display.none)
i_ZPtnLY_2_mu = input.int(34, "", minval = -35, maxval = 35, step = 1, inline = "Long Conditions Most Used", group = "LONG & SHORT FILTERS", display = display.none)
i_ZPtnLY_3_mu = input.int(34, "", minval = -35, maxval = 35, step = 1, inline = "Long Conditions Most Used", group = "LONG & SHORT FILTERS", tooltip = "Choose the number corresponding to the OHLC pattern the system must met in order to open Long trades. \n\n34/-34 = always true \n35/-35 = always false \n 0 = none specified (do not use) \n\nYou can find the pattern list inside 'FT_template_lib' library under 'ZPattern_MostUsed' function.", display = display.none)
i_ZPtnLN_mu = input.int(35, "Go Long if NOT:", minval = -35, maxval = 35, step = 1, group = "LONG & SHORT FILTERS", tooltip = "Choose the number corresponding to the OHLC pattern the system must NOT met in order to open Long trades. \n\n34/-34 = always true \n35/-35 = always false \n 0 = none specified (do not use) \n\nYou can find the pattern list inside 'FT_template_lib' library under 'ZPattern_MostUsed' function.", display = display.none)
i_ZPtnSY_1_mu = input.int(34, "Go Short IF (all):", minval = -35, maxval = 35, step = 1, inline = "Short Conditions Most Used", group = "LONG & SHORT FILTERS", display = display.none)
i_ZPtnSY_2_mu = input.int(34, "", minval = -35, maxval = 35, step = 1, inline = "Short Conditions Most Used", group = "LONG & SHORT FILTERS", display = display.none)
i_ZPtnSY_3_mu = input.int(34, "", minval = -35, maxval = 35, step = 1, inline = "Short Conditions Most Used", group = "LONG & SHORT FILTERS", tooltip = "Choose the number corresponding to the OHLC pattern the system must met in order to open Short trades. \n\n34/-34 = always true \n35/-35 = always false \n 0 = none specified (do not use) \n\nYou can find the pattern list inside 'FT_template_lib' library under 'ZPattern_MostUsed' function.", display = display.none)
i_ZPtnSN_mu = input.int(35, "Go Short if NOT:", minval = -35, maxval = 35, step = 1, group = "LONG & SHORT FILTERS", tooltip = "Choose the number corresponding to the OHLC pattern the system must NOT met in order to open Short trades. \n\n34/-34 = always true \n35/-35 = always false \n 0 = none specified (do not use) \n\nYou can find the pattern list inside 'FT_template_lib' library under 'ZPattern_MostUsed' function.", display = display.none)
 
// LONG - SHORT STATUS TABLE
showLongShortStatusTable = input.bool(false, "Show Long/Short status table", group = "LONG - SHORT TABLE", tooltip = "Shows the status table. Updates only on bar close.", display = display.none)
lsStatusTableSize = input.string("Normal", "Table size", options = ["Compact", "Normal", "Large"], group = "LONG - SHORT TABLE", display = display.none)
lsStatusTablePos = input.string("Top Right", "Table position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = "LONG - SHORT TABLE", display = display.none)
 
//PLOTTED TRADES
i_showLevels = input.bool(true, "Show Trades Levels", group = "PLOTTED TRADES", tooltip = "Choose whether to display stop and profit levels on the chart. To ensure the best manual trading experience, strategy's Recalculation Mode should be set on 'Every Tick', but its logic will always runs only at bar close, preventing any repainting of trades. Users can enable/disable every tick calculation from the strategy’s 'Properties' page.", display = display.none)
 
 
///////////////////////////////////////
// --------------------------------- //
// WEEKDAY SWITCH
// --------------------------------- //
///////////////////////////////////////
 
int i_NotLongTradingDay = switch i_NotLongTradingDay_string
    "None" => -1
    "Sunday" => 1
    "Monday" => 2
    "Tuesday" => 3
    "Wednesday" => 4
    "Thursday" => 5
    "Friday" => 6
    "Saturday" => 7
 
int i_NotShortTradingDay = switch i_NotShortTradingDay_string
    "None" => -1
    "Sunday" => 1
    "Monday" => 2
    "Tuesday" => 3
    "Wednesday" => 4
    "Thursday" => 5
    "Friday" => 6
    "Saturday" => 7
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// GENERAL VARIABLES
// --------------------------------- //
///////////////////////////////////////
 
var float BEprice = 0.00000
var float stopPrice = 0.00000
var float limitPrice = 0.00000
var float SL_tick = 0.00000
var float TP_tick = 0.00000
 
var bool PatternLong = false
var bool PatternShort = false
 
var string timeframe = ""
var string strategyname = ""
var string Long_Order_entry_exit = ""
var string Short_Order_entry_exit = ""
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// INPUTS VARIABLES
// --------------------------------- //
///////////////////////////////////////
 
//var string Engine = ""
var string tmzn = ""
var int SessionStartTime = na
var int SessionEndTime = na 
var string posSize_mode = "Fixed Shares/Contracts"
var int NContracts = 1
var int TimeStart = na
var int TimeEnd = na
var int PauseStart = na
var int PauseEnd = na 
var int MaxDailyTrades = 0
var int MaxNDaysDuration = 0
var int CloseTime = 2500
var int NotLongTradingDay = -1
var int NotShortTradingDay = -1
var string Trades_direction = ""
var string Long_Order_Type = ""
var string Short_Order_Type = ""
var bool ignore_entry_condition = false
var string myle_level = ""
var string myse_level = ""
var float myle = na
var float myse = na
var string SL_mode = ""
var float SL = 0.0000000
var string TP_mode = ""
var float TP = 0.0000000
var string BE_mode = ""
var float BE = 0.0000000
var int Trail_sma_exit_length = 1
var bool Trail_sma_exit = false
var string DailyMode = ""
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// STRATEGY-SPECIFIC INPUTS
// --------------------------------- //
///////////////////////////////////////
 
tmzn := i_tmzn
SessionStartTime := i_SessionStartTime
SessionEndTime := i_SessionEndTime
posSize_mode := i_posSize_mode
TimeStart := i_TimeStart
TimeEnd := i_TimeEnd
PauseStart := i_PauseStart
PauseEnd := i_PauseEnd
MaxDailyTrades := i_MaxDailyTrades
MaxNDaysDuration := i_MaxNDaysDuration
CloseTime := i_CloseTime
NotLongTradingDay := i_NotLongTradingDay
NotShortTradingDay := i_NotShortTradingDay
Trades_direction := i_Trades_direction
Long_Order_Type := i_Long_Order_type
Short_Order_Type := i_Short_Order_type
ignore_entry_condition := i_ignore_entry_condition
myle_level := i_myle_level
myse_level := i_myse_level
SL_mode := i_SL_mode
SL := i_SL
TP_mode := i_TP_mode
TP := i_TP
BE_mode := i_BE_mode
BE := i_BE
Trail_sma_exit_length := i_Trail_sma_exit_length
Trail_sma_exit := i_Trail_sma_exit
DailyMode := i_DailyMode
timeframe := timeframe.main_period + " minutes"
strategyname := System_name
 
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// TRADE ALERTS
// --------------------------------- //
///////////////////////////////////////
 
f_of_msg(string activity, string closedSide, string openedSide, string ordType, float level, string reason) =>
    "\n" + "FT Strategy = " + strategyname + "\n" +  "Activity = " + activity + "\n" + "Closed = " + closedSide + "\n" + "Opened = " + openedSide + "\n" + "OrderType = " + ordType + "\n" + "OrderLevel = " + (na(level) ? "N/A" : str.tostring(level, format.mintick)) + "\n" + "Reason = " + reason + "\n"
 
 
f_price(float p) => na(p) ? "N/A" : str.tostring(p, format.mintick)
 
 
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// GENERAL FUNCTIONS AND OHLC
// --------------------------------- //
///////////////////////////////////////
 
session = ""+str.tostring(SessionStartTime)+"-"+str.tostring(SessionEndTime)
 
timezone = tmzn == "Exchange" ? syminfo.timezone : tmzn
 
session_day = "0000-2359"
isLastBarOfDay = FT.isLastBarOfDay(timezone)
 
 
// POSITION SIZING
if i_posSize_mode != "Fixed Shares/Contracts"
    posSize_mode := i_posSize_mode
 
float cap = posSize_mode == "Fixed Capital" ? i_NContracts : posSize_mode == "Strategy Net Profit" ? strategy.netprofit : 0
NContracts := posSize_mode == "Fixed Shares/Contracts" ? i_NContracts : math.floor((cap * i_leverage) / close)
NContracts := math.max(NContracts, i_minQty)
 
 
//ORDERS
var bool goLong = false
var bool goShort = false
 
if (Trades_direction == "Both Long and Short" or Trades_direction == "Only Long, short is not used" or Trades_direction == "Only Long, short used to close long positions")
    Long_Order_entry_exit := "entry"
    goLong := true
else
    Long_Order_entry_exit := "exit"
 
if (Trades_direction == "Both Long and Short" or Trades_direction == "Only Short, long is not used" or Trades_direction == "Only Short, long used to close short positions")
    Short_Order_entry_exit := "entry"
    goShort := true
else
    Short_Order_entry_exit := "exit"
 
 
//OHLC ARRAYS
var bool StartofSession = false
var float[] ft_ohlc = array.new_float(24, na)
var float[] ptnCtx  = array.new_float(32, na)
 
 
//START OF SESSION
StartofSession := FT.Z_FT_OHLC(SessionStartTime, SessionEndTime, DailyMode, timezone, ft_ohlc)
 
 
//OHLC PRE-CALC
_ = FT.ZPattern_Mir_PreCalc(ft_ohlc, StartofSession, ptnCtx)
mp = FT.mp()
entriestoday = FT.entriestoday(timezone)
 
 
// WEEKDAYS FILTER
weekday = dayofweek(time, timezone)
weekday_prev_long = NotLongTradingDay - 1 == 0 ? (weekday == 6 and session.islastbar) : (weekday == NotLongTradingDay - 1 and isLastBarOfDay)
weekday_prev_short = NotShortTradingDay - 1 == 0 ? (weekday == 6 and session.islastbar) : (weekday == NotShortTradingDay - 1 and isLastBarOfDay)
weekday_long_cond = not (weekday_prev_long or weekday == NotLongTradingDay)
weekday_short_cond = not (weekday_prev_short or weekday == NotShortTradingDay) 
 
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// PATTERN CONDITIONS
// --------------------------------- //
///////////////////////////////////////
int[] pids = array.from(i_ZPtnLS_Y_mu, i_ZPtnLS_N_mu, i_ZPtnLY_1_mu, i_ZPtnLY_2_mu, i_ZPtnLY_3_mu, i_ZPtnLN_mu, i_ZPtnSY_1_mu, i_ZPtnSY_2_mu, i_ZPtnSY_3_mu, i_ZPtnSN_mu)
string[] ftypes = array.from("Long & Short YES", "Long & Short NO", "Long YES #1", "Long YES #2", "Long YES #3", "Long NO", "Short YES #1", "Short YES #2", "Short YES #3", "Short NO")
string[] titles = array.from("Operate IF:", "Operate if NOT:", "Go Long IF #1", "Go Long IF #2", "Go Long IF #3", "Go Long if NOT", "Go Short IF #1", "Go Short IF #2", "Go Short IF #3", "Go Short if NOT")
 
bool PtnLS_Y = FT.ZPattern_MostUsed(i_ZPtnLS_Y_mu, ft_ohlc, ptnCtx)
bool PtnLS_N = FT.ZPattern_MostUsed(i_ZPtnLS_N_mu, ft_ohlc, ptnCtx)
bool PtnLY_1 = FT.ZPattern_MostUsed(i_ZPtnLY_1_mu, ft_ohlc, ptnCtx)
bool PtnLY_2 = FT.ZPattern_MostUsed(i_ZPtnLY_2_mu, ft_ohlc, ptnCtx)
bool PtnLY_3 = FT.ZPattern_MostUsed(i_ZPtnLY_3_mu, ft_ohlc, ptnCtx)
bool PtnLN = FT.ZPattern_MostUsed(i_ZPtnLN_mu, ft_ohlc, ptnCtx)
bool PtnSY_1 = FT.ZPattern_MostUsed(i_ZPtnSY_1_mu, ft_ohlc, ptnCtx)
bool PtnSY_2 = FT.ZPattern_MostUsed(i_ZPtnSY_2_mu, ft_ohlc, ptnCtx)
bool PtnSY_3 = FT.ZPattern_MostUsed(i_ZPtnSY_3_mu, ft_ohlc, ptnCtx)
bool PtnSN = FT.ZPattern_MostUsed(i_ZPtnSN_mu, ft_ohlc, ptnCtx)
 
PatternLong := PtnLS_Y and (not PtnLS_N) and PtnLY_1 and PtnLY_2 and PtnLY_3 and (not PtnLN)
PatternShort := PtnLS_Y and (not PtnLS_N) and PtnSY_1 and PtnSY_2 and PtnSY_3 and (not PtnSN)
 
bool showPatternPanel = i_showPatternPanel
bool hlBars = i_hlBars
[barCol, bgCol] = FT.Z_OHLC_PatternsPanel(showPatternPanel, hlBars, i_uiScale, i_panelPos, SessionStartTime, SessionEndTime, DailyMode, timezone, pids, ftypes, titles, ft_ohlc, ptnCtx)
 
// Highlight
barcolor(i_hlBars ? barCol : na)
bgcolor(i_hlBars ? bgCol : na)
 
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// LONG & SHORT SETUPS
// --------------------------------- //
///////////////////////////////////////
 
 
// --------------------------------------------------- //
// #3 -- SET YOUR CONDITIONS HERE (COMPILE SWITCH)
// --------------------------------------------------- //
 
// LONG
bool Long_cond = switch i_LongCondition
    "None" => false
    "!!! INSERT HERE CONDITION NAMES !!!" => close > open and ta.atr(1) > ta.atr(50) // this is just an example. Insert here your conditions for Long trades
//  Example:
    // "Close crosses over 50 periods SMA" => ta.crossover(close, ta.sma(close, 50))
    // "Streak of higher highs" => high > high[1] and high[1] > high[2] and high[2] > high[3]
    // "It is 9:00 in the morning" => FT.closetimetoHHmm(0, timezone) == 900
 
 
// SHORT
bool Short_cond = switch i_ShortCondition
    "None" => false
    "!!! INSERT HERE CONDITION NAMES !!!" => close < open and ta.atr(1) > ta.atr(50) // this is just an example. Insert here your conditions for Short trades
//  Example:
    // "Close crosses under 50 periods SMA" => ta.crossunder(close, ta.sma(close, 50))
    // "Streak of lower lows" => low > low[1] and low[1] > low[2] and low[2] > low[3]
    // "It is 20:00 in the evening" => FT.closetimetoHHmm(0, timezone) == 2000
 
 
// --------------------------------------------------- //
// END OF NEEDED COMPILATION
// --------------------------------------------------- //
 
 
 
 
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// LONG & SHORT ORDERS LEVELS
// --------------------------------- //
///////////////////////////////////////
 
 
// --------------------------------------------------- //
// #4 -- SET YOUR CONDITIONS HERE (COMPILE SWITCH)
// --------------------------------------------------- //
 
 
// LONG ORDERS
float myle_switch = switch myle_level
    "None" => na
    "!!! INSERT HERE ENTRY LEVELS NAMES !!!" => high // this is just an example. Insert here your entry levels for Long trades
//  Example:
    // "Highest High of latest 10 bars" => ta.highest(high, 10)
    // "Previous high plus ATR" => high + ta.atr(10)
 
 
 
// SHORT ORDERS
float myse_switch = switch myse_level
    "None" => na
    "!!! INSERT HERE ENTRY LEVELS NAMES !!!" => low // this is just an example. Insert here your entry levels for Short trades
//  Example:
    // "Lowest Low of latest 10 bars" => ta.lowest(low, 10)
    // "Previous low minus ATR" => low - ta.atr(10)
 
 
 
// --------------------------------------------------- //
// END OF NEEDED COMPILATION
// --------------------------------------------------- //
 
 
 
 
 
 
if Long_Order_Type == "market" or Trades_direction == "Only Short, long is not used"
    myle := na
    myle_switch := na
 
if Short_Order_Type == "market" or Trades_direction == "Only Long, short is not used"
    myse := na
    myse_switch := na
 
 
 
// SAFE EXECUTION - ONLY WHEN BARS CLOSE
if barstate.isconfirmed
 
    ///////////////////////////////////////
    // --------------------------------- //
    // TRADES AND ORDERS
    // --------------------------------- //
    ///////////////////////////////////////
    myle := myle_switch
    myse := myse_switch
 
    if FT.FT(TimeStart, TimeEnd, timezone) and (FT.closetimetoHHmm(0, timezone) < PauseStart or FT.closetimetoHHmm(0, timezone) > PauseEnd) and entriestoday < MaxDailyTrades
 
        // --------------------------------- //
        // LONG ORDERS
        // --------------------------------- //
 
        if Long_cond and PatternLong and weekday_long_cond
            // MARKET ORDERS
            if Long_Order_Type == "market"
                if goLong
                    bool inv = strategy.position_size[1] < 0
                    string amsg = f_of_msg(inv ? "Inversion" : "Entry", inv ? "Short" : "None, new entry", "Long", "Market", close, "Signal")
                    strategy.entry("LE", strategy.long, NContracts, alert_message = amsg)
 
                else if (not goLong) and (Trades_direction == "Only Short, long used to close short positions") and (not ignore_entry_condition)
                    string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Market", close, "Cover")
                    strategy.close("SE", "Cover", NContracts, alert_message = amsg)
 
 
            // STOP ORDERS
            else if Long_Order_Type == "stop"
                if goLong
                    bool inv = strategy.position_size[1] < 0
                    string amsg = f_of_msg(inv ? "Inversion" : "Entry", inv ? "Short" : "None, new entry", "Long", "Stop", myle, "Signal")
                    strategy.entry("LE", strategy.long, NContracts, stop = myle, alert_message = amsg)
 
                else if mp < 0 and (not goLong) and (Trades_direction == "Only Short, long used to close short positions") and (not ignore_entry_condition)
                    string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Stop", myle, "Cover")
                    strategy.order("Cover", strategy.long, NContracts, stop = myle, alert_message = amsg)
 
 
            // LIMIT ORDERS
            else if Long_Order_Type == "limit"
                if goLong
                    bool inv = strategy.position_size[1] < 0
                    string amsg = f_of_msg(inv ? "Inversion" : "Entry", inv ? "Short" : "None, new entry", "Long", "Limit", myle, "Signal")
                    strategy.entry("LE", strategy.long, NContracts, limit = myle, alert_message = amsg)
 
                else if (not goLong) and (Trades_direction == "Only Short, long used to close short positions") and (not ignore_entry_condition)
                    string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Limit", myle, "Cover")
                    strategy.order("Cover", strategy.long, NContracts, limit = myle, alert_message = amsg)
 
 
        else
            strategy.cancel("LE")
            strategy.cancel("Cover")
 
            if Long_Order_Type != "market" and (goLong or (not goLong and not ignore_entry_condition))
                myle := 0
 
 
 
 
        // --------------------------------- //
        // SHORT ORDERS
        // --------------------------------- //
 
        if Short_cond and PatternShort and weekday_short_cond
            // MARKET ORDERS
            if Short_Order_Type == "market"
                if goShort
                    bool inv = strategy.position_size[1] > 0
                    string amsg = f_of_msg(inv ? "Inversion" : "Entry", inv ? "Long" : "None, new entry", "Short", "Market", close, "Signal")
                    strategy.entry("SE", strategy.short, NContracts, alert_message = amsg)
 
                else if (not goShort) and (Trades_direction == "Only Long, short used to close long positions") and (not ignore_entry_condition)
                    string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Market", close, "Cover")
                    strategy.close("LE", "Cover", NContracts, alert_message = amsg)
 
 
            // STOP ORDERS
            else if Short_Order_Type == "stop"
                if goShort
                    bool inv = strategy.position_size[1] > 0
                    string amsg = f_of_msg(inv ? "Inversion" : "Entry", inv ? "Long" : "None, new entry", "Short", "Stop", myse, "Signal")
                    strategy.entry("SE", strategy.short, NContracts, stop = myse, alert_message = amsg)
 
                else if mp > 0 and (not goShort) and (Trades_direction == "Only Long, short used to close long positions") and (not ignore_entry_condition)
                    string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Stop", myse, "Cover")
                    strategy.order("Cover", strategy.short, NContracts, stop = myse, alert_message = amsg)
 
 
            // LIMIT ORDERS
            else if Short_Order_Type == "limit"
                if goShort
                    bool inv = strategy.position_size[1] > 0
                    string amsg = f_of_msg(inv ? "Inversion" : "Entry", inv ? "Long" : "None, new entry", "Short", "Limit", myse, "Signal")
                    strategy.entry("SE", strategy.short, NContracts, limit = myse, alert_message = amsg)
 
                else if mp > 0 and (not goShort) and (Trades_direction == "Only Long, short used to close long positions") and (not ignore_entry_condition)
                    string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Limit", myse, "Cover")
                    strategy.order("Cover", strategy.short, NContracts, limit = myse, alert_message = amsg)
 
 
        else
            strategy.cancel("SE")
            strategy.cancel("Cover")
 
            if Short_Order_Type != "market" and (goShort or (not goShort and not ignore_entry_condition))
                myse := 0
 
 
    else
        strategy.cancel("LE")
        strategy.cancel("SE")
        strategy.cancel("Cover")
 
        if Long_Order_Type != "market" and (goLong or (not goLong and not ignore_entry_condition))
            myle := 0
 
        if Short_Order_Type != "market" and (goShort or (not goShort and not ignore_entry_condition))
            myse := 0
 
 
 
 
    // ------------------------------------- //
    // LONG EXITS IGNORING ENTRY CONDITIONS
    // ------------------------------------- //
 
    if (not goLong) and ignore_entry_condition and (Trades_direction == "Only Short, long used to close short positions") and Long_cond and PatternLong
 
        // MARKET ORDERS
        if Long_Order_Type == "market"
            string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Market", close, "Cover")
            strategy.close("SE", "Cover", NContracts, alert_message = amsg)
 
        // STOP ORDERS
        else if mp < 0 and Long_Order_Type == "stop"
            string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Stop", myle, "Cover")
            strategy.order("Cover", strategy.long, NContracts, stop = myle, alert_message = amsg)
 
        // LIMIT ORDERS
        else if mp < 0 and Long_Order_Type == "limit"
            string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Limit", myle, "Cover")
            strategy.order("Cover", strategy.long, NContracts, limit = myle, alert_message = amsg)
 
    else if (not goLong) and ignore_entry_condition
        strategy.cancel("Cover")
        if Long_Order_Type != "market"
            myle := 0
 
 
    // ------------------------------------- //
    // SHORT EXITS IGNORING ENTRY CONDITIONS
    // ------------------------------------- //
 
    if (not goShort) and ignore_entry_condition and (Trades_direction == "Only Long, short used to close long positions") and Short_cond and PatternShort
 
        // MARKET ORDERS
        if Short_Order_Type == "market"
            string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Market", close, "Cover")
            strategy.close("LE", "Cover", NContracts, alert_message = amsg)
 
        // STOP ORDERS
        else if mp > 0 and Short_Order_Type == "stop"
            string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Stop", myse, "Cover")
            strategy.order("Cover", strategy.short, NContracts, stop = myse, alert_message = amsg)
 
        // LIMIT ORDERS
        else if mp > 0 and Short_Order_Type == "limit"
            string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Limit", myse, "Cover")
            strategy.order("Cover", strategy.short, NContracts, limit = myse, alert_message = amsg)
 
    else if (not goShort) and ignore_entry_condition
        strategy.cancel("Cover")
        if Short_Order_Type != "market"
            myse := 0
 
 
 
 
 
    ///////////////////////////////////////
    // --------------------------------- //
    // SMA TRAIL STOP EXITS 
    // --------------------------------- //
    ///////////////////////////////////////
    SMA_val = ta.sma(close, Trail_sma_exit_length)
    if Trail_sma_exit == true and mp > 0 and open > strategy.position_avg_price and (close[1] >= SMA_val[1] and close < SMA_val)
        string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Market", close, "SMA Cover")
        strategy.close("LE", "SMA Cover", NContracts, alert_message = amsg)
 
    if Trail_sma_exit == true and mp < 0 and open < strategy.position_avg_price and (close[1] < SMA_val[1] and close > SMA_val)
        string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Market", close, "SMA Cover")        
        strategy.close("SE", "SMA Cover", NContracts, alert_message = amsg)
 
 
 
 
 
    ///////////////////////////////////////
    // --------------------------------- //
    // MAX DAYS IN TRADE LIMIT
    // --------------------------------- //
    ///////////////////////////////////////
 
    if FT.Z_MaxTradeDuration(SessionStartTime, timezone, MaxNDaysDuration)
        if FT.closetimetoHHmm(0, timezone) == SessionEndTime            
            string amsg_long = f_of_msg("Exit", "Long", "None, closed trade", "Market", close, "Max Days Limit")
            strategy.close("LE", "MaxDaysLimit", immediately = true, alert_message = amsg_long)
 
            string amsg_short = f_of_msg("Exit", "Short", "None, closed trade", "Market", close, "Max Days Limit")  
            strategy.close("SE", "MaxDaysLimit", immediately = true, alert_message = amsg_short)
 
        if FT.closetimetoHHmm(0, timezone) == CloseTime
            if mp == 1
                string amsg = f_of_msg("Exit", "Long", "None, closed trade", "Market", close, "Max Days Limit")
                strategy.close("LE", "MaxDaysLimit", alert_message = amsg)
 
            if mp == -1    
                string amsg = f_of_msg("Exit", "Short", "None, closed trade", "Market", close, "Max Days Limit")            
                strategy.close("SE", "MaxDaysLimit", alert_message = amsg)
 
 
 
 
    ///////////////////////////////////////
    // --------------------------------- //
    // RISK MANAGEMENT
    // --------------------------------- //
    ///////////////////////////////////////
 
    var float ATRval_dynamic = 0
    var float ATR50 = 0
    ATRval_dynamic := FT.AvgTrueRange(50)
    preventry = strategy.opentrades.entry_price(strategy.opentrades - 1)
    wasjustopened = (preventry != preventry[1] and (strategy.opentrades.entry_price(strategy.opentrades - 1)) != 0) or (mp != 0 and mp != mp[1])
    if wasjustopened
        ATR50 := ATRval_dynamic
 
    if na(strategy.position_avg_price)
        SL := SL_mode == "points" ? SL : SL_mode == "percentage" ? close*0.01*SL : SL_mode == "ATR" ? ATR50*SL : 0
        TP := TP_mode == "points" ? TP : TP_mode == "percentage" ? close*0.01*TP : TP_mode == "ATR" ? ATR50*TP : 0
        BE := BE_mode == "points" ? BE : BE_mode == "percentage" ? close*0.01*BE : BE_mode == "ATR" ? ATR50*BE : 0
    else
        SL := SL_mode == "points" ? SL : SL_mode == "percentage" ? strategy.position_avg_price*0.01*SL : SL_mode == "ATR" ? ATR50*SL : 0
        TP := TP_mode == "points" ? TP : TP_mode == "percentage" ? strategy.position_avg_price*0.01*TP : TP_mode == "ATR" ? ATR50*TP : 0
        BE := BE_mode == "points" ? BE : BE_mode == "percentage" ? strategy.position_avg_price*0.01*BE : BE_mode == "ATR" ? ATR50*BE : 0
 
    if BE > 0
        if ((strategy.opentrades.max_runup(strategy.opentrades - 1)/NContracts)/syminfo.pointvalue) >= BE 
            BEprice := strategy.position_avg_price
 
        else
            BEprice := 0
    else
        BEprice := 0
 
 
    if mp != 0 and (BEprice != 0)
        stopPrice := BEprice
 
    else if mp > 0 and SL > 0
        stopPrice := strategy.position_avg_price - SL
 
    else if mp < 0 and SL > 0
        stopPrice := strategy.position_avg_price + SL
 
    else if mp == 0 or SL <= 0
        stopPrice := na
 
 
    if mp > 0 and TP > 0
        limitPrice := strategy.position_avg_price + TP
    else if mp < 0 and TP > 0
        limitPrice := strategy.position_avg_price - TP
    else if mp == 0 or TP <= 0
        limitPrice := na
 
 
    if SL > 0
        SL_tick := SL/syminfo.mintick
    else 
        SL_tick := na  
    if TP > 0
        TP_tick := TP/syminfo.mintick
    else 
        TP_tick := na
 
 
    string rmMsgLong  = "FT Strategy = " + strategyname + "\nActivity = Exit \nClosed = Long" + "\nStop Level = " + f_price(stopPrice) + "\nLimit Level = " + f_price(limitPrice) + "\nReason = Risk Management Level"
    string rmMsgShort = "FT Strategy = " + strategyname + "\nActivity = Exit \nClosed = Short" + "\nStop Level =" + f_price(stopPrice) + "\nLimit Level =" + f_price(limitPrice) + "\nReason = Risk Management Level"
 
    strategy.exit("LX", "LE", loss = SL_tick, profit = TP_tick, alert_message = rmMsgLong)
    strategy.exit("SX", "SE", loss = SL_tick, profit = TP_tick, alert_message = rmMsgShort)
 
    if mp > 0
        strategy.exit("LX", "LE", stop = stopPrice, limit = limitPrice, alert_message = rmMsgLong)
 
    if mp < 0
        strategy.exit("SX", "SE", stop = stopPrice, limit = limitPrice, alert_message = rmMsgShort)
 
 
var float ATR50_notclosed = 0
ATR50_notclosed := FT.AvgTrueRange(50)
 
// --- intrabar refresh branch: also pass alert_message here ---
if barstate.isconfirmed == false and FT.BarsSinceLastEntry() == 0
    
    SL := SL_mode == "points" ? SL : SL_mode == "percentage" ? strategy.position_avg_price*0.01*SL : SL_mode == "ATR" ? ATR50_notclosed*SL : 0
    TP := TP_mode == "points" ? TP : TP_mode == "percentage" ? strategy.position_avg_price*0.01*TP : TP_mode == "ATR" ? ATR50_notclosed*TP : 0
    
    if strategy.position_size > 0
        if SL > 0
            stopPrice := strategy.position_avg_price - SL
        else
            stopPrice := na
 
        if TP > 0
            limitPrice := strategy.position_avg_price + TP
        else
            limitPrice := na
 
        string rmMsgLong_i = "FT Strategy =" + strategyname + "\nActivity = Exit \nClosed = Long" + "\nStop Level = " + f_price(stopPrice) + "\nLimit Level = " + f_price(limitPrice) + "\nReason = Risk Management Level"
 
        strategy.exit("LX", "LE", stop = stopPrice, limit = limitPrice, alert_message = rmMsgLong_i)
 
    if strategy.position_size < 0
        if SL > 0
            stopPrice := strategy.position_avg_price + SL
        else
            stopPrice := na
 
        if TP > 0
            limitPrice := strategy.position_avg_price - TP
        else
            limitPrice := na
 
        string rmMsgShort_i = "FT Strategy =" + strategyname + "\nActivity = Exit \nClosed = Short" + "\nStop Level = " + f_price(stopPrice) + "\nLimit Level = " + f_price(limitPrice) + "\nReason = Risk Management"
 
        strategy.exit("SX", "SE", stop = stopPrice, limit = limitPrice, alert_message = rmMsgShort_i)
 
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// SMA TRAIL PLOT
// --------------------------------- //
///////////////////////////////////////
 
[smaLine, smaCol, smaRatio] = FT.Z_SmaTrailPlot(close, Trail_sma_exit_length, i_Trail_sma_exit_plot, mp)
if i_Trail_sma_exit_plot == false
    smaLine := na
 
plot(smaLine, title="SMA Trail Stop", color=smaCol, linewidth=2)
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// VISUAL TRADES & ORDERS
// --------------------------------- //
///////////////////////////////////////
float BEprice_level = 0
 
if mp != 0 and (BEprice != 0)
    BEprice_level := strategy.position_avg_price
else
    BEprice_level := na
 
[TP_lev, SL_lev, BE_lev, mp_plot, inPosPlot] = FT.VisualTrades(limitPrice, stopPrice, BEprice_level)
 
int mpCur  = mp_plot
int mpPrev = nz(mp_plot[1], 0)
 
bool invNow   = (mpCur != 0 and mpPrev != 0 and mpCur != mpPrev)
bool invLtoS  = invNow and (mpPrev > 0) and (mpCur < 0)   // long closed, short opened
bool invStoL  = invNow and (mpPrev < 0) and (mpCur > 0)   // short closed, long opened
 
float tpL = (mpCur > 0) ? TP_lev : (invLtoS ? TP_lev[1] : na)
float slL = (mpCur > 0) ? SL_lev : (invLtoS ? SL_lev[1] : na)
float beL = (mpCur > 0) ? BE_lev : (invLtoS ? BE_lev[1] : na)
 
float tpS = (mpCur < 0) ? TP_lev : (invStoL ? TP_lev[1] : na)
float slS = (mpCur < 0) ? SL_lev : (invStoL ? SL_lev[1] : na)
float beS = (mpCur < 0) ? BE_lev : (invStoL ? BE_lev[1] : na)
 
// LINES
pTP_L = plot(i_showLevels ? tpL : na, title="TP (Long)",      style=plot.style_linebr, linewidth=2, color=color.green)
pSL_L = plot(i_showLevels ? slL : na, title="SL (Long)",      style=plot.style_linebr, linewidth=2, color=color.red)
pBE_L = plot(i_showLevels ? beL : na, title="Entry/BE (Long)",style=plot.style_linebr, linewidth=1, color=color.blue)
 
pTP_S = plot(i_showLevels ? tpS : na, title="TP (Short)",      style=plot.style_linebr, linewidth=2, color=color.green)
pSL_S = plot(i_showLevels ? slS : na, title="SL (Short)",      style=plot.style_linebr, linewidth=2, color=color.red)
pBE_S = plot(i_showLevels ? beS : na, title="Entry/BE (Short)",style=plot.style_linebr, linewidth=1, color=color.blue)
 
// LINES FILLS 
var int fillTransp = 85
fill(pSL_L, pBE_L, color=color.new(color.red,   fillTransp))
fill(pTP_L, pBE_L, color=color.new(color.green, fillTransp))
fill(pSL_S, pBE_S, color=color.new(color.red,   fillTransp))
fill(pTP_S, pBE_S, color=color.new(color.green, fillTransp))
 
 
 
 
 
 
 
 
 
///////////////////////////////////////
// --------------------------------- //
// LONG - SHORT TABLE
// --------------------------------- //
///////////////////////////////////////
 
// LONG MODE - SHORT MODE
var string Long_Mode = ""
var string Short_Mode = ""
var bool Time_window = false
var bool Operational_Pause = false
var bool Max_n_of_entries = false
var bool Pattern_LS_Y = false
var bool Pattern_LS_N = false
var bool Pattern_L_Y = false
var bool Pattern_L_N = false
var bool Pattern_S_Y = false
var bool Pattern_S_N = false
var bool weekday_long_cond_table = false
var bool weekday_short_cond_table = false
var bool Long_cond_table = false
var bool Short_cond_table = false
 
 
 
if (Trades_direction == "Both Long and Short" or Trades_direction == "Only Long, short is not used" or Trades_direction == "Only Long, short used to close long positions")
    Long_Mode := "Enabled"
else if Trades_direction == "Only Short, long is not used"
    Long_Mode := "Disabled"
else if Trades_direction == "Only Short, long used to close short positions"
    Long_Mode := "Close Shorts"
 
 
if (Trades_direction == "Both Long and Short" or Trades_direction == "Only Short, long is not used" or Trades_direction == "Only Short, long used to close short positions")
    Short_Mode := "Enabled"
else if Trades_direction == "Only Long, short is not used"
    Short_Mode := "Disabled"
else if Trades_direction == "Only Long, short used to close long positions"
    Short_Mode := "Close Longs"
 
 
// TABLE VARIABLES
if barstate.isconfirmed
    Time_window := ignore_entry_condition ? true : FT.FT(TimeStart, TimeEnd, timezone)
    Operational_Pause := ignore_entry_condition ? true : (FT.closetimetoHHmm(0, timezone) < PauseStart or FT.closetimetoHHmm(0, timezone) > PauseEnd)
    Max_n_of_entries := ignore_entry_condition ? true : entriestoday < MaxDailyTrades
    weekday_long_cond_table := ignore_entry_condition ? true : weekday_long_cond
    weekday_short_cond_table := ignore_entry_condition ? true : weekday_short_cond
    Pattern_LS_Y := PtnLS_Y
    Pattern_LS_N := (not PtnLS_N)
    Pattern_L_Y := PtnLY_1 and PtnLY_2 and PtnLY_3
    Pattern_L_N := (not PtnLN)
    Pattern_S_Y := PtnSY_1 and PtnSY_2 and PtnSY_3
    Pattern_S_N := (not PtnSN)
    Long_cond_table := Long_cond
    Short_cond_table := Short_cond
 
 
 
 
// ===============================
// LONG/SHORT STATUS TABLE (UI)
// ===============================
 
const int LS_MAX_ROWS = 30
const int LS_KIND_HDR = 1
const int LS_KIND_ROW = 0
const int LS_KIND_SEP = 2
 
 
// Styling
const color LS_TXT        = color.white
const color LS_BG_INFO_L  = color.rgb(25, 25, 25)
const color LS_BG_INFO_V  = color.rgb(18, 18, 18)
const color LS_BG_NAME    = color.rgb(35, 35, 35) 
const color LS_BG_HDR     = color.rgb(12, 16, 75) 
const color LS_BG_SEP     = color.rgb(12, 12, 12)
const color LS_BG_OK      = color.rgb(0, 70, 0)
const color LS_BG_NO      = color.rgb(90, 0, 0) 
 
f_ls_dot(bool v) =>
    (v == true) ? "🟢" : "🔴"
 
f_ls_bg(bool v) =>
    (v == true) ? LS_BG_OK : LS_BG_NO
 
f_pt_txtSize(string s) =>
    switch s
        "Compact" => size.small
        "Large"   => size.large
        => size.normal
 
f_pt_pos(string p) =>
    switch p
        "Top Right"    => position.top_right
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
 
 
var int[]    ls_kind  = array.new_int()
var string[] ls_label = array.new_string()
var bool[]   ls_long  = array.new_bool()
var bool[]   ls_short = array.new_bool()
 
f_ls_add_hdr(string h) =>
    array.push(ls_kind,  LS_KIND_HDR)
    array.push(ls_label, h)
    array.push(ls_long,  false)
    array.push(ls_short, false)
 
f_ls_add_row(string name, bool l, bool s) =>
    array.push(ls_kind,  LS_KIND_ROW)
    array.push(ls_label, name)
    array.push(ls_long,  l)
    array.push(ls_short, s)
 
f_ls_add_sep() =>
    array.push(ls_kind,  LS_KIND_SEP)
    array.push(ls_label, "")
    array.push(ls_long,  false)
    array.push(ls_short, false)
 
 
f_ls_build_rows() =>
    array.clear(ls_kind)
    array.clear(ls_label)
    array.clear(ls_long)
    array.clear(ls_short)
 
    // --- GROUP 1 ---
    f_ls_add_hdr("Value")
    f_ls_add_row("Time Window:", Time_window, Time_window)
    f_ls_add_row("Operational Pause:", Operational_Pause, Operational_Pause)
    f_ls_add_row("Max # of Daily Trades:", Max_n_of_entries, Max_n_of_entries)
    f_ls_add_row("Weekday Filter:", weekday_long_cond_table, weekday_short_cond_table)
 
    // Optional separator row:
    // f_ls_add_sep()
 
    // --- GROUP 2 ---
    f_ls_add_hdr("Filters")
    f_ls_add_row("Both Directions YES:", Pattern_LS_Y, Pattern_LS_Y)
    f_ls_add_row("Both Directions NO:", Pattern_LS_N, Pattern_LS_N)
    f_ls_add_row("Single Direction YES:", Pattern_L_Y, Pattern_S_Y)
    f_ls_add_row("Single Direction NO:", Pattern_L_N, Pattern_S_N)
 
    // Optional separator row:
    // f_ls_add_sep()
 
    // --- GROUP 3 ---
    f_ls_add_hdr("Condition")
    f_ls_add_row("Entry Condition:", Long_cond_table, Short_cond_table)
 
 
 
var table ls_tbl = na
 
f_ls_draw() =>
 
    if not na(ls_tbl)
        table.clear(ls_tbl, 0, 0, 2, LS_MAX_ROWS - 1)
 
    if showLongShortStatusTable
        txtSz = f_pt_txtSize(lsStatusTableSize)
 
        // --- FIRST PART (3 rows, 2 columns) ---
        // Row 0
        table.cell(ls_tbl, 0, 0, "Strategy Name: ", text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_INFO_L, text_halign = text.align_left)
        table.cell(ls_tbl, 1, 0, System_name, text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_INFO_V, text_halign = text.align_right)
        table.merge_cells(ls_tbl, 1, 0, 2, 0)
 
        // Row 1
        table.cell(ls_tbl, 0, 1, "Long Mode: ",  text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_INFO_L, text_halign = text.align_left)
        table.cell(ls_tbl, 1, 1, Long_Mode,      text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_INFO_V, text_halign = text.align_right)
        table.merge_cells(ls_tbl, 1, 1, 2, 1)
 
        // Row 2
        table.cell(ls_tbl, 0, 2, "Short Mode: ", text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_INFO_L, text_halign = text.align_left)
        table.cell(ls_tbl, 1, 2, Short_Mode,     text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_INFO_V, text_halign = text.align_right)
        table.merge_cells(ls_tbl, 1, 2, 2, 2)
 
        // --- SECOND PART (dynamic rows, 3 columns) ---
        f_ls_build_rows()
 
        int r = 3
        int n = array.size(ls_kind)
 
        for i = 0 to n - 1
            if r >= LS_MAX_ROWS
                break
 
            int k = array.get(ls_kind, i)
 
            if k == LS_KIND_HDR
                string h = array.get(ls_label, i)
                table.cell(ls_tbl, 0, r, h,      text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_HDR, text_halign = text.align_left)
                table.cell(ls_tbl, 1, r, "      LONG      ", text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_HDR, text_halign = text.align_center)
                table.cell(ls_tbl, 2, r, "SHORT",text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_HDR, text_halign = text.align_center)
 
            else if k == LS_KIND_ROW
                string nm  = array.get(ls_label, i)
                bool okL   = array.get(ls_long,  i) == true
                bool okS   = array.get(ls_short, i) == true
 
                table.cell(ls_tbl, 0, r, nm,            text_size = txtSz, text_color = LS_TXT, bgcolor = LS_BG_NAME, text_halign = text.align_left)
                table.cell(ls_tbl, 1, r, f_ls_dot(okL), text_size = txtSz, text_color = LS_TXT, bgcolor = f_ls_bg(okL), text_halign = text.align_center)
                table.cell(ls_tbl, 2, r, f_ls_dot(okS), text_size = txtSz, text_color = LS_TXT, bgcolor = f_ls_bg(okS), text_halign = text.align_center)
 
            else
                table.cell(ls_tbl, 0, r, "", bgcolor = LS_BG_SEP)
                table.merge_cells(ls_tbl, 0, r, 2, r)
 
            r += 1
 
 
if barstate.islast
    if showLongShortStatusTable
        if na(ls_tbl)
            ls_tbl := table.new(f_pt_pos(lsStatusTablePos), 3, LS_MAX_ROWS, frame_width = 1, border_width = 1)
        f_ls_draw()
    else
        if not na(ls_tbl)
            table.delete(ls_tbl)
            ls_tbl := na

← 返回列表