Back to Learning

Coding

814 prompts available

Adaptive Scalping MQL5 EA

Create a detailed MQL5 Expert Advisor (EA) script for scalping that includes adaptive trading features. The EA should dynamically adjust trading parameters based on market conditions to optimize scalping performance in forex markets. Key requirements: - Implement fast and frequent trade entries suitable for scalping strategies. - Adapt to changing market volatility and liquidity by adjusting stop-loss, take-profit, and lot size dynamically. - Include configurable input parameters for user customization. - Incorporate risk management techniques such as maximum spread filter and trade frequency limits. - Comment the code thoroughly to explain the logic and adaptive mechanisms. Steps to complete the task: 1. Define input parameters for scalping such as trade volume, stop-loss distance, take-profit distance, maximum spread, and adaptive coefficients. 2. Monitor current market conditions, including spread and volatility indicators. 3. Implement logic to modify stop-loss and take-profit based on volatility measures. 4. Code entry and exit criteria optimized for scalping, using indicators or price action. 5. Enforce risk management rules to avoid overtrading. 6. Test with sample market data to verify adaptive behavior. Output Format: Provide the entire MQL5 EA source code file, including header comments explaining usage, input parameters, and a summary of the adaptive scalping strategy. Format code properly for readability. Example snippet: // Input parameters input double LotSize = 0.1; input int BaseStopLoss = 10; // in points ... // Adjust StopLoss based on current volatility StopLoss = BaseStopLoss * VolatilityCoefficient; Notes: Ensure the EA handles errors gracefully and is safe for live trading conditions. The adaptation should improve scalping effectiveness while managing risk appropriately.

AdaptiveTrend EA

Create a fully functional MQL4 Expert Advisor (EA) for MetaTrader 4 that implements an adaptive trading strategy dynamically responding to market trends (uptrend, downtrend, sideways). The EA must meet the following detailed specifications: - Refresh Rate: 1 millisecond (constantly updating and monitoring the market); - Activate trading only after the specified local time: 2024.02.01 01:00:00; - Initial Lot size: 0.1 lots; - Place Pending Orders (PO) at 200 points distance from current price; - Lot Multiplier ratio: 1.235 between total Buy lots to Sell lots; - Maximum open positions capped at 10; - Target Take Profit (TP) of 9000 USD and Stop Loss (SL) of 3000 USD in USD terms; - Partial Close Profit threshold set at 5000 USD to partially close positions; - Delay at least 3 seconds before starting the next order after one closes or opens; Requirements: 1. Market Condition Awareness: - Continuously loop and identify optimal premium prices to sell and optimal discounted prices to buy. - Execute additional orders during market retests, pullbacks, or when prices approach equilibrium/base prices in demand & supply zones. 2. Profit Protection Strategy: - For orders reaching sufficient profit, move SL to break-even plus spread (20 points) and include commissions. - If this SL is hit, open new orders at better prices than the previous closed orders. 3. User Interface: - Add a "Close All Orders" button in the MT4 terminal to allow the user to immediately close all open trades. 4. Trailing Stop Mechanism: - Implement a dynamic trailing stop that moves SL gradually, maintaining an optimal distance from current price to maximize gains while preventing premature stop outs. 5. Take Profit Adjustments: - Dynamically adjust TP levels targeting high probability zones based on current market momentum. 6. Equity Protection: - Monitor account equity relative to balance, and immediately close all positions if equity drops by 5% or a user-defined threshold. 7. Martingale Strategy: - Apply a Martingale approach when market conditions justify it for high probability zones, with configurable adjustable order distance (default 25 points). 8. Flexible Trading Operations: - Support opening both buy and sell orders based on real-time market conditions and user-configured strategies. Dashboard Display: - Show Active Time (activation time); - Display remaining time until the EA becomes active formatted as hh.mm.ss; - Show the Initial Lot size; - Current floating position profit/loss in USD; - Total accumulated Take Profit since activation in USD; - Number of Take Profit orders not yet fulfilled. Implementation Steps: 1. Define all necessary EA input parameters and settings within MetaEditor 4: - User-customizable options including order comments, magic numbers, lot sizes, martingale distances. 2. Program the lot size logic that multiplies buy and sell lot sizes maintaining the specified ratio. 3. Implement order management: - Close all orders functionality. - Partial profit closures when profit thresholds are met. 4. Design and code the on-screen dashboard with clear visual display of key EA metrics. 5. Develop continuous logic for detecting optimal entry/exit points leveraging retest, pullback, and demand/supply zone analysis. Output Format: Provide the complete MQL4 source code for the Expert Advisor in a single file. The code must be extensively commented, clearly explaining the purpose and function of each major section, variable, and logic block to facilitate understanding, compilation, and backtesting within MetaEditor 4. Ensure the code is ready to run immediately upon compilation without missing dependencies or errors.

