Free MQL5 Programming for Your Trading Strategies!

Jul 05 at 15:53
135 การดู
4 Replies
เป็นสมาชิกตั้งแต่ Jul 05, 2024   1 โพสต์
Jul 05 at 15:53
Hey everyone,

I'm offering to program trading strategies in MQL5 for free!

I'm looking to gather new ideas for developing trading robots and thought this would be a great way to connect with the community. Whether you have a simple strategy or a complex idea, I'd love to hear about it and bring it to life.

Feel free to share your strategies or ideas below.
เป็นสมาชิกตั้งแต่ Apr 14, 2022   37 โพสต์
Jul 15 at 07:06
AndreiW7 posted:
Hey everyone,

I'm offering to program trading strategies in MQL5 for free!

I'm looking to gather new ideas for developing trading robots and thought this would be a great way to connect with the community. Whether you have a simple strategy or a complex idea, I'd love to hear about it and bring it to life.

Feel free to share your strategies or ideas below.
Hi, One strategy I frequently use is two moving averages (one fast, one slow). Buy when the fast MA crosses above the slow MA, and sell when it crosses below. This helps spot trends and make good trades. What do you think?
เป็นสมาชิกตั้งแต่ Feb 16, 2011   1 โพสต์
Jul 15 at 09:45
Hello,

An idea for your next/future EAs.

How about work on 2 pairs with correlation(arround...50-60% negative) for positive swap, e.g. Long for USDJPY and short for EURGBP...with hedge/basket TP closed strategy.

Order Start Distance multiply count=value(order count)
Position Distance multiplication %=1.0~1.1,1.2,1.3.....
Order Start Lot multiply count=value(order count)
Lot Martingale coefficient %= 1.0~1.1,1.2,1.3.....

Spread filter(in point)

Trading time filter:
Start Time: 00:00
End Tine: 00:00

Pause/stop trading when Equity decreased

A simple EA for your reference.

https://www.mql5.com/en/market/product/108353

Hopefully, the idea makes sense.
เป็นสมาชิกตั้งแต่ Sep 16, 2020   76 โพสต์
Aug 04 at 03:13
zero9898 posted:
Hello,

An idea for your next/future EAs.

How about work on 2 pairs with correlation(arround...50-60% negative) for positive swap, e.g. Long for USDJPY and short for EURGBP...with hedge/basket TP closed strategy.

Order Start Distance multiply count=value(order count)
Position Distance multiplication %=1.0~1.1,1.2,1.3.....
Order Start Lot multiply count=value(order count)
Lot Martingale coefficient %= 1.0~1.1,1.2,1.3.....

Spread filter(in point)

Trading time filter:
Start Time: 00:00
End Tine: 00:00

Pause/stop trading when Equity decreased

A simple EA for your reference.

https://www.mql5.com/en/market/product/108353

Hopefully, the idea makes sense.
Just made this in Python for anyone interested as a start:

import MetaTrader5 as mt5
import pandas as pd
import numpy as np
import time
from datetime import datetime, time as dt_time

# Connect to MetaTrader 5
if not mt5.initialize():
    print('initialize() failed')
    mt5.shutdown()
    quit()

# Trading parameters
PAIR1 = 'USDJPY'
PAIR2 = 'EURGBP'
TIMEFRAME = mt5.TIMEFRAME_H1
INITIAL_LOT = 0.01
MAX_ORDERS = 5
CORRELATION_THRESHOLD = -0.5 # Looking for negative correlation
SPREAD_FILTER = 20 # in points
EQUITY_STOP_PERCENT = 0.05 # 5% equity decrease

# Position parameters
POSITION_DISTANCE_MULT = [1.0, 1.1, 1.2, 1.3, 1.4]
LOT_MARTINGALE_MULT = [1.0, 1.1, 1.2, 1.3, 1.4]

# Time filter
START_TIME = dt_time(0, 0)
END_TIME = dt_time(23, 59)

def calculate_correlation():
    data1 = mt5.copy_rates_from_pos(PAIR1, TIMEFRAME, 0, 100)
    data2 = mt5.copy_rates_from_pos(PAIR2, TIMEFRAME, 0, 100)
    df1 = pd.DataFrame(data1)['close']
    df2 = pd.DataFrame(data2)['close']
    return df1.corr(df2)

