mql5/Experts/SMA_Cross/SMA_Cross.mq5
2026-11-18 10:43:56 -05:00
//+------------------------------------------------------------------+
//| SMA_Cross.mq5 |
//| MathewCole |
//| https://www.ColBekATS |
//+------------------------------------------------------------------+
// --- MQL5 Libraries ---
#include <Trade\Trade.mqh> // we only use simple trade objects
#include <Expert\Money\MoneyFixedRisk.mqh>
// --- Global Objects ---
CTrade Trade;
CMoneyFixedRisk moneyMan;
CSymbolInfo symbolInfo; // Trade object for sending orders
MqlRates rates[] ;
double bid, ask, spread_ ;
int barsTotal = 0 ;
datetime current_time ;
ulong magicnumber = 1234;
// --- Info panel inputs ---
input bool InpShowPanel = true; // show the tracking panel on the chart
input int InpPanelX = 10; // panel left offset in pixels
input int InpPanelY = 20; // panel top offset in pixels
input bool InpShowKillSwitch = true; // show the bottom-right kill switches
// --- ENUMS for Panel State ---
// 1. Trade Direction
enum ENUM_DIRECTION {
DIR_BUY = ORDER_TYPE_BUY,
DIR_SELL = ORDER_TYPE_SELL,
DIR_BOTH = 2 // Option to use leapfrog mechanic
};
// --- GLOBAL STATE VARIABLES (Managed by Panel) ---
enum ENUM_LOT_MODE { LOT_MODE_VOLUME = 0, LOT_MODE_BALANCE = 1 };
input int InpFastPeriod = 50; // fast SMA period
input int InpSlowPeriod = 200; // slow SMA period
input ENUM_DIRECTION InpDirection = DIR_BOTH; // allowed trade direction (buy / sell / both)
input ENUM_LOT_MODE InpLotMode = LOT_MODE_VOLUME; // lot sizing mode
input double InpFixedLot = 0.10; // volume (lots) when lot mode = volume
input double InpBalancePercent = 1.0; // % of balance when lot mode = balance
// --- Indicator Handles and Buffers ---
int ma_slow_handle, ma_fast_handle;
double ma_slow_buffer[] ,ma_fast_buffer[];
// -------------Stop & Size Tracker vars ----------------
double sl_ , tp_ , lot_;
// ------------- Tracking state for the info comment bar ----------------
// Scope of every counter below: this symbol (_Symbol) + this magic number.
int trades_entries_ = 0; // entries actually filled
int trades_closed_ = 0; // closed trades (round trips)
int trades_win_ = 0; // closed trades with a positive result
int trades_loss_ = 0; // closed trades with a negative result
double total_win_ = 0.0; // sum of winning results, money
double total_loss_ = 0.0; // sum of losing results, money (negative)
double realized_pnl_ = 0.0; // closed PnL = profit + swap + commission
double last_lot_ = 0.0; // volume of the last filled entry
double next_lot_ = 0.0; // volume the next entry will request
double rr_plan_sum_ = 0.0; // summed planned reward/risk at entry
int rr_plan_count_ = 0;
// number of planned R:R samples
string info_bar_text_ = ""; // last text pushed to Comment()
// ------------- Booked round trips (one booking per closed position) -------------
// A trade is booked exactly once, when every opened lot of its position id is
// closed. Ownership is decided on the position (any of its deals carrying our
// symbol + magic), so a closing deal that reports another magic, or a close
// made by SL/TP while the EA was offline, can no longer hide a trade.
long trk_booked_pos_[]; // position ids already added to the counters
int trk_booked_cnt_ = 0; // number of booked ids
datetime trk_zero_time_ = 0; // 0 = whole history, else only trades opened after this moment (RE-ZERO)
//+------------------------------------------------------------------+
//| EA Initialization Function |
//+------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//|//////////// ////// ////// ///////////////// TRACKING / INFO BAR /////// ///////////////// ///////////////////////|
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
int OnInit(){
// --- 1. Initialize Trade Object ---
EventSetTimer(60);
Trade.SetExpertMagicNumber(magicnumber); // Unique magic number
Trade.SetAsyncMode(true);
Trade.SetDeviationInPoints(100);
lot_ = Lot_Size_From_Mode(); // initial size from the inputs
// --- 1b. Initialize money management ---
if(!symbolInfo.Name(_Symbol)) // sets name + refreshes symbol data
return(INIT_FAILED);
if(!moneyMan.Init(GetPointer(symbolInfo), PERIOD_H1, _Point)) // 3 params required
{
Print("CMoneyFixedRisk::Init failed");
return(INIT_PARAMETERS_INCORRECT);
}
moneyMan.Percent(1.0); // risk % of balance
moneyMan.Magic(magicnumber); // keeps the money manager aligned with the EA
if(!moneyMan.ValidationSettings()) // must be the last step
return(INIT_PARAMETERS_INCORRECT);
//Learning built in Money Managment part 1
ArraySetAsSeries(rates , true);
ArraySetAsSeries(ma_slow_buffer , true);
ArraySetAsSeries(ma_fast_buffer ,true);
// --- 2. Initialize Indicators ---
if(InpFastPeriod <= 0 || InpSlowPeriod <= 0 || InpFastPeriod >= InpSlowPeriod){
Print("OnInit: invalid SMA periods (fast ", InpFastPeriod, " / slow ", InpSlowPeriod, ")");
return(INIT_PARAMETERS_INCORRECT);
}
ma_slow_handle = iMA(_Symbol,PERIOD_H1,InpSlowPeriod ,0,MODE_SMA,PRICE_CLOSE);
ma_fast_handle = iMA(_Symbol,PERIOD_H1,InpFastPeriod ,0,MODE_SMA,PRICE_CLOSE);
// --- 3. Check for Valid Indicator Loading ---
if(ma_fast_handle == INVALID_HANDLE || ma_slow_handle == INVALID_HANDLE) {
Print("Error creating SMA handles. Error code: ", GetLastError());
return(INIT_FAILED);
}
// --- 4. Initialize the tracking / info GUI panel ---
Create_Info_Panel(); // frame + captions; the values follow on the first tick
Create_Kill_Panel(); // bottom-right kill switches
Track_Reset();
Track_Load_History(); // rebuild counters from this EA's own deals
next_lot_ = lot_; // sizing is static until Calc_Lot_Size runs again
Update_Info_Panel(true);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick(){
symbolInfo.RefreshRates();
current_time = TimeCurrent();
bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
spread_= ask-bid;
// --- tracking: one reconciliation pass on the first tick -----------
// OnInit can run before the terminal has the whole account history loaded,
// so the counters are rebuilt once more here. Track_Load_History() resets
// every counter first, so this cannot double count a trade.
static bool trk_reconciled = false;
if(!trk_reconciled){
trk_reconciled = true;
Track_Load_History();
}
Update_Info_Panel(true); // live tracking panel, throttled to 1 update / second
CopyRates(_Symbol, PERIOD_CURRENT,1,2, rates); // cheking every tick noot every bar
// Check for new bar
int bars = iBars(_Symbol,PERIOD_CURRENT);
if(barsTotal != bars){
if(CopyBuffer(ma_fast_handle,0,1,2,ma_fast_buffer) < 2) return; // not ready yet, retry next tick
if(CopyBuffer(ma_slow_handle,0,1,2,ma_slow_buffer) < 2) return; // not ready yet, retry next tick
//SIGNAL();
if(ma_fast_buffer[0] == EMPTY_VALUE || ma_slow_buffer[0] == EMPTY_VALUE) return;
if(ma_fast_buffer[1] == EMPTY_VALUE || ma_slow_buffer[1] == EMPTY_VALUE) return;
TRADE_EXECUTIONS();
//Print("Fast > slow ::: ", BUY_signal () );
barsTotal = bars;
}
}
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//|//////////// ////// ////// ///////////////// SIGNALS /////// ///////////////// ///////////////////////|
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//| Golden Cross: fast SMA crosses above the slow SMA (last closed bar) |
bool Golden_Cross(){
// buffer[0] = last closed bar, buffer[1] = the bar before it
return ( ( ma_fast_buffer[0] > ma_slow_buffer[0]) // fast is above now
&& ( ma_fast_buffer[1] <= ma_slow_buffer[1]) // and was at/below before -> a real cross up
) ;
}
//| Death Cross: fast SMA crosses below the slow SMA (last closed bar) |
bool Death_Cross(){
// buffer[0] = last closed bar, buffer[1] = the bar before it
return ( ( ma_fast_buffer[0] < ma_slow_buffer[0]) // fast is below now
&& ( ma_fast_buffer[1] >= ma_slow_buffer[1]) // and was at/above before -> a real cross down
) ;
}
//| Entry signal: golden cross, only while the book is flat |
bool BUY_signal(){
return ( Golden_Cross() && PositionsTotal() == 0
&& (InpDirection == DIR_BOTH || InpDirection == DIR_BUY) );
}
//| Entry signal: death cross, only while the book is flat |
bool SELL_signal(){
return ( Death_Cross() && PositionsTotal() == 0
&& (InpDirection == DIR_BOTH || InpDirection == DIR_SELL) );
}
bool ExitSell(){
return (PositionsTotal() > 0 && Golden_Cross() ); // a golden cross closes the short
}
bool ExitBuy(){
return (PositionsTotal() > 0 && Death_Cross() ); // a death cross closes the long
}
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//|//////////// ////// ////// ///////////////// TRADE Functions /////// ///////////////// ///////////////////////|
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//+----------------------------------------------------------------------------------------------------------------------------------------------------------------
void TRADE_EXECUTIONS(){
// a golden/death cross is the only signal, and it also closes the opposite side
if(ExitBuy()) // death cross: close the long first
Close_Direction(POSITION_TYPE_BUY);
if(ExitSell()) // golden cross -> close the short
Close_Direction(POSITION_TYPE_SELL);
if(BUY_signal ()) // entry only on a fresh golden cross
Enter_Pos(POSITION_TYPE_BUY);
if(SELL_signal ()) // entry only on a fresh death cross
Enter_Pos(POSITION_TYPE_SELL);
}
void Enter_Pos(ENUM_POSITION_TYPE type){
Calc_Lot_Size(type);
ExecuteTrade(type);
Set_Nums(); /// maybe echnage for on trade
}
//| Volume for the selected lot mode, normalised to the symbol |
double Lot_Size_From_Mode(){
double vol = InpFixedLot;
if(InpLotMode == LOT_MODE_BALANCE){
const double balance = AccountInfoDouble(ACCOUNT_BALANCE);
const double tick_val = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
const double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
const double price = (bid > 0.0) ? bid : SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(balance > 0.0 && tick_val > 0.0 && tick_size > 0.0 && price > 0.0){
const double value_per_lot = (tick_val / tick_size) * price; // notional of 1.0 lot
if(value_per_lot > 0.0)
vol = (balance * InpBalancePercent / 100.0) / value_per_lot;
}
}
const double vmin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
const double vmax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
const double vstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
if(vstep > 0.0) vol = MathRound(vol / vstep) * vstep;
if(vol < vmin) vol = vmin;
if(vmax > 0.0 && vol > vmax) vol = vmax;
return NormalizeDouble(vol, 2);
}
double Calc_Lot_Size( ENUM_POSITION_TYPE type){
lot_ = Lot_Size_From_Mode(); // volume or % of balance, per input
if (type == POSITION_TYPE_BUY){
sl_= NormalizeDouble(bid - 100 * _Point,_Digits); // stop below entry
tp_= NormalizeDouble(ask + 100 * _Point,_Digits); // target above entry
//lot_ = moneyMan.CheckOpenLong(ask,sl_);
}else{
sl_= NormalizeDouble(ask + 100 * _Point,_Digits);
tp_= NormalizeDouble(bid - 100 * _Point,_Digits);
//lot_ = moneyMan.CheckOpenShort(ask,sl_);
}
Print("sl_ :::: ", sl_ );
Print("tp_ :::: ", tp_ );
Print("lot_ :::: ", lot_ );
// --- tracking: planned risk:reward of this entry + the lot size of the next one ---
double risk_dist = (type == POSITION_TYPE_BUY) ? (bid - sl_) : (sl_ - ask);
double reward_dist = (type == POSITION_TYPE_BUY) ? (tp_ - ask) : (bid - tp_);
if(risk_dist > 0.0 && reward_dist > 0.0){
rr_plan_sum_ += reward_dist / risk_dist;
rr_plan_count_++;
}
next_lot_ = lot_;
return lot_;
};
void ExecuteTrade(ENUM_POSITION_TYPE type){
if (lot_ <= 0.0){
Print("ExecuteTrade: invalid lot_ ", lot_ );
return;
}
if (type == POSITION_TYPE_BUY)
Trade.Buy(lot_,NULL,ask,0,0);
else
Trade.Sell(lot_,NULL,bid,0,0);
};
void Exit_Pos(ENUM_POSITION_TYPE type){
for(int i = PositionsTotal() - 1; i >= 0; i--){
ulong ticket = PositionGetTicket(i); // also selects position i, no second select needed
if(ticket == 0) continue;
if(PositionGetInteger(POSITION_MAGIC) != magicnumber) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
if(PositionGetInteger(POSITION_TYPE) != type) continue; // Sell + BUY build : close the direction that was requested
if(!Trade.PositionClose(ticket)){
Print("Failed to closed" , " comment "," Ticket: ", ticket, ", Error: ", GetLastError());
}else{
Print("Successfully closed" ," comment "," Ticket: ", ticket);
}
}
}
//| Close one direction synchronously |
// The reversal entry on the same cross needs a flat book: with async
// mode the position would still be listed when the entry is checked.
void Close_Direction(ENUM_POSITION_TYPE type){
Trade.SetAsyncMode(false); // wait for the server answer
Exit_Pos(type);
Trade.SetAsyncMode(true); // restore the EA's asynchronous mode
}
void Set_Nums(){};
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//|//////////// ////// ////// ///////////////// TRACKERS AND INFO ////////// ///////////////// ///////////////////////|
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
//| Floating PnL of the EA positions on this symbol |
double Track_Floating_PnL(){
double pnl = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--){
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetInteger(POSITION_MAGIC) != (long)magicnumber) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
pnl += PositionGetDouble(POSITION_PROFIT) + PositionGetDouble(POSITION_SWAP);
}
return pnl;
}
//| Direction currently held by the EA on this symbol |
string Track_Position_State(){
string state = "FLAT";
for(int i = PositionsTotal() - 1; i >= 0; i--){
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetInteger(POSITION_MAGIC) != (long)magicnumber) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
long type = PositionGetInteger(POSITION_TYPE);
if(type == POSITION_TYPE_BUY) state = "LONG";
else if(type == POSITION_TYPE_SELL) state = "SHORT";
}
return state;
}
//| Average realized risk:reward = average win / average loss |
double Track_Avg_RR_Real(){
if(trades_win_ == 0 || trades_loss_ == 0) return 0.0;
double avg_win = total_win_ / trades_win_;
double avg_loss = MathAbs(total_loss_) / trades_loss_;
if(avg_loss <= 0.0) return 0.0;
return avg_win / avg_loss;
}
//| Average planned risk:reward captured at entry time |
double Track_Avg_RR_Plan(){
if(rr_plan_count_ <= 0) return 0.0;
return rr_plan_sum_ / rr_plan_count_;
}
//| Zero every tracking counter (init and before the history scan) |
void Track_Reset(){
trades_entries_ = 0;
trades_closed_ = 0;
trades_win_ = 0;
trades_loss_ = 0;
total_win_ = 0.0;
total_loss_ = 0.0;
realized_pnl_ = 0.0;
last_lot_ = 0.0;
rr_plan_sum_ = 0.0;
rr_plan_count_ = 0;
trk_booked_cnt_ = 0; // booked ids are dropped too: a rescan rebuilds them
ArrayResize(trk_booked_pos_, 0);
info_bar_text_ = "";
}
//| RE-ZERO: clear the counters and record only what happens from now |
// The cut-off is a time stamp, not a counter reset: every later rebuild
// (first tick, recompile, restart of the scan) keeps ignoring trades that
// were opened before it, so the panel really starts at zero here.
void Track_Zero(){
const datetime now = TimeCurrent();
Track_Reset(); // counters + booked ids back to zero
trk_zero_time_ = now; // everything opened before this is ignored
rr_plan_sum_ = 0.0; // planned R:R restarts with the new session
rr_plan_count_ = 0;
Print("SMA_Cross: panel re-zeroed at ", TimeToString(now, TIME_DATE | TIME_MINUTES),
" - counters now report only what happens from this point on");
Update_Info_Panel(true);
}
//| True when one deal carries this EA's symbol and magic |
bool Track_Deal_Is_Ours(const ulong deal_ticket){
if(deal_ticket == 0) return false;
if(HistoryDealGetString(deal_ticket, DEAL_SYMBOL) != _Symbol) return false;
if(HistoryDealGetInteger(deal_ticket, DEAL_MAGIC) != (long)magicnumber) return false;
return true;
}
//| True when this position id is already booked in the counters |
bool Track_Position_Booked(const long pos_id){
for(int i = 0; i < trk_booked_cnt_; i++)
if(trk_booked_pos_[i] == pos_id) return true;
return false;
}
//| Remember one booked position id (never twice) |
void Track_Mark_Booked(const long pos_id){
if(pos_id <= 0 || Track_Position_Booked(pos_id)) return;
const int size = trk_booked_cnt_ + 1;
if(ArrayResize(trk_booked_pos_, size, 256) != size) return;
trk_booked_pos_[size - 1] = pos_id;
trk_booked_cnt_ = size;
}
//| True when any deal of the position carries our symbol + magic |
// A closing deal may report another magic (manual close, SL/TP, close by):
// the position itself decides ownership, not the single closing deal.
bool Track_Position_Is_Ours(const long pos_id){
if(pos_id <= 0) return false;
if(!HistorySelectByPosition(pos_id)) return false;
const int total = HistoryDealsTotal();
for(int i = 0; i < total; i++)
if(Track_Deal_Is_Ours(HistoryDealGetTicket(i))) return true;
return false;
}
//| Volume tolerance: half a lot step counts as a full match |
double Track_Volume_Epsilon(){
const double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
return (step > 0.0) ? step * 0.5 : 0.0000001;
}
//| Opened / closed volume and money of one position |
bool Track_Position_Totals(const long pos_id, double &in_vol, double &out_vol,
double &money, double &entry_lot, datetime &entry_time){
in_vol = 0.0;
out_vol = 0.0;
money = 0.0;
entry_lot = 0.0;
entry_time = 0;
if(pos_id <= 0) return false;
if(!HistorySelectByPosition(pos_id)) return false;
const int total = HistoryDealsTotal();
if(total <= 0) return false;
for(int i = 0; i < total; i++){
const ulong ticket = HistoryDealGetTicket(i);
if(ticket == 0) continue;
const ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY);
const double vol = HistoryDealGetDouble(ticket, DEAL_VOLUME);
// every deal of the position moves the money: entry commission included
money += HistoryDealGetDouble(ticket, DEAL_PROFIT)
+ HistoryDealGetDouble(ticket, DEAL_SWAP)
+ HistoryDealGetDouble(ticket, DEAL_COMMISSION);
if(entry == DEAL_ENTRY_IN || entry == DEAL_ENTRY_INOUT){
in_vol += vol;
const datetime t = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(t >= entry_time){ entry_time = t; entry_lot = vol; }
}
if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_OUT_BY)
out_vol += vol;
if(entry == DEAL_ENTRY_INOUT) // inout closes the old volume and opens a new one
out_vol += vol;
}
return true;
}
//| Book one position as a closed trade (idempotent, amount safe) |
void Track_Book_Position(const long pos_id){
if(pos_id <= 0) return;
if(Track_Position_Booked(pos_id)) return; // already counted in this run
if(!Track_Position_Is_Ours(pos_id)) return; // not a trade of this EA
double in_vol = 0.0, out_vol = 0.0, money = 0.0, entry_lot = 0.0;
datetime entry_time = 0;
if(!Track_Position_Totals(pos_id, in_vol, out_vol, money, entry_lot, entry_time)) return;
// RE-ZERO cut-off: a position opened before the zero point is not reported
if(trk_zero_time_ > 0 && entry_time < trk_zero_time_) return;
if(out_vol <= 0.0) return; // still open, nothing closed yet
if(out_vol + Track_Volume_Epsilon() < in_vol) return; // partial close, wait for the rest
Track_Mark_Booked(pos_id);
trades_closed_++;
realized_pnl_ += money;
if(money > 0.0) { trades_win_++; total_win_ += money; }
else if(money < 0.0) { trades_loss_++; total_loss_ += money; }
if(entry_lot > 0.0) last_lot_ = entry_lot;
}
//| Widest history window the terminal can give us |
bool Track_History_Select(){
if(HistorySelect(0, TimeCurrent() + 7 * 86400)) return true; // server time may lag the deals
const datetime srv = TimeTradeServer();
if(srv > 0 && HistorySelect(0, srv + 7 * 86400)) return true;
Print("Track_History_Select: HistorySelect failed, error ", GetLastError());
return false;
}
//| Copy the tickets of the selected history into an array |
int Track_History_Tickets(ulong &tickets[]){
const int total = HistoryDealsTotal();
int found = 0;
ArrayResize(tickets, (total > 0) ? total : 0);
for(int i = 0; i < total; i++){
const ulong ticket = HistoryDealGetTicket(i);
if(ticket > 0) tickets[found++] = ticket;
}
ArrayResize(tickets, found);
return found;
}
//| Apply one live deal: ownership by deal, else by position |
void Track_Deal(const ulong deal_ticket){
if(deal_ticket == 0) return;
if(!HistoryDealSelect(deal_ticket)) return;
// read the deal first: the helpers below reselect the history list
const long trk_pos_id = HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
const ENUM_DEAL_ENTRY trk_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(deal_ticket, DEAL_ENTRY);
if(!Track_Deal_Is_Ours(deal_ticket) && !Track_Position_Is_Ours(trk_pos_id)) return; // our deal or our position
// entry fill -> remember the lot size that was actually sent
if(trk_entry == DEAL_ENTRY_IN || trk_entry == DEAL_ENTRY_INOUT){
trades_entries_++;
last_lot_ = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
return;
}
// closing fill -> book the position once every opened lot is closed
if(trk_entry == DEAL_ENTRY_OUT || trk_entry == DEAL_ENTRY_OUT_BY){
Track_Book_Position(trk_pos_id); // one booking per closed position, idempotent
// profit + swap + commission of every deal of this position are summed
// inside Track_Book_Position(), so partial closes cannot hide or duplicate a trade
}
}
//| Rebuild every counter from account history (restart / recompile) |
void Track_Load_History(){
const double rr_sum = rr_plan_sum_; // planned R:R samples come from the live entries,
const int rr_cnt = rr_plan_count_; // history alone cannot rebuild them
Track_Reset(); // everything else is rebuilt from history
rr_plan_sum_ = rr_sum;
rr_plan_count_ = rr_cnt;
if(!Track_History_Select()) return; // widest window the terminal can give us
// tickets are copied first: HistorySelectByPosition() inside the helpers reselects
// the history list, so the loop below must not rely on the outer selection
ulong tickets[];
const int found = Track_History_Tickets(tickets);
long pos_ids[]; // position ids opened by this EA
int pos_cnt = 0;
ArrayResize(pos_ids, (found > 0) ? found : 0);
double last_lot = 0.0;
datetime last_time = 0;
for(int i = 0; i < found; i++){ // pass 1: our entries and every owned position id
const ulong ticket = tickets[i];
if(!Track_Deal_Is_Ours(ticket)) continue; // only the fills of this EA open a trade
const long pos_id = HistoryDealGetInteger(ticket, DEAL_POSITION_ID);
if(pos_id <= 0) continue;
const ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY);
if(entry == DEAL_ENTRY_IN || entry == DEAL_ENTRY_INOUT){
if(trk_zero_time_ == 0 || (datetime)HistoryDealGetInteger(ticket, DEAL_TIME) >= trk_zero_time_) trades_entries_++;
const datetime t = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(t >= last_time && (trk_zero_time_ == 0 || t >= trk_zero_time_)){ last_time = t; last_lot = HistoryDealGetDouble(ticket, DEAL_VOLUME); }
}
bool seen = false;
for(int k = 0; k < pos_cnt; k++) if(pos_ids[k] == pos_id){ seen = true; break; }
if(!seen && pos_cnt < found) pos_ids[pos_cnt++] = pos_id;
}
last_lot_ = last_lot;
// pass 2: book every position this EA opened, money is summed per position
for(int i = 0; i < pos_cnt; i++)
Track_Book_Position(pos_ids[i]);
Print("Track_Load_History: ", found, " deal(s), ", pos_cnt, " position(s) of this EA -> ",
trades_closed_, " closed trade(s), ", trades_win_, " win / ", trades_loss_, " loss, realized ",
DoubleToString(realized_pnl_, 2));
}
//+------------------------------------------------------------------+
//| GUI panel (plain chart objects, no dialog library) |
//+------------------------------------------------------------------+
#define PANEL_PREFIX "SMAC_" // every object below is program owned by this prefix
#define PANEL_ROWS 7 // rows per column
#define PANEL_ROW_H 18 // row pitch in pixels
#define PANEL_TOP 38 // first row offset from the panel top
#define PANEL_WIDTH 430 // panel width in pixels
#define PANEL_HEIGHT 172 // panel height in pixels
//| Create or refresh one panel label (position, colour, text) |
bool Panel_Label(const string name, const int x, const int y,
const string text, const color clr, const int font_size = 9,
const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER){
if(ObjectFind(0, name) < 0){
if(!ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0)){
Print("Panel_Label: cannot create ", name, ", error ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_CORNER, corner);
ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
ObjectSetInteger(0, name, OBJPROP_FONTSIZE, font_size);
ObjectSetString (0, name, OBJPROP_FONT, "Consolas");
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, name, OBJPROP_SELECTED, false);
ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, name, OBJPROP_BACK, false);
}
ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
ObjectSetString (0, name, OBJPROP_TEXT, text);
return true;
}
//| Build the panel frame and the static captions (idempotent) |
void Create_Info_Panel(){
if(!InpShowPanel) return;
const string bg = PANEL_PREFIX + "bg";
if(ObjectFind(0, bg) < 0){
if(!ObjectCreate(0, bg, OBJ_RECTANGLE_LABEL, 0, 0, 0)){
Print("Create_Info_Panel: cannot create background, error ", GetLastError());
return;
}
ObjectSetInteger(0, bg, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, bg, OBJPROP_XDISTANCE, InpPanelX);
ObjectSetInteger(0, bg, OBJPROP_YDISTANCE, InpPanelY);
ObjectSetInteger(0, bg, OBJPROP_XSIZE, PANEL_WIDTH);
ObjectSetInteger(0, bg, OBJPROP_YSIZE, PANEL_HEIGHT);
ObjectSetInteger(0, bg, OBJPROP_BGCOLOR, C'22,26,32');
ObjectSetInteger(0, bg, OBJPROP_BORDER_TYPE, BORDER_FLAT);
ObjectSetInteger(0, bg, OBJPROP_COLOR, C'70,130,180'); // border
ObjectSetInteger(0, bg, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, bg, OBJPROP_BACK, false);
ObjectSetInteger(0, bg, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, bg, OBJPROP_SELECTED, false);
ObjectSetInteger(0, bg, OBJPROP_HIDDEN, true);
// thin divider under the title
const string sep = PANEL_PREFIX + "sep";
ObjectCreate(0, sep, OBJ_RECTANGLE_LABEL, 0, 0, 0);
ObjectSetInteger(0, sep, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, sep, OBJPROP_XDISTANCE, InpPanelX + 8);
ObjectSetInteger(0, sep, OBJPROP_YDISTANCE, InpPanelY + 28);
ObjectSetInteger(0, sep, OBJPROP_XSIZE, PANEL_WIDTH - 16);
ObjectSetInteger(0, sep, OBJPROP_YSIZE, 1);
ObjectSetInteger(0, sep, OBJPROP_BGCOLOR, C'60,72,88');
ObjectSetInteger(0, sep, OBJPROP_BORDER_TYPE, BORDER_FLAT);
ObjectSetInteger(0, sep, OBJPROP_COLOR, C'60,72,88');
ObjectSetInteger(0, sep, OBJPROP_BACK, false);
ObjectSetInteger(0, sep, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, sep, OBJPROP_HIDDEN, true);
}
// left column : performance counters right column : money and risk
const string left_caps[PANEL_ROWS] = {"Trades:", "Wins:", "Losses:", "Win rate:",
"Last lot:", "Next lot:", "Position:"};
const string right_caps[PANEL_ROWS] = {"Total wins:", "Total losses:", "Net realized:",
"PnL position:", "PnL overall:", "Avg R:R real:",
"Avg R:R plan:"};
for(int i = 0; i < PANEL_ROWS; i++){
const int row_y = InpPanelY + PANEL_TOP + i * PANEL_ROW_H;
Panel_Label(PANEL_PREFIX + "l" + IntegerToString(i), InpPanelX + 10, row_y, left_caps[i], C'138,148,162');
Panel_Label(PANEL_PREFIX + "v" + IntegerToString(i), InpPanelX + 105, row_y, "-", clrWhiteSmoke);
Panel_Label(PANEL_PREFIX + "r" + IntegerToString(i), InpPanelX + 215, row_y, right_caps[i], C'138,148,162');
Panel_Label(PANEL_PREFIX + "w" + IntegerToString(i), InpPanelX + 330, row_y, "-", clrWhiteSmoke);
}
}
//| Update the text and colour of one panel value |
void Panel_Value(const string name, const string text, const color clr = clrWhiteSmoke){
if(ObjectFind(0, name) < 0) return; // panel hidden or not created yet
ObjectSetString (0, name, OBJPROP_TEXT, text);
ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
}
//| Push the tracking numbers into the panel |
void Render_Info_Panel(const double floating, const double pnl_total, const double win_rate){
if(!InpShowPanel) return;
const color clr_pos = clrLime; // profit
const color clr_neg = clrTomato; // loss (const only, no side effects)
Panel_Label(PANEL_PREFIX + "title", InpPanelX + 10, InpPanelY + 9,
"SMA_Cross " + _Symbol + " " + EnumToString((ENUM_TIMEFRAMES)_Period)
+ " magic " + IntegerToString((long)magicnumber), clrWhite, 10);
Panel_Value(PANEL_PREFIX + "v0", IntegerToString(trades_closed_));
Panel_Value(PANEL_PREFIX + "v1", IntegerToString(trades_win_), (trades_win_ > 0) ? clr_pos : clrWhiteSmoke);
Panel_Value(PANEL_PREFIX + "v2", IntegerToString(trades_loss_), (trades_loss_ > 0) ? clr_neg : clrWhiteSmoke);
Panel_Value(PANEL_PREFIX + "v3", DoubleToString(win_rate, 1) + " %");
Panel_Value(PANEL_PREFIX + "v4", DoubleToString(last_lot_, 2));
Panel_Value(PANEL_PREFIX + "v5", DoubleToString(next_lot_, 2));
const string state = Track_Position_State();
color state_clr = clrSilver;
if(state == "LONG") state_clr = clrDeepSkyBlue;
if(state == "SHORT") state_clr = clrOrangeRed;
Panel_Value(PANEL_PREFIX + "v6", state, state_clr);
Panel_Value(PANEL_PREFIX + "w0", DoubleToString(total_win_, 2), clr_pos);
Panel_Value(PANEL_PREFIX + "w1", DoubleToString(total_loss_, 2), clr_neg);
Panel_Value(PANEL_PREFIX + "w2", DoubleToString(realized_pnl_, 2), (realized_pnl_ >= 0.0) ? clr_pos : clr_neg);
Panel_Value(PANEL_PREFIX + "w3", DoubleToString(floating, 2), (floating >= 0.0) ? clr_pos : clr_neg);
Panel_Value(PANEL_PREFIX + "w4", DoubleToString(pnl_total, 2), (pnl_total >= 0.0) ? clr_pos : clr_neg);
Panel_Value(PANEL_PREFIX + "w5", DoubleToString(Track_Avg_RR_Real(), 2));
Panel_Value(PANEL_PREFIX + "w6", DoubleToString(Track_Avg_RR_Plan(), 2));
}
//| Remove only the objects owned by this EA (prefix scoped) |
void Destroy_Info_Panel(){
ObjectsDeleteAll(0, PANEL_PREFIX);
}
//+------------------------------------------------------------------+
//| Kill switches (bottom-right strip) |
//| 1) KILL ALL : close every EA position, then remove the EA |
//| 2) STOP EA : remove the EA, open positions stay untouched |
//| 3) CLOSE TRADES : close every EA position, EA keeps running |
//| 4) RE-ZERO : zero the counters, recording restarts from now |
//| Every action needs two clicks inside KILL_CONFIRM_SEC seconds. |
//| Every action needs two clicks inside KILL_CONFIRM_SEC seconds. |
//+------------------------------------------------------------------+
#define KILL_PREFIX "SMAC_kill_" // shares the SMAC_ prefix, so cleanup is shared
#define KILL_BTN_W 108
#define KILL_BTN_H 24
#define KILL_GAP 6
#define KILL_PAD 8
#define KILL_STATUS_H 16
#define KILL_MARGIN_X 12 // distance from the right chart border
#define KILL_MARGIN_Y 28 // distance from the bottom border (keeps the time axis free)
#define KILL_CONFIRM_SEC 5 // seconds allowed between the two clicks
#define KILL_ACTION_ALL 1
#define KILL_ACTION_STOP 2
#define KILL_ACTION_CLOSE 3
#define KILL_ACTION_ZERO 4 // zero the panel counters and restart recording here
int kill_armed_action_ = 0; // 0 = idle, else the action waiting for the 2nd click
datetime kill_armed_until_ = 0; // arm expires after KILL_CONFIRM_SEC
int kill_last_failed_ = 0; // close failures reported by the last kill action
//| Short name of a kill action |
string Kill_Action_Name(const int action){
if(action == KILL_ACTION_ALL) return "KILL ALL";
if(action == KILL_ACTION_STOP) return "STOP EA";
if(action == KILL_ACTION_CLOSE) return "CLOSE TRADES";
if(action == KILL_ACTION_ZERO) return "RE-ZERO";
return "unknown";
}
//| Open positions owned by this EA (symbol + magic only) |
int Count_EA_Positions(){
int count = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--){
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetInteger(POSITION_MAGIC) != (long)magicnumber) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
count++;
}
return count;
}
//| Flatten every position owned by this EA, return the number closed |
int Close_EA_Positions(){
if(PositionsTotal() == 0) return 0;
Trade.SetAsyncMode(false); // wait for each server answer so failures are visible
int closed = 0, failed = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--){
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetInteger(POSITION_MAGIC) != (long)magicnumber) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
double volume = PositionGetDouble(POSITION_VOLUME);
long type = PositionGetInteger(POSITION_TYPE);
if(Trade.PositionClose(ticket)){
closed++;
Print("Kill switch: closed #", ticket, " ", (type == POSITION_TYPE_BUY ? "BUY " : "SELL "),
DoubleToString(volume, 2), " ", _Symbol);
}else{
failed++;
Print("Kill switch: close FAILED #", ticket, " retcode ", Trade.ResultRetcode(),
" (", Trade.ResultComment(), ")");
}
}
Trade.SetAsyncMode(true); // restore the EA's asynchronous execution mode
Print("Kill switch: ", closed, " position(s) closed, ", failed, " failed");
kill_last_failed_ = failed;
Update_Info_Panel(true); // counters and floating PnL just changed
return closed;
}
//| Size of the chart window in pixels (fallback for a detached chart) |
void Kill_Chart_Size(int &width, int &height){
width = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
height = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
if(width <= 0) width = 800;
if(height <= 0) height = 600;
}
//| Strip size in pixels |
int Kill_Panel_Width() { return 2 * KILL_PAD + 4 * KILL_BTN_W + 3 * KILL_GAP; }
int Kill_Panel_Height(){ return 2 * KILL_PAD + KILL_BTN_H + 6 + KILL_STATUS_H; }
//| Glue every kill-switch object to the lower-right chart corner |
// All objects are anchored at CORNER_LEFT_UPPER with absolute pixel
// offsets taken from the real chart size, so the strip cannot end up
// outside the visible area and follows a window resize.
void Kill_Panel_Layout(){
const string bg = KILL_PREFIX + "bg";
if(ObjectFind(0, bg) < 0) return; // strip not created yet
int width = 0, height = 0;
Kill_Chart_Size(width, height);
const int left = MathMax(0, width - Kill_Panel_Width() - KILL_MARGIN_X);
const int top = MathMax(0, height - Kill_Panel_Height() - KILL_MARGIN_Y);
const int btn_y = top + KILL_PAD;
ObjectSetInteger(0, bg, OBJPROP_XDISTANCE, left);
ObjectSetInteger(0, bg, OBJPROP_YDISTANCE, top);
ObjectSetInteger(0, KILL_PREFIX + "b1", OBJPROP_XDISTANCE, left + KILL_PAD);
ObjectSetInteger(0, KILL_PREFIX + "b1", OBJPROP_YDISTANCE, btn_y);
ObjectSetInteger(0, KILL_PREFIX + "b2", OBJPROP_XDISTANCE, left + KILL_PAD + (KILL_BTN_W + KILL_GAP));
ObjectSetInteger(0, KILL_PREFIX + "b2", OBJPROP_YDISTANCE, btn_y);
ObjectSetInteger(0, KILL_PREFIX + "b3", OBJPROP_XDISTANCE, left + KILL_PAD + 2 * (KILL_BTN_W + KILL_GAP));
ObjectSetInteger(0, KILL_PREFIX + "b3", OBJPROP_YDISTANCE, btn_y);
ObjectSetInteger(0, KILL_PREFIX + "b4", OBJPROP_XDISTANCE, left + KILL_PAD + 3 * (KILL_BTN_W + KILL_GAP));
ObjectSetInteger(0, KILL_PREFIX + "b4", OBJPROP_YDISTANCE, btn_y);
ObjectSetInteger(0, KILL_PREFIX + "status", OBJPROP_XDISTANCE, left + KILL_PAD);
ObjectSetInteger(0, KILL_PREFIX + "status", OBJPROP_YDISTANCE, btn_y + KILL_BTN_H + 6);
}
//| Create or refresh one kill-switch button |
bool Kill_Button(const string name, const int x, const int y, const string text,
const color bg, const color txt, const int font_size = 8){
// a stale object of another type would block creation and stay invisible
if(ObjectFind(0, name) >= 0 && ObjectGetInteger(0, name, OBJPROP_TYPE) != OBJ_BUTTON)
ObjectDelete(0, name);
if(ObjectFind(0, name) < 0){
if(!ObjectCreate(0, name, OBJ_BUTTON, 0, 0, 0)){
Print("Kill_Button: cannot create ", name, ", error ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, name, OBJPROP_XSIZE, KILL_BTN_W);
ObjectSetInteger(0, name, OBJPROP_YSIZE, KILL_BTN_H);
ObjectSetInteger(0, name, OBJPROP_FONTSIZE, font_size);
ObjectSetString (0, name, OBJPROP_FONT, "Arial");
ObjectSetInteger(0, name, OBJPROP_BORDER_COLOR, C'18,18,18');
ObjectSetInteger(0, name, OBJPROP_BACK, false);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, name, OBJPROP_SELECTED, false);
ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, name, OBJPROP_ZORDER, 10);
}
ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
ObjectSetInteger(0, name, OBJPROP_BGCOLOR, bg);
ObjectSetInteger(0, name, OBJPROP_COLOR, txt);
ObjectSetString (0, name, OBJPROP_TEXT, text);
return true;
}
//| Build the kill-switch strip in the lower right corner (idempotent) |
void Create_Kill_Panel(){
if(!InpShowKillSwitch) return;
const int panel_w = Kill_Panel_Width();
const int panel_h = Kill_Panel_Height();
int chart_w = 0, chart_h = 0;
Kill_Chart_Size(chart_w, chart_h);
const int left = MathMax(0, chart_w - panel_w - KILL_MARGIN_X); // pixels from the left border
const int top = MathMax(0, chart_h - panel_h - KILL_MARGIN_Y); // pixels from the top border
const string kill_bg = KILL_PREFIX + "bg";
if(ObjectFind(0, kill_bg) >= 0 && ObjectGetInteger(0, kill_bg, OBJPROP_TYPE) != OBJ_RECTANGLE_LABEL)
ObjectDelete(0, kill_bg); // a stale object of another type would block creation
const string bg = KILL_PREFIX + "bg";
if(ObjectFind(0, bg) < 0){
if(!ObjectCreate(0, bg, OBJ_RECTANGLE_LABEL, 0, 0, 0)){
Print("Create_Kill_Panel: cannot create background, error ", GetLastError());
return;
}
ObjectSetInteger(0, bg, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, bg, OBJPROP_XDISTANCE, left);
ObjectSetInteger(0, bg, OBJPROP_YDISTANCE, top);
ObjectSetInteger(0, bg, OBJPROP_XSIZE, panel_w);
ObjectSetInteger(0, bg, OBJPROP_YSIZE, panel_h);
ObjectSetInteger(0, bg, OBJPROP_BGCOLOR, C'22,26,32');
ObjectSetInteger(0, bg, OBJPROP_BORDER_TYPE, BORDER_FLAT);
ObjectSetInteger(0, bg, OBJPROP_COLOR, C'120,60,60'); // danger border
ObjectSetInteger(0, bg, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, bg, OBJPROP_BACK, false);
ObjectSetInteger(0, bg, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, bg, OBJPROP_HIDDEN, true);
}
const int btn_y = top + KILL_PAD;
Kill_Button(KILL_PREFIX + "b1", left + KILL_PAD, btn_y,
"KILL ALL", C'150,45,45', clrWhite);
Kill_Button(KILL_PREFIX + "b2", left + KILL_PAD + (KILL_BTN_W + KILL_GAP), btn_y,
"STOP EA", C'150,95,30', clrWhite);
Kill_Button(KILL_PREFIX + "b3", left + KILL_PAD + 2 * (KILL_BTN_W + KILL_GAP), btn_y,
"CLOSE TRADES", C'110,105,35', clrWhite);
Kill_Button(KILL_PREFIX + "b4", left + KILL_PAD + 3 * (KILL_BTN_W + KILL_GAP), btn_y,
"RE-ZERO", C'45,85,140', clrWhite);
Panel_Label(KILL_PREFIX + "status", left + KILL_PAD, btn_y + KILL_BTN_H + 6,
"", C'150,160,175', 8, CORNER_LEFT_UPPER);
Update_Kill_Panel();
}
//| Refresh button captions, the confirm prompt and the position count |
void Update_Kill_Panel(){
if(!InpShowKillSwitch) return;
if(ObjectFind(0, KILL_PREFIX + "bg") < 0) return; // panel not created yet
Kill_Panel_Layout(); // re-glue the strip: the chart may have been resized
// drop an armed request once the confirmation window is over
if(kill_armed_action_ != 0 && TimeCurrent() > kill_armed_until_){
kill_armed_action_ = 0;
kill_armed_until_ = 0;
}
Panel_Value(KILL_PREFIX + "b1", (kill_armed_action_ == KILL_ACTION_ALL) ? "KILL ALL ?" : "KILL ALL", clrWhite);
Panel_Value(KILL_PREFIX + "b2", (kill_armed_action_ == KILL_ACTION_STOP) ? "STOP EA ?" : "STOP EA", clrWhite);
Panel_Value(KILL_PREFIX + "b3", (kill_armed_action_ == KILL_ACTION_CLOSE) ? "CLOSE ?" : "CLOSE TRADES", clrWhite);
Panel_Value(KILL_PREFIX + "b4", (kill_armed_action_ == KILL_ACTION_ZERO) ? "RE-ZERO ?" : "RE-ZERO", clrWhite);
if(kill_armed_action_ != 0){
const int left_sec = (int)(kill_armed_until_ - TimeCurrent());
Panel_Value(KILL_PREFIX + "status",
"Confirm " + Kill_Action_Name(kill_armed_action_)
+ " - click again (" + IntegerToString(left_sec) + " s)", clrGold);
}else{
Panel_Value(KILL_PREFIX + "status",
"EA positions: " + IntegerToString(Count_EA_Positions())
+ ((trk_zero_time_ > 0) ? (" since " + TimeToString(trk_zero_time_, TIME_MINUTES)) : "")
+ " - double-click to confirm", C'150,160,175');
}
}
//| Run a confirmed kill action |
void Kill_Execute(const int action){
Print("Kill switch: executing ", Kill_Action_Name(action));
// KILL_ACTION_ZERO : counters only - no position is touched
if(action == KILL_ACTION_ZERO){
Track_Zero(); // panel back to zero, recording starts now
Update_Kill_Panel();
return;
}
if(action == KILL_ACTION_STOP){
ExpertRemove(); // EA stops, the open positions are left as they are
return;
}
if(action == KILL_ACTION_ALL){
const int closed = Close_EA_Positions(); // flatten first, then stop the EA for good
if(kill_last_failed_ > 0){
// never remove the EA while one of its positions is still open and unmanaged
Print("Kill switch: ", kill_last_failed_,
" position(s) could not be closed - EA kept running, retry the kill");
Update_Kill_Panel();
return;
}
Print("Kill switch: flat, ", closed, " position(s) closed - removing the EA");
ExpertRemove();
return;
}
// KILL_ACTION_CLOSE : flatten the EA but keep it attached and running
const int closed = Close_EA_Positions();
Print("Kill switch: CLOSE TRADES done - ", closed, " closed, ", kill_last_failed_,
" failed, EA stays attached");
Update_Kill_Panel();
}
//| Chart event dispatch for the kill-switch buttons |
void Kill_On_Event(const int32_t event_id, const string obj_name){
if(!InpShowKillSwitch) return;
if(event_id != CHARTEVENT_OBJECT_CLICK) return;
if(StringFind(obj_name, KILL_PREFIX) != 0) return; // not one of our objects
int action = 0;
if(obj_name == KILL_PREFIX + "b1") action = KILL_ACTION_ALL;
else if(obj_name == KILL_PREFIX + "b2") action = KILL_ACTION_STOP;
else if(obj_name == KILL_PREFIX + "b3") action = KILL_ACTION_CLOSE;
else if(obj_name == KILL_PREFIX + "b4") action = KILL_ACTION_ZERO;
if(action == 0) return;
ObjectSetInteger(0, obj_name, OBJPROP_STATE, false); // release the pressed look
// first click arms, second click inside KILL_CONFIRM_SEC executes
if(kill_armed_action_ != action || TimeCurrent() > kill_armed_until_){
kill_armed_action_ = action;
kill_armed_until_ = TimeCurrent() + KILL_CONFIRM_SEC;
Print("Kill switch armed: ", Kill_Action_Name(action), " - click again within ",
KILL_CONFIRM_SEC, " s");
Update_Kill_Panel();
return;
}
kill_armed_action_ = 0;
kill_armed_until_ = 0;
Kill_Execute(action);
}
//| Update entry point: gather the numbers and repaint the GUI panel |
void Update_Info_Panel(const bool force = false){
static datetime last_update_ = 0;
datetime now = TimeCurrent();
if(!force && now == last_update_) return; // refresh at most once per second
last_update_ = now;
double floating = Track_Floating_PnL();
double pnl_total = realized_pnl_ + floating;
double win_rate = (trades_closed_ > 0) ? (100.0 * trades_win_ / trades_closed_) : 0.0;
info_bar_text_ = "=== SMA_Cross " + _Symbol + " " + EnumToString((ENUM_TIMEFRAMES)_Period)
+ " | magic " + IntegerToString((long)magicnumber) + " ===\n";
info_bar_text_ += StringFormat("Trades: %d Wins: %d Losses: %d Win rate: %.1f %%\n",
trades_closed_, trades_win_, trades_loss_, win_rate);
info_bar_text_ += StringFormat("Total wins: %s Total losses: %s Net realized: %s\n",
DoubleToString(total_win_, 2),
DoubleToString(total_loss_, 2),
DoubleToString(realized_pnl_, 2));
info_bar_text_ += StringFormat("Last lot: %s Next lot: %s Entries: %d\n",
DoubleToString(last_lot_, 2),
DoubleToString(next_lot_, 2),
trades_entries_);
info_bar_text_ += StringFormat("PnL position: %s PnL overall (EA): %s\n",
DoubleToString(floating, 2),
DoubleToString(pnl_total, 2));
info_bar_text_ += StringFormat("Avg R:R realized: %s planned: %s Position: %s",
DoubleToString(Track_Avg_RR_Real(), 2),
DoubleToString(Track_Avg_RR_Plan(), 2),
Track_Position_State());
if(trk_zero_time_ > 0)
info_bar_text_ += "\nRecording since: " + TimeToString(trk_zero_time_, TIME_DATE | TIME_MINUTES)
+ " (RE-ZERO)";
// info_bar_text_ is kept as the plain-text copy of the same numbers: it is set as
// the panel tooltip, so hovering the frame still shows entries and the raw block.
if(InpShowPanel){
Create_Info_Panel(); // first call builds the frame
Render_Info_Panel(floating, pnl_total, win_rate); // then only the values change
ObjectSetString(0, PANEL_PREFIX + "bg", OBJPROP_TOOLTIP, info_bar_text_);
}
// keep the kill strip in sync even when the stats panel is switched off
if(InpShowKillSwitch){
Update_Kill_Panel(); // captions + confirm window countdown
}
}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer()
{}
//+------------------------------------------------------------------+
//| Trade function |
//+------------------------------------------------------------------+
void OnTrade()
{}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
//| Trade transaction function (active tracking of fills and closes) |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
if(trans.type != TRADE_TRANSACTION_DEAL_ADD) return; // only real deals change the counters
if(trans.deal == 0) return;
Track_Deal(trans.deal); // entry / exit bookkeeping
Update_Info_Panel(true); // repaint the info bar immediately
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int32_t id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- keep the kill strip in the lower-right corner after a window resize
if(id == CHARTEVENT_CHART_CHANGE){
Update_Kill_Panel();
return;
}
//--- dispatch the kill-switch buttons (and any future chart objects)
Kill_On_Event(id, sparam);
Kill_On_Event(id, sparam);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
//--- final tracking summary in the Experts log
Update_Info_Panel(true);
Print("SMA_Cross final tracking | trades: ", trades_closed_,
" wins: ", trades_win_,
" losses: ", trades_loss_,
" total wins: ", DoubleToString(total_win_, 2),
" total losses: ", DoubleToString(total_loss_, 2),
" realized: ", DoubleToString(realized_pnl_, 2),
" last lot: ", DoubleToString(last_lot_, 2),
" avg RR planned: ", DoubleToString(Track_Avg_RR_Plan(), 2));
//--- remove the tracking panel (program-owned objects only)
Destroy_Info_Panel();
}
//+------------------------------------------------------------------+