ADB Tap Script

You are given a Python script using the Android Debug Bridge (ADB) to simulate tapping on a device screen at specific coordinates repeatedly. Your task is to enhance or analyze this code snippet, ensuring it efficiently performs tap actions at given coordinates with a specific delay. When improving or explaining the code: - Ensure the `tap` function correctly executes an ADB command to tap on the specified (x, y) coordinates. - Maintain a delay between taps, which can be adjusted. - Consider adding error handling or improvements for robustness if applicable. - If explaining, describe how the loop and function interact. # Steps 1. Understand the existing function `tap(x, y)` which sends an ADB tap command. 2. Recognize the infinite loop that calls this function repeatedly with a fixed delay. 3. Optionally improve the code with error handling or customizable parameters. # Output Format Provide the revised Python code snippet with optional comments explaining the functionality or improvements included. If providing an explanation, write clear, concise paragraphs describing what the code does and how it can be used or modified. # Examples Example of the existing code: ```python import os import time def tap(x, y): os.system(f"adb shell input tap {x} {y}") # Example: Tap on coordinates (500, 1000) every 2 seconds while True: tap(500, 1000) time.sleep(2) ``` # Notes - Ensure ADB is installed and the device is connected. - Running this script requires permissions to execute ADB commands. - Adjust coordinates or delay as needed for your use case.

Add About Below Login

Enhance the functionality of 'popup.php' such that immediately below the login section, users are shown the content from 'about.php'. Steps: 1. Identify the login section within 'popup.php'. 2. Insert or include the content from 'about.php' directly below the login area. 3. Ensure proper styling and layout so the 'about.php' content appears seamlessly integrated and visually coherent with the login section. 4. Maintain any existing functionality and responsiveness of 'popup.php'. 5. Test the page to verify that after login elements, the 'about.php' content displays as intended without disrupting existing features. Output Format: Provide the updated PHP code snippet(s) or modifications made to 'popup.php' demonstrating how 'about.php' content is integrated below the login section. Include any relevant explanations or notes on changes made.

Add Adaptive Stop Loss (ASL)

Your task is to modify the provided algorithmic trading code to include an Adaptive Stop Loss (ASL) feature. The ASL should dynamically adjust the stop loss level based on current volatility, calculated using the Average True Range (ATR) indicator. # Steps 1. **Import Necessary Libraries**: Ensure all necessary libraries for handling indicators like ATR are included. 2. **Initialize ATR Indicator**: Create a handle for the ATR indicator, similar to how the RSI indicator is handled in the current code. 3. **Implement ASL Logic**: - Calculate the ATR value using the created handle. - Use the ATR to dynamically set a new stop loss level for each trade. - Ensure the stop loss is adjusted on each new tick based on updated ATR values. 4. **Modify Trading Logic**: Integrate the adaptive stop loss into the existing buy and sell conditions. The stop loss should replace or adjust the fixed stop loss points (e.g., `Bid - 80 * _Point`) with an ATR-based stop loss. 5. **Error Handling**: Implement error handling to manage failures in obtaining the ATR value, similar to the existing RSI error handling. # Output Format - Provide a complete, functional code snippet with comments explaining your changes. - Highlight or comment where the ASL logic is integrated into the code. # Examples - Use ["ATR_PERIOD"] or other placeholders to indicate where customizable or dynamic elements may be applied in the code. For example, if the ATR period is a variable that could be adjusted, ensure it's noted. # Notes - Ensure the ASL feature maintains the existing trading conditions and logic, complementing rather than replacing them. - Consider potential performance impacts of adding ATR calculations and optimize where necessary.

Add and Remove Orders in Python Form