def check_spread():
    spread1 = mt5.symbol_info(PAIR1).spread
    spread2 = mt5.symbol_info(PAIR2).spread
    return spread1 <= SPREAD_FILTER and spread2 <= SPREAD_FILTER

def check_time():
    current_time = datetime.now().time()
    return START_TIME <= current_time <= END_TIME

def check_equity():
    account_info = mt5.account_info()
    if account_info is None:
        raise Exception('Failed to get account info')
    initial_equity = account_info.equity
    current_equity = mt5.account_info().equity
    return (initial_equity - current_equity) / initial_equity <= EQUITY_STOP_PERCENT

def open_position(pair, order_type, lot):
    point = mt5.symbol_info(pair).point
    price = mt5.symbol_info_tick(pair).ask if order_type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(pair).bid
    deviation = 20
    request = {
        'action': mt5.TRADE_ACTION_DEAL,
        'symbol': pair,
        'volume': lot,
        'type': order_type,
        'price': price,
        'deviation': deviation,
        'magic': 234000,
        'comment': 'python script',
        'type_time': mt5.ORDER_TIME_GTC,
        'type_filling': mt5.ORDER_FILLING_IOC,
    }
    result = mt5.order_send(request)
    print(f'Order for {pair} sent: {result}')
    return result

def close_all_positions():
    for pair in [PAIR1, PAIR2]:
        positions = mt5.positions_get(symbol=pair)
        for position in positions:
            close_request = {
                'action': mt5.TRADE_ACTION_DEAL,
                'symbol': pair,
                'volume': position.volume,
                'type': mt5.ORDER_TYPE_SELL if position.type == 0 else mt5.ORDER_TYPE_BUY,
                'position': position.ticket,
                'price': mt5.symbol_info_tick(pair).bid if position.type == 0 else mt5.symbol_info_tick(pair).ask,
                'deviation': 20,
                'magic': 234000,
                'comment': 'python script close',
                'type_time': mt5.ORDER_TIME_GTC,
                'type_filling': mt5.ORDER_FILLING_IOC,
            }
            result = mt5.order_send(close_request)
            print(f'Position closed for {pair}: {result}')

def main():
    initial_equity = mt5.account_info().equity
    
    while True:
        try:
            if not check_time():
                print('Outside trading hours. Waiting...')
                time.sleep(3600) # Wait for an hour
                continue
            
            if not check_equity():
                print('Equity decrease threshold reached. Stopping trading.')
                close_all_positions()
                break
            
            correlation = calculate_correlation()
            print(f'Current correlation: {correlation}')
            
            if correlation > CORRELATION_THRESHOLD:
                print('Correlation not negative enough. Waiting...')
                time.sleep(3600) # Wait for an hour
                continue
            
            if not check_spread():
                print('Spread too high. Waiting...')
                time.sleep(300) # Wait for 5 minutes
                continue
            
            # Open positions
            for i in range(MAX_ORDERS):
                lot1 = INITIAL_LOT * LOT_MARTINGALE_MULT[i]
                lot2 = INITIAL_LOT * LOT_MARTINGALE_MULT[i]
                
                result1 = open_position(PAIR1, mt5.ORDER_TYPE_BUY, lot1)
                result2 = open_position(PAIR2, mt5.ORDER_TYPE_SELL, lot2)
                
                if result1.retcode != mt5.TRADE_RETCODE_DONE or result2.retcode != mt5.TRADE_RETCODE_DONE:
                    print('Failed to open positions. Closing all and waiting...')
                    close_all_positions()
                    time.sleep(3600)
                    break
                
                time.sleep(300) # Wait for 5 minutes between orders
            
            # Monitor positions
            while True:
                if not check_time() or not check_equity():
                    close_all_positions()
                    break
                
                total_profit = sum(pos.profit for pos in mt5.positions_get())
                print(f'Current total profit: {total_profit}')
                
                if total_profit > 0:
                    print('Profit target reached. Closing all positions.')
                    close_all_positions()
                    break
                
                time.sleep(60) # Check every minute
            
        except KeyboardInterrupt:
            print('Script terminated by user')
            close_all_positions()
            break
        except Exception as e:
            print(f'An error occurred: {e}')
            time.sleep(60) # Wait a minute before retrying

    mt5.shutdown()

if __name__ == '__main__':
    main()
