| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871 |
- //+------------------------------------------------------------------+
- //| vol_hedge_strategy_mt5.mq5 |
- //| Copyright 2025, MQL Development |
- //| https://www.mqldevelopment.com/ |
- //+------------------------------------------------------------------+
- #property copyright "Copyright 2025, MQL Development"
- #property link "https://www.mqldevelopment.com/"
- #property version "1.00"
- #define MaxOrders 100
- #include <Trade\Trade.mqh>
- CTrade trade;
- //+------------------------------------------------------------------+
- //| Expert initialization function |
- //+------------------------------------------------------------------+
- enum NewsCloseOrder
- {
- CloseAllRunningOrder=0,
- LetTheOrderRun=1,
- };
- enum selectLine
- {
- LineOnNewsBar =0,
- LineOnNewsStop=1
- };
- #import "volHedgeNewsFilter.ex5"
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void initiateNews();
- int returnNewsStatus(bool High_Impact_News=true
- ,int High_Start_Time=60//Stop Trade before high News (min)
- ,int High_Stop_Time=15 //Stop Trade after high News (min)
- ,bool show_high_line=true//Show verticle Line when high news comes
- ,bool Medium_Impact_News=true
- ,int Medium_Start_Time=60//Stop Trade before medium News (min)
- ,int Medium_Stop_Time=15 //Stop Trade after medium News (min)
- ,bool show_medium_line=true//Show verticle Line when medium news comes
- ,bool Low_Impact_News=true
- ,int Low_Start_Time=60//Stop Trade before low News (min)
- ,int Low_Stop_Time=15 //Stop Trade after low News (min)
- ,bool show_low_line=true//Show verticle Line when low news comes
- ,string symbol=""
- ,string expert=""
- ,int GMT_Broker_Time=2
- ,selectLine sl=0
- ,string extraSymbol=""
- );
- void initiateNews();
- bool checkDate(string &lastNewsTitle, string &symbolNews, string &impactNews, string &news1, string &news2, string &news3, datetime &timeRemaining, datetime date,string expertname = "",string symbol = "",string extraSymbol="", int gmt=2,string description_1 = "",int candle = 0);
- void PrintStructure();
- #import
- struct new_trade_store
- {
- ulong buy_ticket; // Buy Ticket
- ulong sell_ticket; // Sell Ticket
- string symbol; // Symbol
- double price; // Price
- double stop_loss; // StopLoss
- double take_profit; // TakeProfit
- datetime start_time; // Start time
- datetime end_time; // End Time
- new_trade_store()
- {
- buy_ticket = -1;
- sell_ticket = -1;
- }
- };
- new_trade_store newTradeStore[MaxOrders];
- enum lotcalculator
- {
- fix, //Fixed Lot Size
- rsk, //Risk Percentage
- dollar, // Risk in Dollars
- };
- sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
- input int magic_no = 333; // Magic no
- input bool bothHitsSl = false; // Open after Both Hits StopLoss
- input int maxTrades = 2; // Max Concurrent Trades
- input int maxSlippage = 5; // Max Slippage
- input bool enableSpreadFilter = false; // Enable Spread Filter
- input double maximumSpread = 10; // Maximum Spread
- input string string_1 = "<><><><><><> Lot Management<><><><><><>"; //__
- input lotcalculator lot_calculator = fix; // Lot Size Option
- input double lot_amount = 0.1; // Lot Size
- input double risk = 0.5; // Risk in Percentage %
- input double dollars = 10; // Risk in GBP
- input string string_2 = "<><><><><><> Time Filter Setting <><><><><><> ";//_
- input bool enableTimeSession = false; // Enable Time Session
- input string start_time_session = "01:00"; // Start Session
- input string end_time_session = "23:59"; // End Session
- input string news = "<><><><><><> News Settings <><><><><><>"; // News
- input NewsCloseOrder newsClose = CloseAllRunningOrder; // On News Action on Running Orders
- input bool High_Impact_News = true; //High Impact News
- input int High_Start_Time = 60; //Stop Trade before high News (min)
- input int High_Stop_Time = 15; //Stop Trade after high News (min)
- input bool show_high_line = true; //Show verticle Line when high news comes
- input selectLine Select_News_Line = 0; //News Line
- input bool mobileAlert = true; //Mobile Alert
- input bool Medium_Impact_News = false; // Medium Impact News
- input int Medium_Start_Time = 60; // Stop Trade before medium News (min)
- input int Medium_Stop_Time = 15; // Stop Trade after medium News (min)
- input bool show_medium_line = false; // Show vertical Line when medium news comes
- input bool Low_Impact_News = false; // Low Impact News
- input int Low_Start_Time = 60; // Stop Trade before low News (min)
- input int Low_Stop_Time = 15; // Stop Trade after low News (min)
- input bool show_low_line = false; // Show vertical Line when low news comes
- // Global Variables
- static double tickCurrentBid = 0;
- double tickPreviousBid = 0;
- static double tickCurrentAsk = 0;
- double tickPreviousAsk = 0;
- datetime startSessionTime, endSessionTime;
- int GMT_Broker_Time = +2; // GMT_Broker_Time Time of your Broker
- int gmt = 0; // GMT_Broker_Time Time of your Broker
- string Lname="newsLabel3";
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- int OnInit()
- {
- //---
- Print(" OnInIt. ");
- trade.SetExpertMagicNumber(magic_no);
- trade.SetDeviationInPoints(maxSlippage);
- trade.SetTypeFilling(ORDER_FILLING_IOC);
- trade.LogLevel(LOG_LEVEL_ALL);
- trade.SetAsyncMode(false);
- int filehandle = FileOpen("vol_hedge_data.csv", FILE_READ | FILE_CSV | FILE_COMMON | FILE_ANSI);
- if(filehandle != INVALID_HANDLE)
- {
- Print(" Valid Handler. ");
- while(!FileIsEnding(filehandle))
- {
- string orderToRead = FileReadString(filehandle);
- string orderData[];
- //Print("Data: ", OrderToRead);
- StringSplit(orderToRead, StringGetCharacter(",",0), orderData);
- Print("Array Size: ", ArraySize(orderData));
- Print(" Order is: ", orderToRead);
- for(int i = 0 ; i < ArraySize(orderData) ; i++)
- {
- Print(" Order Data: ", orderData[i], " i: ", i);
- }
- if(ArraySize(orderData) >= 6)
- {
- if(orderData[0] == Symbol())
- {
- // store into local variables first (trim if needed)
- ulong buy_ticket_local = (ulong)-1; // keep -1 as per your convention
- ulong sell_ticket_local = (ulong)-1;
- string symbol_local = orderData[0];
- double price_local = StringToDouble(orderData[1]);
- double sl_local = StringToDouble(orderData[2]);
- double tp_local = StringToDouble(orderData[3]);
- // if your CSV has extra fields (tp2,tp3, etc.) parse here as needed
- datetime start_local = StringToTime(orderData[4]);
- datetime end_local = StringToTime(orderData[5]);
- // OPTIONAL: only add when price == 0:
- // if(MathAbs(price_local) > 1e-9) { Print("Skipped: price != 0"); continue; }
- // call the single-responsibility function that writes into struct array
- addToNewTradeStore(buy_ticket_local, sell_ticket_local,
- symbol_local, price_local,
- sl_local, tp_local,
- start_local, end_local);
- }
- }
- }
- FileClose(filehandle);
- }
- else
- {
- Print(" InValid Handler. Error: ", GetLastError());
- }
- timeFilter(true,start_time_session, end_time_session, startSessionTime, endSessionTime);
- Print(" Session Start = ", startSessionTime, " Asian Session End = ", endSessionTime);
- int timeDifference = (int)TimeCurrent() - (int)TimeGMT();
- Print("Time Difference is: ", timeDifference);
- if(timeDifference > 0)
- {
- GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
- }
- else
- if(timeDifference < 0)
- {
- GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
- }
- else // timeDifference == 0
- {
- GMT_Broker_Time = 0;
- }
- Print("Gmt Time: ", TimeGMT(), " Broker Gmt Time: ", GMT_Broker_Time);
- gmt = GMT_Broker_Time;
- if(!MQLInfoInteger(MQL_TESTER))
- {
- initiateNews(); // change here
- }
- //---
- return(INIT_SUCCEEDED);
- }
- //+------------------------------------------------------------------+
- //| Expert deinitialization function |
- //+------------------------------------------------------------------+
- void OnDeinit(const int reason)
- {
- //---
- }
- //+------------------------------------------------------------------+
- //| Expert tick function |
- //+------------------------------------------------------------------+
- void OnTick()
- {
- static int status=-1,preStatus=-1;
- if(!MQLInfoInteger(MQL_TESTER))
- {
- status=returnNewsStatus(High_Impact_News
- ,High_Start_Time
- ,High_Stop_Time
- ,show_high_line
- ,Medium_Impact_News
- ,Medium_Start_Time
- ,Medium_Stop_Time
- ,show_medium_line
- ,Low_Impact_News
- ,Low_Start_Time
- ,Low_Stop_Time
- ,show_low_line
- ,Symbol()
- ,MQLInfoString(MQL_PROGRAM_NAME)
- ,GMT_Broker_Time
- ,Select_News_Line
- ,""
- );
- }
- else
- status=0;
- if(status==0)
- {
- mainActivity();
- }
- if(status==1 || status==2 || status==3)
- {
- if(newsClose==0)
- {
- if(orderCount_1(POSITION_TYPE_BUY,magic_no)>0)
- closeTrades(POSITION_TYPE_BUY,magic_no);
- if(orderCount_1(POSITION_TYPE_SELL,magic_no)>0)
- closeTrades(POSITION_TYPE_SELL,magic_no);
- }
- else
- if(newsClose==1)
- {
- if((orderCount_1(POSITION_TYPE_BUY,magic_no)>0) || (orderCount_1(POSITION_TYPE_SELL,magic_no)>0))
- {
- mainActivity();
- }
- }
- }
- if(status!=preStatus)
- {
- if(status==0 && preStatus!=-1)
- {
- // if(ObjectFind(0,Lname))
- {
- // ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
- ObjectSetString(0,Lname,OBJPROP_TEXT,"");
- }
- Alert("Trading is start");
- if(mobileAlert)
- SendNotification("Trading is start");
- preStatus=status;
- }
- else
- if(status==1)
- {
- ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
- ObjectSetString(0,Lname,OBJPROP_TEXT,"High Impact News");
- Alert("Trading Stop due to high impact news");
- if(mobileAlert)
- SendNotification("Trading Stop due to high impact news");
- preStatus=status;
- }
- else
- if(status==2)
- {
- ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrBlue);
- ObjectSetString(0,Lname,OBJPROP_TEXT,"Medium Impact News");
- Alert("Trading Stop due to medium impact news");
- if(mobileAlert)
- SendNotification("Trading Stop due to medium impact news");
- preStatus=status;
- }
- else
- if(status==3)
- {
- ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrGreen);
- ObjectSetString(0,Lname,OBJPROP_TEXT,"Low Impact News");
- Alert("Trading Stop due to low impact news");
- if(mobileAlert)
- SendNotification("Trading Stop due to low impact news");
- preStatus=status;
- }
- }
- else
- {
- mainActivity();
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void mainActivity()
- {
- //---
- double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);
- double Ask = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
- if(tickPreviousBid == 0 && tickCurrentBid == 0)
- {
- tickPreviousBid = Bid;
- tickCurrentBid = Bid;
- }
- else
- {
- tickPreviousBid = tickCurrentBid;
- tickCurrentBid = Bid;
- }
- if(tickPreviousAsk == 0 && tickCurrentAsk == 0)
- {
- tickPreviousAsk = Ask;
- tickCurrentAsk = Ask;
- }
- else
- {
- tickPreviousAsk = tickCurrentAsk;
- tickCurrentAsk = Ask;
- }
- // Print(" Time is: ", TimeCurrent());
- timeFilter(false,start_time_session, end_time_session, startSessionTime, endSessionTime);
- // Comment(" Session Start = ", startSessionTime, " Asian Session End = ", endSessionTime);
- if((!enableTimeSession) || (enableTimeSession && TimeCurrent() >= startSessionTime && TimeCurrent() <= endSessionTime))
- {
- tradePlacingCheck();
- if(bothHitsSl)
- {
- removeBuySellOnSlHit();
- }
- }
- }
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void closeTrades(int type,int magicno)
- {
- Print("Total order: ",OrdersTotal());
- for(int i= PositionsTotal()-1; i>=0; i--)
- {
- // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- if(PositionGetInteger(POSITION_TYPE) == type)
- {
- if(PositionGetInteger(POSITION_MAGIC) == magicno && PositionGetString(POSITION_SYMBOL) == Symbol())
- {
- //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
- if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
- {Print("Problem in closing order order ",PositionGetInteger(POSITION_TICKET)); }
- else
- {
- Print("Order Closed by closeTrades() new filter",PositionGetInteger(POSITION_TICKET));
- }
- }
- }
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- int orderCount_1(int type,int magic)
- {
- int count1=0;
- for(int i= PositionsTotal()-1; i>=0; i--)
- {
- // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- // if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
- if(PositionGetInteger(POSITION_MAGIC) == magic && PositionGetString(POSITION_SYMBOL) == Symbol())
- {
- //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
- if(PositionGetInteger(POSITION_TYPE) == type)
- {
- count1++;
- }
- }
- }
- }
- return count1;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- int orderCount(int type)
- {
- int count = 0;
- for(int i= PositionsTotal()-1; i>=0; i--)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- if(PositionGetInteger(POSITION_MAGIC) == magic_no && PositionGetString(POSITION_SYMBOL) == Symbol())
- {
- if(PositionGetInteger(POSITION_TYPE) == type)
- {
- count++;
- }
- }
- }
- }
- return count;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void addToNewTradeStore(ulong r_buy_ticket, ulong r_sell_ticket,
- string r_symbol, double r_price,
- double r_stop_loss, double r_take_profit,
- datetime r_start_time, datetime r_end_time)
- {
- for(int i = 0; i < MaxOrders; i++)
- {
- // treat slot as empty when both tickets are -1 (same convention as constructor)
- if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
- {
- newTradeStore[i].buy_ticket = r_buy_ticket;
- newTradeStore[i].sell_ticket = r_sell_ticket;
- newTradeStore[i].symbol = r_symbol;
- newTradeStore[i].price = r_price;
- newTradeStore[i].stop_loss = r_stop_loss;
- newTradeStore[i].take_profit = r_take_profit;
- newTradeStore[i].start_time = r_start_time;
- newTradeStore[i].end_time = r_end_time;
- Print("Stored -> idx: ", i,
- " | sym: ", newTradeStore[i].symbol,
- " | price: ", DoubleToString(newTradeStore[i].price, Digits()),
- " | sl: ", DoubleToString(newTradeStore[i].stop_loss, Digits()),
- " | tp: ", DoubleToString(newTradeStore[i].take_profit, Digits()),
- " | start: ", TimeToString(newTradeStore[i].start_time, TIME_DATE|TIME_SECONDS),
- " | end: ", TimeToString(newTradeStore[i].end_time, TIME_DATE|TIME_SECONDS));
- break;
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void tradePlacingCheck()
- {
- for(int i = 0; i < MaxOrders; i++)
- {
- if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
- {
- if(newTradeStore[i].price > 0)
- {
- if(TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time)
- {
- double levelPriceIs = newTradeStore[i].price;
- if((tickPreviousBid > levelPriceIs && tickCurrentBid < levelPriceIs) ||
- (tickPreviousBid < levelPriceIs && tickCurrentBid > levelPriceIs))
- {
- if(countLiveTrades() < maxTrades)
- {
- if((enableSpreadFilter && spreadFilter()) || !enableSpreadFilter)
- {
- ulong buyTicket = placeBuyTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
- ulong sellTicket = placeSellTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
- newTradeStore[i].buy_ticket = buyTicket;
- newTradeStore[i].sell_ticket = sellTicket;
- }
- }
- }
- }
- }
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- ulong placeBuyTrade(double stoploss, double takeprofit)
- {
- double buySL = 0, buyTp=0;
- //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
- double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
- double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
- if(stoploss != 0)
- {
- buySL = Ask - (stoploss * Point());
- }
- if(takeprofit != 0)
- {
- buyTp = Ask + (takeprofit * Point());
- }
- double distance = MathAbs((Ask - buySL) / Point());
- if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,getLot(distance),Ask,buySL,buyTp,"Buy Trade Placed"))
- {
- Print("Buy Trade Placed: ",trade.ResultOrder());
- return trade.ResultOrder();
- }
- else
- {
- Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
- return -1;
- }
- return -1;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- ulong placeSellTrade(double stoploss, double takeprofit)
- {
- double sellSL = 0, sellTp = 0;
- double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
- double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
- if(stoploss != 0)
- {
- sellSL = Bid + (stoploss * Point());
- }
- if(takeprofit != 0)
- {
- sellTp = Bid - (takeprofit * Point());
- }
- double distance = MathAbs((Bid - sellSL) / Point());
- if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,getLot(distance),Bid,sellSL,sellTp,"Sell Trade Placed"))
- {
- Print("Sell Trade PLaced: ",trade.ResultOrder());
- return trade.ResultOrder();
- }
- else
- {
- Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
- return -1;
- }
- return -1;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- double getLot(double stop_loss)
- {
- Print("Tick Value: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE));
- Print("Tick Size: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE));
- double modeTickV=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)
- ,modeTickS=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
- // Print("Pip value: ", NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point))*10),2));
- double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
- // pipvalue=NormalizeDouble((modeTickV/modeTickS/Point()),)
- // pipvalue=
- pipvalue = pipvalue / 10;
- double lotSize = lot_amount;
- if(lot_calculator == rsk || lot_calculator == dollar) //calculating risk
- {
- double riskamount = 0;
- if(lot_calculator == rsk)
- {
- riskamount = (risk/100)*AccountInfoDouble(ACCOUNT_BALANCE);
- }
- if(lot_calculator == dollar)
- {
- riskamount = dollars;
- }
- double pipvalue_required=riskamount/stop_loss;
- lotSize = pipvalue_required/pipvalue;
- //sl=riskamount/pipValuelot
- int roundDigit=0;
- double step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);
- while(step<1)
- {
- roundDigit++;
- step=step*10;
- }
- Print("Round Digits:",roundDigit);
- lotSize = NormalizeDouble(lotSize,roundDigit);
- //
- }
- Print("Lot Size: ",lotSize);
- if(lotSize > SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX))
- {
- lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
- }
- else
- if(lotSize<SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN))
- {
- lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
- }
- //---
- return lotSize;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void timeFilter(bool onInit,string startTime,string endTime,datetime & sessionStart,datetime & sessionEnd)
- {
- int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
- datetime newYorkStartTrading,newYorkEndTrading;
- string time[];
- StringSplit(startTime,':',time);
- newYorkStartHour = (int)StringToInteger(time[0]);
- newYorkStartMin = (int)StringToInteger(time[1]);
- EventSetMillisecondTimer(500);
- time[0] = "";
- time[1] = "";
- StringSplit(endTime,':',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 removeBuySellOnSlHit()
- {
- for(int i = 0 ; i < MaxOrders ; i++)
- {
- bool isBuyPresent=false, isSellPresent=false;
- if(newTradeStore[i].buy_ticket != -1 && newTradeStore[i].sell_ticket != -1)
- {
- for(int j = PositionsTotal()-1; j>=0; j--)
- {
- ulong ticket = PositionGetTicket(j);
- if(PositionSelectByTicket(ticket))
- {
- if(ticket == newTradeStore[i].buy_ticket)
- {
- isBuyPresent=true;
- }
- }
- }
- for(int j = PositionsTotal()-1; j>=0; j--)
- {
- ulong ticket = PositionGetTicket(j);
- if(PositionSelectByTicket(ticket))
- {
- if(ticket == newTradeStore[i].sell_ticket)
- {
- isSellPresent = true;
- }
- }
- }
- if(!isBuyPresent && !isSellPresent)
- {
- if(tradeHitSL(newTradeStore[i].buy_ticket) && tradeHitSL(newTradeStore[i].sell_ticket))
- {
- Print("Buy/Sell Ticket is closed on StopLoss so removed from struct. Buy Ticket: ", newTradeStore[i].buy_ticket, " Sell Ticket: ", newTradeStore[i].sell_ticket);
- newTradeStore[i].buy_ticket = (ulong)-1;
- newTradeStore[i].sell_ticket = (ulong)-1;
- //newTradeStore[i].symbol = "";
- //newTradeStore[i].price = 0.0;
- //newTradeStore[i].stop_loss = 0.0;
- //newTradeStore[i].take_profit = 0.0;
- //newTradeStore[i].start_time = 0;
- //newTradeStore[i].end_time = 0;
- }
- }
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool tradeHitSL(ulong positionID)
- {
- if(HistorySelectByPosition(positionID))
- {
- for(int i = 0; i < HistoryDealsTotal(); i++)
- {
- ulong dealTicket = HistoryDealGetTicket(i);
- ulong dealPositionID = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
- if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT && dealPositionID == positionID)
- {
- int dealType = (int)HistoryDealGetInteger(dealTicket, DEAL_TYPE);
- string comment = HistoryDealGetString(dealTicket, DEAL_COMMENT);
- if(StringFind(comment, "sl", 0) >= 0)
- {
- // if(dealType == DEAL_TYPE_BUY)
- // {
- //
- // }
- return true;
- }
- }
- }
- }
- return false;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- int countLiveTrades()
- {
- int count = 0;
- for(int i = 0; i < PositionsTotal(); i++)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- if(PositionGetInteger(POSITION_MAGIC) == magic_no)
- {
- if(PositionGetString(POSITION_SYMBOL) == Symbol())
- {
- if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
- {
- count++;
- }
- }
- }
- }
- }
- return count;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool spreadFilter()
- {
- long spreadIs = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD);
- if(spreadIs > maximumSpread)
- {
- return false;
- }
- return true;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
|