You are tasked with enhancing a Python customer form by adding "Add Order" and "Delete Order" buttons. Your goal is to enable the functionality to add or remove orders directly from the customer form interface. Use the Java implementations of the customer and product forms as a reference. In particular, examine how the Java customer form handles adding an order to a customer and apply the same logic and workflow principles within the Python form. Steps to accomplish this task: 1. Review the Java customer and product form code, focusing on the add order functionality to understand the sequence of operations, data handling, and UI updates. 2. In the Python customer form: - Add two buttons labeled "Add Order" and "Delete Order". - Implement the "Add Order" button to enable selecting or creating an order and associating it with the current customer, following the workflow derived from the Java version. - Implement the "Delete Order" button to allow removal of a selected order from the customer's list. - Ensure the UI updates correctly after adding or deleting orders. 3. Handle any underlying data structures or database updates necessary to keep the customer’s orders synchronized. Output Format: Provide the updated Python code snippets or modules for the customer form showing: - The UI components added (buttons). - The event handlers or functions implementing add order and delete order functionality, with comments relating to how they correspond to the Java form implementation. - Any necessary scaffolding or data manipulation code to support these features. Include explanations or comments to clarify how the Java form’s add order logic was adapted for Python. Example (placeholder): ```python # Add 'Add Order' and 'Delete Order' buttons to the form add_order_button = Button(text='Add Order', command=add_order) delete_order_button = Button(text='Delete Order', command=delete_order) # Function to add an order to the current customer # Adapted from Java customer form's addOrder method def add_order(): # [Implementation] # Function to delete an order from the current customer def delete_order(): # [Implementation] ``` Make sure to keep the same user experience and data consistency as the Java implementation while using idiomatic Python programming practices.

Add AR Calculator Module

Add an AR (Auto-Regressive) calculator module to the existing TimeseriesAnalysisProject GitHub repository, ensuring it is implemented similarly to the existing MA (Moving Average) module without introducing any new dependencies. Your task is to extend the project by creating an AR calculator that fits seamlessly with the current codebase, follows the established coding style and conventions, and integrates into the analysis workflow like the existing MA calculator. # Steps 1. **Review Existing MA Module:** - Examine the current MA calculator code within the project to fully understand its structure, methods, and integration points. - Note how input data is handled, parameters are configured, and outputs are generated. 2. **Implement AR Calculator Class/Module:** - Using the same style and architectural patterns as the MA module, implement the AR calculator. - Ensure you only use already existing dependencies in the project (likely numpy, pandas, standard libraries). - The AR calculator should be able to take time series data and calculate auto-regressive values based on a chosen lag parameter. 3. **Integrate AR Calculator:** - Add the AR calculator to the same place(s) in the project where the MA calculator is referenced and invoked. - Modify or extend any interface (e.g., command line options, configuration files) that should allow users to select AR calculation, mirroring how MA is selected. 4. **Add Testing/Validation:** - Create or extend unit tests similar to those for MA to verify the correctness of your AR implementation. - Test with sample datasets to ensure AR behaves as expected. 5. **Documentation:** - Add comments and docstrings in your AR calculator code consistent with existing project style. - Optionally update README or related documentation to mention the new AR calculator feature. # Output Format Provide detailed step-by-step instructions combined with complete code snippets for the AR calculator and integration changes. Code should be clearly commented and formatted to match the existing project style. # Examples If the MA calculator class looks like this: ```python class MovingAverageCalculator: def __init__(self, window_size): self.window_size = window_size def calculate(self, series): return series.rolling(window=self.window_size).mean() ``` Then the AR calculator could be analogous, for example: ```python class AutoRegressiveCalculator: def __init__(self, lag): self.lag = lag def calculate(self, series): # Implementation details here without new dependencies pass ``` Replace `pass` with the suitable AR calculation logic using pandas or numpy. # Notes - Do not add any new external libraries. - Maintain consistency with the existing project structure. - Assume you have access to current project code for reference and modification. - Follow best practices for Python coding style and documentation. Execute the task with clear guidance and code samples enabling the addition of a working AR calculator similar to the MA module in the TimeseriesAnalysisProject repository.

Add Asset Selection Route

Add a route to the application where users can select assets to buy. This route should provide an interface or endpoint that lists available assets clearly, allowing the user to browse, filter, or search through the assets. Users should be able to select one or multiple assets they wish to purchase. Ensure the route is well-structured, properly named, and integrated with existing backend or frontend frameworks appropriately. # Steps 1. Identify the appropriate URL path for the new route, following existing naming conventions. 2. Design and implement the route handler (backend or frontend) to fetch and display available assets. 3. Provide user interface elements such as lists, filters, or search bars to facilitate asset selection. 4. Enable selection controls (checkboxes, buttons, etc.) for users to choose assets. 5. Integrate with the purchase workflow to handle selected assets. 6. Test the route for usability, accessibility, and correctness. # Output Format Provide the code snippets or configuration required to implement the route, including route definitions, controller/handler code, and front-end components if applicable. Include comments to explain the purpose and functionality of each part. # Notes - Maintain consistency with existing application structure and coding standards. - Ensure the route is secure and handles invalid or unauthorized access gracefully. - Consider pagination or lazy loading if the asset list is large.

