- Home
- Community
- Programming
- Free MQL5 Programming for Your Trading Strategies!
Edit Your Comment
Free MQL5 Programming for Your Trading Strategies!
Jul 05 at 15:53
Member Since Jul 05, 2024
2 posts
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.
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.
Member Since Apr 14, 2022
37 posts
Jul 15 at 07:06
Member Since Apr 14, 2022
37 posts
AndreiW7 posted: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?
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.
Jul 15 at 09:45
Member Since Feb 16, 2011
1 posts
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.
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.
Member Since Sep 16, 2020
76 posts
Aug 04 at 03:13
Member Since Sep 16, 2020
76 posts
zero9898 posted:Just made this in Python for anyone interested as a start:
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.
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
Member Since Sep 16, 2020
76 posts
Aug 04 at 03:15
Member Since Sep 16, 2020
76 posts
zero9898 posted:MT5 EA Version - not complied or tested:
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.
//+------------------------------------------------------------------+
//| 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
Sep 13 at 16:11
Member Since Mar 21, 2023
2 posts
AndreiW7 posted:Hi sir
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.
can you make platform mt4 for copy demo only?
Member Since Aug 30, 2022
1 posts
Oct 15 at 06:14
Member Since Aug 30, 2022
1 posts
AndreiW7 posted:Hey, yes -
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.
i am a fulltime intraday trader and i am searching someone who can code my stuff. Is this still uptodate?
Oct 15 at 11:03
Member Since Jul 05, 2024
2 posts
XreyTrading posted:Yes friend, I can help youAndreiW7 posted:Hey, yes -
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.
i am a fulltime intraday trader and i am searching someone who can code my stuff. Is this still uptodate?
*Commercial use and spam will not be tolerated, and may result in account termination.
Tip: Posting an image/youtube url will automatically embed it in your post!
Tip: Type the @ sign to auto complete a username participating in this discussion.