//+------------------------------------------------------------------+
//| GUI Panel Class |
//+------------------------------------------------------------------+
class CPanel
{
private:
string m_name;
int m_width;
//+------------------------------------------------------------------+
//| Volume Indicator Class (Candle Volume Display) |
//+------------------------------------------------------------------+
class CVolumeIndicator
{
private:
// Volume tracking
long buy_volume;
long sell_volume;
long current_candle_buy;
long current_candle_sell;
long maxPositiveDiff;
long maxNegativeDiff;
double basePrice;
double maxUpMove;
double maxDownMove;
Assistant
User
kindly provide the full code that will intergrate the above , i assume the code excutes the filliing mode sequencially , that means the last filling mode is one that works , edit the expert to use the working filling mode ie the last, i assume this should lead to faster orders
Assistant
User
kindly provide the full updated code as i may make a mistake when placing the updated code into the original code
Assistant
// Display settings
int panel_x;
int panel_y;
color panel_color;
color buy_color;
color sell_color;
color diff_color;
int max_candles_to_show;
// Check for new candle
if(current_time != last_candle_time)
{
if(current_candle_buy > 0 || current_candle_sell > 0)
{
// Shift history
for(int i = max_candles_to_show-1; i > 0; i--)
candle_history[i] = candle_history[i-1];
// Store current candle data
candle_history[0].buy = current_candle_buy;
candle_history[0].sell = current_candle_sell;
candle_history[0].time = last_candle_time;
// Update candle displays
UpdateCandleDisplays();
}
// Reset for new candle
current_candle_buy = 0;
current_candle_sell = 0;
last_candle_time = current_time;
// Delete current candle label when new candle starts
ObjectDelete(0, current_candle_label_prefix+"B");
ObjectDelete(0, current_candle_label_prefix+"S");
ObjectDelete(0, current_candle_label_prefix+"D");
}
// Update volumes
if(prevPrice > 0)
{
if(lastPrice > prevPrice)
{
buy_volume++;
current_candle_buy++;
}
else if(lastPrice < prevPrice)
{
sell_volume++;
current_candle_sell++;
}
}
prevPrice = lastPrice;
// Calculate movement in points and pips
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
double movement = (lastPrice - basePrice) / point;
// Update max up and down movement
if (movement > maxUpMove)
maxUpMove = movement;
if (movement < -maxDownMove)
maxDownMove = -movement;
// Update max positive and negative differences
long totalDiff = buy_volume - sell_volume;
if(totalDiff > maxPositiveDiff)
maxPositiveDiff = totalDiff;
if(totalDiff < maxNegativeDiff)
maxNegativeDiff = totalDiff;
// Format labels
string buyText = "Total Buy: " + IntegerToString(buy_volume);
string sellText = "Total Sell: " + IntegerToString(sell_volume);
string diffSign = (buy_volume - sell_volume) >= 0 ? "+" : "";
string diffText = "Total Diff: " + diffSign + IntegerToString(MathAbs(buy_volume - sell_volume));
string maxPosText = "Max +Diff: " + IntegerToString(maxPositiveDiff);
string maxNegText = "Max -Diff: " + IntegerToString(MathAbs(maxNegativeDiff));
string movementText = "Movement: " + DoubleToString(movement, 1) + " points ";
string maxUpMoveText = "Max Up Move: " + DoubleToString(maxUpMove, 1) + " points ";
string maxDownMoveText = "Max Down Move: " + DoubleToString(maxDownMove, 1) + " points ";
string moveDiffText = "Move Diff: " + DoubleToString(maxUpMove + maxDownMove, 1) + " points ";
// Update colors based on difference
if((buy_volume - sell_volume) > 0)
ObjectSetInteger(0, "TotalDiffLabel", OBJPROP_COLOR, buy_color);
else if((buy_volume - sell_volume) < 0)
ObjectSetInteger(0, "TotalDiffLabel", OBJPROP_COLOR, sell_color);
else
ObjectSetInteger(0, "TotalDiffLabel", OBJPROP_COLOR, diff_color);
// Update movement label color based on movement direction
if (movement > 0)
ObjectSetInteger(0, movementLabelName, OBJPROP_COLOR, clrLimeGreen);
else if (movement < 0)
ObjectSetInteger(0, movementLabelName, OBJPROP_COLOR, clrRed);
else
ObjectSetInteger(0, movementLabelName, OBJPROP_COLOR, diff_color);
// Update all labels
ObjectSetString(0, "BuyVolumeLabel", OBJPROP_TEXT, buyText);
ObjectSetString(0, "SellVolumeLabel", OBJPROP_TEXT, sellText);
ObjectSetString(0, "TotalDiffLabel", OBJPROP_TEXT, diffText);
ObjectSetString(0, "MaxPosDiffLabel", OBJPROP_TEXT, maxPosText);
ObjectSetString(0, "MaxNegDiffLabel", OBJPROP_TEXT, maxNegText);
ObjectSetString(0, movementLabelName, OBJPROP_TEXT, movementText);
ObjectSetString(0, maxUpMoveLabelName, OBJPROP_TEXT, maxUpMoveText);
ObjectSetString(0, maxDownMoveLabelName, OBJPROP_TEXT, maxDownMoveText);
ObjectSetString(0, moveDiffLabelName, OBJPROP_TEXT, moveDiffText);
// Update current candle labels
UpdateCurrentCandleDisplay();
// Add label on current candle
DisplayCurrentCandleVolume();
}
void DisplayCurrentCandleVolume()
{
int bar_index = 0; // Current candle
double high = iHigh(_Symbol, PERIOD_CURRENT, bar_index);
datetime time = iTime(_Symbol, PERIOD_CURRENT, bar_index);
code
// Calculate price position (above candle high)
int window = 0; // Main chart window
// Calculate the x-coordinate based on the chart's properties
int chartWidth = ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
int visibleBars = ChartGetInteger(0, CHART_VISIBLE_BARS);
double timeDiff = (TimeCurrent() - time) / PeriodSeconds(PERIOD_CURRENT);
int x = chartWidth - (int)(timeDiff * chartWidth / visibleBars);
// Introduce offsets to move the label
int x_offset = 50; // Adjust this value to move the label further left or right
int y_offset = 100; // Adjust this value to move the label further up or down
x -= x_offset;
// Convert price to y-coordinate
int y = (int)((ChartGetDouble(0, CHART_PRICE_MAX, window) - high) /
(ChartGetDouble(0, CHART_PRICE_MAX, window) - ChartGetDouble(0, CHART_PRICE_MIN, window)) *
ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, window));
// Adjust y-coordinate with offset
y -= y_offset;
// Calculate difference
long diff = current_candle_buy - current_candle_sell;
string diff_sign = diff >= 0 ? "+" : "";
// Create current candle volume display
CreateSmallLabel(current_candle_label_prefix+"B", "B:"+IntegerToString(current_candle_buy), x, y, buy_color);
CreateSmallLabel(current_candle_label_prefix+"S", "S:"+IntegerToString(current_candle_sell), x, y+15, sell_color);
CreateSmallLabel(current_candle_label_prefix+"D", "D:"+diff_sign+IntegerToString(diff), x, y+30,
diff >= 0 ? buy_color : sell_color);
and calls OrderSend() repeatedly until one succeeds.
For some brokers/instruments, some filling modes like ORDER_FILLING_FOK or ORDER_FILLING_RETURN may not be supported and will respond with "Unsupported filling mode".
However, your code falls back to another filling mode until it finally sends successfully with one compatible mode.
The last accepted filling mode is normally ORDER_FILLING_IOC, which is typically supported by most brokers.
So, your logic is working correctly by trying multiple filling modes.
Suggestions to optimize and clean up
Check supported filling mode only once and use the supported one
You can query the symbol properties for supported filling modes and avoid trying all possible modes blindly.
Your EA tries 3 filling modes; some brokers do not support all modes, so errors appear for unsupported ones.
The final accepted trade is done using one filling mode that works.
To avoid the "Unsupported filling mode" errors, query and use only a supported filling mode.
Your SL/TP calculations are correct assuming minimum stop level checks are respected.
If you want, I can help you integrate this fix fully into your expert!
Certainly! Below is the full updated EA code, integrating the fix to:
Detect and use only the last working filling mode, based on your existing sequence (IOC, RETURN, FOK).
Avoid trying every filling mode on each order, instead remembering which filling mode worked last and using it directly for subsequent orders.
If no filling mode has worked yet, the code will try the original sequence once, remember the successful mode, and then always reuse it.
Summary of changes:
Added a static/global variableENUM_ORDER_TYPE_FILLING lastWorkingFillingMode initialized to ORDER_FILLING_FOK (last in your existing list).
Modified ExecuteTrade() to:
If lastWorkingFillingMode is known, try only that mode.
Otherwise try the modes sequentially until success.
If success found in testing, store it in lastWorkingFillingMode.
This means after the first successful order, the EA will avoid multiple attempts, speeding up trades and reducing log spam.
Full updated EA code (only relevant parts changed or added comments)
mql5
#property strict
// --- Your other class definitions remain unchanged (CPanel, CVolumeIndicator) ---
//+------------------------------------------------------------------+
//| Global Variables |
//+------------------------------------------------------------------+
CPanel gui;
CVolumeIndicator volumeIndicator;
double currentLotSize = 0.01;
int currentSlippage = 3;
int numberOfTrades = 1;
double currentStopLoss = 0.0;
double currentTakeProfit = 100.0;
double currentTrailingStop = 0.0;
// Store last working filling mode (default last in the sequence)
ENUM_ORDER_TYPE_FILLING lastWorkingFillingMode = (ENUM_ORDER_TYPE_FILLING)(-1); // invalid initially
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Create trading panel GUI (unchanged)
gui.Create("TradingPanel", 180);
gui.AddLabel("title", "Trading Terminal", 5, 20, clrWhite);
gui.AddLabel("lotLabel", "Lot Size:", 5, 40, clrWhite);
gui.AddEdit("lotEdit", DoubleToString(currentLotSize, 2), 100, 38, 40);
gui.AddLabel("tradesLabel", "No. of Trades:", 5, 70, clrWhite);
gui.AddEdit("tradesEdit", IntegerToString(numberOfTrades), 100, 68, 40);
gui.AddLabel("slippageLabel", "Slippage (points):", 5, 100, clrWhite);
gui.AddEdit("slippageEdit", IntegerToString(currentSlippage), 100, 98, 40);
gui.AddLabel("slLabel", "Stop Loss :", 5, 130, clrWhite);
gui.AddEdit("slEdit", DoubleToString(currentStopLoss, 1), 100, 128, 40);
gui.AddLabel("tpLabel", "Take Profit :", 5, 160, clrWhite);
gui.AddEdit("tpEdit", DoubleToString(currentTakeProfit, 1), 100, 158, 40);
gui.AddLabel("tsLabel", "Trailing Stop :", 5, 190, clrWhite);
gui.AddEdit("tsEdit", DoubleToString(currentTrailingStop, 1), 100, 188, 40);
gui.AddButton("btnBuy", "BUY", 5, 220, 70, 30, clrLime, clrWhite);
gui.AddButton("btnSell", "SELL", 85, 220, 70, 30, clrRed, clrWhite);
gui.AddButton("btnBuySell", "BUY & SELL", 5, 260, 150, 30, clrBlue, clrWhite);
gui.AddLabel("status", "Ready", 5, 270, clrWhite);
// Create volume indicator (unchanged)
volumeIndicator.Create(200, 20, clrBlack, clrLime, clrRed);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
gui.Destroy();
volumeIndicator.Destroy();
}
//+------------------------------------------------------------------+
//| Chart event handler |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
if(id == CHARTEVENT_OBJECT_CLICK)
{
currentLotSize = StringToDouble(gui.GetEditValue("lotEdit"));
numberOfTrades = (int)StringToInteger(gui.GetEditValue("tradesEdit"));
currentSlippage = (int)StringToInteger(gui.GetEditValue("slippageEdit"));
currentStopLoss = StringToDouble(gui.GetEditValue("slEdit"));
currentTakeProfit = StringToDouble(gui.GetEditValue("tpEdit"));
currentTrailingStop = StringToDouble(gui.GetEditValue("tsEdit"));
if(sparam == "TradingPanel_btnBuy")
{
double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_BUY, currentLotSize, price, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
gui.UpdateLabel("status", "Buy order failed", clrRed);
return;
}
}
gui.UpdateLabel("status", "Buy orders executed", clrLime);
}
else if(sparam == "TradingPanel_btnSell")
{
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_SELL, currentLotSize, price, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
gui.UpdateLabel("status", "Sell order failed", clrRed);
return;
}
}
gui.UpdateLabel("status", "Sell orders executed", clrRed);
}
else if(sparam == "TradingPanel_btnBuySell")
{
double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
bool buySuccess = true;
bool sellSuccess = true;
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_BUY, currentLotSize, askPrice, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
buySuccess = false;
break;
}
}
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_SELL, currentLotSize, bidPrice, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
sellSuccess = false;
break;
}
}
if(buySuccess && sellSuccess)
gui.UpdateLabel("status", "Buy & Sell orders executed", clrBlue);
else if (!buySuccess && !sellSuccess)
gui.UpdateLabel("status", "Both Buy & Sell failed", clrRed);
else if (!buySuccess)
gui.UpdateLabel("status", "Buy failed, Sell succeeded", clrOrange);
else
gui.UpdateLabel("status", "Sell failed, Buy succeeded", clrOrange);
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
volumeIndicator.Update();
}
//+------------------------------------------------------------------+
//| ExecuteTrade function: tries last known filling mode or sequence|
//+------------------------------------------------------------------+
bool ExecuteTrade(ENUM_ORDER_TYPE type, double lot, double price, int slippage_points, ulong magic_number,
double stopLossPoints, double takeProfitPoints, double trailingStopPoints)
{
if (lot <= 0 || price <= 0)
{
Print("Invalid trade parameters: lot size = ", lot, ", price = ", price);
return false;
}
MqlTradeRequest request;
MqlTradeResult result;
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
int stopLevelPoints = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
double stopLevel = stopLevelPoints * point;
double sl = 0, tp = 0;
// Calculate SL and TP price with POINTS, only if distance >= stopLevel
if (stopLossPoints > 0)
{
double sl_dist = stopLossPoints * point;
if(sl_dist >= stopLevel)
sl = (type == ORDER_TYPE_BUY) ? price - sl_dist : price + sl_dist;
else
Print("Stop Loss too close. Minimum: ", stopLevelPoints, " points");
}
if (takeProfitPoints > 0)
{
double tp_dist = takeProfitPoints * point;
if(tp_dist >= stopLevel)
tp = (type == ORDER_TYPE_BUY) ? price + tp_dist : price - tp_dist;
else
Print("Take Profit too close. Minimum: ", stopLevelPoints, " points");
}
// Prepare request parameters (same except filling mode)
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot;
request.type = type;
request.price = NormalizeDouble(price, digits);
request.deviation = slippage_points;
request.magic = magic_number;
if(sl>0) request.sl = NormalizeDouble(sl, digits);
if(tp>0) request.tp = NormalizeDouble(tp, digits);
ZeroMemory(result);
// Check if we have a last working filling mode
if(lastWorkingFillingMode >= 0)
{
// Use the last working filling mode directly, no retries
request.type_filling = lastWorkingFillingMode;
if(OrderSend(request, result))
{
Print("Trade executed successfully with cached filling mode ", (int)request.type_filling,
" Order ID: ", result.order);
return true;
}
else
{
Print("Trade failed with cached filling mode ", (int)request.type_filling, ": ", GetRetcodeDescription(result.retcode));
return false;
}
}
else
{
// No cached mode yet, try them in sequence (your original sequence)
ENUM_ORDER_TYPE_FILLING filling_modes[] = {ORDER_FILLING_IOC, ORDER_FILLING_RETURN, ORDER_FILLING_FOK};
for(int i=0; i<ArraySize(filling_modes); i++)
{
request.type_filling = filling_modes[i];
ZeroMemory(result); // reset before each try
if(OrderSend(request, result))
{
Print("Trade executed successfully. Order ID: ", result.order, ", filling mode: ", request.type_filling);
// Cache this filling mode for next trades
lastWorkingFillingMode = filling_modes[i];
return true;
}
else
{
Print("Trade failed with filling mode ", request.type_filling, ": ", GetRetcodeDescription(result.retcode));
}
}
Print("All filling modes failed.");
return false;
}
}
//+------------------------------------------------------------------+
//| Error code translator |
//+------------------------------------------------------------------+
string GetRetcodeDescription(int retcode)
{
switch(retcode)
{
case 10004: return "Requote";
case 10006: return "Order rejected";
case 10007: return "Order canceled";
case 10008: return "Order placed";
case 10009: return "Order completed";
case 10010: return "Order partially completed";
case 10014: return "Invalid volume";
case 10015: return "Invalid price";
case 10016: return "Invalid stops";
case 10017: return "Trade is disabled";
case 10018: return "Market closed";
case 10019: return "No prices";
case 10020: return "Too many requests";
default: return "Unknown error code: " + IntegerToString(retcode);
}
}
//--- rest of the code remains same ---
How this works now:
At first call, because lastWorkingFillingMode is -1, the EA tries IOC, RETURN, FOK sequentially.
When one mode succeeds, lastWorkingFillingMode is set and stored in memory for following calls.
All subsequent trades skip repeated attempts and use the known working filling mode directly, reducing delays and logs.
If for some reason a trade fails with the cached mode later, the EA can optionally be extended to detect failure and reset the cached mode — not implemented here but can be added if needed.
If you want, I can help you extend the error handling further, eg to reset the cached mode on certain failures.
Let me know if you want the complete full code with your classes included or only this updated trade-execution part.
Certainly! Below is the full updated Expert Advisor code including your original GUI and volume indicator classes, with the ExecuteTrade function modified to implement the logic of using the last successful filling mode to speed up order execution and avoid repeated trials.
Key points:
Cached last working filling mode globally in lastWorkingFillingMode.
First run tries all modes sequentially until success.
Afterwards, uses cached mode directly.
Original class definitions and logic remain untouched.
I preserved all your original functionality and formatting.
Full updated code:
mql5
#property strict
//+------------------------------------------------------------------+
//| GUI Panel Class |
//+------------------------------------------------------------------+
class CPanel
{
private:
string m_name;
int m_width;
public:
void Create(string name, int width)
{
m_name = name;
m_width = width;
ObjectCreate(0, m_name, OBJ_RECTANGLE_LABEL, 0, 0, 0);
ObjectSetInteger(0, m_name, OBJPROP_XDISTANCE, 1);
ObjectSetInteger(0, m_name, OBJPROP_YDISTANCE, 20);
//ObjectSetInteger(0, m_name, OBJPROP_XSIZE, width);
ObjectSetInteger(0, m_name, OBJPROP_XSIZE, 300);
ObjectSetInteger(0, m_name, OBJPROP_YSIZE, 275);
ObjectSetInteger(0, m_name, OBJPROP_BGCOLOR, clrBlack);
ObjectSetInteger(0, m_name, OBJPROP_BORDER_TYPE, BORDER_FLAT);
}
void AddLabel(string objName, string text, int x, int y, color clr)
{
ObjectCreate(0, m_name+"_"+objName, OBJ_LABEL, 0, 0, 0);
ObjectSetString(0, m_name+"_"+objName, OBJPROP_TEXT, text);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_XDISTANCE, x);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_YDISTANCE, y);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_COLOR, clr);
}
void AddEdit(string objName, string text, int x, int y, int width)
{
ObjectCreate(0, m_name+"_"+objName, OBJ_EDIT, 0, 0, 0);
ObjectSetString(0, m_name+"_"+objName, OBJPROP_TEXT, text);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_XDISTANCE, x);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_YDISTANCE, y);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_XSIZE, width);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_YSIZE, 20);
}
void AddButton(string objName, string text, int x, int y, int width, int height, color bgColor, color textColor)
{
ObjectCreate(0, m_name+"_"+objName, OBJ_BUTTON, 0, 0, 0);
ObjectSetString(0, m_name+"_"+objName, OBJPROP_TEXT, text);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_XDISTANCE, x);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_YDISTANCE, y);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_XSIZE, width);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_YSIZE, height);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_BGCOLOR, bgColor);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_COLOR, textColor);
}
void UpdateLabel(string objName, string text, color clr)
{
ObjectSetString(0, m_name+"_"+objName, OBJPROP_TEXT, text);
ObjectSetInteger(0, m_name+"_"+objName, OBJPROP_COLOR, clr);
}
string GetEditValue(string objName)
{
return ObjectGetString(0, m_name+"_"+objName, OBJPROP_TEXT);
}
void Destroy()
{
ObjectsDeleteAll(0, m_name);
}
};
//+------------------------------------------------------------------+
//| Volume Indicator Class (Candle Volume Display) |
//+------------------------------------------------------------------+
class CVolumeIndicator
{
private:
// Volume tracking
long buy_volume;
long sell_volume;
long current_candle_buy;
long current_candle_sell;
long maxPositiveDiff;
long maxNegativeDiff;
double basePrice;
double maxUpMove;
double maxDownMove;
// Display settings
int panel_x;
int panel_y;
color panel_color;
color buy_color;
color sell_color;
color diff_color;
int max_candles_to_show;
// Candle tracking
datetime last_candle_time;
double prevPrice;
// Label management
struct CandleData {
long buy;
long sell;
datetime time;
};
CandleData candle_history[];
// Current candle label
string current_candle_label_prefix;
// Movement label
string movementLabelName;
string maxUpMoveLabelName;
string maxDownMoveLabelName;
string moveDiffLabelName;
public:
void Create(int x, int y, color p_color, color b_color, color s_color, int max_candles = 5)
{
panel_x = x;
panel_y = y;
panel_color = p_color;
buy_color = b_color;
sell_color = s_color;
diff_color = clrWhite;
max_candles_to_show = max_candles;
current_candle_label_prefix = "CurrentVol_";
movementLabelName = "MovementLabel";
maxUpMoveLabelName = "MaxUpMoveLabel";
maxDownMoveLabelName = "MaxDownMoveLabel";
moveDiffLabelName = "MoveDiffLabel";
ArrayResize(candle_history, max_candles_to_show);
ResetCounters();
CreateMainPanel();
}
void ResetCounters()
{
buy_volume = 0;
sell_volume = 0;
current_candle_buy = 0;
current_candle_sell = 0;
maxPositiveDiff = 0;
maxNegativeDiff = 0;
basePrice = SymbolInfoDouble(_Symbol, SYMBOL_BID); // Set basePrice once
maxUpMove = 0;
maxDownMove = 0;
last_candle_time = 0;
prevPrice = 0;
// Initialize candle history
for(int i = 0; i < max_candles_to_show; i++)
{
candle_history[i].buy = 0;
candle_history[i].sell = 0;
candle_history[i].time = 0;
}
// Delete any existing current candle labels
ObjectDelete(0, current_candle_label_prefix+"B");
ObjectDelete(0, current_candle_label_prefix+"S");
ObjectDelete(0, current_candle_label_prefix+"D");
}
void CreateMainPanel()
{
// Main panel labels
CreateLabel("BuyVolumeLabel", "Total Buy: 0", panel_x - 50, panel_y, buy_color);
CreateLabel("SellVolumeLabel", "Total Sell: 0", panel_x - 50 , panel_y + 20, sell_color);
CreateLabel("TotalDiffLabel", "Total Diff: +0", panel_x - 50, panel_y + 40, diff_color);
CreateLabel("MaxPosDiffLabel", "Max +Diff: 0", panel_x - 50, panel_y + 60, buy_color);
CreateLabel("MaxNegDiffLabel", "Max -Diff: 0", panel_x - 50, panel_y + 80, sell_color);
CreateLabel(movementLabelName, "Movement: 0", panel_x - 50, panel_y + 100, diff_color);
CreateLabel(maxUpMoveLabelName, "Max Up Move: 0", panel_x - 50, panel_y + 120, buy_color);
CreateLabel(maxDownMoveLabelName, "Max Down Move: 0", panel_x - 50, panel_y + 140, sell_color);
CreateLabel(moveDiffLabelName, "Move Diff: 0", panel_x - 50, panel_y + 160, diff_color);
// Current candle labels
CreateLabel("SepLabel", "----------------------------", panel_x - 40, panel_y + 180, clrSilver);
CreateLabel("CurrentBuyLabel", "Current Candle Buy: 0", panel_x - 30, panel_y + 200, buy_color);
CreateLabel("CurrentSellLabel", "Current Candle Sell: 0", panel_x - 30, panel_y + 220, sell_color);
CreateLabel("CurrentDiffLabel", "Current Diff: +0", panel_x - 30, panel_y + 240, diff_color);
}
void CreateLabel(string name, string text, int x, int y, color clr)
{
ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
ObjectSetString(0, name, OBJPROP_TEXT, text);
ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 9); // change text font size
ObjectSetInteger(0, name, OBJPROP_ANCHOR, CORNER_LEFT_UPPER);
}
void Update()
{
datetime current_time = iTime(_Symbol, PERIOD_CURRENT, 0);
double lastPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Check for new candle
if(current_time != last_candle_time)
{
if(current_candle_buy > 0 || current_candle_sell > 0)
{
// Shift history
for(int i = max_candles_to_show-1; i > 0; i--)
candle_history[i] = candle_history[i-1];
// Store current candle data
candle_history[0].buy = current_candle_buy;
candle_history[0].sell = current_candle_sell;
candle_history[0].time = last_candle_time;
// Update candle displays
UpdateCandleDisplays();
}
// Reset for new candle
current_candle_buy = 0;
current_candle_sell = 0;
last_candle_time = current_time;
// Delete current candle label when new candle starts
ObjectDelete(0, current_candle_label_prefix+"B");
ObjectDelete(0, current_candle_label_prefix+"S");
ObjectDelete(0, current_candle_label_prefix+"D");
}
// Update volumes
if(prevPrice > 0)
{
if(lastPrice > prevPrice)
{
buy_volume++;
current_candle_buy++;
}
else if(lastPrice < prevPrice)
{
sell_volume++;
current_candle_sell++;
}
}
prevPrice = lastPrice;
// Calculate movement in points and pips
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
double movement = (lastPrice - basePrice) / point;
// Update max up and down movement
if (movement > maxUpMove)
maxUpMove = movement;
if (movement < -maxDownMove)
maxDownMove = -movement;
// Update max positive and negative differences
long totalDiff = buy_volume - sell_volume;
if(totalDiff > maxPositiveDiff)
maxPositiveDiff = totalDiff;
if(totalDiff < maxNegativeDiff)
maxNegativeDiff = totalDiff;
// Format labels
string buyText = "Total Buy: " + IntegerToString(buy_volume);
string sellText = "Total Sell: " + IntegerToString(sell_volume);
string diffSign = (buy_volume - sell_volume) >= 0 ? "+" : "";
string diffText = "Total Diff: " + diffSign + IntegerToString(MathAbs(buy_volume - sell_volume));
string maxPosText = "Max +Diff: " + IntegerToString(maxPositiveDiff);
string maxNegText = "Max -Diff: " + IntegerToString(MathAbs(maxNegativeDiff));
string movementText = "Movement: " + DoubleToString(movement, 1) + " points ";
string maxUpMoveText = "Max Up Move: " + DoubleToString(maxUpMove, 1) + " points ";
string maxDownMoveText = "Max Down Move: " + DoubleToString(maxDownMove, 1) + " points ";
string moveDiffText = "Move Diff: " + DoubleToString(maxUpMove + maxDownMove, 1) + " points ";
// Update colors based on difference
if((buy_volume - sell_volume) > 0)
ObjectSetInteger(0, "TotalDiffLabel", OBJPROP_COLOR, buy_color);
else if((buy_volume - sell_volume) < 0)
ObjectSetInteger(0, "TotalDiffLabel", OBJPROP_COLOR, sell_color);
else
ObjectSetInteger(0, "TotalDiffLabel", OBJPROP_COLOR, diff_color);
// Update movement label color based on movement direction
if (movement > 0)
ObjectSetInteger(0, movementLabelName, OBJPROP_COLOR, clrLimeGreen);
else if (movement < 0)
ObjectSetInteger(0, movementLabelName, OBJPROP_COLOR, clrRed);
else
ObjectSetInteger(0, movementLabelName, OBJPROP_COLOR, diff_color);
// Update all labels
ObjectSetString(0, "BuyVolumeLabel", OBJPROP_TEXT, buyText);
ObjectSetString(0, "SellVolumeLabel", OBJPROP_TEXT, sellText);
ObjectSetString(0, "TotalDiffLabel", OBJPROP_TEXT, diffText);
ObjectSetString(0, "MaxPosDiffLabel", OBJPROP_TEXT, maxPosText);
ObjectSetString(0, "MaxNegDiffLabel", OBJPROP_TEXT, maxNegText);
ObjectSetString(0, movementLabelName, OBJPROP_TEXT, movementText);
ObjectSetString(0, maxUpMoveLabelName, OBJPROP_TEXT, maxUpMoveText);
ObjectSetString(0, maxDownMoveLabelName, OBJPROP_TEXT, maxDownMoveText);
ObjectSetString(0, moveDiffLabelName, OBJPROP_TEXT, moveDiffText);
// Update current candle labels
UpdateCurrentCandleDisplay();
// Add label on current candle
DisplayCurrentCandleVolume();
}
void DisplayCurrentCandleVolume()
{
int bar_index = 0; // Current candle
double high = iHigh(_Symbol, PERIOD_CURRENT, bar_index);
datetime time = iTime(_Symbol, PERIOD_CURRENT, bar_index);
// Calculate price position (above candle high)
int window = 0; // Main chart window
// Calculate the x-coordinate based on the chart's properties
int chartWidth = ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
int visibleBars = ChartGetInteger(0, CHART_VISIBLE_BARS);
double timeDiff = (TimeCurrent() - time) / PeriodSeconds(PERIOD_CURRENT);
int x = chartWidth - (int)(timeDiff * chartWidth / visibleBars);
// Introduce offsets to move the label
int x_offset = 50; // Adjust this value to move the label further left or right
int y_offset = 100; // Adjust this value to move the label further up or down
x -= x_offset;
// Convert price to y-coordinate
int y = (int)((ChartGetDouble(0, CHART_PRICE_MAX, window) - high) /
(ChartGetDouble(0, CHART_PRICE_MAX, window) - ChartGetDouble(0, CHART_PRICE_MIN, window)) *
ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, window));
// Adjust y-coordinate with offset
y -= y_offset;
// Calculate difference
long diff = current_candle_buy - current_candle_sell;
string diff_sign = diff >= 0 ? "+" : "";
// Create current candle volume display
CreateSmallLabel(current_candle_label_prefix+"B", "B:"+IntegerToString(current_candle_buy), x, y, buy_color);
CreateSmallLabel(current_candle_label_prefix+"S", "S:"+IntegerToString(current_candle_sell), x, y+15, sell_color);
CreateSmallLabel(current_candle_label_prefix+"D", "D:"+diff_sign+IntegerToString(diff), x, y+30,
diff >= 0 ? buy_color : sell_color);
}
void UpdateCandleDisplays()
{
// Clear existing candle displays
ObjectsDeleteAll(0, "CandleVol_");
// Display volume for each historical candle
for(int i = 0; i < max_candles_to_show; i++)
{
if(candle_history[i].time > 0)
{
DisplayCandleVolume(i, candle_history[i].buy, candle_history[i].sell, candle_history[i].time);
}
}
}
void DisplayCandleVolume(int index, long buy_vol, long sell_vol, datetime candle_time)
{
int bar_index = iBarShift(_Symbol, PERIOD_CURRENT, candle_time);
if(bar_index < 0) return;
double high = iHigh(_Symbol, PERIOD_CURRENT, bar_index);
double low = iLow(_Symbol, PERIOD_CURRENT, bar_index);
datetime time = iTime(_Symbol, PERIOD_CURRENT, bar_index);
// Calculate price position (above candle high)
int window = 0; // Main chart window
// Calculate the x-coordinate based on the chart's properties
int chartWidth = ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
int visibleBars = ChartGetInteger(0, CHART_VISIBLE_BARS);
double timeDiff = (TimeCurrent() - time) / PeriodSeconds(PERIOD_CURRENT);
int x = chartWidth - (int)(timeDiff * chartWidth / visibleBars);
// Introduce offsets to move the label
int x_offset = 50;
int y_offset = 100;
x -= x_offset;
// Convert price to y-coordinate
int y = (int)((ChartGetDouble(0, CHART_PRICE_MAX, window) - high) /
(ChartGetDouble(0, CHART_PRICE_MAX, window) - ChartGetDouble(0, CHART_PRICE_MIN, window)) *
ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, window));
// Adjust y-coordinate with offset
y -= y_offset;
// Calculate difference
long diff = buy_vol - sell_vol;
string diff_sign = diff >= 0 ? "+" : "";
// Create candle volume display
string prefix = "CandleVol_"+IntegerToString(index)+"_";
CreateSmallLabel(prefix+"B", "B:"+IntegerToString(buy_vol), x, y, buy_color);
CreateSmallLabel(prefix+"S", "S:"+IntegerToString(sell_vol), x, y+15, sell_color);
CreateSmallLabel(prefix+"D", "D:"+diff_sign+IntegerToString(diff), x, y+30,
diff >= 0 ? buy_color : sell_color);
}
void CreateSmallLabel(string name, string text, int x, int y, color clr)
{
ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
ObjectSetString(0, name, OBJPROP_TEXT, text);
ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 6);// change font size of counter abave candle stick
ObjectSetInteger(0, name, OBJPROP_ANCHOR, CORNER_LEFT_UPPER);
}
void UpdateCurrentCandleDisplay()
{
long candleDiff = current_candle_buy - current_candle_sell;
string diffSign = candleDiff >= 0 ? "+" : "";
ObjectSetString(0, "CurrentBuyLabel", OBJPROP_TEXT, "Current Candle Buy: "+IntegerToString(current_candle_buy));
ObjectSetString(0, "CurrentSellLabel", OBJPROP_TEXT, "Current Candle Sell: "+IntegerToString(current_candle_sell));
ObjectSetString(0, "CurrentDiffLabel", OBJPROP_TEXT, "Current Diff: "+diffSign+IntegerToString(candleDiff));
ObjectSetInteger(0, "CurrentDiffLabel", OBJPROP_COLOR, candleDiff >= 0 ? buy_color : sell_color);
}
void Destroy()
{
// Delete all objects
string main_labels[] = {
"BuyVolumeLabel", "SellVolumeLabel", "TotalDiffLabel",
"MaxPosDiffLabel", "MaxNegDiffLabel",
"CurrentBuyLabel", "CurrentSellLabel", "CurrentDiffLabel",
"SepLabel", movementLabelName, maxUpMoveLabelName, maxDownMoveLabelName, moveDiffLabelName
};
for(int i = 0; i < ArraySize(main_labels); i++)
ObjectDelete(0, main_labels[i]);
ObjectsDeleteAll(0, "CandleVol_");
ObjectsDeleteAll(0, current_candle_label_prefix);
}
};
//+------------------------------------------------------------------+
//| Global Variables |
//+------------------------------------------------------------------+
CPanel gui;
CVolumeIndicator volumeIndicator;
double currentLotSize = 0.01;
int currentSlippage = 3;
int numberOfTrades = 1;
double currentStopLoss = 0.0;
double currentTakeProfit = 100.0;
double currentTrailingStop = 0.0;
// Cache last working filling mode: -1 means unknown
ENUM_ORDER_TYPE_FILLING lastWorkingFillingMode = (ENUM_ORDER_TYPE_FILLING)(-1);
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Create trading panel
gui.Create("TradingPanel", 180);
gui.AddLabel("title", "Trading Terminal", 5, 20, clrWhite);
gui.AddLabel("lotLabel", "Lot Size:", 5, 40, clrWhite);
gui.AddEdit("lotEdit", DoubleToString(currentLotSize, 2), 100, 38, 40);
gui.AddLabel("tradesLabel", "No. of Trades:", 5, 70, clrWhite);
gui.AddEdit("tradesEdit", IntegerToString(numberOfTrades), 100, 68, 40);
gui.AddLabel("slippageLabel", "Slippage (points):", 5, 100, clrWhite);
gui.AddEdit("slippageEdit", IntegerToString(currentSlippage), 100, 98, 40);
gui.AddLabel("slLabel", "Stop Loss :", 5, 130, clrWhite);
gui.AddEdit("slEdit", DoubleToString(currentStopLoss, 1), 100, 128, 40);
gui.AddLabel("tpLabel", "Take Profit :", 5, 160, clrWhite);
gui.AddEdit("tpEdit", DoubleToString(currentTakeProfit, 1), 100, 158, 40);
gui.AddLabel("tsLabel", "Trailing Stop :", 5, 190, clrWhite);
gui.AddEdit("tsEdit", DoubleToString(currentTrailingStop, 1), 100, 188, 40);
gui.AddButton("btnBuy", "BUY", 5, 220, 70, 30, clrLime, clrWhite);
gui.AddButton("btnSell", "SELL", 85, 220, 70, 30, clrRed, clrWhite);
gui.AddButton("btnBuySell", "BUY & SELL", 5, 260, 150, 30, clrBlue, clrWhite);
gui.AddLabel("status", "Ready", 5, 270, clrWhite);
// Create volume indicator
volumeIndicator.Create(200, 20, clrBlack, clrLime, clrRed);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
gui.Destroy();
volumeIndicator.Destroy();
}
//+------------------------------------------------------------------+
//| Chart event handler |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
if(id == CHARTEVENT_OBJECT_CLICK)
{
currentLotSize = StringToDouble(gui.GetEditValue("lotEdit"));
numberOfTrades = (int)StringToInteger(gui.GetEditValue("tradesEdit"));
currentSlippage = (int)StringToInteger(gui.GetEditValue("slippageEdit"));
currentStopLoss = StringToDouble(gui.GetEditValue("slEdit"));
currentTakeProfit = StringToDouble(gui.GetEditValue("tpEdit"));
currentTrailingStop = StringToDouble(gui.GetEditValue("tsEdit"));
if(sparam == "TradingPanel_btnBuy")
{
double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_BUY, currentLotSize, price, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
gui.UpdateLabel("status", "Buy order failed", clrRed);
return;
}
}
gui.UpdateLabel("status", "Buy orders executed", clrLime);
}
else if(sparam == "TradingPanel_btnSell")
{
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_SELL, currentLotSize, price, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
gui.UpdateLabel("status", "Sell order failed", clrRed);
return;
}
}
gui.UpdateLabel("status", "Sell orders executed", clrRed);
}
else if(sparam == "TradingPanel_btnBuySell")
{
double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
bool buySuccess = true;
bool sellSuccess = true;
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_BUY, currentLotSize, askPrice, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
buySuccess = false;
break;
}
}
for(int i = 0; i < numberOfTrades; i++)
{
if(!ExecuteTrade(ORDER_TYPE_SELL, currentLotSize, bidPrice, currentSlippage, 123456, currentStopLoss, currentTakeProfit, currentTrailingStop))
{
sellSuccess = false;
break;
}
}
if(buySuccess && sellSuccess)
gui.UpdateLabel("status", "Buy & Sell orders executed", clrBlue);
else if (!buySuccess && !sellSuccess)
gui.UpdateLabel("status", "Both Buy & Sell failed", clrRed);
else if (!buySuccess)
gui.UpdateLabel("status", "Buy failed, Sell succeeded", clrOrange);
else
gui.UpdateLabel("status", "Sell failed, Buy succeeded", clrOrange);
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
volumeIndicator.Update();
}
//+------------------------------------------------------------------+
//| ExecuteTrade function with cached filling mode |
//+------------------------------------------------------------------+
bool ExecuteTrade(ENUM_ORDER_TYPE type, double lot, double price, int slippage_points, ulong magic_number,
double stopLossPoints, double takeProfitPoints, double trailingStopPoints)
{
if (lot <= 0 || price <= 0)
{
Print("Invalid trade parameters: lot size = ", lot, ", price = ", price);
return false;
}
MqlTradeRequest request;
MqlTradeResult result;
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
int stopLevelPoints = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
double stopLevel = stopLevelPoints * point;
double sl = 0, tp = 0;
// Calculate SL and TP price with POINTS, only if distance >= stopLevel
if (stopLossPoints > 0)
{
double sl_dist = stopLossPoints * point;
if(sl_dist >= stopLevel)
sl = (type == ORDER_TYPE_BUY) ? price - sl_dist : price + sl_dist;
else
Print("Stop Loss too close. Minimum: ", stopLevelPoints, " points");
}
if (takeProfitPoints > 0)
{
double tp_dist = takeProfitPoints * point;
if(tp_dist >= stopLevel)
tp = (type == ORDER_TYPE_BUY) ? price + tp_dist : price - tp_dist;
else
Print("Take Profit too close. Minimum: ", stopLevelPoints, " points");
}
// Prepare request parameters (same except filling mode)
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot;
request.type = type;
request.price = NormalizeDouble(price, digits);
request.deviation = slippage_points;
request.magic = magic_number;
if(sl>0) request.sl = NormalizeDouble(sl, digits);
if(tp>0) request.tp = NormalizeDouble(tp, digits);
ZeroMemory(result);
// If cached mode available, use it else try all modes sequentially
if(lastWorkingFillingMode >= 0)
{
request.type_filling = lastWorkingFillingMode;
if(OrderSend(request, result))
{
Print("Trade executed successfully with cached filling mode ", (int)request.type_filling,
" Order ID: ", result.order);
return true;
}
else
{
Print("Trade failed with cached filling mode ", (int)request.type_filling, ": ", GetRetcodeDescription(result.retcode));
return false;
}
}
else
{
ENUM_ORDER_TYPE_FILLING filling_modes[] = {ORDER_FILLING_IOC, ORDER_FILLING_RETURN, ORDER_FILLING_FOK};
for(int i=0; i<ArraySize(filling_modes); i++)
{
request.type_filling = filling_modes[i];
ZeroMemory(result); // reset before each try
if(OrderSend(request, result))
{
Print("Trade executed successfully. Order ID: ", result.order, ", filling mode: ", request.type_filling);
// Cache this filling mode for next trades
lastWorkingFillingMode = filling_modes[i];
return true;
}
else
{
Print("Trade failed with filling mode ", request.type_filling, ": ", GetRetcodeDescription(result.retcode));
}
}
Print("All filling modes failed.");
return false;
}
}
//+------------------------------------------------------------------+
//| Error code translator |
//+------------------------------------------------------------------+
string GetRetcodeDescription(int retcode)
{
switch(retcode)
{
case 10004: return "Requote";
case 10006: return "Order rejected";
case 10007: return "Order canceled";
case 10008: return "Order placed";
case 10009: return "Order completed";
case 10010: return "Order partially completed";
case 10014: return "Invalid volume";
case 10015: return "Invalid price";
case 10016: return "Invalid stops";
case 10017: return "Trade is disabled";
case 10018: return "Market closed";
case 10019: return "No prices";
case 10020: return "Too many requests";
default: return "Unknown error code: " + IntegerToString(retcode);
}
}
If you copy-paste this entire file into MetaEditor, compile and run, it will:
Create your GUI and volume display exactly as before.
Manage your trade orders using the better filling-mode detection and caching.
Once a filling mode has been identified as accepted, it uses it directly for fast and clean order execution.
Optional Enhancement (not in this code):
You could add logic to reset lastWorkingFillingMode if orders start failing repeatedly with cached mode, to retry fallback modes. But often not required unless the broker changes conditions.
Feel free to ask if you want me to provide that enhancement or explain how to extend this further!