Add Authentication to To-Do App

You are tasked with enhancing a simple "to do" web application that uses HTML, CSS, JavaScript for the frontend, and PHP files for server-side operations connected to a local MySQL database via XAMPP. Currently, the app has the following files: - `config.php`: Contains the database connection logic. - `api.php`: Handles the CRUD requests. - `index.html`: Contains the HTML markup, CSS styles, and JavaScript for the client-side. Your goal is to add a complete authentication system to this application with the following requirements: 1. **User Registration:** Implement a registration feature allowing new users to create accounts. This should capture at least a username and password, storing credentials securely in the database (use password hashing). 2. **User Login:** Implement a login feature enabling existing users to authenticate. 3. **Header Navigation:** Place the authentication buttons (`Login`, `Register`, and after login `Logout`) in the header section of `index.html`, which is currently empty. The UI should change appropriately based on the authentication state. 4. **Session Management:** Use PHP sessions to manage login state securely across pages or actions. 5. **Integration:** Integrate the authentication with the existing CRUD operations such that only authenticated users can access to-do functionality. 6. **Security:** Follow best practices for securing authentication (e.g., input validation, password hashing, session security). 7. **User Experience:** Implement navigation or UI changes based on authentication status (e.g., hide login/register after login, show logout, optionally display username). # Steps - Design and create necessary database tables for users, ensuring fields for username, hashed password, and any other needed fields. - Extend `api.php` or create new PHP endpoints for registration and login handling. - Modify `index.html` header to include buttons for `Login`, `Register`, and `Logout` appropriately. - Implement frontend JavaScript to handle authentication workflows (form submissions, state changes). - Use PHP sessions to track login state. - Protect existing CRUD functionalities so they require authentication. - Test the full flow: registration, login, accessing to-do items, logout. # Output Format Provide an outline or code snippets illustrating how to implement these features, including: - Database schema for users table. - Sample PHP code for registration, login, session management. - HTML changes for header and authentication forms. - JavaScript snippets needed for handling UI state and form submission. Ensure clear explanations accompany code examples to clarify how integration occurs. # Notes - Assume knowledge of standard security practices. - Focus on simplicity and clarity suitable for a beginner-to-intermediate full stack developer. - Do not rewrite the entire app—show minimal changes and additions needed for authentication integration.

Add Buffers and Dots to MQL4

You are provided with existing MQL4 code that implements certain indicator functionality. Your task is to enhance this code by adding new buffers and displaying additional dots on the chart as specified below. **Requirements:** 1. **Maintain the existing code and all current functionality without removal or alteration unless necessary for integration.** 2. **Add buffer index values to appear in the Data Window:** - Add a buffer for a green dot value. 3. **Add new dot buffers and display dots for Bullish FVG High and Bearish FVG Low:** - After a Bullish FVG confirmation, identify the Bullish FVG High as the low of the last candle (the third candle) involved in the FVG formation. Mark this point with a blue dot on the chart. - After a Bearish FVG confirmation, identify the Bearish FVG Low as the low of the last candle (the third candle). Mark this point with a red dot on the chart. **Additional details:** - Use separate buffers for each dot type (green, blue, red). - Ensure these buffers correspond to properly indexed candles so the dots align visually on the chart. - The values in the buffers should be set in a manner that they appear correctly in the Data Window and on the price chart. # Steps 1. Review the existing MQL4 code to understand current buffers and how dots are plotted. 2. Define new buffers for green dot, blue dot (Bullish FVG High), and red dot (Bearish FVG Low). 3. Update the `OnInit` function or equivalent to allocate buffers and set their properties. 4. In the calculation function (e.g., `OnCalculate`), implement logic to: - Detect Bullish and Bearish FVG confirmation. - Mark the Bullish FVG High with a blue dot at the low of the last candle. - Mark the Bearish FVG Low with a red dot similarly. - Add the green dot value to its buffer at the appropriate candle. 5. Ensure all buffer values are properly indexed, and values for candles without dots are set to `EMPTY_VALUE`. 6. Confirm that the Data Window displays the new buffers and their values. # Output Format Provide the complete, updated MQL4 code with the added buffers and dot plotting logic integrated. The code must compile and run within MetaTrader 4, showing the new green, blue, and red dots correctly aligned with their respective candle points and displaying buffer values in the Data Window.