"Or die trying...." Sonny Crockett, Miami Vice 1980's
เป็นสมาชิกตั้งแต่ Sep 16, 2020   76 โพสต์
Aug 04 at 03:15
zero9898 posted:
Hello,

An idea for your next/future EAs.

How about work on 2 pairs with correlation(arround...50-60% negative) for positive swap, e.g. Long for USDJPY and short for EURGBP...with hedge/basket TP closed strategy.

Order Start Distance multiply count=value(order count)
Position Distance multiplication %=1.0~1.1,1.2,1.3.....
Order Start Lot multiply count=value(order count)
Lot Martingale coefficient %= 1.0~1.1,1.2,1.3.....

Spread filter(in point)

Trading time filter:
Start Time: 00:00
End Tine: 00:00

Pause/stop trading when Equity decreased

A simple EA for your reference.

https://www.mql5.com/en/market/product/108353

Hopefully, the idea makes sense.
MT5 EA Version - not complied or tested:

//+------------------------------------------------------------------+
//| CorrelatedPairsEA.mq5 |
//| Copyright 2024, Your Name Here |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright 'Copyright 2024, Your Name Here'
#property link 'https://www.mql5.com'
#property version '1.00'
#property strict

// Input parameters
input string Pair1 = 'USDJPY';
input string Pair2 = 'EURGBP';
input ENUM_TIMEFRAMES Timeframe = PERIOD_H1;
input double InitialLot = 0.01;
input int MaxOrders = 5;
input double CorrelationThreshold = -0.5;
input int SpreadFilter = 20;
input double EquityStopPercent = 5.0;
input double PositionDistanceMultBase = 1.0;
input double PositionDistanceMultStep = 0.1;
input double LotMartingaleMultBase = 1.0;
input double LotMartingaleMultStep = 0.1;
input string StartTime = '00:00';
input string EndTime = '23:59';

// Global variables
double initialEquity;
int magic = 234000;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
    initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Close all positions when EA is removed
    CloseAllPositions();
}

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
    if (!CheckTime())
    {
        Print('Outside trading hours. Waiting...');
        return;
    }
    
    if (!CheckEquity())
    {
        Print('Equity decrease threshold reached. Stopping trading.');
        CloseAllPositions();
        return;
    }
    
    double correlation = CalculateCorrelation();
    Print('Current correlation: ', correlation);
    
    if (correlation > CorrelationThreshold)
    {
        Print('Correlation not negative enough. Waiting...');
        return;
    }
    
    if (!CheckSpread())
    {
        Print('Spread too high. Waiting...');
        return;
    }
    
    // Open positions
    for (int i = 0; i < MaxOrders; i++)
    {
        double lot1 = InitialLot * (LotMartingaleMultBase + i * LotMartingaleMultStep);
        double lot2 = InitialLot * (LotMartingaleMultBase + i * LotMartingaleMultStep);
        
        if (!OpenPosition(Pair1, ORDER_TYPE_BUY, lot1) ||
            !OpenPosition(Pair2, ORDER_TYPE_SELL, lot2))
        {
            Print('Failed to open positions. Closing all and waiting...');
            CloseAllPositions();
            return;
        }
        
        Sleep(300000); // Wait for 5 minutes between orders
    }
    
    // Monitor positions
    while (true)
    {
        if (!CheckTime() || !CheckEquity())
        {
            CloseAllPositions();
            return;
        }
        
        double totalProfit = CalculateTotalProfit();
        Print('Current total profit: ', totalProfit);
        
        if (totalProfit > 0)
        {
            Print('Profit target reached. Closing all positions.');
            CloseAllPositions();
            return;
        }
        
        Sleep(60000); // Check every minute
    }
}

//+------------------------------------------------------------------+
//| Calculate correlation between two pairs |
//+------------------------------------------------------------------+
double CalculateCorrelation()
{
    int bars = 100;
    double close1[], close2[];
    
    ArraySetAsSeries(close1, true);
    ArraySetAsSeries(close2, true);
    
    CopyClose(Pair1, Timeframe, 0, bars, close1);
    CopyClose(Pair2, Timeframe, 0, bars, close2);
    
    return MathCorrelation(close1, close2, bars);
}

//+------------------------------------------------------------------+
//| Check if current time is within trading hours |
//+------------------------------------------------------------------+
bool CheckTime()
{
    datetime currentTime = TimeCurrent();
    datetime startTime = StringToTime(StartTime);
    datetime endTime = StringToTime(EndTime);
    
    return (currentTime >= startTime && currentTime <= endTime);
}

