//+------------------------------------------------------------------+ //| Death_Cross.mq5 | //| MathewCole | //| https://www.ColBekATS | //+------------------------------------------------------------------+ // --- MQL5 Libraries --- #include // we only use simple trade objects #include // --- 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 = 1236; // own magic : keeps Death Cross trades apart from Golden Cross (1235) and SMA Cross (1234) // --- 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) --- int period_slow = 200 ; int period_fast = 50; // --- 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() //+------------------------------------------------------------------+ //| EA Initialization Function | //+------------------------------------------------------------------+ int OnInit(){ // --- 1. Initialize Trade Object --- EventSetTimer(60); Trade.SetExpertMagicNumber(magicnumber); // Unique magic number Trade.SetAsyncMode(true); Trade.SetDeviationInPoints(100); lot_ = 1 ; // --- 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 --- ma_slow_handle = iMA(_Symbol,PERIOD_H1,period_slow ,0,MODE_SMA,PRICE_CLOSE); ma_fast_handle = iMA(_Symbol,PERIOD_H1,period_fast ,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 comment bar --- 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_Bar(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; Update_Info_Bar(); // 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(); TRADE_EXECUTIONS(); Print("Fast < slow ::: ", SELL_signal () ); barsTotal = bars; } } //+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ //+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ //|//////////// ////// ////// ///////////////// SIGNALS /////// ///////////////// ///////////////////////| //+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ //+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ // SELL-side build (Death Cross) : short side only, the long side is disabled in Calc_Lot_Size/ExecuteTrade bool SELL_signal(){ return ( ( ma_fast_buffer[1] < ma_slow_buffer[1]) && PositionsTotal() == 0 ) ; } bool ExitSell(){ return (PositionsTotal() > 0 && ( ma_fast_buffer[1] > ma_slow_buffer[1]) ); } //+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ //+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ //|//////////// ////// ////// ///////////////// TRADE Functions /////// ///////////////// ///////////////////////| //+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ //+---------------------------------------------------------------------------------------------------------------------------------------------------------------- void TRADE_EXECUTIONS(){ if(SELL_signal ()) Enter_Pos(POSITION_TYPE_SELL); // tracking , position if(ExitSell()) Exit_Pos(POSITION_TYPE_SELL); } void Enter_Pos(ENUM_POSITION_TYPE type){ Calc_Lot_Size(type); ExecuteTrade(type); Set_Nums(); /// maybe echnage for on trade } double Calc_Lot_Size( ENUM_POSITION_TYPE type){ if (type != POSITION_TYPE_SELL) return 0.0; // SELL-side build : no long side sl_= NormalizeDouble(ask + 100 * _Point,_Digits); // stop above entry tp_= NormalizeDouble(bid - 100 * _Point,_Digits); // target below entry //lot_ = moneyMan.CheckOpenShort(bid,sl_); // enable for 1% risk sizing 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 = sl_ - ask; // SELL only build : risk sits above entry double reward_dist = bid - tp_; // target sits below entry 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 (type != POSITION_TYPE_SELL) return; // SELL-side build : no long side if (lot_ <= 0.0){ Print("ExecuteTrade: invalid lot_ ", lot_ ); return; } 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) != POSITION_TYPE_SELL) continue; // SELL-side build : leave longs alone if(!Trade.PositionClose(ticket)){ Print("Failed to closed" , " comment "," Ticket: ", ticket, ", Error: ", GetLastError()); }else{ Print("Successfully closed" ," comment "," Ticket: ", ticket); } } } 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_; } //| Apply one deal of this EA (symbol + magic) to the counters | void Track_Deal(const ulong deal_ticket){ if(deal_ticket == 0) return; if(!HistoryDealSelect(deal_ticket)) return; if(HistoryDealGetString(deal_ticket, DEAL_SYMBOL) != _Symbol) return; if(HistoryDealGetInteger(deal_ticket, DEAL_MAGIC) != (long)magicnumber) return; ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(deal_ticket, DEAL_ENTRY); // entry fill -> remember the lot size that was actually sent if(entry == DEAL_ENTRY_IN || entry == DEAL_ENTRY_INOUT){ trades_entries_++; last_lot_ = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME); return; } // closing fill -> one trade is finished, classify its result if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_OUT_BY){ double result = HistoryDealGetDouble(deal_ticket, DEAL_PROFIT) + HistoryDealGetDouble(deal_ticket, DEAL_SWAP) + HistoryDealGetDouble(deal_ticket, DEAL_COMMISSION); trades_closed_++; realized_pnl_ += result; if(result > 0.0) { trades_win_++; total_win_ += result; } else if(result < 0.0) { trades_loss_++; total_loss_ += result; } } } //| Rebuild the counters from account history (restart / recompile) | void Track_Load_History(){ Track_Reset(); if(!HistorySelect(0, TimeCurrent() + 60)){ Print("Track_Load_History: HistorySelect failed, error ", GetLastError()); return; } // collect the tickets first: HistoryDealSelect() inside Track_Deal() reselects a single deal ulong tickets[]; int total = HistoryDealsTotal(); int found = 0; ArrayResize(tickets, total); for(int i = 0; i < total; i++){ ulong ticket = HistoryDealGetTicket(i); if(ticket > 0) tickets[found++] = ticket; } ArrayResize(tickets, found); for(int i = 0; i < found; i++) Track_Deal(tickets[i]); // no history scans after init: counters are kept live by OnTradeTransaction } //| Build and draw the tracking / info comment bar | void Update_Info_Bar(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_ = "=== Death_Cross (SELL only) " + _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()); Comment(info_bar_text_); } //| 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; info_bar_text_ = ""; } //+------------------------------------------------------------------+ //| 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_Bar(true); // repaint the info bar immediately } //+------------------------------------------------------------------+ //| ChartEvent function | //+------------------------------------------------------------------+ void OnChartEvent(const int32_t id, const long &lparam, const double &dparam, const string &sparam) { //--- } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- destroy timer EventKillTimer(); //--- final tracking summary in the Experts log Update_Info_Bar(true); Print("Death_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)); //--- clear the tracking / info comment bar Comment(""); } //+------------------------------------------------------------------+