### Detect New Bar Formation in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Checks if a new bar has formed for a given symbol and timeframe, synchronizing with a specified daily start time. This function is crucial for executing bar-based trading strategies exactly once per bar. It relies on the MarketDataUtils library. ```mql5 #include MarketDataUtils m_utils; void OnTimer() { string symbol = "EURUSD"; ENUM_TIMEFRAMES timeframe = PERIOD_H1; string daily_start_time = "00:05"; // Daily bar sync time // Returns true only once when a new bar forms if (m_utils.is_new_bar(symbol, timeframe, daily_start_time)) { Print("New H1 bar formed - execute strategy logic"); // Your bar-based strategy code here // This ensures logic runs once per bar } } ``` -------------------------------- ### MQL5 Multi-Symbol EA with MyLibs Framework Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt A complete MQL5 Expert Advisor demonstrating integrated usage of the MyLibs framework for multi-symbol trading. It includes initialization of various order and indicator management classes, setting up indicator handles for multiple symbols, and defining trading logic within the OnTimer function. Dependencies include multiple MyLibs header files for order entry, exit, position adjustment, and indicator analysis. ```mql5 #include #include #include #include #include #include #include // Initialize classes EntryOrders entry_orders; ExitOrders exit_orders; AdjustPosition adjust_pos; AtrBands atr_bands; TrendlineAnalyser tl_tools; MarketDataUtils m_utils; ResourceManager resource_manager; // Trading parameters int magic_number = 1000; int runner_magic = 1001; string symbols[] = {"EURUSD", "GBPUSD", "USDJPY"}; int ma_handles[], rsi_handles[]; int OnInit() { ArrayResize(ma_handles, ArraySize(symbols)); ArrayResize(rsi_handles, ArraySize(symbols)); // Create and register indicator handles for each symbol for (int i = 0; i < ArraySize(symbols); i++) { ma_handles[i] = iMA(symbols[i], PERIOD_CURRENT, 100, 0, MODE_SMA, PRICE_CLOSE); rsi_handles[i] = iRSI(symbols[i], PERIOD_CURRENT, 14, PRICE_CLOSE); resource_manager.register_handle(ma_handles[i]); resource_manager.register_handle(rsi_handles[i]); } EventSetTimer(60); return INIT_SUCCEEDED; } void OnDeinit(const int reason) { EventKillTimer(); resource_manager.release_all_handles(); } void OnTimer() { for (int i = 0; i < ArraySize(symbols); i++) { string symbol = symbols[i]; // Apply breakeven logic every tick adjust_pos.set_breakeven_if_profit_target_hit(symbol, runner_magic); // Execute strategy logic only on new bars if (!m_utils.is_new_bar(symbol, PERIOD_CURRENT, "00:05")) continue; // Apply ATR trailing stop adjust_pos.trailing_stop_atr(symbol, runner_magic, PERIOD_CURRENT, 2.0, 1.5, 14, true); // Detect signals bool tl_cross_long, tl_cross_short; tl_tools.detect_cross(symbol, ma_handles[i], tl_cross_long, tl_cross_short, 1); double rsi = m_utils.get_buffer_value(rsi_handles[i], 1); bool rsi_oversold = (rsi < 30); bool rsi_overbought = (rsi > 70); bool entry_long = tl_cross_long && rsi_oversold; bool entry_short = tl_cross_short && rsi_overbought; bool exit_long = tl_cross_short; bool exit_short = tl_cross_long; // Manage exits exit_orders.close_buy_orders(symbol, exit_long, 0, PERIOD_CURRENT, magic_number); exit_orders.close_sell_orders(symbol, exit_short, 0, PERIOD_CURRENT, magic_number); exit_orders.close_buy_orders(symbol, exit_long, 0, PERIOD_CURRENT, runner_magic); exit_orders.close_sell_orders(symbol, exit_short, 0, PERIOD_CURRENT, runner_magic); // Manage entries (only if no open positions) if (entry_orders.count_open_positions(symbol, 0, magic_number) == 0) { // Open TP position entry_orders.open_buy_orders(symbol, entry_long, PERIOD_CURRENT, "SL_ATR_MULTIPLE", 1.5, "TP_ATR_MULTIPLE", 2.0, "LOT_MODE_PCT_RISK", 1.0, magic_number); // Open runner position entry_orders.open_runner_buy_order_with_virtual_tp(symbol, entry_long, PERIOD_CURRENT, "SL_ATR_MULTIPLE", 1.5, "TP_ATR_MULTIPLE", 2.0, "LOT_MODE_PCT_RISK", 0.5, runner_magic); } } } ``` -------------------------------- ### Opening Runner Trades with Virtual Take Profit Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Opens a runner position without a hard take-profit, storing the virtual TP in the order comment for later breakeven logic. ```APIDOC ## Opening Runner Trades with Virtual Take Profit ### Description Opens a runner position without a hard take-profit, storing the virtual TP in the order comment for later breakeven logic. ### Method `open_runner_buy_order_with_virtual_tp` ### Endpoint `MyLibs/Orders/EntryOrders.mqh` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (string) - Required - The trading symbol (e.g., "GBPUSD"). - **long_signal** (bool) - Required - Boolean indicating if a long entry signal is present. - **timeframe** (ENUM_TIMEFRAMES) - Required - Timeframe for calculations. - **sl_mode** (string) - Required - Stop loss calculation mode (e.g., "SL_ATR_MULTIPLE"). - **sl_var** (double) - Required - Value for stop loss calculation (e.g., ATR multiplier). - **tp_mode** (string) - Required - Virtual take profit calculation mode (e.g., "TP_ATR_MULTIPLE"). - **tp_var** (double) - Required - Value for virtual take profit calculation (e.g., ATR multiplier). - **lot_mode** (string) - Required - Lot sizing calculation mode (e.g., "LOT_MODE_PCT_RISK"). - **lot_var** (double) - Required - Value for lot sizing calculation (e.g., percentage risk). - **runner_magic** (int) - Required - Magic number for the runner order. ### Request Example ```mql5 #include EntryOrders entry_orders; // Inside an EA function (e.g., OnTimer) string symbol = "GBPUSD"; bool long_signal = true; int runner_magic = 1001; entry_orders.open_runner_buy_order_with_virtual_tp( symbol, long_signal, PERIOD_CURRENT, "SL_ATR_MULTIPLE", 1.5, // SL parameters "TP_ATR_MULTIPLE", 2.0, // Virtual TP parameters "LOT_MODE_PCT_RISK", 1.0, // Risk 1% on runner runner_magic ); ``` ### Response #### Success Response (200) - **result** (bool) - True if the order was opened successfully, false otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Opening Market Buy Orders Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt This function opens a market BUY position with configurable stop loss, take profit, and lot sizing based on risk parameters. ```APIDOC ## Opening Market Buy Orders ### Description Opens a market BUY position with calculated stop loss, take profit, and position sizing based on configurable risk parameters. ### Method `open_buy_orders` ### Endpoint `MyLibs/Orders/EntryOrders.mqh` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (string) - Required - The trading symbol (e.g., "EURUSD"). - **entry_signal** (bool) - Required - Boolean indicating if an entry signal is present. - **atr_period** (ENUM_TIMEFRAMES) - Required - Timeframe for ATR calculation. - **sl_mode** (string) - Required - Stop loss calculation mode (e.g., "SL_ATR_MULTIPLE"). - **sl_var** (double) - Required - Value for stop loss calculation (e.g., ATR multiplier). - **tp_mode** (string) - Required - Take profit calculation mode (e.g., "TP_ATR_MULTIPLE"). - **tp_var** (double) - Required - Value for take profit calculation (e.g., ATR multiplier). - **lot_mode** (string) - Required - Lot sizing calculation mode (e.g., "LOT_MODE_PCT_RISK"). - **lot_var** (double) - Required - Value for lot sizing calculation (e.g., percentage risk). - **magic_number** (long) - Required - Magic number for the order. ### Request Example ```mql5 #include EntryOrders entry_orders; // Inside an EA function (e.g., OnTick) string symbol = "EURUSD"; bool entry_signal = true; ENUM_TIMEFRAMES atr_period = PERIOD_CURRENT; string sl_mode = "SL_ATR_MULTIPLE"; double sl_var = 1.5; string tp_mode = "TP_ATR_MULTIPLE"; double tp_var = 2.0; string lot_mode = "LOT_MODE_PCT_RISK"; double lot_var = 2.0; long magic_number = 1000; entry_orders.open_buy_orders( symbol, entry_signal, atr_period, sl_mode, sl_var, tp_mode, tp_var, lot_mode, lot_var, magic_number ); ``` ### Response #### Success Response (200) - **result** (bool) - True if the order was opened successfully, false otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Open Market Buy Orders in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Opens a market BUY position with dynamic stop loss, take profit, and position sizing. It calculates these based on configurable risk parameters, such as ATR multiples and percentage risk per trade. This function is crucial for initiating trades according to a defined strategy. ```mql5 #include EntryOrders entry_orders; void OnTick() { string symbol = "EURUSD"; bool entry_signal = true; // Your entry logic here ENUM_TIMEFRAMES atr_period = PERIOD_CURRENT; string sl_mode = "SL_ATR_MULTIPLE"; double sl_var = 1.5; // 1.5x ATR for stop loss string tp_mode = "TP_ATR_MULTIPLE"; double tp_var = 2.0; // 2x ATR for take profit string lot_mode = "LOT_MODE_PCT_RISK"; double lot_var = 2.0; // Risk 2% per trade long magic_number = 1000; // Opens BUY position when entry_signal is true bool result = entry_orders.open_buy_orders( symbol, entry_signal, atr_period, sl_mode, sl_var, tp_mode, tp_var, lot_mode, lot_var, magic_number ); if (result) Print("Buy order opened successfully"); } ``` -------------------------------- ### Open Runner Trades with Virtual Take Profit in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Opens a runner BUY position without a hard take-profit level. Instead, it stores the virtual take-profit target within the order's comment field. This allows for flexible position management, enabling subsequent breakeven logic or trailing stop adjustments without pre-defined exit prices. ```mql5 #include EntryOrders entry_orders; void OnTimer() { string symbol = "GBPUSD"; bool long_signal = true; int runner_magic = 1001; // Opens runner with virtual TP stored in comment // No hard TP is set, allowing position to run entry_orders.open_runner_buy_order_with_virtual_tp( symbol, long_signal, PERIOD_CURRENT, "SL_ATR_MULTIPLE", 1.5, // SL parameters "TP_ATR_MULTIPLE", 2.0, // Virtual TP parameters "LOT_MODE_PCT_RISK", 1.0, // Risk 1% on runner runner_magic ); } ``` -------------------------------- ### MQL5: Custom Optimization Criteria for Backtesting Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Defines custom fitness functions for strategy optimization in the MT5 Strategy Tester. This allows users to go beyond default metrics by specifying criteria like win percentage or win/loss ratio, along with a minimum trade count. The function `calculate_custom_criteria` returns a double value representing the custom metric for the optimizer to maximize. ```mql5 #include CustomMax c_max; // Called by MT5 Strategy Tester during optimization double OnTester() { CUSTOM_MAX_TYPE criteria = CM_WIN_PERCENT; // or CM_WIN_LOSS_RATIO int min_trades = 30; // Require minimum 30 trades // Returns custom metric for optimizer to maximize // Win percent example: filters out results with <30 trades double custom_value = c_max.calculate_custom_criteria(criteria, min_trades); Print("Custom fitness value: ", custom_value); return custom_value; } void OnTick() { // Your strategy logic here } ``` -------------------------------- ### MQL5: Dynamic Lot Sizing Based on Drawdown Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Adjusts position sizing dynamically based on account equity and drawdown state. This function calculates a lot multiplier between 0.5 and 1.0, which is then applied to the base lot size. It depends on the DrawdownControl library and requires initial equity, min/max lot factors, and optional trailing buffer settings. ```mql5 #include DrawdownControl dd_control; void OnTick() { double starting_equity = 10000.0; double min_lot_factor = 0.5; // Scale down to 50% at max DD double max_lot_factor = 1.0; // Full size at starting equity bool use_dynamic = true; // Enable dynamic trailing double trail_percent = 20.0; // 20% trailing buffer // Returns multiplier between 0.5 and 1.0 based on equity double lot_multiplier = dd_control.lot_correction_factor( starting_equity, min_lot_factor, max_lot_factor, use_dynamic, trail_percent ); // Apply to your normal lot calculation double base_lots = 0.1; double adjusted_lots = base_lots * lot_multiplier; Print("Base lots: ", base_lots, " Adjusted: ", adjusted_lots); } ``` -------------------------------- ### Retrieve Indicator Buffer Values Safely in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Safely retrieves indicator buffer values using provided handles, with built-in error checking for invalid handles or data. It allows fetching values from the last closed bar or the current live bar. Requires the MarketDataUtils library. ```mql5 #include MarketDataUtils m_utils; void OnTick() { int rsi_handle = iRSI("EURUSD", PERIOD_CURRENT, 14, PRICE_CLOSE); // Get RSI value from last closed bar double rsi_value = m_utils.get_buffer_value(rsi_handle, 1); if (rsi_value != EMPTY_VALUE) { Print("RSI value: ", rsi_value); if (rsi_value > 70) Print("Overbought"); if (rsi_value < 30) Print("Oversold"); } // Get current (live) bar value double rsi_live = m_utils.get_latest_buffer_value(rsi_handle); } ``` -------------------------------- ### Implement Daily Drawdown Control in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Monitors and enforces daily and account-level drawdown limits, automatically halting trading if thresholds are breached. This is useful for complying with prop firm rules. It persists data and resets daily based on a configured time. Utilizes the DrawdownControl library. ```mql5 #include DrawdownControl dd_control; int OnInit() { string data_file = "dd_control_data.txt"; double max_account_dd_percent = 10.0; // 10% max account DD double max_daily_dd_percent = 5.0; // 5% max daily DD string reset_time = "00:00"; // Reset at midnight bool print_debug = true; dd_control.init_dd_control( data_file, max_account_dd_percent, max_daily_dd_percent, reset_time, print_debug ); return INIT_SUCCEEDED; } void OnTick() { // Check if daily drawdown limit reached // Automatically closes all positions if limit breached bool limit_reached = dd_control.determine_daily_dd_limit(); if (limit_reached) { Print("Daily drawdown limit reached - trading stopped"); return; // Skip all trading logic } // Continue with normal trading logic } ``` -------------------------------- ### Closing Positions with Exit Logic Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Closes BUY or SELL positions based on exit signals or after a specified number of bars. ```APIDOC ## Closing Positions with Exit Logic ### Description Closes BUY or SELL positions based on exit signals or after a specified number of bars. ### Method `close_buy_orders`, `close_sell_orders` ### Endpoint `MyLibs/Orders/ExitOrders.mqh` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (string) - Required - The trading symbol (e.g., "EURUSD"). - **exit_signal** (bool) - Required - Boolean indicating if an exit signal is present. - **close_after_bars** (int) - Required - Number of bars after which to close the position (0 to disable). - **timeframe** (ENUM_TIMEFRAMES) - Required - Timeframe for calculations. - **magic_number** (long) - Required - Magic number of the positions to close. ### Request Example ```mql5 #include ExitOrders exit_orders; // Inside an EA function (e.g., OnTick) string symbol = "EURUSD"; bool exit_signal = false; // Your exit logic int close_after_bars = 0; // Set to >0 for time-based exit ENUM_TIMEFRAMES timeframe = PERIOD_H1; long magic_number = 1000; // Close all buy positions for symbol if exit_signal is true exit_orders.close_buy_orders( symbol, exit_signal, close_after_bars, timeframe, magic_number ); // Close all sell positions exit_orders.close_sell_orders( symbol, exit_signal, close_after_bars, timeframe, magic_number ); ``` ### Response #### Success Response (200) - **result** (bool) - True if positions were closed successfully, false otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### ATR-Based Trailing Stop Adjustment in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Applies a dynamic trailing stop loss to open positions based on the Average True Range (ATR). The trailing stop activates only when the position reaches a specified profit threshold (in ATR multiples) and adjusts the stop loss dynamically as the price moves favorably. It can use either the live price or the previous bar's close for adjustments. ```mql5 #include AdjustPosition adjust_pos; void OnTick() { string symbol = "EURUSD"; int runner_magic = 1001; ENUM_TIMEFRAMES tf = PERIOD_CURRENT; double activation_mult = 2.0; // Activate after 2x ATR profit double trail_mult = 1.5; // Trail at 1.5x ATR distance int atr_period = 14; bool use_bar_close = true; // Use previous bar close instead of live price // Updates trailing stop for all runner positions // Only trails when position is in profit >= activation_mult * ATR adjust_pos.trailing_stop_atr( symbol, runner_magic, tf, activation_mult, trail_mult, atr_period, use_bar_close ); } ``` -------------------------------- ### ATR-Based Trailing Stop Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Applies a dynamic trailing stop based on ATR to runner positions, activating only after a profit threshold is reached. ```APIDOC ## ATR-Based Trailing Stop ### Description Applies a dynamic trailing stop based on ATR to runner positions, activating only after profit threshold is reached. ### Method `trailing_stop_atr` ### Endpoint `MyLibs/Orders/AdjustPosition.mqh` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (string) - Required - The trading symbol (e.g., "EURUSD"). - **runner_magic** (int) - Required - Magic number of the runner positions. - **tf** (ENUM_TIMEFRAMES) - Required - Timeframe for ATR calculation. - **activation_mult** (double) - Required - ATR multiplier to activate trailing stop (e.g., 2.0 means activate after 2x ATR profit). - **trail_mult** (double) - Required - ATR multiplier for the trailing stop distance. - **atr_period** (int) - Required - Period for ATR calculation. - **use_bar_close** (bool) - Required - If true, uses the previous bar's close for trailing stop adjustment; otherwise, uses live price. ### Request Example ```mql5 #include AdjustPosition adjust_pos; // Inside an EA function (e.g., OnTick) string symbol = "EURUSD"; int runner_magic = 1001; ENUM_TIMEFRAMES tf = PERIOD_CURRENT; double activation_mult = 2.0; // Activate after 2x ATR profit double trail_mult = 1.5; // Trail at 1.5x ATR distance int atr_period = 14; bool use_bar_close = true; // Use previous bar close instead of live price adjust_pos.trailing_stop_atr( symbol, runner_magic, tf, activation_mult, trail_mult, atr_period, use_bar_close ); ``` ### Response #### Success Response (200) - **result** (bool) - True if trailing stop was updated successfully, false otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Visualize ATR Bands on Chart (MQL5) Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt This function plots the calculated ATR bands as visual lines directly on the trading chart. It utilizes the 'AtrBands.mqh' library and is typically called during the OnInit event. The function takes the symbol, trendline handle, ATR period, timeframe, multiplier, the number of bars to plot, line color, and line width as parameters, enabling visual confirmation of volatility zones. ```mql5 #include AtrBands atr_bands; void OnInit() { string symbol = _Symbol; int tl_handle = iMA(symbol, PERIOD_CURRENT, 100, 0, MODE_SMA, PRICE_CLOSE); // Draw 100 bars of ATR bands atr_bands.plot_bands( symbol, tl_handle, 14, // symbol, trendline handle, ATR period PERIOD_CURRENT, 1.0, // timeframe, multiplier 100, // number of bars to plot clrSkyBlue, // line color 1 // line width ); } ``` -------------------------------- ### Manage Indicator Handles with ResourceManager in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Manages indicator handles centrally, ensuring all created indicators are automatically cleaned up upon script deinitialization to prevent memory leaks. Handles are registered during initialization and released in OnDeinit. Uses the ResourceManager library. ```mql5 #include ResourceManager resource_manager; int ma_handle, rsi_handle, cci_handle; int OnInit() { // Create indicator handles ma_handle = iMA("EURUSD", PERIOD_CURRENT, 100, 0, MODE_SMA, PRICE_CLOSE); rsi_handle = iRSI("EURUSD", PERIOD_CURRENT, 14, PRICE_CLOSE); cci_handle = iCCI("EURUSD", PERIOD_CURRENT, 50, PRICE_TYPICAL); // Register handles for automatic cleanup resource_manager.register_handle(ma_handle); resource_manager.register_handle(rsi_handle); resource_manager.register_handle(cci_handle); return INIT_SUCCEEDED; } void OnDeinit(const int reason) { // Releases all registered handles automatically resource_manager.release_all_handles(); Print("All indicator handles released"); } ``` -------------------------------- ### Track Signal State Across Bars in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Tracks the number of bars since a specific signal (long or short) occurred for a given symbol. This is useful for implementing delayed entry logic based on signal recency. Updates and queries are handled by the MultiSymbolSignalTracker library. ```mql5 #include MultiSymbolSignalTracker signal_tracker; void OnTimer() { string symbol = "EURUSD"; bool long_signal = true; // Your signal detection logic bool short_signal = false; // Update tracker with current signals signal_tracker.get_tracker(symbol).update_signal_tracker(long_signal, short_signal); // Get bars since last long signal (0 = current, 1 = previous bar, etc.) int bars_since_long = signal_tracker.get_tracker(symbol).get_long_signal(); // Allow entry if signal occurred within last 5 bars if (bars_since_long > 0 && bars_since_long <= 5) { Print("Valid entry: signal was ", bars_since_long, " bars ago"); } } ``` -------------------------------- ### Detect ATR Band Pullbacks (MQL5) Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt This function identifies when price has crossed back into the ATR bands after a breakout, signaling a potential pullback entry. It uses the 'AtrBands.mqh' library. The function checks for two types of pullbacks: crossing below the upper band (bullish opportunity) and crossing above the lower band (bearish opportunity). It requires the symbol, trendline handle, ATR period, timeframe, multiplier, and shift. ```mql5 #include AtrBands atr_bands; void OnTick() { string symbol = "GBPUSD"; int tl_handle = iMA(symbol, PERIOD_CURRENT, 100, 0, MODE_SMA, PRICE_CLOSE); // Detect pullback from above upper band bool pullback_from_above = atr_bands.crossed_below_upper_band( symbol, tl_handle, 14, PERIOD_CURRENT, 1.0, 1 ); // Detect pullback from below lower band bool pullback_from_below = atr_bands.crossed_above_lower_band( symbol, tl_handle, 14, PERIOD_CURRENT, 1.0, 1 ); if (pullback_from_above) Print("Bullish pullback entry opportunity"); if (pullback_from_below) Print("Bearish pullback entry opportunity"); } ``` -------------------------------- ### Set Breakeven After Virtual TP Hit (MQL5) Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt This function moves the stop loss of a runner position to the breakeven point once the price reaches a predefined virtual take-profit target. It requires the 'AdjustPosition.mqh' library. Inputs include the symbol, a runner magic number, and a buffer in points to add around the entry price for the breakeven level. The virtual take-profit is assumed to be stored in the position's comment. ```mql5 #include AdjustPosition adjust_pos; void OnTick() { string symbol = "GBPUSD"; int runner_magic = 1001; double buffer_points = 5; // Add 5 point buffer above/below entry // Checks all runner positions // If current price >= virtual TP (stored in comment) // Moves SL to entry + buffer and removes hard TP adjust_pos.set_breakeven_if_profit_target_hit( symbol, runner_magic, buffer_points ); } ``` -------------------------------- ### Close Buy/Sell Positions with Exit Logic in MQL5 Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt Closes existing BUY or SELL positions based on predefined exit signals or after a specified number of bars have passed since opening. This function provides control over trade closure, enabling dynamic exits or time-based limitations. ```mql5 #include ExitOrders exit_orders; void OnTick() { string symbol = "EURUSD"; bool exit_signal = false; // Your exit logic int close_after_bars = 0; // Set to >0 for time-based exit ENUM_TIMEFRAMES timeframe = PERIOD_H1; long magic_number = 1000; // Close all buy positions for symbol if exit_signal is true exit_orders.close_buy_orders( symbol, exit_signal, close_after_bars, timeframe, magic_number ); // Close all sell positions exit_orders.close_sell_orders( symbol, exit_signal, close_after_bars, timeframe, magic_number ); } ``` -------------------------------- ### Check Price Position Relative to Trendline (MQL5) Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt This function determines whether the current price is positioned above or below a specified trendline. It uses the 'TrendlineAnalyser.mqh' library and requires the symbol and the handle of the trendline indicator. Boolean output variables indicate whether the price is in an uptrend (above trendline) or a downtrend (below trendline). A shift parameter can be used to analyze past bars. ```mql5 #include TrendlineAnalyser tl_tools; void OnTick() { string symbol = "GBPUSD"; int ma_handle = iMA(symbol, PERIOD_CURRENT, 50, 0, MODE_SMA, PRICE_CLOSE); bool direction_long = false; bool direction_short = false; // Check current bar direction tl_tools.trend_direction(symbol, ma_handle, direction_long, direction_short, 1); if (direction_long) Print("Price above trendline - uptrend"); if (direction_short) Print("Price below trendline - downtrend"); } ``` -------------------------------- ### ATR Band Analysis for Volatility Filtering (MQL5) Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt This function checks if the current price is within specified Average True Range (ATR) bands plotted around a trendline. It leverages the 'AtrBands.mqh' library. Inputs include the symbol, trendline handle, ATR period, ATR multiplier, and a shift for bar analysis. It returns boolean values indicating if the price is inside the upper or lower ATR band, useful for volatility-based filtering in trading strategies. ```mql5 #include AtrBands atr_bands; void OnTimer() { string symbol = "EURUSD"; int tl_handle = iMA(symbol, PERIOD_CURRENT, 100, 0, MODE_SMA, PRICE_CLOSE); int atr_period = 14; double multiplier = 1.0; // 1x ATR band width int shift = 1; // Check if price is between trendline and upper band bool inside_upper = atr_bands.inside_upper_band( symbol, tl_handle, atr_period, PERIOD_CURRENT, multiplier, shift ); // Check if price is between trendline and lower band bool inside_lower = atr_bands.inside_lower_band( symbol, tl_handle, atr_period, PERIOD_CURRENT, multiplier, shift ); if (inside_upper) Print("Price in upper volatility band"); if (inside_lower) Print("Price in lower volatility band"); } ``` -------------------------------- ### Detect Trendline Crossovers (MQL5) Source: https://context7.com/xmattc/mt5-quant-lib/llms.txt This function detects when the price crosses above or below a specified trendline indicator, such as a moving average. It utilizes the 'TrendlineAnalyser.mqh' library. The function takes the symbol, the handle of the trendline indicator, and boolean variables to indicate a long or short crossover. An optional shift parameter can be used to check historical bars. Crossovers are typically detected on the last closed bar. ```mql5 #include TrendlineAnalyser tl_tools; void OnTimer() { string symbol = "EURUSD"; int ma_handle = iMA(symbol, PERIOD_CURRENT, 100, 0, MODE_SMA, PRICE_CLOSE); bool cross_long = false; bool cross_short = false; int shift = 1; // Check last closed bar // Detects crossover on last closed bar tl_tools.detect_cross(symbol, ma_handle, cross_long, cross_short, shift); if (cross_long) Print("Bullish crossover detected"); if (cross_short) Print("Bearish crossover detected"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.