Pending order behavior under news load: compare notes
Re: Pending order behavior under news load: compare notes
What makes this version pro?
AccessRights.FullAccess: Added at the top to allow the bot to read/write files to your hard drive. cTrader will prompt you to accept this permission when you run it.
Millisecond Timestamps: The CSV logs time down to the exact millisecond (yyyy-MM-dd HH:mm:ss.fff), which is vital for proving exactly when a news gap hit.
Safe File Handling: If you leave the CSV open in Excel while the bot is running, standard bots crash. This one uses a try/catch block so it will print an error to the log, skip that single write, but keep the bot running and tracking seamlessly.
Thread-Safe UI: cTrader requires UI updates to happen on the main thread. The Chart.BeginInvokeOnMainThread wrapper ensures your on-chart dashboard updates smoothly without freezing the platform during high-volatility news events.
AccessRights.FullAccess: Added at the top to allow the bot to read/write files to your hard drive. cTrader will prompt you to accept this permission when you run it.
Millisecond Timestamps: The CSV logs time down to the exact millisecond (yyyy-MM-dd HH:mm:ss.fff), which is vital for proving exactly when a news gap hit.
Safe File Handling: If you leave the CSV open in Excel while the bot is running, standard bots crash. This one uses a try/catch block so it will print an error to the log, skip that single write, but keep the bot running and tracking seamlessly.
Thread-Safe UI: cTrader requires UI updates to happen on the main thread. The Chart.BeginInvokeOnMainThread wrapper ensures your on-chart dashboard updates smoothly without freezing the platform during high-volatility news events.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Pending order behavior under news load: compare notes
Here are the dedicated Expert Advisors (EAs) for both MetaTrader 4 (MQL4) and MetaTrader 5 (MQL5).
Both versions replicate the pro features from cTrader:
Automated CSV Export: Logs timestamp, symbol, order type, expected price, fill price, and slippage in pips.
Mathematical Accuracy: Correctly distinguishes between entry orders (Stops/Limits) and exit triggers (SL/TP), marking positive slippage (price improvement) with + and negative slippage with -.
On-Chart Heads-Up Display (HUD): Displays tracked events, average slippage, best fill, and worst fill in real-time.
Both versions replicate the pro features from cTrader:
Automated CSV Export: Logs timestamp, symbol, order type, expected price, fill price, and slippage in pips.
Mathematical Accuracy: Correctly distinguishes between entry orders (Stops/Limits) and exit triggers (SL/TP), marking positive slippage (price improvement) with + and negative slippage with -.
On-Chart Heads-Up Display (HUD): Displays tracked events, average slippage, best fill, and worst fill in real-time.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Pending order behavior under news load: compare notes
1. MetaTrader 4 (MQL4) — SlippageMonitorPro.mq4
In MT4, an order retains its ticket when a pending order fills into a market position. This script tracks active pending tickets and cached SL/TP targets, comparing them when an execution occurs.
In MT4, an order retains its ticket when a pending order fills into a market position. This script tracks active pending tickets and cached SL/TP targets, comparing them when an execution occurs.
Code: Select all
//+------------------------------------------------------------------+
//| SlippageMonitorPro.mq4 |
//| Real-Time Slippage Analytics |
//+------------------------------------------------------------------+
#property copyright "Trading Research"
#property link ""
#property version "1.00"
#property strict
//--- Input Parameters
input string InpGroupExport = "--- Data Export ---";
input bool EnableCsv = true; // Export to CSV
input string CsvFileName = "NewsSlippage_MT4.csv";// File Name
//--- Internal Caches
struct PendingCache
{
int ticket;
string symbol;
int type;
double target_price;
};
struct PositionCache
{
int ticket;
string symbol;
int type;
double sl;
double tp;
};
PendingCache g_pending[];
PositionCache g_positions[];
//--- Analytics
int g_totalEvents = 0;
double g_totalPips = 0.0;
double g_bestPips = 0.0;
double g_worstPips = 0.0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
EventSetTimer(1);
InitializeCsv();
RefreshCaches();
UpdateHud();
Print("SlippageMonitorPro (MT4) initialized. Tracking account-wide.");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
EventKillTimer();
Comment("");
}
//+------------------------------------------------------------------+
//| Timer function (Checks state every second) |
//+------------------------------------------------------------------+
void OnTimer()
{
CheckExecutions();
}
void OnTick()
{
CheckExecutions();
}
//+------------------------------------------------------------------+
//| Core Detection Engine |
//+------------------------------------------------------------------+
void CheckExecutions()
{
// 1. Check for Pending Order Executions
for(int i = ArraySize(g_pending) - 1; i >= 0; i--)
{
if(OrderSelect(g_pending[i].ticket, SELECT_BY_TICKET, MODE_TRADES))
{
int currentType = OrderType();
// If a pending order transitioned to an open Buy or Sell
if(currentType == OP_BUY || currentType == OP_SELL)
{
double fillPrice = OrderOpenPrice();
double targetPrice = g_pending[i].target_price;
string sym = g_pending[i].symbol;
double pipSize = GetPipSize(sym);
double pips = 0.0;
if(currentType == OP_BUY)
pips = (targetPrice - fillPrice) / pipSize; // Lower buy fill = positive
else
pips = (fillPrice - targetPrice) / pipSize; // Higher sell fill = positive
pips = NormalizeDouble(pips, 1);
string orderName = GetOrderTypeName(g_pending[i].type);
RecordEvent(orderName, sym, targetPrice, fillPrice, pips);
ArrayRemove(g_pending, i, 1);
}
}
else
{
// Order no longer in active pool (cancelled or expired)
ArrayRemove(g_pending, i, 1);
}
}
// 2. Check for SL / TP Exits in Closed History
for(int i = ArraySize(g_positions) - 1; i >= 0; i--)
{
if(!OrderSelect(g_positions[i].ticket, SELECT_BY_TICKET, MODE_TRADES))
{
// Position is no longer open; check history
if(OrderSelect(g_positions[i].ticket, SELECT_BY_TICKET, MODE_HISTORY))
{
double closePrice = OrderClosePrice();
string sym = g_positions[i].symbol;
double pipSize = GetPipSize(sym);
int posType = g_positions[i].type;
// Check if closed by SL
if(g_positions[i].sl > 0 && MathAbs(closePrice - g_positions[i].sl) <= 100 * pipSize)
{
double pips = (posType == OP_BUY) ? (closePrice - g_positions[i].sl) / pipSize
: (g_positions[i].sl - closePrice) / pipSize;
RecordEvent("StopLoss", sym, g_positions[i].sl, closePrice, NormalizeDouble(pips, 1));
}
// Check if closed by TP
else if(g_positions[i].tp > 0 && MathAbs(closePrice - g_positions[i].tp) <= 100 * pipSize)
{
double pips = (posType == OP_BUY) ? (closePrice - g_positions[i].tp) / pipSize
: (g_positions[i].tp - closePrice) / pipSize;
RecordEvent("TakeProfit", sym, g_positions[i].tp, closePrice, NormalizeDouble(pips, 1));
}
}
ArrayRemove(g_positions, i, 1);
}
else
{
// Update SL/TP in case user modified them
g_positions[i].sl = OrderStopLoss();
g_positions[i].tp = OrderTakeProfit();
}
}
RefreshCaches();
}
//+------------------------------------------------------------------+
//| Populate active caches |
//+------------------------------------------------------------------+
void RefreshCaches()
{
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
int type = OrderType();
int ticket = OrderTicket();
if(type >= OP_BUYLIMIT && type <= OP_SELLSTOP)
{
if(!IsTicketInPendingCache(ticket))
{
int size = ArraySize(g_pending);
ArrayResize(g_pending, size + 1);
g_pending[size].ticket = ticket;
g_pending[size].symbol = OrderSymbol();
g_pending[size].type = type;
g_pending[size].target_price = OrderOpenPrice();
}
}
else if(type == OP_BUY || type == OP_SELL)
{
if(!IsTicketInPositionCache(ticket))
{
int size = ArraySize(g_positions);
ArrayResize(g_positions, size + 1);
g_positions[size].ticket = ticket;
g_positions[size].symbol = OrderSymbol();
g_positions[size].type = type;
g_positions[size].sl = OrderStopLoss();
g_positions[size].tp = OrderTakeProfit();
}
}
}
}
}
bool IsTicketInPendingCache(int ticket)
{
for(int i = 0; i < ArraySize(g_pending); i++)
if(g_pending[i].ticket == ticket) return true;
return false;
}
bool IsTicketInPositionCache(int ticket)
{
for(int i = 0; i < ArraySize(g_positions); i++)
if(g_positions[i].ticket == ticket) return true;
return false;
}
//+------------------------------------------------------------------+
//| Record and Display Results |
//+------------------------------------------------------------------+
void RecordEvent(string orderType, string sym, double target, double fill, double pips)
{
g_totalEvents++;
g_totalPips += pips;
if(g_totalEvents == 1) { g_bestPips = pips; g_worstPips = pips; }
else
{
if(pips > g_bestPips) g_bestPips = pips;
if(pips < g_worstPips) g_worstPips = pips;
}
string sign = (pips >= 0) ? "+" : "";
PrintFormat("[%s] %s | Target: %s | Fill: %s | Slippage: %s%.1f pips",
orderType, sym, DoubleToString(target, (int)MarketInfo(sym, MODE_DIGITS)),
DoubleToString(fill, (int)MarketInfo(sym, MODE_DIGITS)), sign, pips);
if(EnableCsv)
{
int handle = FileOpen(CsvFileName, FILE_CSV|FILE_READ|FILE_WRITE, ",");
if(handle != INVALID_HANDLE)
{
FileSeek(handle, 0, SEEK_END);
FileWrite(handle, TimeToStr(TimeCurrent(), TIME_DATE|TIME_SECONDS), sym, orderType,
DoubleToString(target, (int)MarketInfo(sym, MODE_DIGITS)),
DoubleToString(fill, (int)MarketInfo(sym, MODE_DIGITS)),
DoubleToString(pips, 1));
FileClose(handle);
}
}
UpdateHud();
}
void UpdateHud()
{
double avg = (g_totalEvents > 0) ? (g_totalPips / g_totalEvents) : 0.0;
string sign = (avg >= 0) ? "+" : "";
string hud = "\n====================================\n";
hud += " SLIPPAGE ANALYTICS (MT4) \n";
hud += "====================================\n";
hud += StringFormat(" Events Tracked : %d\n", g_totalEvents);
hud += StringFormat(" Avg Slippage : %s%.2f pips\n", sign, avg);
hud += StringFormat(" Best Execution : +%.1f pips\n", g_bestPips);
hud += StringFormat(" Worst Execution: %.1f pips\n", g_worstPips);
hud += "====================================\n";
if(EnableCsv) hud += StringFormat(" Logging to: MQL4/Files/%s\n", CsvFileName);
Comment(hud);
}
void InitializeCsv()
{
if(!EnableCsv) return;
int handle = FileOpen(CsvFileName, FILE_CSV|FILE_READ|FILE_WRITE, ",");
if(handle != INVALID_HANDLE)
{
if(FileSize(handle) == 0)
FileWrite(handle, "Timestamp", "Symbol", "OrderType", "TargetPrice", "FillPrice", "Slippage(Pips)");
FileClose(handle);
}
}
double GetPipSize(string sym)
{
double point = MarketInfo(sym, MODE_POINT);
int digits = (int)MarketInfo(sym, MODE_DIGITS);
return (digits == 3 || digits == 5) ? point * 10 : point;
}
string GetOrderTypeName(int type)
{
switch(type)
{
case OP_BUYLIMIT: return "Buy Limit";
case OP_SELLLIMIT: return "Sell Limit";
case OP_BUYSTOP: return "Buy Stop";
case OP_SELLSTOP: return "Sell Stop";
default: return "Order";
}
}Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Pending order behavior under news load: compare notes
2. MetaTrader 5 (MQL5) — SlippageMonitorPro.mq5
MT5 uses an event-driven trade architecture. The OnTradeTransaction event gives millisecond execution access to incoming deals (DEAL_ENTRY_IN and DEAL_ENTRY_OUT), pulling requested order prices directly from execution history.
MT5 uses an event-driven trade architecture. The OnTradeTransaction event gives millisecond execution access to incoming deals (DEAL_ENTRY_IN and DEAL_ENTRY_OUT), pulling requested order prices directly from execution history.
Code: Select all
//+------------------------------------------------------------------+
//| SlippageMonitorPro.mq5 |
//| Real-Time Slippage Analytics |
//+------------------------------------------------------------------+
#property copyright "Trading Research"
#property link ""
#property version "1.00"
//--- Inputs
input group "--- Data Export ---"
input bool EnableCsv = true; // Export to CSV
input string CsvFileName = "NewsSlippage_MT5.csv"; // File Name
//--- Internal Tracking for Position SL/TP
struct PosTarget
{
ulong ticket;
double sl;
double tp;
};
PosTarget g_posTargets[];
//--- Analytics
int g_totalEvents = 0;
double g_totalPips = 0.0;
double g_bestPips = 0.0;
double g_worstPips = 0.0;
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
InitializeCsv();
UpdatePositionCache();
UpdateHud();
Print("SlippageMonitorPro (MT5) active. Listening for transaction events.");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
Comment("");
}
//+------------------------------------------------------------------+
//| Event-Driven Execution Monitor |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
// Only trigger when an actual order execution deal is added
if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
{
ulong dealTicket = trans.deal;
if(HistoryDealSelect(dealTicket))
{
long entryType = HistoryDealGetInteger(dealTicket, DEAL_ENTRY);
long dealReason = HistoryDealGetInteger(dealTicket, DEAL_REASON);
string symbol = HistoryDealGetString(dealTicket, DEAL_SYMBOL);
double fillPrice = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
long dealType = HistoryDealGetInteger(dealTicket, DEAL_TYPE);
double pipSize = GetPipSize(symbol);
// 1. Entry from a Pending Order (Buy Stop, Buy Limit, Sell Stop, Sell Limit)
if(entryType == DEAL_ENTRY_IN && dealReason == DEAL_REASON_PENDING)
{
ulong orderTicket = trans.order;
if(HistoryOrderSelect(orderTicket))
{
double targetPrice = HistoryOrderGetDouble(orderTicket, ORDER_PRICE_OPEN);
ENUM_ORDER_TYPE orderType = (ENUM_ORDER_TYPE)HistoryOrderGetInteger(orderTicket, ORDER_TYPE);
double pips = 0.0;
if(dealType == DEAL_TYPE_BUY)
pips = (targetPrice - fillPrice) / pipSize; // Lower buy fill = positive
else if(dealType == DEAL_TYPE_SELL)
pips = (fillPrice - targetPrice) / pipSize; // Higher sell fill = positive
RecordEvent(EnumToString(orderType), symbol, targetPrice, fillPrice, NormalizeDouble(pips, 1));
}
}
// 2. Position closed via SL or TP
if(entryType == DEAL_ENTRY_OUT && (dealReason == DEAL_REASON_SL || dealReason == DEAL_REASON_TP))
{
ulong posId = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
double targetPrice = 0.0;
string orderName = (dealReason == DEAL_REASON_SL) ? "StopLoss" : "TakeProfit";
// Retrieve the original target from our cache
for(int i = 0; i < ArraySize(g_posTargets); i++)
{
if(g_posTargets[i].ticket == posId)
{
targetPrice = (dealReason == DEAL_REASON_SL) ? g_posTargets[i].sl : g_posTargets[i].tp;
break;
}
}
if(targetPrice > 0)
{
double pips = 0.0;
// Closing a Buy position means the deal is a SELL: higher fill is positive
if(dealType == DEAL_TYPE_SELL)
pips = (fillPrice - targetPrice) / pipSize;
// Closing a Sell position means the deal is a BUY: lower fill is positive
else if(dealType == DEAL_TYPE_BUY)
pips = (targetPrice - fillPrice) / pipSize;
RecordEvent(orderName, symbol, targetPrice, fillPrice, NormalizeDouble(pips, 1));
}
}
}
}
// Keep SL/TP cache aligned with active positions
UpdatePositionCache();
}
//+------------------------------------------------------------------+
//| Maintain Target Cache for SL and TP |
//+------------------------------------------------------------------+
void UpdatePositionCache()
{
int total = PositionsTotal();
ArrayResize(g_posTargets, total);
for(int i = 0; i < total; i++)
{
ulong ticket = PositionGetTicket(i);
g_posTargets[i].ticket = ticket;
g_posTargets[i].sl = PositionGetDouble(POSITION_SL);
g_posTargets[i].tp = PositionGetDouble(POSITION_TP);
}
}
//+------------------------------------------------------------------+
//| Record and Display Results |
//+------------------------------------------------------------------+
void RecordEvent(string orderType, string sym, double target, double fill, double pips)
{
g_totalEvents++;
g_totalPips += pips;
if(g_totalEvents == 1) { g_bestPips = pips; g_worstPips = pips; }
else
{
if(pips > g_bestPips) g_bestPips = pips;
if(pips < g_worstPips) g_worstPips = pips;
}
string sign = (pips >= 0) ? "+" : "";
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
PrintFormat("[%s] %s | Target: %s | Fill: %s | Slippage: %s%.1f pips",
orderType, sym, DoubleToString(target, digits),
DoubleToString(fill, digits), sign, pips);
if(EnableCsv)
{
int handle = FileOpen(CsvFileName, FILE_CSV|FILE_READ|FILE_WRITE, ",");
if(handle != INVALID_HANDLE)
{
FileSeek(handle, 0, SEEK_END);
FileWrite(handle, TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS), sym, orderType,
DoubleToString(target, digits),
DoubleToString(fill, digits),
DoubleToString(pips, 1));
FileClose(handle);
}
}
UpdateHud();
}
void UpdateHud()
{
double avg = (g_totalEvents > 0) ? (g_totalPips / g_totalEvents) : 0.0;
string sign = (avg >= 0) ? "+" : "";
string hud = "\n====================================\n";
hud += " SLIPPAGE ANALYTICS (MT5) \n";
hud += "====================================\n";
hud += StringFormat(" Events Tracked : %d\n", g_totalEvents);
hud += StringFormat(" Avg Slippage : %s%.2f pips\n", sign, avg);
hud += StringFormat(" Best Execution : +%.1f pips\n", g_bestPips);
hud += StringFormat(" Worst Execution: %.1f pips\n", g_worstPips);
hud += "====================================\n";
if(EnableCsv) hud += StringFormat(" Logging to: MQL5/Files/%s\n", CsvFileName);
Comment(hud);
}
void InitializeCsv()
{
if(!EnableCsv) return;
int handle = FileOpen(CsvFileName, FILE_CSV|FILE_READ|FILE_WRITE, ",");
if(handle != INVALID_HANDLE)
{
if(FileSize(handle) == 0)
FileWrite(handle, "Timestamp", "Symbol", "OrderType", "TargetPrice", "FillPrice", "Slippage(Pips)");
FileClose(handle);
}
}
double GetPipSize(string sym)
{
double point = SymbolInfoDouble(sym, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
return (digits == 3 || digits == 5) ? point * 10.0 : point;
}Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Pending order behavior under news load: compare notes
How to Install and Locate the CSV Files
1.) Open MetaEditor (F4 in MT4 or MT5).
2.) Click New -> Expert Advisor (template), name it SlippageMonitorPro, and click through the wizard.
3.) Paste the code into the file and press Compile (F7).
4.) Drag the EA onto one chart only (it monitors your entire account). Make sure Allow Algorithmic Trading / Allow Live Trading is checked.
5.) Where the CSV is saved:
In MT4: Click File -> Open Data Folder -> MQL4 -> Files -> NewsSlippage_MT4.csv
In MT5: Click File -> Open Data Folder -> MQL5 -> Files -> NewsSlippage_MT5.csv
1.) Open MetaEditor (F4 in MT4 or MT5).
2.) Click New -> Expert Advisor (template), name it SlippageMonitorPro, and click through the wizard.
3.) Paste the code into the file and press Compile (F7).
4.) Drag the EA onto one chart only (it monitors your entire account). Make sure Allow Algorithmic Trading / Allow Live Trading is checked.
5.) Where the CSV is saved:
In MT4: Click File -> Open Data Folder -> MQL4 -> Files -> NewsSlippage_MT4.csv
In MT5: Click File -> Open Data Folder -> MQL5 -> Files -> NewsSlippage_MT5.csv
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Pending order behavior under news load: compare notes
There is a strict technical boundary to understand before using TradingView for this: Pine Script cannot read your live broker's private execution feed. Unlike cTrader or MetaTrader, Pine Script does not have access to your account's order tickets, transaction history, or actual fill prices.
However, we can build a highly effective alternative for your thread: a News Gap & Theoretical Slippage Analyzer.
Because slippage during news is caused by liquidity gaps (price jumping from 1.1000 to 1.1025 without printing the prices in between), we can write a script that scans the raw chart feed (OANDA, FXCM, Pepperstone) to detect these micro-gaps. This script maps exactly how many pips a Stop order would have slipped negatively, or a Limit order would have improved positively,
However, we can build a highly effective alternative for your thread: a News Gap & Theoretical Slippage Analyzer.
Because slippage during news is caused by liquidity gaps (price jumping from 1.1000 to 1.1025 without printing the prices in between), we can write a script that scans the raw chart feed (OANDA, FXCM, Pepperstone) to detect these micro-gaps. This script maps exactly how many pips a Stop order would have slipped negatively, or a Limit order would have improved positively,
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Pending order behavior under news load: compare notes
The Pine Script (v5) Slippage Analyzer
Code: Select all
//@version=5
indicator("Pro News Gap & Slippage Analyzer", overlay=true, max_labels_count=500)
// --- INPUTS ---
grp1 = "Slippage & Gap Settings"
minGapPips = input.float(1.5, title="Minimum Gap (Pips) to Detect", group=grp1, tooltip="Ignores normal tick movement. Only flags jumps larger than this size.")
showLabels = input.bool(true, title="Show Slippage Labels on Chart", group=grp1)
// --- PIP SIZE CALCULATION ---
// Adjusts for Forex 5-digit brokers, Metals, and Indices
pipSize = syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)
// --- GAP DETECTION LOGIC ---
prevClose = close[1]
currOpen = open
gapRaw = currOpen - prevClose
gapPips = gapRaw / pipSize
isGapUp = gapPips >= minGapPips
isGapDown = gapPips <= -minGapPips
isSignificantGap = isGapUp or isGapDown
// --- STATS TRACKING ---
var int totalEvents = 0
var float sumSlippage = 0.0
var float maxGapUp = 0.0
var float maxGapDown = 0.0
if isSignificantGap
totalEvents += 1
sumSlippage += math.abs(gapPips)
if gapPips > maxGapUp
maxGapUp := gapPips
if gapPips < maxGapDown
maxGapDown := gapPips
// --- DRAW CHART LABELS ---
if showLabels
txt = "Gap: " + str.tostring(math.round(math.abs(gapPips), 1)) + " pips\n"
txt += "Stop Slip: -" + str.tostring(math.round(math.abs(gapPips), 1)) + "\n"
txt += "Limit Slip: +" + str.tostring(math.round(math.abs(gapPips), 1))
lblColor = isGapUp ? color.new(color.green, 20) : color.new(color.red, 20)
lblStyle = isGapUp ? label.style_label_down : label.style_label_up
label.new(bar_index, currOpen, text=txt, color=lblColor, style=lblStyle, textcolor=color.white, size=size.small)
// --- HEADS UP DISPLAY (HUD) ---
var table hud = table.new(position.top_right, 2, 6, bgcolor=color.new(#1e222d, 10), border_width=1, border_color=color.gray)
if barstate.islast
// Header
table.cell(hud, 0, 0, "SLIPPAGE & GAP ANALYTICS", text_color=color.rgb(255, 215, 0), text_halign=text.align_center, text_size=size.small)
table.merge_cells(hud, 0, 0, 1, 0)
// Total Events
table.cell(hud, 0, 1, "News Gaps Tracked:", text_color=color.white, text_halign=text.align_left, text_size=size.small)
table.cell(hud, 1, 1, str.tostring(totalEvents), text_color=color.white, text_halign=text.align_right, text_size=size.small)
// Average Slippage
avgGap = totalEvents > 0 ? sumSlippage / totalEvents : 0
table.cell(hud, 0, 2, "Avg Stop Slippage:", text_color=color.white, text_halign=text.align_left, text_size=size.small)
table.cell(hud, 1, 2, "-" + str.tostring(math.round(avgGap, 1)) + " pips", text_color=color.red, text_halign=text.align_right, text_size=size.small)
table.cell(hud, 0, 3, "Avg Limit Slippage:", text_color=color.white, text_halign=text.align_left, text_size=size.small)
table.cell(hud, 1, 3, "+" + str.tostring(math.round(avgGap, 1)) + " pips", text_color=color.green, text_halign=text.align_right, text_size=size.small)
// Extremes
table.cell(hud, 0, 4, "Worst Gap Up:", text_color=color.white, text_halign=text.align_left, text_size=size.small)
table.cell(hud, 1, 4, str.tostring(math.round(maxGapUp, 1)) + " pips", text_color=color.green, text_halign=text.align_right, text_size=size.small)
table.cell(hud, 0, 5, "Worst Gap Down:", text_color=color.white, text_halign=text.align_left, text_size=size.small)
table.cell(hud, 1, 5, str.tostring(math.round(maxGapDown, 1)) + " pips", text_color=color.red, text_halign=text.align_right, text_size=size.small)Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Pending order behavior under news load: compare notes
How to use this for your forum thread
1.) Open TradingView, go to the Pine Editor tab at the bottom, delete the default code, paste this in, and click Add to Chart.
2.) Switch to the 1-second or 5-second timeframe. The higher the timeframe, the less accurate the gap detection is. A 1-minute candle hides the micro-gaps inside of it, but a 1-second chart shows exactly what happened the millisecond CPI data dropped.
3.) Compare Liquidity Providers. This is a massive "cheat code" for a forum thread about broker slippage. In TradingView, you can type the ticker (e.g., EURUSD) and choose different data feeds (OANDA vs. FOREX.com vs. Pepperstone vs. ICE). If you apply this script to the exact same news event across three different brokers' feeds on TradingView, the HUD will objectively show you which broker's order book dried up the most and suffered the worst theoretical slippage.
1.) Open TradingView, go to the Pine Editor tab at the bottom, delete the default code, paste this in, and click Add to Chart.
2.) Switch to the 1-second or 5-second timeframe. The higher the timeframe, the less accurate the gap detection is. A 1-minute candle hides the micro-gaps inside of it, but a 1-second chart shows exactly what happened the millisecond CPI data dropped.
3.) Compare Liquidity Providers. This is a massive "cheat code" for a forum thread about broker slippage. In TradingView, you can type the ticker (e.g., EURUSD) and choose different data feeds (OANDA vs. FOREX.com vs. Pepperstone vs. ICE). If you apply this script to the exact same news event across three different brokers' feeds on TradingView, the HUD will objectively show you which broker's order book dried up the most and suffered the worst theoretical slippage.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
-
LondonScalper
- Posts: 965
- Joined: Sat Sep 05, 2026 7:54 am
Re: Pending order behavior under news load: compare notes
Useful logs — especially the TP and limit rows. I had written “limits fill at the price or not at all” from my own stop-heavy sample, and your CPI take-profit with 2.3 pips of positive slippage is a clean counter-example on a raw ECN book.
Same pattern on your GBPUSD NFP buy limit at +1.1. So I will soften that line: on the raw accounts I use, limits have never filled worse than the price, but they can fill better when the book gaps through. Stops remain the ugly side — your XAUUSD FOMC sell stop at 6.5 pips beyond is worse than anything in my gold notes, and I will add it to the table in the same format.
If you have times in London for those three, I will drop them into the sheet next to mine so the comparison is not just pair and release.
Same pattern on your GBPUSD NFP buy limit at +1.1. So I will soften that line: on the raw accounts I use, limits have never filled worse than the price, but they can fill better when the book gaps through. Stops remain the ugly side — your XAUUSD FOMC sell stop at 6.5 pips beyond is worse than anything in my gold notes, and I will add it to the table in the same format.
If you have times in London for those three, I will drop them into the sheet next to mine so the comparison is not just pair and release.
-
FXS Prop Desk
- Posts: 1689
- Joined: Wed Oct 07, 2026 9:52 am
Re: Pending order behavior under news load: compare notes
That is a good test of broker quality. Readers can check it in their own history: find take-profit fills during gaps or news and compare the fill price with the TP level. If every fill is exactly at the TP level even when price clearly gapped through it, the broker is likely not passing positive slippage, which is worth knowing when comparing execution.PTScalper wrote:Because the only available price (1.1025) is mathematically better than your limit, true ECN/STP brokers pass that price improvement directly to you.
If price improvement never appears, it may be worth asking the broker directly how they handle positive slippage, since their execution policy should describe it.
FXS Official Team | The Idea Lab & Strategy