Coding
814 prompts available
Advanced Mold Simulator
You are given a partial Python program that simulates advanced mold growth using Pygame. Your task is to continue developing this program with the following goals: - Implement the simulation logic for mold growth using the properties defined in the `Mold` and `MoldInstance` classes. - Develop a graphical user interface (GUI) with Pygame that allows interaction via tools such as "plant", "erase", and "eyedropper". - Create an intuitive UI panel with controls, buttons, and real-time status displays. - Support functionalities like pausing and resuming the simulation, showing mold creators, toggling fullscreen, and confirming user actions. - Handle loading and saving mold types to the specified JSON file path `/mnt/data/mold_types.json`. - Maintain consistent styling using the defined colors and fonts. - Efficiently manage grid or surface data representing mold instances. - Ensure performance is optimized to run at approximately 12 FPS, or better. Throughout simulation steps, apply mold mutation logic using the `maybe_mutate()` method for individual mold instances to introduce variation. # Recommended Development Steps 1. **Grid / Surface Management:** Implement data structures to track mold instances in each cell of the simulation area, despite `GRID_SIZE` being zero currently. 2. **Rendering:** Draw molds using their colors and characteristics onto the Pygame screen. Overlay the UI panel below the simulation area. 3. **User Input:** Detect mouse and keyboard input to switch tools, plant molds, erase them, or sample properties with the eyedropper. 4. **Simulation Update:** Each frame, increment mold ages, manage lifespans, apply growth and spread considering growth rates and invasiveness. 5. **UI Controls:** Implement interactive buttons with hover and active states using the `generate_button_texture()` for visual feedback. 6. **File I/O:** Read from and write to `mold_types.json` to allow persistence of custom mold types. 7. **Additional Features:** Manage popup windows for mold creation and confirmation dialogs. # Output Format Return a Python script file continuing the simulation implementation. Maintain modular, well-commented code. Do not include extraneous explanations or commentary. Your output should be ready to run and integrate with the existing code provided. # Notes - Preserve all existing classes and functions as given. - Do not reduce functionality or remove the default mold types. - Assume all necessary imports are present. - Optimize rendering and updates for clarity and performance. - Use the existing fonts and colors defined for consistent style. Your response should only include the completed Python code extending from where the given snippet ends.
Advanced Movie Streaming Site
Create a comprehensive and advanced movie streaming website featuring a full front-end and back-end implementation. The website must include an intuitive and visually appealing user interface using HTML, CSS, and JavaScript, with advanced features such as user registration and login, movie browsing by categories/genres, search functionality, video playback with controls, and user reviews or ratings. Additionally, develop a fully functional admin panel with features for managing movies (adding, editing, deleting), users, and site content. The back-end should handle data storage and API endpoints to support dynamic operations, session management, and security measures. # Steps - Design and implement a responsive UI for the movie streaming platform. - Create user authentication (registration, login, logout, session management). - Enable movie browsing and searching with filtering options. - Integrate video player with playback controls and responsive design. - Support user reviews and ratings per movie. - Develop an admin panel to manage movies, users, and content. - Implement back-end API to handle front-end requests (CRUD operations, authentication, streaming links). - Ensure data persistence using an appropriate database or local storage. - Optimize for performance and security best practices. # Output Format Provide the complete source code files for both front-end and back-end portions, with clear organization and comments. Include any configuration files or instructions needed to run the website locally. Structure code to separate concerns logically (e.g., front-end HTML/CSS/JS files, back-end server files).
Advanced Movie Streaming Website
Create a complete, advanced movie streaming website named "Movie Universe" that includes the following features: - Well-organized categories and trending pages to showcase movies. - A visually appealing design using HTML, CSS, and JavaScript for both frontend and backend to ensure full functionality. - Ability to add movies with images that look attractive and professional. - When a user clicks on any movie, open a single movie view displaying detailed information about the movie. - Video player with advanced features: play, pause, forward, backward, and full screen. - A fully responsive design to ensure smooth experience across all devices. - An admin panel to manage movies, categories, and website content efficiently. - Ensure the website is monetizable, with considerations for potential earnings. Focus on clean, maintainable, and efficient code to build this fully functional movie streaming platform. # Steps 1. Design the website layout focusing on aesthetics and user experience. 2. Implement movie categories and trending pages. 3. Add movie listing with images. 4. Build single movie view page with movie details and an advanced video player. 5. Create admin panel for adding, editing, and removing movies and categories. 6. Implement backend logic to support full frontend functionality. 7. Make the website mobile-friendly and fully responsive. 8. Optimize for performance and monetization readiness. # Output Format Provide the complete website source code with separate files for HTML, CSS, JavaScript, and backend logic. Include comments explaining key sections and instructions for deployment. Also, include screenshots or descriptions of user interactions for clarity if possible.
Advanced MQL4 EA
Generate a fully integrated Expert Advisor (EA) coded in MQL4 for MetaTrader 4 that incorporates the following advanced trading techniques and features: Fibonacci retracements, fractal-based entry signals with precise wick validations, real-time volatility filtering using ATR, Bollinger Bands, and spread analysis, hedging for market-neutral strategies, and high-frequency scalping methods adopted by institutional traders. The EA must adhere to these detailed implementation considerations for maximum profitability and robustness: - Ensure all trade executions occur in real-time without any delays. - Implement and validate hedging logic that maintains market neutrality. - Incorporate trailing stops that dynamically adjust in response to evolving market conditions. - Automatically detect Fibonacci retracement zones based on previous daily highs and lows with accurate calculations. - Use fractal indicators with strict validation of fractal wick formations before triggering entries. - Apply volatility-based filters to execute trades only under optimal market conditions by analyzing ATR, Bollinger Bands, and spread. - Dynamically adjust trade frequency based on current market volatility, increasing trading during low-volatility periods and reducing during unpredictable swings. - Employ scalping, hedging, and high-frequency trading (HFT) strategies including mean reversion, order flow scalping, Fibonacci and fractal signals, and arbitrage opportunities. - Strictly limit risk per trade to a maximum loss of $0.50 per lot, dynamically adapting stop-loss levels to maintain this risk threshold while optimizing for profit potential. # Steps 1. Calculate and update Fibonacci retracement levels daily based on high and low prices. 2. Identify fractal formations and confirm wick lengths before considering trade entries. 3. Continuously monitor market volatility using ATR, Bollinger Bands, and spread for trade timing and frequency modulation. 4. Implement hedging mechanisms to neutralize market exposure when triggered. 5. Integrate scalping and HFT techniques with order flow and mean reversion methods. 6. Adjust trailing stops in real-time for trade protection and profit maximization. 7. Apply adaptive risk management keeping loss per lot within $0.50. # Output Format Provide the complete, well-commented, and tested MQL4 Expert Advisor source code file (.mq4) that integrates all specified functionalities and constraints. Demonstrate validation and calculation methods within the code via clear comments, ensuring readability and maintainability. # Notes - Ensure performance efficiency suitable for live trading conditions. - Carefully handle edge cases such as sudden volatility spikes, market gaps, and spread widening. - Use best practices for order handling and memory management in MQL4. - The EA should be configurable for standard currency pairs but adaptable to others. Generate the full MQL4 Expert Advisor code accordingly.
Advanced MQL4 EA Generator
You are to generate a fully integrated, high-performance Expert Advisor (EA) coded in MQL4 for MetaTrader 4 that implements all the advanced trading techniques and features outlined below. This EA must: - Compute Fibonacci retracement levels daily using the previous day's high and low. - Detect fractals and validate fractal wick lengths strictly before trade entries. - Monitor volatility in real-time using ATR, Bollinger Bands width, and spread analysis to optimize trade timing and frequency. - Implement hedging logic to maintain market neutrality by opening offsetting positions, neutralizing exposure automatically. - Include institutional-style high-frequency scalping strategies such as mean reversion, order flow scalping, Fibonacci and fractal signals, and arbitrage opportunities. - Dynamically adjust trade frequency based on current market volatility—more trades during stable, low volatility periods, fewer during high volatility. - Use adaptive trailing stops that respond dynamically to evolving market conditions to protect profits and limit losses. - Employ adaptive risk management ensuring losses do not exceed $0.50 per lot per trade by dynamically adjusting stop-loss levels, using pending orders, trailing stops, and immediate break-even when appropriate. - Use BuyStop/SellStop orders configured for ultra-fast market execution and automatic, intelligent order management. - Guarantee stop-loss protection and intelligent trailing stop functionality for each position. - Execute all trades in real-time without delays, suitable for live trading environments. Implementation specifics include: - Calculating Fibonacci retracements at each new trading day start based on prior day high and low. - Strict fractal detection using wick length validation. - Continuous volatility evaluation with ATR, Bollinger Bands width, and spread. - Automatic hedging to maintain market neutrality. - Integration of scalping and HFT strategies with mean reversion, order flow analysis, Fibonacci/fractal signals, and arbitrage. - Dynamic trailing stop adjustments based on volatility and price movement. - Risk per trade capped at $0.50 per lot through dynamic stop-loss sizing. - Robust handling of volatility spikes, market gaps, and spread widening. - Efficient, clean, well-commented code adhering to MQL4 best practices for live trading performance. - Configurability primarily for major currency pairs with flexibility to adapt to others. # Steps 1. At each new trading day, compute and store Fibonacci retracement levels from the previous day's high and low. 2. Continuously analyze incoming bars to detect fractal patterns, strictly validating wick lengths. 3. Calculate ATR, Bollinger Bands width, and spread continuously to assess volatility. 4. Dynamically modulate trade frequency depending on volatility metrics. 5. Implement hedging trades automatically to maintain market exposure neutrality. 6. Apply trailing stops that update dynamically with market moves. 7. Calculate and adjust stop-loss distances dynamically to ensure maximum risk per trade is $0.50 per lot. 8. Place, modify, and close trades instantly without delay. # Output Format - Provide a fully functioning MQL4 Expert Advisor source code file (.mq4). - Ensure the source code is thoroughly commented, explaining calculation logic, trade signal generation, hedging, risk management, and execution flow. - Structure code cleanly and modularly for readability and maintainability. - Optimize and test code for robust performance in live trading conditions. # Notes - Prioritize efficient execution and resource management for instantaneous trade responsiveness. - Implement safeguards for abnormal market conditions including gaps, sudden volatility spikes, and spread widening. - Follow MQL4 best practices for order handling, memory management, and error checking. Your response should be the complete MQL4 source code text implementing this Expert Advisor exactly following the above specifications, fully commented and production-ready for immediate live use.
Advanced MQL4 Trading EA
Generate a fully integrated Expert Advisor (EA) coded in MQL4 for MetaTrader 4 that incorporates the following advanced trading techniques and features: - Fibonacci retracements based on previous daily highs and lows with automatic daily updates and accurate calculations. - Fractal-based entry signals with strict validation of fractal wick lengths before triggering entries. - Real-time volatility filtering using Average True Range (ATR), Bollinger Bands, and spread analysis to optimize trade timing and frequency. - Hedging logic that maintains market neutrality by opening offsetting positions to neutralize market exposure. - High-frequency scalping strategies inspired by institutional methods, including mean reversion, order flow scalping, Fibonacci and fractal signals, and arbitrage opportunities. - Dynamic adjustment of trade frequency based on current market volatility: increasing trades during stable, low-volatility periods and reducing during high volatility. - Trailing stops that adapt dynamically in response to evolving market conditions to protect profits and reduce losses. - Adaptive risk management ensuring maximum loss of $0.50 per lot per trade by dynamically calculating and adjusting stop-loss levels. - Execution of all trades in real-time without delays, suitable for live account environments. # Implementation Details: - Calculate Fibonacci retracement levels at the start of each new day using the previous day’s high and low prices. - Detect fractal formations on relevant timeframes and validate each fractal's wick length meets minimum criteria before entry. - Continuously monitor volatility metrics (ATR, Bollinger Bands bands width, spread) and only allow trades within optimal volatility ranges. - Implement hedging by opening counter positions automatically when triggered, ensuring the overall market exposure is neutralized. - Incorporate scalping and high-frequency trading (HFT) methods encompassing mean reversion strategies, order flow analysis, Fibonacci & fractal signals, and arbitrage. - Adjust trailing stops based on market volatility and price movement patterns dynamically. - Ensure per-trade risk stays within $0.50 per lot by dynamically adjusting stop-loss distance based on current volatility and market conditions. - Handle edge cases such as sudden volatility spikes, market gaps, and spread widening gracefully. - Use efficient, clean, and well-commented MQL4 code adhering to best practices for order handling, memory management, and live trading performance. - Provide configurability for standard major currency pairs with the ability to adapt to others. # Steps: 1. On each new trading day, compute and store Fibonacci retracement levels from the previous day’s high and low. 2. Analyze incoming bars to identify fractal patterns and validate fractal wick lengths strictly. 3. Continuously calculate ATR, Bollinger Bands width, and spread to evaluate market volatility. 4. Modulate trade frequency dynamically based on volatility metrics. 5. Execute hedging trades to maintain market neutrality when conditions evolve. 6. Apply trailing stops that update dynamically with market moves. 7. Calculate appropriate stop-loss distances dynamically to maintain maximum risk of $0.50 per lot. 8. Place, modify, and close trades without delay. # Output Format Produce a fully functioning, compiled MQL4 Expert Advisor (.mq4 source code) file. The source code must be: - Fully commented explaining calculation logic, trade signal generation, hedging mechanism, and risk management. - Structured for readability and maintainability. - Tested and optimized for live trading conditions. # Notes - Prioritize execution speed and resource efficiency to ensure live trading responsiveness. - Carefully handle abnormal market events (gaps, spread widening, sudden volatility) with safeguards within the code. - Follow MQL4 best practices for trade handling, error checking, and memory management. Generate the complete, integrated MQL4 Expert Advisor source code to satisfy all above requirements.
Advanced Python Assistant
You are an advanced Python Code Production Assistant, tasked with helping advanced programmers produce efficient, high-quality Python code. Follow the detailed steps below to ensure a comprehensive coding process. # Steps 1. **Understand the User's Request** - Clarify any ambiguities and grasp the specific coding requirements and objectives. Ask targeted questions if necessary to fully understand the task. 2. **Articulate Thought Process** - Clearly outline your approach, including the algorithms and Python features to be used. Discuss assumptions, potential challenges, and strategies for addressing them. 3. **Code Writing** - Write the complete Python code in the provided Python Code Interpreter (PCI). Comment out all function and method calls to prevent execution. If using unavailable libraries, write the code assuming they are accessible. 4. **Conduct Code Review** - Review the code for PEP-8 compliance, efficiency, readability, and maintainability. Evaluate advanced aspects such as algorithmic efficiency and scalability. 5. **Code Optimization** - Optimize and refine the code within the PCI, focusing on performance, complexity simplification, and robustness. 6. **User Feedback and Clarifications** - Seek user feedback and discuss any further clarifications or needed refinements. 7. **Iterative Code Improvements** - Based on feedback, iteratively improve and enhance the code. Refine logic, add features, or optimize performance as necessary. 8. **Finalize and Upload Code** - Once finalized, uncomment the function calls and upload the complete Python file to the user, ensuring it is executable and reflects the final optimized code. # Output Format - Provide detailed step-by-step reasoning and planning before offering solutions. - Clearly name and explain any advanced Python constructs or libraries used. - Deliver a finalized Python file in .py format, ready for execution.
Advanced Python Bug Fixing
**Python Bug Fixing Guide** Given a Python script and a description of its expected functionality, identify and resolve any bugs present in the code to ensure it performs as designed. ## Steps 1. **Understand the Bug Description**: Carefully read the provided information regarding what the script is supposed to achieve and what issue it is currently experiencing. 2. **Examine the Code**: Review the provided script to understand its structure, logic, and any potential error points. 3. **Identify the Bug**: Look for common issues such as syntax errors, logical mistakes, misused functions, or incorrect data manipulations. 4. **Debugging Techniques**: - Use print statements to trace variable values and code execution paths. - Employ Python's built-in debugging tools such as `pdb`. - Consider edge cases and test the script with diverse input scenarios. 5. **Fix the Bug**: Modify the code to address the identified issues, ensuring the solution is efficient and maintains overall functionality. 6. **Test the Solution**: Run the script to confirm the bug is fixed. Check if it meets the expected outcomes without introducing new errors. 7. **Refactor if Necessary**: Optimize any suboptimal code sections for improved performance or readability, while keeping functionality intact. ## Output Format - **Description of the Identified Bug**: Clearly explain the issue found. - **Revised Code**: Provide the complete fixed script. - **Explanation of Changes**: Describe what was modified and why. - **Testing Evidence**: Present results from testing the fixed code to demonstrate it works as expected. - **Suggestions for Future Improvement**: Optional recommendations for further enhancements or preventative measures. ## Examples **Input Script**: ```python # A sample input with a simple bug # Expectation: Calculate the square of each number in the list numbers = [1, 2, 3] squares = [n * n for m in numbers] # Bug: wrong variable used ``` **Expected Outcome**: An explanation of the bug, a corrected script, and evidence of successful output. **Corrected Script**: ```python # Corrected script numbers = [1, 2, 3] squares = [n * n for n in numbers] print(squares) # Output should be [1, 4, 9] ``` **Explanation**: - **Identified Bug**: 'm' was incorrectly used in the list comprehension, causing a NameError. - **Correction**: Replaced 'm' with 'n' to fix the variable usage. - **Testing**: Successfully calculated squares, confirmed output is as expected. ## Notes - Assume the latest Python version unless otherwise specified. - Consider additional libraries or dependencies if mentioned explicitly in the script.
Advanced MQL5 EA Generator
Create an advanced MetaTrader 5 Expert Advisor (MQL5) with a target win rate of 89% or higher, implementing Smart Money Concepts (SMC), Price Action, Spha Strength Strategy, Order Blocks, Fair Value Gaps, Break of Structure, session filtering, adaptive risk management, and continuous trade cycling (close and reopen logic). The EA must be modular, well-commented, cleanly coded in MQL5, and designed to be manually extended later. --- ## Core Requirements - Trade only high-probability setups with multiple stacked confirmations before entry. - Dynamically adapt lot size based on market conditions and recent trade results. - Close trades early upon change in conditions and reopen if logic remains valid. - Strictly limit overtrading, enforce daily trade loss limits, and protect from high drawdowns. - The EA must only trade the following symbols: XAUUSD, US30, BTCUSD, USDJPY, and GBPUSD; it must not trade any others. ## Strategy Components 1. Indicators (Filters only, no standalone signals): - EMA 9 & EMA 20 (trend direction and pullbacks) - ADX (minimum threshold for trend strength) - ATR (volatility filter and stop loss/take profit scaling) - RSI (momentum and divergence confirmation) - Optional MACD histogram for directional bias 2. Smart Money Concepts Primary Logic: - Break of Structure (BoS): Require candle close beyond structural levels, filtering minor noise. - Order Blocks (OB): Detect last bullish/bearish candle before impulsive moves; entry only when price returns to OB aligned with higher timeframe bias. - Fair Value Gaps (FVG): Identify 3-candle imbalance zones; entries only allowed on price retracement into these zones; visually draw FVG boxes on chart. 3. Price Action Rules: - Trade only on strong impulsive candles with minimum candle body-to-wick ratio. - Avoid entries during choppy or low-volume periods. - Prefer rejection candles at OB/FVG zones. 4. Spha Strength Strategy: - Implement a scoring system (0.0 to 1.0) incorporating trend strength, volatility, structure clarity, and momentum. - Only trade setups with strength score ≥ 0.89 for enhanced win probability. ## Session & Trading Time Filters - Allow trades exclusively during London, New York, and London-New York overlap sessions. - Block trades during Asian sessions (except BTCUSD), low volatility times, and spread spikes. ## Order Lock & Overtrading Protection - Limit to one open trade per symbol. - Implement cooldown periods between trades per symbol. - Lock trading after reaching max daily loss threshold; unlock at start of the next trading day. ## Risk and Money Management - Dynamic lot sizing based on a user-defined base lot. - Increase lot size after wins (with controlled multiplier), decrease after losses. - Scale lot size factoring ATR, volatility, and Spha Strength score. - Enforce configurable max risk per trade (default 1-2%). - Enforce hard limit on max trades per day and max daily drawdown with shutdown. ## Trade Cycling & Management - If a trade closes early in profit and original conditions remain valid, reopen a new trade immediately with adjusted lot size. - Close trades early if conditions weaken. - Do not perform revenge trading. ## Code Structure (Approx. 400 lines total) - Section 1 (Lines 1–100): Core Setup — properties, metadata, input definitions (checkbox booleans for features), symbol validation, session filters, indicator initialization. - Section 2 (Lines 101–200): Market Analysis — structure detection, OB and FVG detection and chart drawing, trend & strength scoring (Spha logic). - Section 3 (Lines 201–300): Trade Logic — buy/sell entry conditions, risk and lot size calculations, order execution, stop loss and take profit placement. - Section 4 (Lines 301–400): Management & Safety — trade monitoring, early close logic, re-entry logic, daily limits enforcement, logging and debugging. ## Feature Checklist - Implement boolean flags for: - Structure confirmation - Valid Order Block - FVG tapped - Valid trading session - Spha Strength score >= threshold Only execute trades when all flags are true. ## Constraints - No repainting or future candle access. - Do not include unrealistic win-rate claims in comments. - Must compile without errors on MQL5 platform. - Fully commented for manual expansion. ## Output Format - Provide the complete, syntactically correct MQL5 Expert Advisor source code file. - Include comprehensive comments explaining each major block and logic component. - The code must be modular and well-structured according to the 4-section layout described. --- Follow all instructions carefully to produce a professional, institutional-style EA with a realistic high precision, low-frequency trading approach. The final code will serve as a master template for future manual customization and extensions.
Advanced Python One-Liners
Create a comprehensive toolbox of advanced Python one-liners that go beyond common functions like sum() or join(). Focus on smart, time-saving, real-world tricks that a data architect would find essential. These should aid in faster debugging, writing cleaner scripts, and enhancing your Python expertise to feel like a Python wizard 🧙♂️. # Guidelines - Include only advanced, less obvious Python one-liners that solve practical problems encountered in data architecture, debugging, or scripting. - Provide a brief explanation for each one-liner, describing its purpose and why it is useful. - Avoid trivial or commonly known shortcuts; aim for clever and powerful uses that demonstrate deep Python knowledge. - Organize the one-liners by the type of task they assist with, such as debugging, data manipulation, script cleanup, or performance improvements. # Output Format - Present each one-liner in Python code format with a short heading or title. - Follow each one-liner with a concise explanation in plain English. - Use markdown formatting for readability (e.g., triple backticks for code blocks). # Examples **1. One-liner to find duplicate items in a list:** ```python duplicates = set(x for x in list if list.count(x) > 1) ``` *Find all duplicates in a list efficiently.* **2. One-liner to flatten a nested list:** ```python flat_list = [item for sublist in nested_list for item in sublist] ``` *Flattens a list of lists into a single list.* # Notes - Prioritize versatility and real-world application over just novelty. - Feel free to include elegant uses of modules like itertools, functools, collections, or built-in functions used in sophisticated ways. Generate the Python one-liners accordingly.
Advanced Python Program
Create an advanced Python program that demonstrates your understanding of object-oriented programming, data structures, and algorithms. The program should implement a specific functionality or solve a problem of your choice. Consider incorporating error handling, testing, and modularity to showcase best practices. Include aspects like classes, inheritance, and possibly recursion or iterative algorithms. Ensure that your code is well-commented for clarity.
Advanced MQL5 Forex EA
Create a comprehensive MQL5 Expert Advisor (EA) script for MetaTrader 5 that implements an advanced Forex trading bot integrating multiple technical indicators, adaptive risk management, and time-based trading restrictions as specified below. --- ### Core Requirements: - **Market Sensing Indicators:** Implement EMA (Exponential Moving Average), RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Stochastic Oscillator, and Volume analysis. - **Adaptive Trade Execution:** Automated buy and sell order placement based on indicator signals, with dynamic lot sizing at 1% of the current account balance. - **Time-Restricted Trading:** Limit all trade executions strictly to the specified New York session hours, defined by customizable start and end hours. - **News Event Avoidance:** Detect and avoid trading during scheduled news events for the symbol using SymbolInfo() functions or alternative MQL5 news APIs. - **TP/SL Management:** Implement tailored Take Profit (TP) and Stop Loss (SL) levels appropriate for minimum account balances as low as $20. - **Automatic Reversal Handling:** Detect market reversals via divergence and indicator signals; close existing positions upon reversal detection and open reverse trades accordingly. --- ### Global Variables (to be declared in the Global section of mql5\headers\StrategyTester.mqh): - `EMA_PERIOD` (e.g., 20) - `RSI_PERIOD` (e.g., 14) - `OVERBOUGHT_THRESHOLD` (RSI or Stochastic upper bound) - `OVERSOLD_THRESHOLD` (RSI or Stochastic lower bound) - `START_HOUR` (New York session start) - `END_HOUR` (New York session end) - `MIN_ACCOUNT_BALANCE` (minimum account balance to enable trading) --- ### EA Lifecycle Functions: **1. `Init()` Function:** - Validate all input parameters for acceptable ranges. - Initialize and attach all required indicators (EMA, RSI, MACD, Stochastic). - Calculate adaptive lot size as 1% of the current account balance. **2. `DeInit()` Function:** - Clean up and detach indicators. - Free any allocated resources. **3. Custom News Detection Indicator/Module:** - Create or integrate a module that identifies upcoming or current news events affecting the traded symbol within the trading session hours. - Prevent trade opening during detected news events. **4. `Calculate()` Function (Main Trading Logic):** - Calculate current values of EMA, RSI, MACD, Stochastic Oscillator, and analyze volume data. - Confirm current time is within `START_HOUR` and `END_HOUR`, and no news events are detected. - Identify trade signals based on combined indicators: - **Buy Signal:** Price > EMA and RSI < oversold threshold AND confirm bullish divergences (MACD, RSI), Stochastic %K crossing %D in oversold zone, and supportive volume trends. - **Sell Signal:** Price < EMA and RSI > overbought threshold AND confirm bearish divergences (MACD, RSI), Stochastic %K crossing %D in overbought zone, and volume confirmation. - Execute trades: - Open new trades with calculated lot size, setting SL and TP levels appropriately considering minimum balance. - Modify existing orders if necessary. - Detect reversals: - If reversal signals occur, close existing open positions and initiate reverse trades. **5. Order Management Functions:** - Implement `OrderSend()` wrapper that handles order opening/modification including SL/TP setting. - Implement `OrderDelete()` to close existing orders safely by ticket. --- ### Testing and Optimization: - Include inline code comments explaining logic and parameters. - Provide notes on optimizing parameters such as EMA/RSI periods and thresholds. - Support backtesting on historical data specifically within New York session hours and optionally on demo accounts for live strategy validation. --- # Output Format - Deliver a full, well-commented MQL5 EA source code file (.mq5) implementing all above components. - Ensure clear modular structure separating initialization, indicator calculation, signal generation, order execution, and cleanup. - Document global variables and input parameter usage. --- # Example Behavior (conceptual): - On receiving a price bar, EA calculates EMA(20), RSI(14), MACD histogram, Stochastic %K and %D, and analyzes volume. - If price > EMA(20) and RSI < 30 with bullish MACD divergence and Stochastic %K crosses above %D in the oversold region, and volume confirms upward momentum within New York session hours (e.g., 14:30 to 21:00 EST), EA opens a buy order with lot size = 1% balance. - If price reverses or bearish divergence is detected, EA closes buy order and opens a corresponding sell order. - All trades have SL and TP set respecting the minimum account balance constraints. --- Ensure robust error handling, parameter validation, and compliance with MQL5 programming standards throughout. The final product should serve as a ready-to-use, optimized Forex trading EA designed by an expert with a deep understanding of the MQL5 language and Forex trading strategies.