//+------------------------------------------------------------------+
//| Check if equity has decreased beyond threshold |
//+------------------------------------------------------------------+
bool CheckEquity()
{
    double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    return ((initialEquity - currentEquity) / initialEquity <= EquityStopPercent / 100);
}

//+------------------------------------------------------------------+
//| Check if spread is within acceptable range |
//+------------------------------------------------------------------+
bool CheckSpread()
{
    return (SymbolInfoInteger(Pair1, SYMBOL_SPREAD) <= SpreadFilter &&
            SymbolInfoInteger(Pair2, SYMBOL_SPREAD) <= SpreadFilter);
}

//+------------------------------------------------------------------+
//| Open a new position |
//+------------------------------------------------------------------+
bool OpenPosition(string symbol, ENUM_ORDER_TYPE orderType, double lot)
{
    MqlTradeRequest request = {};
    MqlTradeResult result = {};
    
    request.action = TRADE_ACTION_DEAL;
    request.symbol = symbol;
    request.volume = lot;
    request.type = orderType;
    request.price = (orderType == ORDER_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_ASK) : SymbolInfoDouble(symbol, SYMBOL_BID);
    request.deviation = 20;
    request.magic = magic;
    request.comment = 'CorrelatedPairsEA';
    request.type_filling = ORDER_FILLING_IOC;
    
    bool success = OrderSend(request, result);
    
    if (!success)
    {
        Print('OrderSend error: ', GetLastError());
        return false;
    }
    
    return true;
}

//+------------------------------------------------------------------+
//| Close all open positions |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        if (ticket > 0)
        {
            if (PositionSelectByTicket(ticket))
            {
                MqlTradeRequest request = {};
                MqlTradeResult result = {};
                
                request.action = TRADE_ACTION_DEAL;
                request.position = ticket;
                request.symbol = PositionGetString(POSITION_SYMBOL);
                request.volume = PositionGetDouble(POSITION_VOLUME);
                request.type = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
                request.price = (request.type == ORDER_TYPE_SELL) ? SymbolInfoDouble(request.symbol, SYMBOL_BID) : SymbolInfoDouble(request.symbol, SYMBOL_ASK);
                request.deviation = 20;
                request.magic = magic;
                
                OrderSend(request, result);
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Calculate total profit of all open positions |
//+------------------------------------------------------------------+
double CalculateTotalProfit()
{
    double totalProfit = 0;
    
    for (int i = 0; i < PositionsTotal(); i++)
    {
        ulong ticket = PositionGetTicket(i);
        if (ticket > 0)
        {
            if (PositionSelectByTicket(ticket))
            {
                totalProfit += PositionGetDouble(POSITION_PROFIT);
            }
        }
    }
    
    return totalProfit;
}

//+------------------------------------------------------------------+
//| Custom function to calculate correlation |
//+------------------------------------------------------------------+
double MathCorrelation(const double &x[], const double &y[], int size)
{
    if (size <= 1)
        return 0;
    
    double sum_x = 0, sum_y = 0, sum_xy = 0;
    double sum_x2 = 0, sum_y2 = 0;
    
    for (int i = 0; i < size; i++)
    {
        sum_x += x[i];
        sum_y += y[i];
        sum_xy += x[i] * y[i];
        sum_x2 += x[i] * x[i];
        sum_y2 += y[i] * y[i];
    }
    
    double numerator = size * sum_xy - sum_x * sum_y;
    double denominator = MathSqrt((size * sum_x2 - sum_x * sum_x) * (size * sum_y2 - sum_y * sum_y));
    
    if (denominator == 0)
        return 0;
    
    return numerator / denominator;
}
"Or die trying...." Sonny Crockett, Miami Vice 1980's
You must be connected to Myfxbook in order to leave a comment
*การใช้งานเชิงพาณิชย์และสแปมจะไม่ได้รับการยอมรับ และอาจส่งผลให้บัญชีถูกยกเลิก
เคล็ดลับ: การโพสต์รูปภาพ/youtube url จะฝังลงในโพสต์ของคุณโดยอัตโนมัติ!
เคล็ดลับ: พิมพ์เครื่องหมาย @ เพื่อป้อนชื่อผู้ใช้ที่เข้าร่วมการสนทนานี้โดยอัตโนมัติ