| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301 |
- //+------------------------------------------------------------------+
- //| Pulse_EA_project_MT5.mq5 |
- //| Copyright 2024, MQL Development |
- //| https://www.mqldevelopment.com/ |
- //+------------------------------------------------------------------+
- #property copyright "Copyright 2024, MQL Development"
- #property link "https://www.mqldevelopment.com/"
- #property version "1.00"
-
- #include <Trade\Trade.mqh>
- CTrade trade;
-
- #define MaxOrders 10000
-
- struct new_trade_store
- {
- int trade_ticket;
- int trade_type;
- int trade_magic_no;
- double trade_open_price;
- double trade_close_price;
- datetime trade_open_time;
- datetime trade_close_time;
- double trade_sl;
- double trade_tp;
- double trade_lot;
- double trade_profit;
-
- new_trade_store()
- {
- trade_ticket = -1;
- trade_type = -1;
- trade_magic_no = -1;
- trade_open_price = -1;
- trade_close_price = -1;
- trade_open_time = -1;
- trade_close_time = -1;
- trade_sl = -1;
- trade_tp = -1;
- trade_lot = -1;
- trade_profit = -1;
- }
-
- };
- new_trade_store od[MaxOrders];
-
- enum trade_typ
- {
- buy, // Buy
- reverse, // Reverse
- };
- enum EA_TYPE
- {
- Tally_Sim, // Tally Sim
- Tally_Trade, // Tally Trade
- };
-
- input string gnrlsettings = " ================ General Settings =================== ";//_
- input EA_TYPE eaType = Tally_Sim; // EA Option
- input double tpPips = 20; // Tp Pips
- input double slPips = 20; // SL Pips
- input double lot = 0.1; // Lot Size
-
- input string gnrlesettings = " ================ Tally Sim Settings =================== ";//_
- trade_typ ordTyp = buy; // Order Type (Tally Sim)
- input int magicNo = 123; // Magic #
- input string fileName = "TradeDataFile"; // File Name (Tally Sim)
-
- input string grlesettings = " ================ Tally Trade Settings =================== ";//_
- input trade_typ tradesDirection = buy; // Order Type (Tally Trade)
- input int magicNo1 = 1; // Copy Trade Magic #
- input bool CopyTallyTrade = true; // Enable Copy Trade
- input double glTp = 20; // Copy Take Profit
- input double glSl = 10; // Copy Stop Loss
-
- input string Settings6 = "------------- Display Settings -------------"; //_
- input int tradeLineThickness = 2; // Trade Line Thickness
- input int dollarFontSize = 10; // Dollar Text Font Size
- input color dollarFontColor = clrAqua; // Dollar Text Font Colour
- input string horizontalLineName = "close"; // Horizontal Line Name
-
- input string Settings5 = "------------- Time Filter Settings -------------"; //_
- input bool enableTimeFilter = false; // Enable Time Filter
- input string startTime = "22:00"; // Start Time
- input string endTime = "01:00"; // End Time
- input bool useFridayClose = false; // Use Friday Close
- input string closeFriday = "23:00"; // Friday Close Time
- input bool useMondayOpen = false; // Use Monday Open
- input string mondayOpen = "01:00"; // Monday Open Time
-
- input string Settings25 = "------------- Daily Draw Limit Settings -------------"; //_
- input bool UseDailyDrawdownLimit = true; // Enable Daily Draw Down
- input double DailyDrawdownAmount = 2000; // $2000 limit
- input string DrawdownResetTime = "05:00"; // Enable Trading At
-
- input string indSettings = " ================ Indicator Settings =================== ";//_
- input color Dot_Color = clrOrangeRed;
- input double StartingBalance = 10000;
- input string MagicNumbers = "123";
- input int MA_Period = 5;
- input ENUM_MA_METHOD MA_Method = MODE_SMA;
- input string fileName1 = "TradeDataFile"; // File Name
- input int historyTrades = 50;
-
-
- bool tpSlHit = false;
- int ticketAssigner = 1;
- int handler;
- double bufferData[];
-
- ushort u_sep; // The code of the separator character
- string sep = ":"; // A separator as a character
- string result1[];
- datetime startTradingTime = 0, endTradingTime = 0, dailyDrawDownTime = 0;
-
- datetime mondayTradingStart = 0, fridayTradingClose = 0;
- datetime eaStartTime; // Store EA start time
- double g_dailyStartBalance;
- bool enableTradingDaily = true;
- bool doTrading = true;
- int prevOrderCount = 0;
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- string filename = fileName + Symbol() + ".csv";
- //+------------------------------------------------------------------+
- //| Expert initialization function |
- //+------------------------------------------------------------------+
- int OnInit()
- {
- //---
- if(eaType == Tally_Sim)
- {
- FileDelete(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END);
- int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END,",");
-
- if(filehandle != INVALID_HANDLE)
- {
- FileClose(filehandle);
- }
- }
- else
- {
- prevOrderCount = orderCount();
- }
-
- string typ = eaType == 0 ? "Tally Sim" :"Tally Trade";
- Comment(" Current Mode: ",typ);
-
- tpSlHit = false;
- doTrading = true;
- ticketAssigner = 1;
-
- if(eaType == Tally_Trade)
- {
- ArrayInitialize(bufferData,0.0);
- handler = iCustom(Symbol(),PERIOD_CURRENT,"Pulse Balance Indicator Sim",Dot_Color,StartingBalance,MagicNumbers,MA_Period,MA_Method,fileName1,historyTrades);
- ArraySetAsSeries(bufferData,true);
- }
-
- trade.SetExpertMagicNumber(magicNo1);
- trade.SetDeviationInPoints(10);
- trade.SetTypeFilling(ORDER_FILLING_IOC);
- trade.LogLevel(LOG_LEVEL_ALL);
- trade.SetAsyncMode(false);
-
-
- setStart_EndTime_modify(true,startTime,endTime,startTradingTime,endTradingTime);
- setStart_EndTime(true,startTime,endTime,startTradingTime,endTradingTime);
-
-
- g_dailyStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
- enableTradingDaily = true;
- eaStartTime = TimeCurrent(); // Track EA start time
- //---
- return(INIT_SUCCEEDED);
- }
- //+------------------------------------------------------------------+
- //| Expert deinitialization function |
- //+------------------------------------------------------------------+
- void OnDeinit(const int reason)
- {
- //---
- Comment("");
- }
- //+------------------------------------------------------------------+
- //| Expert tick function |
- //+------------------------------------------------------------------+
- void OnTick()
- {
- //---
-
- doTrading = true;
-
- timeConversion();
-
- if(TimeCurrent() >= dailyDrawDownTime && enableTradingDaily == false)
- {
- enableTradingDaily = true;
- }
- if(eaType == Tally_Trade)
- {
- markClosedOrder(eaStartTime);
- CheckVirtualGlobalTpSl();
- }
- if(eaType == Tally_Sim)
- checkTPSLHit();
-
- newBar();
-
- if(newDayBar())
- {
- g_dailyStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
- }
-
- MqlDateTime dt;
- TimeToStruct(TimeCurrent(), dt);
-
-
- if(useMondayOpen)
- {
- if(dt.day_of_week == 1 && TimeCurrent() < mondayTradingStart) // it's Monday
- {
- doTrading = false;
- }
- }
- if(useFridayClose)
- {
- if(dt.day_of_week == 5 && TimeCurrent() >= fridayTradingClose) // it's Friday
- {
- doTrading = false;
- closeAllActiveOrders();
- }
- }
-
- setStart_EndTime_modify(false,startTime,endTime,startTradingTime,endTradingTime);
- setStart_EndTime(false,startTime,endTime,startTradingTime,endTradingTime);
-
- if(enableTimeFilter && TimeCurrent() >= startTradingTime && TimeCurrent() < endTradingTime)
- {
- return;
- }
-
- placeTrade();
-
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool newBar()
- {
- static datetime lastbar;
- datetime curbar = iTime(Symbol(), PERIOD_CURRENT, 0);
- if(lastbar != curbar)
- {
- lastbar = curbar;
- Print(" ---------------------- New Bar :: ---------------------- ",lastbar);
- return (true);
- }
- else
- {
- return (false);
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool newDayBar()
- {
- static datetime lastbar1;
- datetime curbar1 = iTime(Symbol(), PERIOD_D1, 0);
- if(lastbar1 != curbar1)
- {
- lastbar1 = curbar1;
- Print(" ---------------------- New Day Bar :: ---------------------- ",lastbar1);
- return (true);
- }
- else
- {
- return (false);
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void closeAllActiveOrders()
- {
- for(int i=PositionsTotal()-1; i >=0 ; i--)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- if(PositionGetInteger(POSITION_MAGIC) == magicNo &&
- PositionGetString(POSITION_SYMBOL) == Symbol())
- {
- if(trade.PositionClose(ticket))
- {
- Print("Closing All Active Orders");
- Print("Position closed ", ticket);
- }
- else
- {
- Print("Cannot close order: ",GetLastError());
- }
- }
- }
- }
-
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void timeConversion()
- {
- MqlDateTime date1, date_1,date_2;
-
- TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date1);
- u_sep=StringGetCharacter(sep,0);
- StringSplit(mondayOpen,u_sep,result1);
- date1.hour = (int)StringToInteger(result1[0]);
- date1.min = (int)StringToInteger(result1[1]);
- mondayTradingStart = StructToTime(date1);
-
- TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date_1);
- StringSplit(closeFriday,u_sep,result1);
- date_1.hour = (int)StringToInteger(result1[0]);
- date_1.min = (int)StringToInteger(result1[1]);
- fridayTradingClose = StructToTime(date_1);
-
- TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date_2);
- StringSplit(DrawdownResetTime,u_sep,result1);
- date_2.hour = (int)StringToInteger(result1[0]);
- date_2.min = (int)StringToInteger(result1[1]);
- dailyDrawDownTime = StructToTime(date_2);
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void placeTrade()
- {
- if(tpSlHit == false || eaType == Tally_Trade)
- {
- if(ordTyp == buy)
- {
- placeBuyTrade();
- }
- if(ordTyp == reverse)
- {
- placeSellTrade();
- }
- tpSlHit = true;
- }
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void placeBuyTrade()
- {
- double buySl = 0,buyTp=0;
- double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
-
- if(slPips != 0)
- {
- buySl = Ask - (slPips * Point() * 10);
- }
- if(tpPips != 0)
- {
- buyTp = Ask + (tpPips * Point() * 10);
- }
-
- if(eaType == Tally_Sim)
- {
- AddToStructure(ticketAssigner,0,magicNo,Ask,0,TimeCurrent(),0,buySl,buyTp,lot,0);
- ticketAssigner++;
- DrawVirtualBuyOpen(Ask);
- }
- else
- {
-
- int count = orderCount();
- if(prevOrderCount != count && count != -1)
- {
-
- for(int k = prevOrderCount + 1;k <= count;k++)
- {
- getTicketByNumber(k,buySl,buyTp);
-
- if(enableTradingDaily == true && doTrading == true)
- {
- if(eaType == Tally_Trade && CopyTallyTrade)
- {
- if(CopyBuffer(handler, 0, 0, 4, bufferData) < 0)
- {
- Print("Error in copying Buffer data ", GetLastError());
- }
-
- double balance = bufferData[1];
-
- if(CopyBuffer(handler, 1, 0, 4, bufferData) < 0)
- {
- Print("Error in copying Buffer data ", GetLastError());
- }
-
- double MA = bufferData[1];
-
- Print(" Balance = ",balance," MA = ",MA);
-
- if(tradesDirection == buy)
- {
- if(balance > MA)
- {
- if(!trade.Buy(lot, Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_ASK),buySl,buyTp,"Buy Trade"))
- {
- Print(" Error in Placing Buy Trade : ",GetLastError());
- }
- }
- else
- {
- Print(" Trade is not Placed because Balance is less than MA Value ");
- }
- }
- else
- {
- if(balance < MA)
- {
- if(!trade.Sell(lot,Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_BID),buyTp,buySl,"Sell Trade"))
- {
- Print(" Error in Placing Sell Trade : ",GetLastError());
- }
- }
- else
- {
- Print(" Trade is not Placed because Balance is less than MA Value ");
- }
- }
- }
- }
- }
- prevOrderCount = count;
- }
- }
-
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void placeSellTrade()
- {
-
- double sellSl = 0, sellTp = 0;
- double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
-
- if(slPips != 0)
- {
- sellSl = Bid + (slPips * 10 * Point());
- }
- if(tpPips != 0)
- {
- sellTp = Bid - (tpPips * 10 * Point());
- }
- if(eaType == Tally_Sim)
- {
- AddToStructure(ticketAssigner,1,magicNo,Bid,0,TimeCurrent(),0,sellSl,sellTp,lot,0);
-
- ticketAssigner++;
- }
- else
- {
-
- int count = orderCount();
-
- if(prevOrderCount != count && count != -1)
- {
-
- for(int k = prevOrderCount + 1;k <= count;k++)
- {
- getTicketByNumber(k,sellSl,sellTp);
- if(enableTradingDaily == true)
- {
- if(eaType == Tally_Trade && CopyTallyTrade)
- {
- if(CopyBuffer(handler, 0, 0, 4, bufferData) < 0)
- {
- Print("Error in copying Buffer data ", GetLastError());
- }
-
- double balance = bufferData[1];
-
- if(CopyBuffer(handler, 1, 0, 4, bufferData) < 0)
- {
- Print("Error in copying Buffer data ", GetLastError());
- }
-
- double MA = bufferData[1];
-
- Print(" Balance = ",balance," MA = ",MA);
-
- if(tradesDirection == reverse)
- {
- if(balance < MA)
- {
- if(!trade.Sell(lot,Symbol(),Bid,sellSl,sellTp,"Sell Trade"))
- {
- Print(" Error in Placing Sell Trade : ",GetLastError());
- }
- }
- else
- {
- Print(" Trade is not Placed because Balance is less than MA Value ");
- }
- }
- else
- {
- if(balance > MA)
- {
- if(!trade.Buy(lot,Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_ASK),sellTp,sellSl,"Buy Trade"))
- {
- Print(" Error in Placing Buy Trade : ",GetLastError());
- }
- }
- else
- {
- Print(" Trade is not Placed because Balance is less than MA Value ");
- }
- }
- }
- }
- }
- prevOrderCount = count;
- }
- }
-
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void AddToStructure(int ticket, int type, int magic, double open_price,
- double close_price, datetime open_time, datetime close_time,
- double sl, double tp, double lotSize, double profit)
- {
- for(int i = 0; i < MaxOrders; i++)
- {
- if(od[i].trade_ticket == -1)
- {
-
- od[i].trade_ticket = ticket;
- od[i].trade_type = type;
- od[i].trade_magic_no = magic;
- od[i].trade_open_price = open_price;
- od[i].trade_close_price = close_price;
- od[i].trade_open_time = open_time;
- od[i].trade_close_time = close_time;
- od[i].trade_sl = sl;
- od[i].trade_tp = tp;
- od[i].trade_lot = lotSize;
- od[i].trade_profit = profit;
-
- Print(" ========== Trade Placed of Ticket ========== ",ticket);
- Print("[AddToStructure] Added at index: ", i,
- " | Ticket = ", ticket,
- " | Type = ", type,
- " | Magic = ", magic,
- " | OpenPrice = ", open_price,
- " | ClosePrice = ", close_price,
- " | SL = ", sl,
- " | TP = ", tp,
- " | Lots = ", lotSize,
- " | Profit = ", profit);
-
- break;
- }
- }
- }
-
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void checkTPSLHit()
- {
-
- double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
- double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
-
- for(int i = 0; i < MaxOrders; i++)
- {
- if(od[i].trade_ticket != -1 && od[i].trade_close_price == 0)
- {
-
- int ticket = od[i].trade_ticket;
- int type = od[i].trade_type;
- double sl = od[i].trade_sl;
- double tp = od[i].trade_tp;
-
- double closePrice = 0;
-
- // ----------------------------------------------
- // BUY ORDER CHECK
- // ----------------------------------------------
- if(type == 0)
- {
- // TP hit → Bid >= TP
- if(bid >= tp && tp > 0)
- {
- closePrice = bid;
- Print(" ======== Buy Trade TP Hit ======= ",ticket);
- }
-
- // SL hit → Bid <= SL
- if(bid <= sl && sl > 0)
- {
- closePrice = bid;
- Print(" ======== Buy Trade SL Hit ======= ",ticket);
- }
- }
-
- // ----------------------------------------------
- // SELL ORDER CHECK
- // ----------------------------------------------
- if(type == 1)
- {
- // TP hit → Ask <= TP (price goes DOWN)
- if(ask <= tp && tp > 0)
- {
- closePrice = ask;
- Print(" ======== Sell Trade TP Hit ======= ",ticket);
- }
-
- // SL hit → Ask >= SL
- if(ask >= sl && sl > 0)
- {
- closePrice = ask;
- Print(" ======== Sell Trade SL Hit ======= ",ticket);
- }
- }
-
- // ----------------------------------------------
- // IF ANYTHING TRIGGERED → CLOSE TRADE
- // ----------------------------------------------
- if(closePrice > 0)
- {
-
- od[i].trade_close_price = closePrice;
- od[i].trade_close_time = TimeCurrent();
-
- double tpdifference = type == 1 ? (od[i].trade_open_price - od[i].trade_close_price) / Point() : (od[i].trade_close_price - od[i].trade_open_price) / Point();
-
- od[i].trade_profit += tpinDollar(od[i].trade_lot, tpdifference);
-
- Print("======= TRADE CLOSED of ticket =======",ticket);
- Print("Index: ", i,
- " | Ticket: ", ticket,
- " | Type: ", type,
- " | ClosePrice: ", closePrice,
- " | Time: ", od[i].trade_close_time,
- " | Profit: ", od[i].trade_profit);
-
- DrawVirtualBuyClose(closePrice);
-
- datetime t1 = od[i].trade_open_time;
- double price1 = od[i].trade_open_price;
-
- datetime t2 = od[i].trade_close_time;
- double price2 = od[i].trade_close_price;
-
- DrawDottedTrendline("Ticket "+string(ticket), t1, price1, t2, price2, clrGreen);
-
- tpSlHit = false; // make these zero so new trade place's
-
-
- string line = MakeTradeString(
- od[i].trade_ticket,
- od[i].trade_type,
- od[i].trade_magic_no,
- od[i].trade_open_price,
- od[i].trade_close_price,
- od[i].trade_open_time,
- od[i].trade_close_time,
- od[i].trade_sl,
- od[i].trade_tp,
- od[i].trade_lot,
- od[i].trade_profit
- );
-
- writeDatainFile(line);
-
- }
- }
- }
- }
-
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- double tpinDollar(double lotSize, double distance)
- {
-
- double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
- pipvalue = pipvalue / 10;
- double dollar = lotSize * distance * pipvalue;
- return NormalizeDouble(dollar,2);
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void writeDatainFile(string str)
- {
-
- int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END,",");
-
- if(filehandle != INVALID_HANDLE)
- {
-
- FileSeek(filehandle, 0, SEEK_END);
- FileWrite(filehandle,str);
- Print(str);
-
- FileClose(filehandle);
- }
-
-
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- string MakeTradeString(int ticket, int type, int magic,
- double open_price, double close_price,
- datetime open_time, datetime close_time,
- double sl, double tp, double lotSize, double profit)
- {
- string str = StringFormat("%d,%d,%d,%.5f,%.5f,%s,%s,%.5f,%.5f,%.2f,%.2f",
- ticket,
- type,
- magic,
- open_price,
- close_price,
- TimeToString(open_time, TIME_DATE|TIME_SECONDS),
- TimeToString(close_time, TIME_DATE|TIME_SECONDS),
- sl,
- tp,
- lotSize,
- profit);
-
- return str;
- }
-
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void setStart_EndTime(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
- {
-
- int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
-
- datetime newYorkStartTrading,newYorkEndTrading;
-
- string time[];
- StringSplit(start,':',time);
- newYorkStartHour = (int)StringToInteger(time[0]);
- newYorkStartMin = (int)StringToInteger(time[1]);
-
- EventSetMillisecondTimer(500);
- time[0] = "";
- time[1] = "";
- StringSplit(end,':',time);
- newYorkEndHour = (int)StringToInteger(time[0]);
- newYorkEndMin = (int)StringToInteger(time[1]);
-
- // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
- // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
-
-
- datetime startDateTime;
- MqlDateTime st;
- TimeCurrent(st); // get current date
- st.hour = newYorkStartHour;
- st.min = newYorkStartMin;
- st.sec = 0;
- startDateTime = StructToTime(st);
-
-
- datetime endDateTime;
- MqlDateTime et;
- TimeCurrent(et); // get current date
- et.hour = newYorkEndHour;
- et.min = newYorkEndMin;
- et.sec = 0;
- endDateTime = StructToTime(et);
-
-
- MqlDateTime sdate,edate;
- datetime start_Time = 0, end_Time = 0;
- if(startDateTime > endDateTime)
- {
- if(onInit)
- {
- start_Time = iTime(Symbol(),PERIOD_D1,1);
- end_Time = iTime(Symbol(),PERIOD_D1,0);
- }
- else
- {
- start_Time = sessionStart;
- end_Time = sessionEnd;
- if(TimeCurrent() >= sessionEnd && sessionEnd != 0)
- {
- start_Time = iTime(Symbol(),PERIOD_D1,0);
- end_Time = start_Time + 86400;
- }
- }
- }
- else
- {
- start_Time = iTime(Symbol(),PERIOD_D1,0);
- end_Time = iTime(Symbol(),PERIOD_D1,0);
- }
-
- if(TimeToStruct(end_Time,edate))
- {
- edate.hour = newYorkEndHour;
- edate.min = newYorkEndMin;
- edate.sec = 0;
- }
- else
- Print("Error in Converting Time: ",GetLastError());
- newYorkEndTrading = StructToTime(edate);
-
- if(TimeToStruct(start_Time,sdate))
- {
- sdate.hour = newYorkStartHour;
- sdate.min = newYorkStartMin;
- sdate.sec = 0;
- }
- else
- Print("Error in Converting Time: ",GetLastError());
- newYorkStartTrading = StructToTime(sdate);
-
- sessionStart = newYorkStartTrading;
- sessionEnd = newYorkEndTrading;
-
-
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void setStart_EndTime_modify(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
- {
-
- int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
-
- datetime newYorkStartTrading,newYorkEndTrading;
-
- string time[];
- StringSplit(start,':',time);
- newYorkStartHour = (int)StringToInteger(time[0]);
- newYorkStartMin = (int)StringToInteger(time[1]);
-
- time[0] = "";
- time[1] = "";
- StringSplit(end,':',time);
- newYorkEndHour = (int)StringToInteger(time[0]);
- newYorkEndMin = (int)StringToInteger(time[1]);
-
- // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
- // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
-
- datetime startDateTime;
- MqlDateTime st;
- TimeCurrent(st); // get current date
- st.hour = newYorkStartHour;
- st.min = newYorkStartMin;
- st.sec = 0;
- startDateTime = StructToTime(st);
-
-
- datetime endDateTime;
- MqlDateTime et;
- TimeCurrent(et); // get current date
- et.hour = newYorkEndHour;
- et.min = newYorkEndMin;
- et.sec = 0;
- endDateTime = StructToTime(et);
-
-
- MqlDateTime sdate,edate;
- datetime start_Time = 0, end_Time = 0;
- if(startDateTime > endDateTime)
- {
- start_Time = iTime(Symbol(),PERIOD_D1,1);
- end_Time = iTime(Symbol(),PERIOD_D1,0);
-
- }
- else
- {
- start_Time = iTime(Symbol(),PERIOD_D1,0);
- end_Time = iTime(Symbol(),PERIOD_D1,0);
- }
-
- if(TimeToStruct(end_Time,edate))
- {
- edate.hour = newYorkEndHour;
- edate.min = newYorkEndMin;
- edate.sec = 0;
- }
- else
- Print("Error in Converting Time: ",GetLastError());
- newYorkEndTrading = StructToTime(edate);
-
- if(TimeToStruct(start_Time,sdate))
- {
- sdate.hour = newYorkStartHour;
- sdate.min = newYorkStartMin;
- sdate.sec = 0;
- }
- else
- Print("Error in Converting Time: ",GetLastError());
- newYorkStartTrading = StructToTime(sdate);
-
- sessionStart = newYorkStartTrading;
- sessionEnd = newYorkEndTrading;
-
- }
-
-
- //+------------------------------------------------------------------+
- //| Check Virtual TP/SL for all positions |
- //+------------------------------------------------------------------+
- void CheckVirtualGlobalTpSl()
- {
-
- double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
- double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
-
- for(int i=PositionsTotal()-1; i >=0 ; i--)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- if(PositionGetInteger(POSITION_MAGIC) == magicNo &&
- PositionGetString(POSITION_SYMBOL) == _Symbol)
- {
- if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
- {
- double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) + glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
- double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) - glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
-
- if(bid >= tp_price || bid <= sl_price)
- {
- closeAllActiveOrders();
- return;
- }
- }
- if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
- {
- double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) - glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
- double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) + glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
-
- if(ask <= tp_price || ask >= sl_price)
- {
- closeAllActiveOrders();
- return;
- }
- }
- }
- }
- }
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void CheckDailyDrawdown()
- {
- if(!UseDailyDrawdownLimit)
- return;
-
- double equity = AccountInfoDouble(ACCOUNT_EQUITY);
- double drawdown = g_dailyStartBalance - equity;
-
- if(drawdown >= DailyDrawdownAmount)
- {
- Print("Daily Drawdown Limit Hit: ", drawdown, " >= ", DailyDrawdownAmount);
- closeAllActiveOrders();
- }
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void markClosedOrder(datetime eaTime)
- {
- HistorySelect(eaTime, TimeCurrent());
-
- for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
- {
- ulong dealTicket = HistoryDealGetTicket(i);
-
- long dealMagic = HistoryDealGetInteger(dealTicket, DEAL_MAGIC);
- if(dealMagic != magicNo && dealMagic != 0)
- continue;
-
- if(HistoryDealGetString(dealTicket, DEAL_SYMBOL) == Symbol())
- {
- //Print("Condition 2 ",HistoryDealGetInteger(dealTicket, DEAL_ENTRY)," HistoryDealsTotal(): ",HistoryDealsTotal());
- if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
- {
- //Print("deal out close: ",dealTicket);
- long dealType = HistoryDealGetInteger(dealTicket, DEAL_TYPE);
- if(dealType != DEAL_TYPE_BUY && dealType != DEAL_TYPE_SELL)
- continue;
-
- double profit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
- profit = NormalizeDouble(profit, 2);
-
- string lineName = "TradeLine_" + (string)dealTicket;
- if(ObjectFind(0, lineName) >= 0)
- continue;
-
- ulong entryDeal = findEntryDeal(dealTicket);
- if(entryDeal == 0)
- continue;
-
- datetime openTime = (datetime)HistoryDealGetInteger(entryDeal, DEAL_TIME);
- double openPrice = HistoryDealGetDouble(entryDeal, DEAL_PRICE);
- datetime closeTime = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);
- double closePrice = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
-
- createTrendLine(lineName, openTime, openPrice, closeTime, closePrice, dealType, profit);
- PrintFormat("Trend line created for closed trade #%I64u | Profit: %.2f", dealTicket, profit);
- }
- }
-
- }
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void createTrendLine(string name,
- datetime openTime, double openPrice,
- datetime closeTime, double closePrice,
- long dealType, double profit)
- {
- if(ObjectFind(0, name) >= 0)
- return;
-
- if(!ObjectCreate(0, name, OBJ_TREND, 0, openTime, openPrice, closeTime, closePrice))
- {
- Print("Error creating trend line: ", GetLastError());
- return;
- }
-
- ObjectSetInteger(0, name, OBJPROP_WIDTH, tradeLineThickness);
- ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
- ObjectSetInteger(0, name, OBJPROP_RAY, false);
-
- color lineColor = (dealType == DEAL_TYPE_BUY) ? clrRed : clrBlue;
- ObjectSetInteger(0, name, OBJPROP_COLOR, lineColor);
-
- createProfitLabel(name + "_label", openTime, openPrice, closeTime, closePrice, dealType, profit);
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void createProfitLabel(string name,
- datetime openTime, double openPrice,
- datetime closeTime, double closePrice,
- long dealType, double profit)
- {
- if(ObjectFind(0, name) >= 0)
- return;
-
- datetime middleTime = openTime + (closeTime - openTime) / 2;
- double midPrice = (openPrice + closePrice) / 2;
-
- if(!ObjectCreate(0, name, OBJ_TEXT, 0, middleTime, midPrice))
- {
- Print("Error creating profit label: ", GetLastError());
- return;
- }
-
- string profitText = "$" + DoubleToString(profit, 2);
- ObjectSetString(0, name, OBJPROP_TEXT, profitText);
- ObjectSetInteger(0, name, OBJPROP_FONTSIZE, dollarFontSize);
- ObjectSetInteger(0, name, OBJPROP_COLOR, dollarFontColor);
- ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_TOP);
- ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- ulong findEntryDeal(ulong closeDeal)
- {
- string symbol = HistoryDealGetString(closeDeal, DEAL_SYMBOL);
- long positionID = HistoryDealGetInteger(closeDeal, DEAL_POSITION_ID);
- int dealOutCount = 0;
- for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
- {
- ulong deal = HistoryDealGetTicket(i);
- if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID)
- {
- if(HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
- {
- dealOutCount++;
- }
- }
- }
- if(dealOutCount < 2)
- {
- for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
- {
- ulong deal = HistoryDealGetTicket(i);
-
- if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
- HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_IN &&
- HistoryDealGetString(deal, DEAL_SYMBOL) == symbol)
- return deal;
- //Print("Deal: ", deal);
- }
- }
- else
- {
- for(int i = 0; i < HistoryDealsTotal(); i++)
- {
- ulong deal = HistoryDealGetTicket(i);
-
- if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
- HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
- {
- return deal;
- }
- //Print("Deal: ", deal);
- }
- }
- return 0;
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void DrawArrow(string name, datetime time, double price, color clr, int arrow)
- {
- if(ObjectFind(0, name) == -1)
- {
- ObjectCreate(0, name, OBJ_ARROW, 0, time, price);
- ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
- ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
- ObjectSetInteger(0, name, OBJPROP_ARROWCODE, arrow);
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void DrawVirtualBuyOpen(double openPrice)
- {
- datetime t = TimeCurrent();
- string name = "VBUY_OPEN_" + IntegerToString(t);
-
- // DrawArrow(name, t, openPrice, clrLime, 233);
-
- ObjectCreate(0,name,OBJ_ARROW_BUY,0,TimeCurrent(),openPrice);
-
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void DrawVirtualBuyClose(double closePrice)
- {
- datetime t = TimeCurrent();
- string name = "VBUY_CLOSE_" + IntegerToString(t);
-
- // DrawArrow(name, t, closePrice, clrRed, 234);
- ObjectCreate(0,name,OBJ_ARROW_SELL,0,TimeCurrent(),closePrice);
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void DrawDottedTrendline(string name, datetime time1, double price1, datetime time2, double price2, color clr)
- {
- // Delete if already exists
- if(ObjectFind(0, name) != -1)
- ObjectDelete(0, name);
-
- // Create the trendline
- if(!ObjectCreate(0, name, OBJ_TREND, 0, time1, price1, time2, price2))
- Print("Error creating trendline: ", GetLastError());
-
- // Set properties
- ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
- ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT); // Dotted line
- ObjectSetInteger(0, name, OBJPROP_WIDTH, 1); // Line width
- }
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- int orderCount()
- {
- int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
-
- if(handle == INVALID_HANDLE)
- {
- Print("EA=> Handler invalid: orderCount() ", filename," ",GetLastError()," eaType: ",eaType);
- return -1;
- }
-
- int index = 0;
-
- while(!FileIsEnding(handle))
- {
- string line = FileReadString(handle);
-
- // Skip empty line
- if(StringLen(line) < 2)
- continue;
-
- string parts[];
- int count = StringSplit(line, ',', parts);
-
- int ticket = (int)StringToInteger(parts[0]);
- int type = (int)StringToInteger(parts[1]);
- int magic = (int)StringToInteger(parts[2]);
- double open_price = StringToDouble(parts[3]);
- double close_price = StringToDouble(parts[4]);
- datetime open_time = StringToTime(parts[5]);
- datetime close_time = StringToTime(parts[6]);
- double sl = StringToDouble(parts[7]);
- double tp = StringToDouble(parts[8]);
- double lotS = StringToDouble(parts[9]);
- double profit = StringToDouble(parts[10]);
-
- index++;
-
- }
-
- FileClose(handle);
-
- return index;
- }
-
-
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- int getTicketByNumber(int id,double & buySl,double & buyTp)
- {
-
- int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
-
- if(handle == INVALID_HANDLE)
- {
- Print("EA=> Handler invalid: getTicketByNumber() ", filename," error: ",GetLastError()," eaType: ",eaType);
- return 0;
- }
-
- int index = 0;
-
- while(!FileIsEnding(handle))
- {
- string line = FileReadString(handle);
-
- // Skip empty line
- if(StringLen(line) < 2)
- continue;
-
- string parts[];
- int count = StringSplit(line, ',', parts);
-
- int ticket = (int)StringToInteger(parts[0]);
- int type = (int)StringToInteger(parts[1]);
- int magic = (int)StringToInteger(parts[2]);
- double open_price = StringToDouble(parts[3]);
- double close_price = StringToDouble(parts[4]);
- datetime open_time = StringToTime(parts[5]);
- datetime close_time = StringToTime(parts[6]);
- double sl = StringToDouble(parts[7]);
- double tp = StringToDouble(parts[8]);
- double lotS = StringToDouble(parts[9]);
- double profit = StringToDouble(parts[10]);
-
- if(id == ticket)
- {
- buySl = sl;
- buyTp = tp;
- }
-
- }
-
- FileClose(handle);
-
- return index;
- }
- //+------------------------------------------------------------------+
|