I am wanting to run multiple accounts on my VPS. Each account with it's own EA running. When I switch accounts, my EA opens on the account i login to. I need it to continue running on the original account. How do I stop this from happening.
@Aldo Errico#:I am wanting to run multiple accounts on my VPS. Each account with it's own EA running. When I switch accounts, my EA opens on the account i login to. I need it to continue running on the original account. How do I stop this from happening.
A MetaQuotes virtual host can only host one trade account at a time, so you will need multiple virtual hosts ...
If using 3rd party VPS, then a single MetaTrader desktop terminal can only run one trade account at a time. So you will need to run multiple terminals (maximum of 32).
I am experiencing some problem which I find difficult to explain and hence difficult to find a working solution from the Codebase and forums. I have an indicator which runs well when back testing but when I place it on a live chart, it shows/draws bogus arrows. If I recompile the code while the indicator is placed on a live chart, the bogus arrows become even more. I am thinking that somewhere in the code I have to delete old data from buffers/arrays or set them to empty values, but I don't know how to do that because I don't understand what is causing the bogus arrows.
Please see image below:
The code is below, I have excluded the unnecessary if conditions which in the end only set bool variables to either true or false.
#property indicator_chart_window#property indicator_buffers6#property indicator_plots6// For the 10% RRT ratio signal#property indicator_color1 DarkTurquoise
#property indicator_type1DRAW_ARROW#property indicator_style1STYLE_SOLID#property indicator_width11#property indicator_color2 Orange
#property indicator_type2DRAW_ARROW#property indicator_style2STYLE_SOLID#property indicator_width21// For the 20% RRT ratio signal#property indicator_color3 Red
#property indicator_type3DRAW_ARROW#property indicator_style3STYLE_SOLID#property indicator_width33#property indicator_color4 Green
#property indicator_type4DRAW_ARROW#property indicator_style4STYLE_SOLID#property indicator_width43// For the b1 formation setup#property indicator_color5 DarkTurquoise
#property indicator_type5DRAW_ARROW#property indicator_style5STYLE_SOLID#property indicator_width51#property indicator_color6 Orange
#property indicator_type6DRAW_ARROW#property indicator_style6STYLE_SOLID#property indicator_width61//----- Indicator buffers -----// For the 10% RRT ratio signaldouble upArrow[];
double downArrow[];
// For the 20% RRT ratio signaldouble upArrow2[];
double downArrow2[];
// For the b1 formation setupdouble upArrow3[];
double downArrow3[];
// The below flags are initially set to false and become true when conditions are metbool MconditionBuy = false;
bool MconditionSell = false;
bool MconditionBuy2 = false;
bool MconditionSell2 = false;
bool MconditionBuy3 = false;
bool MconditionSell3 = false;
bool UseAlerts = true; // Use Alerts// bool UseEmailAlerts = false; // Use Email Alerts (configure SMTP parameters in Tools->Options->Emails)bool Push=false; //Enable Push Notificationint prev_calc; // To hold value of previously calculatd and make it accessible // outside the for loop (accessible in the Alerts function)//+------------------------------------------------------------------+//| Custom indicator initialization function |//+------------------------------------------------------------------+voidOnInit()
{
IndicatorSetString(INDICATOR_SHORTNAME,"RRT");
PlotIndexSetInteger(0,PLOT_ARROW,233);
PlotIndexSetInteger(1,PLOT_ARROW,234);
PlotIndexSetInteger(2,PLOT_ARROW,217);
PlotIndexSetInteger(3,PLOT_ARROW,218);
PlotIndexSetInteger(4,PLOT_ARROW,221);
PlotIndexSetInteger(5,PLOT_ARROW,222);
SetIndexBuffer(0,upArrow);
SetIndexBuffer(1,downArrow);
SetIndexBuffer(2,upArrow2);
SetIndexBuffer(3,downArrow2);
SetIndexBuffer(4,upArrow3);
SetIndexBuffer(5,downArrow3);
}
//+------------------------------------------------------------------+//| Custom indicator deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
ObjectsDeleteAll(0,0,OBJ_ARROW);
ObjectsDeleteAll(0,0,OBJ_TEXT);
Comment("");
//--- Clearing the buffersArrayFree(upArrow);
ArrayFree(downArrow);
ArrayFree(upArrow2);
ArrayFree(downArrow2);
ArrayFree(upArrow3);
ArrayFree(downArrow3);
}
//+------------------------------------------------------------------+//| Custom indicator iteration function |//+------------------------------------------------------------------+intOnCalculate(constint rates_total,
constint prev_calculated,
constdatetime &Time[],
constdouble &open[],
constdouble &high[],
constdouble &low[],
constdouble &close[],
constlong &tick_volume[],
constlong &volume[],
constint &spread[])
{
//--- Return value of prev_calculated for next callint total, limit;
if (prev_calculated == 0) // i.e The indicator is running for the first time
{
total = rates_total - 1; // leave at least 1 candle to the right to avoid array out of range
limit = 20; // This is the limit of candles / bars to count backwards, i.e. the lookback and zero is// the last candle / bar on the left of the chart.
prev_calc = 0; // Make the value of previously calculated available in the Alerts function
}
elseif (rates_total - prev_calculated <= 0) // i.e The indicator is not running for the first time but is on same candle// total is zero and the for loop will not run
{
total = rates_total - prev_calculated; // total is/has zero
limit = 0;
prev_calc = prev_calculated;
}
else
{
total = rates_total-2;
limit = prev_calculated-2;
prev_calc = prev_calculated;
}
for(int i = total; i > limit; i--)
{
if (conditions_Sell_met) MconditionSell = true;
if (conditions_Sell2_met) MconditionSell2 = true;
if (conditions_Buy_met) MconditionBuy = true;
if (conditions_Buy2_met) MconditionBuy2 = true;
if (conditions_Sell3_met) MconditionSell3 = true;
if (conditions_Buy3_met) MconditionBuy3 = true;
//------------------- Buy conditions ---------------------------if(MconditionBuy)
{
upArrow[i]=low[i];
SendAlert(signalText);
MconditionBuy = false; // reset the market condition and wait for new conditions to arrive - to prevent repetitions
}
if(MconditionBuy2)
{
upArrow2[i]=low[i];
SendAlert(signalText);
MconditionBuy2 = false; // reset the market condition and wait for new conditions to arrive - to prevent repetitions
}
if(MconditionBuy3)
{
upArrow3[i]=low[i];
SendAlert(signalText);
MconditionBuy3 = false;
}
//------------------- Sell conditions ---------------------------if(MconditionSell)
{
downArrow[i]=high[i];
SendAlert(signalText);
MconditionSell = false;
}
if(MconditionSell2)
{
downArrow2[i]=high[i];
SendAlert(signalText);
MconditionSell2 = false;
}
if(MconditionSell3)
{
downArrow3[i]=high[i];
SendAlert(signalText);
MconditionSell3 = false;
}
}
//--- Return value for the next callreturn(rates_total);
}
//+------------------------------------------------------------------+void SendAlert(string signal)
{
if (UseAlerts && prev_calc != 0) // prev_calc is to avoid making alerts when the indicator is // calculating historical data (backwards), alerts should only// be made going forward and not for past patterns.
{
Alert(signal);
PlaySound("alert.wav");
}
// if (UseEmailAlerts)// SendMail(signal);if(Push)
{
SendNotification(signal);
}
}
//+------------------------------------------------------------------+
Your assistance in explaining why the bogus arrows appear and showing me how to get rid of them is much appreciated.
I am experiencing some problem which I find difficult to explain and hence difficult to find a working solution from the Codebase and forums. I have an indicator which runs well when back testing but when I place it on a live chart, it shows/draws bogus arrows. If I recompile the code while the indicator is placed on a live chart, the bogus arrows become even more. I am thinking that somewhere in the code I have to delete old data from buffers/arrays or set them to empty values, but I don't know how to do that because I don't understand what is causing the bogus arrows.
Please see image below:
The code is below, I have excluded the unnecessary if conditions which in the end only set bool variables to either true or false.
Your assistance in explaining why the bogus arrows appear and showing me how to get rid of them is much appreciated.
I found the solution, and now I see how simple it was. Before the indicator runs, clean all buffers. Since you would like to do this only once, clean the buffers at the instance the indicator is first dropped on the chart, and that would be when prev_calculated is zero. See code below:
if (prev_calculated == 0) // i.e The indicator is running for the first time
{
total = rates_total - 1; // leave at least 1 candle to the right to avoid array out of range
limit = 20; // This is the limit of candles / bars to count backwards, i.e. the lookback and zero is// the last candle / bar on the left of the chart.
prev_calc = 0; // Make the value of previously calculated available in the Alerts function// Clean / delete old buffer values to avoid bogus arrows// This is done once only when prev_calculated is zero, i.e when u first drop the indicatorfor(int i = total; i > limit; i--)
{
upArrow[i] = EMPTY_VALUE;
downArrow[i] = EMPTY_VALUE;
upArrow2[i] = EMPTY_VALUE;
downArrow2[i] = EMPTY_VALUE;
upArrow3[i] = EMPTY_VALUE;
downArrow3[i] = EMPTY_VALUE;
}
}
I was working on a personalprojectand I realized that the already available MT5 API won't work for my purposes because it requires the terminal to simultaneously be open. I looked all over the internet but all the API's I could find were either just wrappers that still needed a terminal or were just really expensive. So I am making my own API that won't need a terminal and will work on any platform. And I wanted to know if anyone else would be interested so I could develop with the public in mind.
I was working on a personalprojectand I realized that the already available MT5 API won't work for my purposes because it requires the terminal to simultaneously be open. I looked all over the internet but all the API's I could find were either just wrappers that still needed a terminal or were just really expensive. So I am making my own API that won't need a terminal and will work on any platform. And I wanted to know if anyone else would be interested so I could develop with the public in mind.
This section is about MT4, not MT5.
You can't do such API legally. MT5 servers require an MT5 Terminal or official WebTerminal to connect.
Hello, I have a ready made EA, however its not opening trades on tester, the EA is based on MA cross over, and Martingale applied, kindly help me with fixing the errors, here is the EA below
input int TimeFrame1 = PERIOD_M15; // Timeframe 15 minuites
input int EMA1_Period1 = 50; // EMA period for TimeFrame1
input int EMA2_Period1 = 200; // Another EMA period for TimeFrame1
Omeh Philip #: , I have a ready made EA, however its not opening trades on tester, the EA is based on MA cross over, and Martingale applied, kindly help me with fixing the errors,
Help you with what? You haven't stated a problem, you stated a want. Show us your attempt (using the CODE button) and state the nature of your difficulty. No free help(2017)
We're not going to code it for you (although it could happen if you are lucky or the issue is interesting). No free help(2017)
voidOnDeinit(constint reason)
{
Print("MultiTF EA Deinitialized");
// Clean up any resources if neededEventKillTimer();
voidOnTimer()
{
ExecuteTradingLogic();
}
You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.
Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?
Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread. MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25
The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
Hi
I am wanting to run multiple accounts on my VPS. Each account with it's own EA running. When I switch accounts, my EA opens on the account i login to. I need it to continue running on the original account. How do I stop this from happening.
Thanking you in advance
Aldo
A MetaQuotes virtual host can only host one trade account at a time, so you will need multiple virtual hosts ...
If using 3rd party VPS, then a single MetaTrader desktop terminal can only run one trade account at a time. So you will need to run multiple terminals (maximum of 32).
Hello everyone.
I started to study MQL4 last week with the intention of making something similar to the Magic Keys device.
Reading the MQL4 manual raised some questions and I was wondering if someone could help me to solve them.
I wonder if it would be possible to create a macro so I can select the rectangle tool and draw in the chart.I would like to
be able to activate/select some of the tools that have no shortcut in the mt4 plataform from a macro pad.
Is that possible? If so, could you tell me what do I need to learn or focuss my attention on?
Thank you.
SaltedPN
Good day everyone,
I am experiencing some problem which I find difficult to explain and hence difficult to find a working solution from the Codebase and forums. I have an indicator which runs well when back testing but when I place it on a live chart, it shows/draws bogus arrows. If I recompile the code while the indicator is placed on a live chart, the bogus arrows become even more. I am thinking that somewhere in the code I have to delete old data from buffers/arrays or set them to empty values, but I don't know how to do that because I don't understand what is causing the bogus arrows.
Please see image below:
The code is below, I have excluded the unnecessary if conditions which in the end only set bool variables to either true or false.
Your assistance in explaining why the bogus arrows appear and showing me how to get rid of them is much appreciated.
Good day everyone,
I am experiencing some problem which I find difficult to explain and hence difficult to find a working solution from the Codebase and forums. I have an indicator which runs well when back testing but when I place it on a live chart, it shows/draws bogus arrows. If I recompile the code while the indicator is placed on a live chart, the bogus arrows become even more. I am thinking that somewhere in the code I have to delete old data from buffers/arrays or set them to empty values, but I don't know how to do that because I don't understand what is causing the bogus arrows.
Please see image below:
The code is below, I have excluded the unnecessary if conditions which in the end only set bool variables to either true or false.
Your assistance in explaining why the bogus arrows appear and showing me how to get rid of them is much appreciated.
I found the solution, and now I see how simple it was. Before the indicator runs, clean all buffers. Since you would like to do this only once, clean the buffers at the instance the indicator is first dropped on the chart, and that would be when prev_calculated is zero. See code below:
I looked all over the internet but all the API's I could find were either just wrappers that still needed a terminal or were just really expensive.
So I am making my own API that won't need a terminal and will work on any platform. And I wanted to know if anyone else would be interested so I could develop with the public in mind.
I looked all over the internet but all the API's I could find were either just wrappers that still needed a terminal or were just really expensive.
So I am making my own API that won't need a terminal and will work on any platform. And I wanted to know if anyone else would be interested so I could develop with the public in mind.
This section is about MT4, not MT5.
You can't do such API legally. MT5 servers require an MT5 Terminal or official WebTerminal to connect.
Hello, I have a ready made EA, however its not opening trades on tester, the EA is based on MA cross over, and Martingale applied, kindly help me with fixing the errors, here is the EA below
input int TimeFrame1 = PERIOD_M15; // Timeframe 15 minuites
input int EMA1_Period1 = 50; // EMA period for TimeFrame1
input int EMA2_Period1 = 200; // Another EMA period for TimeFrame1
input double LotSize = 0.1; // Initial lot size
input double MartingaleMultiplier = 2.0; // Martingale multiplier
input double StopLoss = 50; // Stop loss in pips
input double TakeProfit = 100; // Take profit in pips
input bool UseHedging = true; // Enable/disable hedging
input double TrailingStart = 20; // Trailing stop start distance in pips
input double TrailingStop = 10; // Trailing stop distance in pips
input int RSI_High = 70; // RSI high level for filtering
input int RSI_Low = 30; // RSI low level for filtering
input int GridStep = 200; // Grid trading step in pips
input int MaxGridTrades = 15; // Maximum number of grid trades allowed
input int GridGap = 100; // Minimum distance between grid levels in pips
input double EquityStopLoss = 20.0; // Equity stop loss percentage
input bool FilterNewTrades = false; // Filter for new trades
input bool DynamicPips = false; // Enable dynamic pips calculation
input double DEL = 100.0; // Delete pending order distance in pips
//--- Global variables
double InitialLotSize;
double InitialAccountBalance;
int MAGIC_NUMBER = 12345;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
InitialLotSize = LotSize;
InitialAccountBalance = AccountEquity();
Print("EA Initialized");
// Subscribe to necessary events if needed
EventSetTimer(1); // Run every second
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("MultiTF EA Deinitialized");
// Clean up any resources if needed
EventKillTimer();
void OnTimer()
{
ExecuteTradingLogic();
}
//+------------------------------------------------------------------+
//| Custom function to execute trading logic |
//+------------------------------------------------------------------+
void ExecuteTradingLogic()
{
// Check for equity stop loss
if(CheckEquityStopLoss())
return;
// Check for EMA crossovers on a single timeframe
bool buySignal = CheckEMACrossover(TimeFrame1, EMA1_Period1, EMA2_Period1);
bool sellSignal = CheckEMACrossover(TimeFrame1, EMA1_Period1, EMA2_Period1, true);
// Apply RSI filter
double rsi = iRSI(NULL, 0, 14, PRICE_CLOSE, 0);
if(rsi > RSI_High)
buySignal = false; // Prevent buy trades
if(rsi < RSI_Low)
sellSignal = false; // Prevent sell trades
// Debug prints for signals
Print("Buy Signal: ", buySignal, " | Sell Signal: ", sellSignal);
// Filter new trades if the parameter is set
if(FilterNewTrades)
return;
// Open trades based on signals
if(buySignal)
{
Print("Opening Buy Trade");
OpenTrade(OP_BUY);
}
if(sellSignal)
{
Print("Opening Sell Trade");
OpenTrade(OP_SELL);
}
// Update trailing stops for open trades
UpdateTrailingStops();
// Check for grid trading opportunities
if(GridStep > 0 && GridGap > 0)
CheckGridTrading();
}
//+------------------------------------------------------------------+
//| Custom function to check grid trading opportunities |
//+------------------------------------------------------------------+
void CheckGridTrading()
{
double gridLevel = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_POINT) * GridStep, Digits);
double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
// Calculate nearest grid level
double nearestBuyLevel = MathCeil(SymbolInfoDouble(Symbol(), SYMBOL_BID) / gridLevel) * gridLevel;
double nearestSellLevel = MathFloor(SymbolInfoDouble(Symbol(), SYMBOL_BID) / gridLevel) * gridLevel;
// Check if we can open new buy grid trade
if(nearestBuyLevel - SymbolInfoDouble(Symbol(), SYMBOL_BID) >= GridGap * Point)
OpenTradeAtPrice(OP_BUY, nearestBuyLevel);
// Check if we can open new sell grid trade
if(SymbolInfoDouble(Symbol(), SYMBOL_BID) - nearestSellLevel >= GridGap * Point)
OpenTradeAtPrice(OP_SELL, nearestSellLevel);
}
//+------------------------------------------------------------------+
//| Custom function to open trades at a specific price |
//+------------------------------------------------------------------+
void OpenTradeAtPrice(int tradeType, double price)
{
double lotSize = LotSize;
// Martingale logic
if(tradeType == OP_BUY)
{
lotSize = CalculateLotSize(OP_BUY);
if(!UseHedging && OrdersTotal() > 0)
CloseAll(OP_SELL);
}
else if(tradeType == OP_SELL)
{
lotSize = CalculateLotSize(OP_SELL);
if(!UseHedging && OrdersTotal() > 0)
CloseAll(OP_BUY);
}
// Calculate stop loss and take profit prices
double sl = 0, tp = 0;
if(tradeType == OP_BUY)
{
sl = price - StopLoss * Point;
tp = price + TakeProfit * Point;
}
else if(tradeType == OP_SELL)
{
sl = price + StopLoss * Point;
tp = price - TakeProfit * Point;
}
// Place trade
int ticket = OrderSend(Symbol(), tradeType, lotSize, price, 3, sl, tp, "", MAGIC_NUMBER, 0, Blue);
if(ticket < 0)
{
Print("Error opening trade: ", GetLastError(), " (", ErrorDescription(GetLastError()), ")");
}
}
//+------------------------------------------------------------------+
//| Custom function to check for equity stop loss |
//+------------------------------------------------------------------+
bool CheckEquityStopLoss()
{
double currentEquity = AccountEquity();
double equityDrawdown = ((InitialAccountBalance - currentEquity) / InitialAccountBalance) * 100;
if(equityDrawdown >= EquityStopLoss)
{
CloseAllTrades();
return(true);
}
return(false);
}
//+------------------------------------------------------------------+
//| Custom function to get error description |
//+------------------------------------------------------------------+
string ErrorDescription(int error)
{
switch(error)
{
case 1: return "No error returned";
case 2: return "Common error";
case 3: return "Invalid trade parameters";
case 4: return "Trade server is busy";
case 5: return "Old version of the client terminal";
case 6: return "No connection with trade server";
case 7: return "Not enough rights";
case 8: return "Too frequent requests";
case 9: return "Malfunctional trade operation";
case 10: return "Invalid price";
case 11: return "Invalid stops";
case 12: return "Invalid trade volume";
case 13: return "Market is closed";
case 14: return "Trade is disabled";
case 15: return "Not enough money";
case 16: return "Price changed";
case 17: return "Off quotes";
case 18: return "Broker is busy";
case 19: return "Requote";
case 20: return "Order is locked";
case 21: return "Long positions only allowed";
case 22: return "Too many requests";
default: return "Unknown error";
}
}
//+------------------------------------------------------------------+
//| Custom function to close all trades |
//+------------------------------------------------------------------+
void CloseAllTrades()
{
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
int ticket = OrderTicket(); // Store the ticket number for logging
if(OrderType() == OP_BUY || OrderType() == OP_SELL)
{
bool closeResult = OrderClose(ticket, OrderLots(), OrderClosePrice(), 3, clrRed);
if(closeResult)
{
Print("Order ", ticket, " closed successfully.");
}
else
{
Print("Failed to close order ", ticket, ": Error ", GetLastError(), " (", ErrorDescription(GetLastError()), ")");
}
}
}
}
}
//+------------------------------------------------------------------+
//| Custom function to get EMA value |
//+------------------------------------------------------------------+
double GetEMA(int timeFrame, int period, int shift)
{
return(iMA(NULL, timeFrame, period, 0, MODE_EMA, PRICE_CLOSE, shift));
}
//+------------------------------------------------------------------+
//| Custom function to check EMA crossover |
//+------------------------------------------------------------------+
bool CheckEMACrossover(int timeFrame, int emaPeriod1, int emaPeriod2, bool reverse = false)
{
double ema1_prev = iMA(NULL, timeFrame, emaPeriod1, 0, MODE_EMA, PRICE_CLOSE, 1);
double ema2_prev = iMA(NULL, timeFrame, emaPeriod2, 0, MODE_EMA, PRICE_CLOSE, 1);
double ema1_curr = iMA(NULL, timeFrame, emaPeriod1, 0, MODE_EMA, PRICE_CLOSE, 0);
double ema2_curr = iMA(NULL, timeFrame, emaPeriod2, 0, MODE_EMA, PRICE_CLOSE, 0);
if(!reverse)
return (ema1_prev < ema2_prev && ema1_curr > ema2_curr);
else
return (ema1_prev > ema2_prev && ema1_curr < ema2_curr);
}
//+------------------------------------------------------------------+
//| Custom function to open trades |
//+------------------------------------------------------------------+
void OpenTrade(int tradeType)
{
double lotSize = LotSize;
// Martingale logic
if(tradeType == OP_BUY)
{
lotSize = CalculateLotSize(OP_BUY);
if(!UseHedging && OrdersTotal() > 0)
CloseAll(OP_SELL);
}
else if(tradeType == OP_SELL)
{
lotSize = CalculateLotSize(OP_SELL);
if(!UseHedging && OrdersTotal() > 0)
CloseAll(OP_BUY);
}
// Place trade
double price = tradeType == OP_BUY ? Ask : Bid;
int ticket = OrderSend(Symbol(), tradeType, lotSize, price, 3, 0, 0, "", MAGIC_NUMBER, 0, clrBlue);
if(ticket < 0)
{
Print("Error opening trade: ", GetLastError(), " (", ErrorDescription(GetLastError()), ")");
}
}
//+------------------------------------------------------------------+
//| Custom function to calculate lot size for Martingale strategy |
//+------------------------------------------------------------------+
double CalculateLotSize(int tradeType)
{
double lotSize = InitialLotSize;
int trades = 0;
for(int i=0; i<OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType() == tradeType)
trades++;
}
}
if(trades > 0)
lotSize *= MathPow(MartingaleMultiplier, trades);
return(lotSize);
}
//+------------------------------------------------------------------+
//| Custom function to close all trades of a specific type |
//+------------------------------------------------------------------+
void CloseAll(int tradeType)
{
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType() == tradeType)
{
bool closeResult = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrRed);
if(!closeResult)
{
Print("Failed to close order ", OrderTicket(), ": Error ", GetLastError(), " (", ErrorDescription(GetLastError()), ")");
}
}
}
}
}
//+------------------------------------------------------------------+
//| Custom function to update trailing stops |
//+------------------------------------------------------------------+
void UpdateTrailingStops()
{
for(int i=0; i<OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType() == OP_BUY)
{
if(Bid - OrderOpenPrice() >= TrailingStart * Point)
{
double newStopLoss = Bid - TrailingStop * Point;
if(newStopLoss > OrderStopLoss())
{
bool result = OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, Green);
if(!result)
{
Print("Failed to modify buy order ", OrderTicket(), ": Error ", GetLastError(), " (", ErrorDescription(GetLastError()), ")");
}
}
}
}
else if(OrderType() == OP_SELL)
{
if(OrderOpenPrice() - Ask >= TrailingStart * Point)
{
double newStopLoss = Ask + TrailingStop * Point;
if(newStopLoss < OrderStopLoss())
{
bool result = OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, Red);
if(!result)
{
Print("Failed to modify sell order ", OrderTicket(), ": Error ", GetLastError(), " (", ErrorDescription(GetLastError()), ")");
}
}
}
}
}
}
}
Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
Messages Editor
Forum rules and recommendations - General - MQL5 programming forum (2023)
Help you with what? You haven't stated a problem, you stated a want. Show us your attempt (using the CODE button) and state the nature of your difficulty.
No free help (2017)
Or pay someone. Top of every page is the link Freelance.
Hiring to write script - General - MQL5 programming forum (2018)
We're not going to code it for you (although it could happen if you are lucky or the issue is interesting).
No free help (2017)
Do not post code that will not even compile.
MT4: Learn to code it.
MT5: Begin learning to code it.
If you don't learn MQL4/5, there is no common language for us to communicate. If we tell you what you need, you can't code it. If we give you the code, you don't know how to integrate it into your code.
I need HEEEELP, please, it's URGENT...really ! - General - MQL5 programming forum (2017)
You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.
Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?
Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25
The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)
Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
My GBPJPY shows average spread = 26 points, average maximum spread = 134.
My EURCHF shows average spread = 18 points, average maximum spread = 106.
(your broker will be similar).
Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)
Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number/symbol filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum (2013)
PositionClose is not working - MQL5 programming forum (2020)
MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)
You need one Magic Number for each symbol/timeframe/strategy.
Trade current timeframe, one strategy, and filter by symbol requires one MN.
If trading multiple timeframes, and filter by symbol requires use a range of MN (base plus timeframe).
Why are MT5 ENUM_TIMEFRAMES strange? - General - MQL5 programming forum - Page 2 #11 (2020)