Add Buy/Sell Signal Icons

You are given the complete MQL5 code for an indicator named "Corrected JMA + Signals.mq5" which includes definitions for buffers, initialization, calculation logic, trend label display, and support functions for JMA logic by the author mladen and modification by Meta Coder. Your task is to **add custom icons for the Buy and Sell signals**, replacing or enhancing the current arrow plots. The code currently sets: - BuySignal plot to use arrow code 233 - SellSignal plot to use arrow code 234 You need to update the code so that it uses distinctive custom icons (not just arrows) for Buy and Sell signals. These icons should clearly represent buy and sell actions respectively on the chart, improving visual clarity. **Requirements:** - Modify the relevant PlotIndexSetInteger or similar function calls for the Buy and Sell signal plots to use the appropriate custom icon codes. - Ensure the icons align visually with the existing indicator style, colors, and sizes. - Keep the rest of the indicator logic and style intact. You can use standard MQL5 Wingdings or Webdings character codes or Unicode characters suitable for buy and sell icons. Do not alter any unrelated logic or input parameters. Provide the updated code snippet specifically showing where and how to declare the new Buy and Sell icon codes and configure the buffers or plots accordingly. # Steps 1. Identify the current PlotIndexSetInteger calls configuring the arrow plots for BuySignal and SellSignal (using code 233 and 234). 2. Choose appropriate custom icon character codes for buy and sell (e.g., bull or up arrow for buy, bear or down arrow for sell) from MQL5 Wingdings or Unicode. 3. Update the PlotIndexSetInteger calls accordingly to these new codes. 4. Ensure color, width, and size are set consistently. 5. Confirm no other code changes affect calculation or plotting functionality. # Output Format Provide the modified portions of the MQL5 code with detailed comments indicating what was changed. Present this as a valid code snippet ready to replace the old icon definitions. # Notes - The indicator properties for the BuySignal and SellSignal buffers include color and width that should remain unchanged. - The icon codes must be valid for PlotIndexSetInteger PLOT_ARROW setting in MQL5. - If necessary, add a brief note on how the codes correspond to the new icons. # Examples Example of setting a custom arrow icon: ```mql5 PlotIndexSetInteger(2, PLOT_ARROW, 234); // old arrow for buy PlotIndexSetInteger(3, PLOT_ARROW, 235); // old arrow for sell ``` Modified example: ```mql5 PlotIndexSetInteger(2, PLOT_ARROW, 159); // Bull icon for Buy PlotIndexSetInteger(3, PLOT_ARROW, 160); // Bear icon for Sell ``` Replace the arrow codes with those described in your solution accordingly.

Add Auto-Minimize Toggle

You are given an Expert Advisor (EA) trade panel that currently auto-minimizes based on built-in logic. Your task is to add an input option (true/false) that allows the user to enable or disable this auto-minimize feature without changing any existing code or logic of the EA. You must only add this option as a configurable input parameter; do not modify any core functionality, flow, or logic of the EA. Steps: 1. Identify the portion of the EA where the auto-minimize behavior is triggered. 2. Without altering the logic, add an input parameter called something like `AutoMinimize` that accepts boolean values (true/false). 3. Use this input parameter as a toggle to control whether the EA auto-minimizes or not. 4. Ensure that default behavior remains the same if the input is set to true. 5. No other code or logic should be changed besides adding this input and conditioning the auto-minimizing behavior on this input. Output Format: Provide the exact input declaration syntax for the EA language (e.g., MQL4 or MQL5), including the new input parameter with description. Then provide a code snippet showing how this parameter is used to toggle the auto-minimize functionality in the existing code snippet. Examples: Input declaration: input bool AutoMinimize = true; // Enable or disable auto-minimize of the trade panel Usage snippet: if(AutoMinimize) { // Existing auto-minimize code } Notes: - Do not change any logic or flow outside of adding this input and condition. - The input should be user-friendly and clearly documented. - Assume the user will integrate this code snippet into their existing EA manually, so keep changes minimal.

Page 27 of 68

    Coding Prompts - Learning AI Prompts | Elevato